qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
39,855
<p>Is it possible to embed a PowerPoint presentation (.ppt) into a webpage (.xhtml)?</p> <p>This will be used on a local intranet where there is a mix of Internet&nbsp;Explorer&nbsp;6 and Internet&nbsp;Explorer&nbsp;7 only, so no need to consider other browsers.</p> <hr> <p>I've given up... I guess Flash is the way forward.</p>
[ { "answer_id": 39857, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "<p>The first few results on Google all sound like good options:</p>\n\n<p><a href=\"http://www.pptfaq.com/FAQ00708.htm\" rel=\...
2008/09/02
[ "https://Stackoverflow.com/questions/39855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Is it possible to embed a PowerPoint presentation (.ppt) into a webpage (.xhtml)? This will be used on a local intranet where there is a mix of Internet Explorer 6 and Internet Explorer 7 only, so no need to consider other browsers. --- I've given up... I guess Flash is the way forward.
Google Docs can serve up PowerPoint (and PDF) documents in it's document viewer. You don't have to sign up for Google Docs, just upload it to your website, and call it from your page: ``` <iframe src="//docs.google.com/gview?url=https://www.yourwebsite.com/powerpoint.ppt&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe> ```
39,856
<p>I have an actionscript file that defines a class that I would like to use inside a Flex application. </p> <p>I have defined some custom controls in a actionscript file and then import them via the application tag:</p> <pre> <code> &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:scorecard="com.apterasoftware.scorecard.controls.*" ... &lt;/mx:Application&gt; </code> </pre> <p>but this code is not a flex component, rather it is a library for performing math routines, how do I import this class?</p>
[ { "answer_id": 39864, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 4, "selected": true, "text": "<p>You'd need to import the class inside a script tag.</p>\n\n<pre><code>&lt;mx:Application\n xmlns:mx=\"http://www.adobe.com/2...
2008/09/02
[ "https://Stackoverflow.com/questions/39856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have an actionscript file that defines a class that I would like to use inside a Flex application. I have defined some custom controls in a actionscript file and then import them via the application tag: ``` <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:scorecard="com.apterasoftware.scorecard.controls.*" ... </mx:Application> ``` but this code is not a flex component, rather it is a library for performing math routines, how do I import this class?
You'd need to import the class inside a script tag. ``` <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script> import com.apterasoftware.scorecard.controls.*; // Other imports go here // Functions and other code go here </mx:Script> <!-- Components and other MXML stuff go here --> <mx:VBox> <!-- Just a sample --> </mx:VBox> </mx:Application> ``` Then you'll be able to reference that class anywhere else in your script tag. Depending on how the class is written you may not be able to use binding within the MXML, but you could define your own code to handle that. Namespace declarations are only used to import other MXML components. AS classes are imported using the import statement either within a Script block or another AS file.
39,867
<p>I have a script that has a part that looks like that:</p> <pre><code>for file in `ls *.tar.gz`; do echo encrypting $file gpg --passphrase-file /home/$USER/.gnupg/backup-passphrase \ --simple-sk-checksum -c $file done </code></pre> <p>For some reason if I run this script manually, works perfectly fine and all files are encrypted. If I run this as cron job, <code>echo $file</code> works fine (I see "encrypting &lt;file&gt;" in the log), but the file doesn't get encrypted and gpg silent fails with no stdout/stderr output.</p> <p>Any clues?</p>
[ { "answer_id": 39877, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<p>make sure the user that is running the cron job has the permissions needed to encrypt the file. </p>\n" }, { "an...
2008/09/02
[ "https://Stackoverflow.com/questions/39867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105/" ]
I have a script that has a part that looks like that: ``` for file in `ls *.tar.gz`; do echo encrypting $file gpg --passphrase-file /home/$USER/.gnupg/backup-passphrase \ --simple-sk-checksum -c $file done ``` For some reason if I run this script manually, works perfectly fine and all files are encrypted. If I run this as cron job, `echo $file` works fine (I see "encrypting <file>" in the log), but the file doesn't get encrypted and gpg silent fails with no stdout/stderr output. Any clues?
It turns out that the answer was easier than I expected. There is a `--batch` parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used `--exit-on-status-write-error` param. But to use that I was inspired by exit status 2, reported by echoing `$?` as Cd-Man suggested.
39,874
<p>What data structures would you use to represent a chessboard for a computer chess program?</p>
[ { "answer_id": 39881, "author": "slm", "author_id": 4262, "author_profile": "https://Stackoverflow.com/users/4262", "pm_score": 3, "selected": false, "text": "<p>The simple approach is to use an 8x8 integer array. Use 0 for empty squares and assign values for the pieces:</p>\n\n<pre><cod...
2008/09/02
[ "https://Stackoverflow.com/questions/39874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4262/" ]
What data structures would you use to represent a chessboard for a computer chess program?
Initially, use an **8 \* 8 integer array** to represent the chess board. You can start programing using this notation. Give point values for the pieces. For example: ``` **White** 9 = white queen 5 = white rook 3 = bishop 3 = knight 1 = pawn **black** -9 = white queen -5 = white rook -3 = bishop -3 = knight -1 = pawn White King: very large positive number Black King: very large negative number ``` etc. (Note that the points given above are approximations of trading power of each chess piece) After you develop the basic backbones of your application and clearly understand the working of the algorithms used, try to improve the performance by using bit boards. In bit boards, you use eight 8 -bit words to represent the boards. This representation needs a board for each chess piece. In one bit board you will be storing the position of the rook while in another you will be storing the position of the knight... etc Bit boards can improve the performance of your application very much because manipulating the pieces with bit boards are very easy and fast. As you pointed out, > > Most chessprograms today, especially > those that run on a 64 bit CPU, use a > bitmapped approach to represent a > chessboard and generate moves. x88 is > an alternate board model for machines > without 64 bit CPUs. > > >
39,910
<p>I want to use the MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.</p>
[ { "answer_id": 40929, "author": "Matt Bishop", "author_id": 4301, "author_profile": "https://Stackoverflow.com/users/4301", "pm_score": 3, "selected": true, "text": "<p>I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if...
2008/09/02
[ "https://Stackoverflow.com/questions/39910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
I want to use the MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.
I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question! Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part. Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it "Related", have it be a Lookup into the Title field of the Tasks list, and allow multiple values. Now create a web part, do all the usual boilerplate and then add this: ``` Label l; MultipleLookupField mlf; protected override void CreateChildControls() { base.CreateChildControls(); SPList list = SPContext.Current.Web.Lists["Shared Documents"]; if (list != null && list.Items.Count > 0) { LiteralControl lit = new LiteralControl("Associate tasks to " + list.Items[0].Name); this.Controls.Add(lit); mlf = new MultipleLookupField(); mlf.ControlMode = SPControlMode.Edit; mlf.FieldName = "Related"; mlf.ItemId = list.Items[0].ID; mlf.ListId = list.ID; mlf.ID = "Related"; this.Controls.Add(mlf); Button b = new Button(); b.Text = "Change"; b.Click += new EventHandler(bClick); this.Controls.Add(b); l = new Label(); this.Controls.Add(l); } } void bClick(object sender, EventArgs e) { l.Text = ""; foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value) { l.Text += val.LookupValue.ToString() + " "; } SPListItem listitem = mlf.List.Items[0]; listitem["Related"] = mlf.Value; listitem.Update(); mlf.Value = listitem["Related"]; } protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); } ``` Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library. The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach...
39,912
<p>I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.</p>
[ { "answer_id": 39923, "author": "bradtgmurray", "author_id": 1546, "author_profile": "https://Stackoverflow.com/users/1546", "pm_score": 4, "selected": false, "text": "<p>Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove ...
2008/09/02
[ "https://Stackoverflow.com/questions/39912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1546/" ]
I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.
`std::remove` does not actually erase elements from the container: it moves the elements to be removed to the end of the container, and returns the new end iterator which can be passed to `container_type::erase` to do the actual removal of the extra elements that are now at the end of the container: ``` std::vector<int> vec; // .. put in some values .. int int_to_remove = n; vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end()); ```
39,916
<p>Is there a programmatic way to build <em>htpasswd</em> files, without depending on OS specific functions (i.e. <code>exec()</code>, <code>passthru()</code>)?</p>
[ { "answer_id": 39935, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://trac.edgewall.org\" rel=\"nofollow noreferrer\">Trac</a> ships with a Python replacement for htpas...
2008/09/02
[ "https://Stackoverflow.com/questions/39916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
Is there a programmatic way to build *htpasswd* files, without depending on OS specific functions (i.e. `exec()`, `passthru()`)?
.httpasswd files are just text files with a specific format depending on the hash function specified. If you are using MD5 they look like this: ``` foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241 ``` That's the login, a colon, ,$apr1$, the salt and 1000 times md5 encoded as base64. If you select SHA1 they look like this: ``` foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M= ``` That's the login, a colon, the string {SHA} and the SHA1 hash encoded with base64. If your language has an implementation of either MD5 or SHA1 and base64 you can just create the file like this: ``` <?php $login = 'foo'; $pass = 'pass'; $hash = base64_encode(sha1($pass, true)); $contents = $login . ':{SHA}' . $hash; file_put_contents('.htpasswd', $contents); ?> ``` Here's more information on the format: <http://httpd.apache.org/docs/2.2/misc/password_encryptions.html>
39,928
<p>I'm getting a <strong><code>Connection Busy With Results From Another Command</code></strong> error from a SQLServer Native Client driver when a SSIS package is running. Only when talking to SQLServer 2000. A different part that talks to SQLServer 2005 seems to always run fine. Any thoughts?</p>
[ { "answer_id": 40105, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://support.microsoft.com/kb/822668\" rel=\"nofollow noreferrer\">Microsoft KB article 822668</a> is relevant he...
2008/09/02
[ "https://Stackoverflow.com/questions/39928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2978/" ]
I'm getting a **`Connection Busy With Results From Another Command`** error from a SQLServer Native Client driver when a SSIS package is running. Only when talking to SQLServer 2000. A different part that talks to SQLServer 2005 seems to always run fine. Any thoughts?
[Microsoft KB article 822668](http://support.microsoft.com/kb/822668) is relevant here: > > FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query > ------------------------------------------------------------------------------------------------------------------ > > > ### Symptoms > > > Under stress conditions, you may receive the following error message when you perform linked server activity: > > > > ``` > Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error. > OLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005: > > OLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .]. > OLE/DB provider returned message: Connection is busy with results for another command > OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005. > > ``` > > **Note** The OLE DB source of the error may vary. However, all variations of the error message include the text "Connection is busy with results for another command". > > > ### Resolution > > > To resolve this problem, obtain the latest service pack for Microsoft SQL Server 2000. > > > As noted there, the problem was first corrected in SQL Server 2000 Service Pack 4. [This blog post](https://web.archive.org/web/20071124140051/http://bisqlserver.blogspot.com/2007/02/issues-transferring-data-back-and-forth.html) by Mark Meyerovich, a Senior Software Engineer at RDA Corp, also provides some insight (now archived, because the original link went dead): > > **SQL Server service pack upgrade** > > > A quick search on Google turns up the following article (<http://support.microsoft.com/kb/822668>): > FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query. > > > It basically implies the issue is a bug and recommends an upgrade to Service Pack 4. We have started out with SQL Server 2000 SP3 and we do have some linked servers in the equation, so we give it a try. After the upgrade to SP4 – same result. > > >
39,960
<p>In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions <code>locals()</code> and <code>globals()</code>. Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
[ { "answer_id": 39982, "author": "Bartosz Bierkowski", "author_id": 3666, "author_profile": "https://Stackoverflow.com/users/3666", "pm_score": 2, "selected": false, "text": "<p>Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like ...
2008/09/02
[ "https://Stackoverflow.com/questions/39960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions `locals()` and `globals()`. Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following: ``` var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' ``` Is this at all possible, or should I just be using a local object for the lookup?
* locals() - No. * globals() - Yes. `window` is a reference to the global scope, like `globals()` in python. ``` globals()["foo"] ``` is the same as: ``` window["foo"] ```
40,022
<p>I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux.</p> <p>Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes?</p>
[ { "answer_id": 40027, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 2, "selected": false, "text": "<p>I think Jeff complained about this recently. One common technique is to drag all the objects into the designer again...<...
2008/09/02
[ "https://Stackoverflow.com/questions/40022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048/" ]
I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux. Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes?
You can use SQLMetal.exe to generate your dbml and or cs/vb file. Use a pre-build script to start it and target the directory where your datacontext project belongs. ``` C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\sqlmetal.exe /server:<SERVER> /database:<database> /code:"path\Solution\DataContextProject\dbContext.cs" /language:csharp /namespace:<your namespace> ```
40,028
<p>I think it can be done by applying the transformation matrix of the scenegraph to z-normal (0, 0, 1), but it doesn't work. My code goes like this:</p> <pre><code>Vector3f toScreenVector = new Vector3f(0, 0, 1); Transform3D t3d = new Transform3D(); tg.getTransform(t3d); //tg is Transform Group of all objects in a scene t3d.transform(toScreenVector); </code></pre> <p>Then I tried something like this too:</p> <pre><code>Point3d eyePos = new Point3d(); Point3d mousePos = new Point3d(); canvas.getCenterEyeInImagePlate(eyePos); canvas.getPixelLocationInImagePlate(new Point2d(Main.WIDTH/2, Main.HEIGHT/2), mousePos); //Main is the class for main window. Transform3D motion = new Transform3D(); canvas.getImagePlateToVworld(motion); motion.transform(eyePos); motion.transform(mousePos); Vector3d toScreenVector = new Vector3f(eyePos); toScreenVector.sub(mousePos); toScreenVector.normalize(); </code></pre> <p>But still this doesn't work correctly. I think there must be an easy way to create such vector. Do you know what's wrong with my code or better way to do so?</p>
[ { "answer_id": 40666, "author": "caramelcarrot", "author_id": 3877, "author_profile": "https://Stackoverflow.com/users/3877", "pm_score": 2, "selected": false, "text": "<p>If I get this right, you want a vector that is normal to the screen plane, but in world coordinates?</p>\n\n<p>In th...
2008/09/02
[ "https://Stackoverflow.com/questions/40028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3388/" ]
I think it can be done by applying the transformation matrix of the scenegraph to z-normal (0, 0, 1), but it doesn't work. My code goes like this: ``` Vector3f toScreenVector = new Vector3f(0, 0, 1); Transform3D t3d = new Transform3D(); tg.getTransform(t3d); //tg is Transform Group of all objects in a scene t3d.transform(toScreenVector); ``` Then I tried something like this too: ``` Point3d eyePos = new Point3d(); Point3d mousePos = new Point3d(); canvas.getCenterEyeInImagePlate(eyePos); canvas.getPixelLocationInImagePlate(new Point2d(Main.WIDTH/2, Main.HEIGHT/2), mousePos); //Main is the class for main window. Transform3D motion = new Transform3D(); canvas.getImagePlateToVworld(motion); motion.transform(eyePos); motion.transform(mousePos); Vector3d toScreenVector = new Vector3f(eyePos); toScreenVector.sub(mousePos); toScreenVector.normalize(); ``` But still this doesn't work correctly. I think there must be an easy way to create such vector. Do you know what's wrong with my code or better way to do so?
Yes, you got my question right. Sorry that I was a little bit confused yesterday. Now I have corrected the code by following your suggestion and mixing two pieces of code in the question together: ``` Vector3f toScreenVector = new Vector3f(0, 0, 1); Transform3D t3d = new Transform3D(); canvas.getImagePlateToVworld(t3d); t3d.transform(toScreenVector); tg.getTransform(t3d); //tg is Transform Group of all objects in a scene t3d.transform(toScreenVector); ``` Thank you.
40,043
<p>How can I create a new database from my C# application?</p> <p>I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the CREATE TABLE statements.</p>
[ { "answer_id": 40061, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://support.microsoft.com/kb/307283\" rel=\"noreferrer\">KB307283</a> explains how to create a database using ADO...
2008/09/02
[ "https://Stackoverflow.com/questions/40043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
How can I create a new database from my C# application? I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the CREATE TABLE statements.
[KB307283](http://support.microsoft.com/kb/307283) explains how to create a database using ADO.NET. From the article: ``` String str; SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master"); str = "CREATE DATABASE MyDatabase ON PRIMARY " + "(NAME = MyDatabase_Data, " + "FILENAME = 'C:\\MyDatabaseData.mdf', " + "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " + "LOG ON (NAME = MyDatabase_Log, " + "FILENAME = 'C:\\MyDatabaseLog.ldf', " + "SIZE = 1MB, " + "MAXSIZE = 5MB, " + "FILEGROWTH = 10%)"; SqlCommand myCommand = new SqlCommand(str, myConn); try { myConn.Open(); myCommand.ExecuteNonQuery(); MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (System.Exception ex) { MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (myConn.State == ConnectionState.Open) { myConn.Close(); } } ```
40,054
<p>Code below does not run correctly and throws <code>InvalidOperationExcepiton</code>.</p> <pre><code>public void Foo() { DataContext context = new DataContext(); LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ; context.LinqEntities.Attach(item, true); } </code></pre>
[ { "answer_id": 40079, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 1, "selected": false, "text": "<p>I'm not sure what you mean by disconnected from the database.</p>\n\n<p>It appears that you are trying to insert a new...
2008/09/02
[ "https://Stackoverflow.com/questions/40054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4215/" ]
Code below does not run correctly and throws `InvalidOperationExcepiton`. ``` public void Foo() { DataContext context = new DataContext(); LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ; context.LinqEntities.Attach(item, true); } ```
By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException. This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data. Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values. ``` LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"}; context.LinqEntities.Attach(item); item.Name = "John"; item.Surname = "Doe"; context.SubmitChanges(); ```
40,075
<p>I am writing a few extensions to mimic the map and reduce functions in Lisp.</p> <pre><code>public delegate R ReduceFunction&lt;T,R&gt;(T t, R previous); public delegate void TransformFunction&lt;T&gt;(T t, params object[] args); public static R Reduce&lt;T,R&gt;(this List&lt;T&gt; list, ReduceFunction&lt;T,R&gt; r, R initial) { var aggregate = initial; foreach(var t in list) aggregate = r(t,aggregate); return aggregate; } public static void Transform&lt;T&gt;(this List&lt;T&gt; list, TransformFunction&lt;T&gt; f, params object [] args) { foreach(var t in list) f(t,args); } </code></pre> <p>The transform function will cut down on cruft like:</p> <pre><code>foreach(var t in list) if(conditions &amp;&amp; moreconditions) //do work etc </code></pre> <p>Does this make sense? Could it be better?</p>
[ { "answer_id": 40084, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": 2, "selected": false, "text": "<p>I would use the built in Func delegates instead. This same code would work on any IEnumerable. Your code would turn i...
2008/09/02
[ "https://Stackoverflow.com/questions/40075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455/" ]
I am writing a few extensions to mimic the map and reduce functions in Lisp. ``` public delegate R ReduceFunction<T,R>(T t, R previous); public delegate void TransformFunction<T>(T t, params object[] args); public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial) { var aggregate = initial; foreach(var t in list) aggregate = r(t,aggregate); return aggregate; } public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args) { foreach(var t in list) f(t,args); } ``` The transform function will cut down on cruft like: ``` foreach(var t in list) if(conditions && moreconditions) //do work etc ``` Does this make sense? Could it be better?
These look very similar to extensions in Linq already: ``` //takes a function that matches the Func<T,R> delegate listInstance.Aggregate( startingValue, (x, y) => /* aggregate two subsequent values */ ); //takes a function that matches the Action<T> delegate listInstance.ForEach( x => /* do something with x */); ``` Why is the 2nd example called Transform? Do you intend to change the values in the list somehow? If that's the case you may be better off using `ConvertAll<T>` or `Select<T>`.
40,090
<p>Is it true that the only way to handle default function arguments is through function overloading?</p> <p>For example, in PHP I can do this:</p> <pre><code>function foo($x, $y=0) { } </code></pre> <p>Would the best way to handle it in C# be this?</p> <pre><code>void foo(int x) { foo(x, 0); } void foo(int x, int y) { } </code></pre> <p><strong><em><a href="http://bytes.com/forum/thread224970.html" rel="noreferrer">Example lifted from here</a></em></strong></p> <p>Edit</p> <p><strong><em>Made the C# example into actual C# (Thanks Blair Conrad)</em></strong></p>
[ { "answer_id": 40093, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": true, "text": "<p>Yes, that'd be best<s>, except you'd omit the <code>$</code>s on the parameter names</s>, as others have pointed out. ...
2008/09/02
[ "https://Stackoverflow.com/questions/40090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Is it true that the only way to handle default function arguments is through function overloading? For example, in PHP I can do this: ``` function foo($x, $y=0) { } ``` Would the best way to handle it in C# be this? ``` void foo(int x) { foo(x, 0); } void foo(int x, int y) { } ``` ***[Example lifted from here](http://bytes.com/forum/thread224970.html)*** Edit ***Made the C# example into actual C# (Thanks Blair Conrad)***
Yes, that'd be best~~, except you'd omit the `$`s on the parameter names~~, as others have pointed out. For those interested in the rationale behind the lack of default parameter values, see @Giovanni Galbo's explanation.
40,107
<p>I imagine everyone has seen code like:</p> <pre><code>public void Server2ClientEnumConvert( ServerEnum server) { switch(server) { case ServerEnum.One: return ClientEnum.ABC //And so on. </code></pre> <p>Instead of this badness we could do somthing like:</p> <pre><code>public enum ServerEnum { [Enum2Enum(ClientEnum.ABC)] One, } </code></pre> <p>Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself.</p> <p>The problem I am having here is in the declaration of the Enum2Enum attribute.</p> <p>This works but replacing object o with Enum e does not. I do not want to be able to pass in objects to the constructor, only other enums.</p> <pre><code>public class EnumToEnumAttribute : Attribute { public EnumToEnumAttribute(object o){} } </code></pre> <p>This fails to compile.</p> <pre><code>public class EnumToEnumAttribute : Attribute { public EnumToEnumAttribute(Enum e){} } </code></pre> <p>Is there a reason for the compile error? How else could I pass in the information needed to map besides: </p> <pre><code>EnumtoEnumAttribute(Type dest, string enumString) </code></pre> <p>This seems too verbose but if it is the only way then I guess I will use it.</p>
[ { "answer_id": 40128, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 0, "selected": false, "text": "<p>I would probably use struct as the type, and then throw an exception if it isn't an Enum type. I don't see how your (Type,...
2008/09/02
[ "https://Stackoverflow.com/questions/40107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455/" ]
I imagine everyone has seen code like: ``` public void Server2ClientEnumConvert( ServerEnum server) { switch(server) { case ServerEnum.One: return ClientEnum.ABC //And so on. ``` Instead of this badness we could do somthing like: ``` public enum ServerEnum { [Enum2Enum(ClientEnum.ABC)] One, } ``` Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself. The problem I am having here is in the declaration of the Enum2Enum attribute. This works but replacing object o with Enum e does not. I do not want to be able to pass in objects to the constructor, only other enums. ``` public class EnumToEnumAttribute : Attribute { public EnumToEnumAttribute(object o){} } ``` This fails to compile. ``` public class EnumToEnumAttribute : Attribute { public EnumToEnumAttribute(Enum e){} } ``` Is there a reason for the compile error? How else could I pass in the information needed to map besides: ``` EnumtoEnumAttribute(Type dest, string enumString) ``` This seems too verbose but if it is the only way then I guess I will use it.
Using almost the same example, you can achieve this directly in the enum: ``` public enum ServerEnum { One = ClientEnum.ABC, } ``` This has the benefit of not requiring Reflection, is easier to read (in my opinion), and overall requires less overhead.
40,112
<p>I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users).</p> <p>For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder.</p> <p>How can I get MS Access to display the contents of a .jpg?</p>
[ { "answer_id": 40182, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": "<p>The easiest way is probably to plop an Internet Explorer onto one of your forms. Check out this site: <a href=\"http:...
2008/09/02
[ "https://Stackoverflow.com/questions/40112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685/" ]
I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users). For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder. How can I get MS Access to display the contents of a .jpg?
Another option is to put an image control on your form. There is a property of that control (Picture) that is simply the path to the image. Here is a short example in VBA of how you might use it. txtPhoto would be a text box bound to the database field with the path to the image imgPicture is the image control The example is a click event for a button that would advance to the next record. ``` Private Sub cmdNextClick() DoCmd.GoToRecord , , acNext txtPhoto.SetFocus imgPicture.Picture = txtPhoto.Text Exit Sub End Sub ```
40,116
<p>How do I get it to work with my project?</p> <p><a href="http://ajax.asp.net/" rel="noreferrer">http://ajax.asp.net/</a></p> <p><a href="http://www.codeplex.com/AjaxControlToolkit/" rel="noreferrer">http://www.codeplex.com/AjaxControlToolkit/</a></p>
[ { "answer_id": 40118, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 5, "selected": false, "text": "<p><strong>Install the ASP.NET AJAX Control Toolkit</strong></p>\n\n<ol>\n<li><p>Download the ZIP file\nAjaxControlToolkit-...
2008/09/02
[ "https://Stackoverflow.com/questions/40116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
How do I get it to work with my project? <http://ajax.asp.net/> <http://www.codeplex.com/AjaxControlToolkit/>
**Install the ASP.NET AJAX Control Toolkit** 1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the [ASP.NET AJAX Control Toolkit Releases](http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488) page of the CodePlex web site. 2. Copy the contents of this zip file directly into the bin directory of your web site. **Update web.config** 3. Put this in your web.config under the <controls> section: ``` <?xml version="1.0"?> <configuration> ... <system.web> ... <pages> ... <controls> ... <add tagPrefix="ajaxtoolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolKit"/> </controls> </pages> ... </system.web> ... </configuration> ``` **Setup Visual Studio** 4. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit" 5. Inside that tab, right-click on the Toolbox and select "Choose Items..." 6. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog. You can now use the controls in your web sites!
40,122
<p>My group is developing a service-based (.NET WCF) application and we're trying to decide how to handle exceptions in our internal services. Should we throw exceptions? Return exceptions serialized as XML? Just return an error code?</p> <p>Keep in mind that the user will never see these exceptions, it's only for other parts of the application.</p>
[ { "answer_id": 40140, "author": "Phil Bennett", "author_id": 2995, "author_profile": "https://Stackoverflow.com/users/2995", "pm_score": 1, "selected": false, "text": "<p>I'm a bit confused, I'm not being flippant -- you say you want to return exceptions serialised as XML on the one hand...
2008/09/02
[ "https://Stackoverflow.com/questions/40122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4219/" ]
My group is developing a service-based (.NET WCF) application and we're trying to decide how to handle exceptions in our internal services. Should we throw exceptions? Return exceptions serialized as XML? Just return an error code? Keep in mind that the user will never see these exceptions, it's only for other parts of the application.
WCF uses `SoapFaults` as its native way of transmitting exceptions from either the service to the client, or the client to the service. You can declare a custom SOAP fault using the `FaultContract` attribute in your contract interface: For example: ``` [ServiceContract(Namespace="foobar")] interface IContract { [OperationContract] [FaultContract(typeof(CustomFault))] void DoSomething(); } [DataContract(Namespace="Foobar")] class CustomFault { [DataMember] public string error; public CustomFault(string err) { error = err; } } class myService : IContract { public void DoSomething() { throw new FaultException<CustomFault>( new CustomFault("Custom Exception!")); } } ```
40,125
<p>I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.</p> <p>My quesion then is: Does anyone have any sample code that will do this?</p>
[ { "answer_id": 40167, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 2, "selected": false, "text": "<p>Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugi...
2008/09/02
[ "https://Stackoverflow.com/questions/40125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4165/" ]
I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu. My quesion then is: Does anyone have any sample code that will do this?
Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request: ``` var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", url, true); xmlhttp.onreadystatechange = function() { if(this.readyState == 4) { // Done loading? if(this.status == 200) { // Everything okay? // read content from this.responseXML or this.responseText } else { // Error occurred; handle it alert("Error " + this.status + ":\n" + this.statusText); } } }; xmlhttp.send(null); ``` A couple of notes on this code: * You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found [here](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html). * You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time. * You may want to do things when earlier readyStates are received. [This page](http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-object) documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.
40,133
<p>I have been experimenting with <a href="http://www.woopra.com/" rel="nofollow noreferrer">woopra.com</a> A web analytics tool. Which requires a piece of javascript code to be added to each page to function. This is easy enough with more dynamic sites with universal headers or footers but not for totally static html pages.</p> <p>I attempted to work round it by using a combination of Apache rewrites and SSI's to &quot;Wrap&quot; the static html with the required code. For example...</p> <p>I made the following changes to my apache config</p> <pre><code> RewriteEngine On RewriteCond %{REQUEST_URI} !=test.shtml RewriteCond %{IS_SUBREQ} false RewriteRule (.*)\.html test.shtml?$1.html </code></pre> <p>The test.shtml file contains...</p> <pre><code> &lt;script type=&quot;text/javascript&quot;&gt; var XXXXid = 'xxxxxxx'; &lt;/script&gt; &lt;script src=&quot;http://xxxx.woopra.com/xx/xxx.js&quot;&gt;&lt;/script&gt; &lt;!--#set var=&quot;page&quot; value=&quot;$QUERY_STRING&quot; --&gt; &lt;!--#include virtual= $page --&gt; </code></pre> <p>The idea was that a request coming in for</p> <pre><code> /abc.html </code></pre> <p>would be redirected to</p> <pre><code> /test.shtml?abc.html </code></pre> <p>the shtml would then include the original file into the response page.</p> <p>Unfortunately it doesn't quite work as planed :) can anyone see what I am doing wrong or perhaps suggest an alternative approach. Is there any apache modules that could do the same thing. Preferably that can be configured on a per site basis.</p> <p>Thanks</p> <p>Peter</p>
[ { "answer_id": 40156, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 3, "selected": true, "text": "<p>I think that <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_ext_filter.html\" rel=\"nofollow noreferrer\">mod_filt...
2008/09/02
[ "https://Stackoverflow.com/questions/40133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3720/" ]
I have been experimenting with [woopra.com](http://www.woopra.com/) A web analytics tool. Which requires a piece of javascript code to be added to each page to function. This is easy enough with more dynamic sites with universal headers or footers but not for totally static html pages. I attempted to work round it by using a combination of Apache rewrites and SSI's to "Wrap" the static html with the required code. For example... I made the following changes to my apache config ``` RewriteEngine On RewriteCond %{REQUEST_URI} !=test.shtml RewriteCond %{IS_SUBREQ} false RewriteRule (.*)\.html test.shtml?$1.html ``` The test.shtml file contains... ``` <script type="text/javascript"> var XXXXid = 'xxxxxxx'; </script> <script src="http://xxxx.woopra.com/xx/xxx.js"></script> <!--#set var="page" value="$QUERY_STRING" --> <!--#include virtual= $page --> ``` The idea was that a request coming in for ``` /abc.html ``` would be redirected to ``` /test.shtml?abc.html ``` the shtml would then include the original file into the response page. Unfortunately it doesn't quite work as planed :) can anyone see what I am doing wrong or perhaps suggest an alternative approach. Is there any apache modules that could do the same thing. Preferably that can be configured on a per site basis. Thanks Peter
I think that [mod\_filter\_ext](http://httpd.apache.org/docs/2.2/mod/mod_ext_filter.html) is the module you are looking for. You can write a short Perl script for example to insert the JS code in the pages and register it to process HTML pages: ``` while (<>) { s/<html>/\Q<script>....\E/; print $_; } ``` You could even use something like `sed` to perform the substitution.
40,161
<p>Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited.</p> <p>Something like this:</p> <pre><code>1,3,5-10,12 </code></pre> <p>What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string. In the above example, getting a list back like this would be nice:</p> <pre><code>1,3,5,6,7,8,9,10,12 </code></pre> <p>I just want to avoid rolling my own if there's an easy way to do it.</p>
[ { "answer_id": 40165, "author": "Daniel Jennings", "author_id": 3641, "author_profile": "https://Stackoverflow.com/users/3641", "pm_score": 3, "selected": false, "text": "<p>It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.</p>\n\n<p>Simply spli...
2008/09/02
[ "https://Stackoverflow.com/questions/40161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited. Something like this: ``` 1,3,5-10,12 ``` What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string. In the above example, getting a list back like this would be nice: ``` 1,3,5,6,7,8,9,10,12 ``` I just want to avoid rolling my own if there's an easy way to do it.
Should be simple: ``` foreach( string s in "1,3,5-10,12".Split(',') ) { // try and get the number int num; if( int.TryParse( s, out num ) ) { yield return num; continue; // skip the rest } // otherwise we might have a range // split on the range delimiter string[] subs = s.Split('-'); int start, end; // now see if we can parse a start and end if( subs.Length > 1 && int.TryParse(subs[0], out start) && int.TryParse(subs[1], out end) && end >= start ) { // create a range between the two values int rangeLength = end - start + 1; foreach(int i in Enumerable.Range(start, rangeLength)) { yield return i; } } } ``` **Edit:** thanks for the fix ;-)
40,193
<p>I've got to get a directory listing that contains about 2 million files, but when I do an <code>ls</code> command on it nothing comes back. I've waited 3 hours. I've tried <code>ls | tee directory.txt</code>, but that seems to hang forever. </p> <p>I assume the server is doing a lot of inode sorting. Is there any way to speed up the <code>ls</code> command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.</p>
[ { "answer_id": 40195, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 1, "selected": false, "text": "<p>How about <code>find ./ -type f</code> (which will find all files in the currently directory)? Take off the <code>-type f...
2008/09/02
[ "https://Stackoverflow.com/questions/40193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536194/" ]
I've got to get a directory listing that contains about 2 million files, but when I do an `ls` command on it nothing comes back. I've waited 3 hours. I've tried `ls | tee directory.txt`, but that seems to hang forever. I assume the server is doing a lot of inode sorting. Is there any way to speed up the `ls` command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.
``` ls -U ``` will do the ls without sorting. Another source of slowness is `--color`. On some linux machines, there is a convenience alias which adds `--color=auto'` to the ls call, making it look up file attributes for each file found (slow), to color the display. This can be avoided by `ls -U --color=never` or `\ls -U`.
40,211
<p>I have a flag enum below.</p> <pre><code>[Flags] public enum FlagTest { None = 0x0, Flag1 = 0x1, Flag2 = 0x2, Flag3 = 0x4 } </code></pre> <p>I cannot make the if statement evaluate to true.</p> <pre><code>FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2; if (testItem == FlagTest.Flag1) { // Do something, // however This is never true. } </code></pre> <p>How can I make this true?</p>
[ { "answer_id": 40213, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 3, "selected": false, "text": "<p>For bit operations, you need to use bitwise operators.</p>\n\n<p>This should do the trick:</p>\n\n<pre><code>if ((testIte...
2008/09/02
[ "https://Stackoverflow.com/questions/40211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
I have a flag enum below. ``` [Flags] public enum FlagTest { None = 0x0, Flag1 = 0x1, Flag2 = 0x2, Flag3 = 0x4 } ``` I cannot make the if statement evaluate to true. ``` FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2; if (testItem == FlagTest.Flag1) { // Do something, // however This is never true. } ``` How can I make this true?
In .NET 4 there is a new method [Enum.HasFlag](http://msdn.microsoft.com/en-us/library/system.enum.hasflag%28VS.100%29.aspx). This allows you to write: ``` if ( testItem.HasFlag( FlagTest.Flag1 ) ) { // Do Stuff } ``` which is much more readable, IMO. The .NET source indicates that this performs the same logic as the accepted answer: ``` public Boolean HasFlag(Enum flag) { if (!this.GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException( Environment.GetResourceString( "Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); } ulong uFlag = ToUInt64(flag.GetValue()); ulong uThis = ToUInt64(GetValue()); // test predicate return ((uThis & uFlag) == uFlag); } ```
40,244
<p>Assume that I have programs <code>P0</code>, <code>P1</code>, ...<code>P(n-1)</code> for some <code>n &gt; 0</code>. How can I easily redirect the output of program <code>Pi</code> to program <code>P(i+1 mod n)</code> for all <code>i</code> (<code>0 &lt;= i &lt; n</code>)?</p> <p>For example, let's say I have a program <code>square</code>, which repeatedly reads a number and than prints the square of that number, and a program <code>calc</code>, which sometimes prints a number after which it expects to be able to read the square of it. How do I connect these programs such that whenever <code>calc</code> prints a number, <code>square</code> squares it returns it to <code>calc</code>?</p> <p>Edit: I should probably clarify what I mean with "easily". The named pipe/fifo solution is one that indeed works (and I have used in the past), but it actually requires quite a bit of work to do properly if you compare it with using a bash pipe. (You need to get a not yet existing filename, make a pipe with that name, run the "pipe loop", clean up the named pipe.) Imagine you could no longer write <code>prog1 | prog2</code> and would always have to use named pipes to connect programs.</p> <p>I'm looking for something that is almost as easy as writing a "normal" pipe. For instance something like <code>{ prog1 | prog2 } &gt;&amp;0</code> would be great.</p>
[ { "answer_id": 40339, "author": "Mark Witczak", "author_id": 1536194, "author_profile": "https://Stackoverflow.com/users/1536194", "pm_score": 3, "selected": false, "text": "<p>This is a very interesting question. I (vaguely) remember an assignment very similar in college 17 years ago. W...
2008/09/02
[ "https://Stackoverflow.com/questions/40244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4285/" ]
Assume that I have programs `P0`, `P1`, ...`P(n-1)` for some `n > 0`. How can I easily redirect the output of program `Pi` to program `P(i+1 mod n)` for all `i` (`0 <= i < n`)? For example, let's say I have a program `square`, which repeatedly reads a number and than prints the square of that number, and a program `calc`, which sometimes prints a number after which it expects to be able to read the square of it. How do I connect these programs such that whenever `calc` prints a number, `square` squares it returns it to `calc`? Edit: I should probably clarify what I mean with "easily". The named pipe/fifo solution is one that indeed works (and I have used in the past), but it actually requires quite a bit of work to do properly if you compare it with using a bash pipe. (You need to get a not yet existing filename, make a pipe with that name, run the "pipe loop", clean up the named pipe.) Imagine you could no longer write `prog1 | prog2` and would always have to use named pipes to connect programs. I'm looking for something that is almost as easy as writing a "normal" pipe. For instance something like `{ prog1 | prog2 } >&0` would be great.
After spending quite some time yesterday trying to redirect `stdout` to `stdin`, I ended up with the following method. It isn't really nice, but I think I prefer it over the named pipe/fifo solution. ``` read | { P0 | ... | P(n-1); } >/dev/fd/0 ``` The `{ ... } >/dev/fd/0` is to redirect stdout to stdin for the pipe sequence as a whole (i.e. it redirects the output of P(n-1) to the input of P0). Using `>&0` or something similar does not work; this is probably because bash assumes `0` is read-only while it doesn't mind writing to `/dev/fd/0`. The initial `read`-pipe is necessary because without it both the input and output file descriptor are the same pts device (at least on my system) and the redirect has no effect. (The pts device doesn't work as a pipe; writing to it puts things on your screen.) By making the input of the `{ ... }` a normal pipe, the redirect has the desired effect. To illustrate with my `calc`/`square` example: ``` function calc() { # calculate sum of squares of numbers 0,..,10 sum=0 for ((i=0; i<10; i++)); do echo $i # "request" the square of i read ii # read the square of i echo "got $ii" >&2 # debug message let sum=$sum+$ii done echo "sum $sum" >&2 # output result to stderr } function square() { # square numbers read j # receive first "request" while [ "$j" != "" ]; do let jj=$j*$j echo "square($j) = $jj" >&2 # debug message echo $jj # send square read j # receive next "request" done } read | { calc | square; } >/dev/fd/0 ``` Running the above code gives the following output: ``` square(0) = 0 got 0 square(1) = 1 got 1 square(2) = 4 got 4 square(3) = 9 got 9 square(4) = 16 got 16 square(5) = 25 got 25 square(6) = 36 got 36 square(7) = 49 got 49 square(8) = 64 got 64 square(9) = 81 got 81 sum 285 ``` Of course, this method is quite a bit of a hack. Especially the `read` part has an undesired side-effect: termination of the "real" pipe loop does not lead to termination of the whole. I couldn't think of anything better than `read` as it seems that you can only determine that the pipe loop has terminated by try to writing write something to it.
40,264
<p>Let's say you have a class called Customer, which contains the following fields:</p> <ul> <li>UserName</li> <li>Email</li> <li>First Name</li> <li>Last Name</li> </ul> <p>Let's also say that according to your business logic, all Customer objects must have these four properties defined.</p> <p>Now, we can do this pretty easily by forcing the constructor to specify each of these properties. But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object. </p> <p>I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them. But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.</p> <p>Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?</p>
[ { "answer_id": 40276, "author": "Aldie", "author_id": 4133, "author_profile": "https://Stackoverflow.com/users/4133", "pm_score": -1, "selected": false, "text": "<p>Unless it's more than 1 argument, I always use arrays or objects as constructor parameters and rely on error checking to ma...
2008/09/02
[ "https://Stackoverflow.com/questions/40264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
Let's say you have a class called Customer, which contains the following fields: * UserName * Email * First Name * Last Name Let's also say that according to your business logic, all Customer objects must have these four properties defined. Now, we can do this pretty easily by forcing the constructor to specify each of these properties. But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object. I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them. But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties. Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?
Two design approaches to consider The [essence](http://www.hillside.net/plop/plop98/final_submissions/P10.pdf) pattern The [fluent interface](https://martinfowler.com/bliki/FluentInterface.html) pattern These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step. An example of the fluent interface in action would be: ```java public class CustomerBuilder { String surname; String firstName; String ssn; public static CustomerBuilder customer() { return new CustomerBuilder(); } public CustomerBuilder withSurname(String surname) { this.surname = surname; return this; } public CustomerBuilder withFirstName(String firstName) { this.firstName = firstName; return this; } public CustomerBuilder withSsn(String ssn) { this.ssn = ssn; return this; } // client doesn't get to instantiate Customer directly public Customer build() { return new Customer(this); } } public class Customer { private final String firstName; private final String surname; private final String ssn; Customer(CustomerBuilder builder) { if (builder.firstName == null) throw new NullPointerException("firstName"); if (builder.surname == null) throw new NullPointerException("surname"); if (builder.ssn == null) throw new NullPointerException("ssn"); this.firstName = builder.firstName; this.surname = builder.surname; this.ssn = builder.ssn; } public String getFirstName() { return firstName; } public String getSurname() { return surname; } public String getSsn() { return ssn; } } ``` ```java import static com.acme.CustomerBuilder.customer; public class Client { public void doSomething() { Customer customer = customer() .withSurname("Smith") .withFirstName("Fred") .withSsn("123XS1") .build(); } } ```
40,269
<p>Is there an easy way to find the storage card's path on a Windows Mobile device when there is a storage card and a bluetooth ftp connection?</p>
[ { "answer_id": 41316, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 1, "selected": false, "text": "<p>On Windows CE 5 (which is the base for Windows Mobile 6) the storage cards get mounted at the root file system as ...
2008/09/02
[ "https://Stackoverflow.com/questions/40269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
Is there an easy way to find the storage card's path on a Windows Mobile device when there is a storage card and a bluetooth ftp connection?
Keep in mind that "\Storage Card" is english oriented. A device made for a different region may have a different name. The name of the storage card path on my device varies with how I am using the device. Some time ago in the MSDN forms I responded to a few questions on how to detect the storage cards in the file system and how does one get the storage card's capacity. I wrote the following could are a response to those questions and thought it would be helpful to share. Storage cards show up in the file system as temporary directories. This program examines the objects in the root of the device and any folders that have temp attribute are considered to be a positive match ``` using System; using System.IO; using System.Runtime.InteropServices; namespace StorageCardInfo { class Program { const ulong Megabyte = 1048576; const ulong Gigabyte = 1073741824; [DllImport("CoreDLL")] static extern int GetDiskFreeSpaceEx( string DirectoryName, out ulong lpFreeBytesAvailableToCaller, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes ); static void Main(string[] args) { DirectoryInfo root = new DirectoryInfo("\\"); DirectoryInfo[] directoryList = root.GetDirectories(); ulong FreeBytesAvailable; ulong TotalCapacity; ulong TotalFreeBytes; for (int i = 0; i < directoryList.Length; ++i) { if ((directoryList.Attributes & FileAttributes.Temporary) != 0) { GetDiskFreeSpaceEx(directoryList.FullName, out FreeBytesAvailable, out TotalCapacity, out TotalFreeBytes); Console.Out.WriteLine("Storage card name: {0}", directoryList.FullName); Console.Out.WriteLine("Available Bytes : {0}", FreeBytesAvailable); Console.Out.WriteLine("Total Capacity : {0}", TotalCapacity); Console.Out.WriteLine("Total Free Bytes : {0}", TotalFreeBytes); } } } } ```
40,273
<p>A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of REST. They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible. I looked into soap4r, but it seems to have a slightly bad reputation.</p> <p>So what's the best way to integrate SOAP calls into a Rails app?</p>
[ { "answer_id": 40318, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 2, "selected": false, "text": "<p>Try <strong>SOAP4R</strong></p>\n\n<ul>\n<li><a href=\"http://dev.ctor.org/soap4r\" rel=\"nofollow noreferrer\">SO...
2008/09/02
[ "https://Stackoverflow.com/questions/40273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884/" ]
A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of REST. They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible. I looked into soap4r, but it seems to have a slightly bad reputation. So what's the best way to integrate SOAP calls into a Rails app?
We used the built in `soap/wsdlDriver` class, which is actually SOAP4R. It's dog slow, but really simple. The SOAP4R that you get from gems/etc is just an updated version of the same thing. Example code: ``` require 'soap/wsdlDriver' client = SOAP::WSDLDriverFactory.new( 'http://example.com/service.wsdl' ).create_rpc_driver result = client.doStuff(); ``` That's about it
40,317
<p>I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work:</p> <pre><code>$ umount -f /mnt/data $ umount2: Device or resource busy $ umount: /mnt/data: device is busy </code></pre> <p>If I type "<code>mount</code>", it appears that the directory is no longer mounted, but it hangs if I do "<code>ls /mnt/data</code>", and if I try to remove the mountpoint, I get:</p> <pre><code>$ rmdir /mnt/data rmdir: /mnt/data: Device or resource busy </code></pre> <p>Is there anything I can do other than reboot the machine?</p>
[ { "answer_id": 40320, "author": "tessein", "author_id": 3075, "author_profile": "https://Stackoverflow.com/users/3075", "pm_score": 9, "selected": true, "text": "<p>You might try a lazy unmount:</p>\n\n<pre><code>umount -l\n</code></pre>\n" }, { "answer_id": 40331, "author": ...
2008/09/02
[ "https://Stackoverflow.com/questions/40317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work: ``` $ umount -f /mnt/data $ umount2: Device or resource busy $ umount: /mnt/data: device is busy ``` If I type "`mount`", it appears that the directory is no longer mounted, but it hangs if I do "`ls /mnt/data`", and if I try to remove the mountpoint, I get: ``` $ rmdir /mnt/data rmdir: /mnt/data: Device or resource busy ``` Is there anything I can do other than reboot the machine?
You might try a lazy unmount: ``` umount -l ```
40,335
<p>I'm need to find a method to programmatically determine which disk drive Windows is using to boot. In other words, I need a way from Windows to determine which drive the BIOS is using to boot the whole system. </p> <p>Does Windows expose an interface to discover this? With how big the Windows API is, I'm hoping there is something buried in there that might do the trick.</p> <p>Terry</p> <p>p.s. Just reading the first sectors of the hard disk isn't reveling anything. On my dev box I have two hard disks, and when I look at the contents of the first couple of sectors on either of the hard disks I have a standard boiler plate MBR.</p> <p>Edit to clarify a few things. The way I want to identify the device is with a string which will identify a physical disk drive (as opposed to a logical disk drive). Physical disk drives are of the form "\\.\PHYSICALDRIVEx" where x is a number. On the other hand, a logical drive is identified by a string of the form, "\\.\x" where x is a drive letter.</p> <p>Edit to discuss a few of the ideas that were thrown out. Knowing which logical volume Windows used to boot doesn't help me here. Here is the reason. Assume that C: is using a mirrored RAID setup. Now, that means we have at least two physical drives. Now, I get the mapping from Logical Drive to Physical Drive and I discover that there are two physical drives used by that volume. Which one did Windows use to boot? Of course, this is assuming that the physical drive Windows used to boot is the same physical drive that contains the MBR. </p>
[ { "answer_id": 40347, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 3, "selected": false, "text": "<p>Unless C: is not the drive that windows booted from.<br />Parse the %SystemRoot% variable, it contains the location of the...
2008/09/02
[ "https://Stackoverflow.com/questions/40335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2171/" ]
I'm need to find a method to programmatically determine which disk drive Windows is using to boot. In other words, I need a way from Windows to determine which drive the BIOS is using to boot the whole system. Does Windows expose an interface to discover this? With how big the Windows API is, I'm hoping there is something buried in there that might do the trick. Terry p.s. Just reading the first sectors of the hard disk isn't reveling anything. On my dev box I have two hard disks, and when I look at the contents of the first couple of sectors on either of the hard disks I have a standard boiler plate MBR. Edit to clarify a few things. The way I want to identify the device is with a string which will identify a physical disk drive (as opposed to a logical disk drive). Physical disk drives are of the form "\\.\PHYSICALDRIVEx" where x is a number. On the other hand, a logical drive is identified by a string of the form, "\\.\x" where x is a drive letter. Edit to discuss a few of the ideas that were thrown out. Knowing which logical volume Windows used to boot doesn't help me here. Here is the reason. Assume that C: is using a mirrored RAID setup. Now, that means we have at least two physical drives. Now, I get the mapping from Logical Drive to Physical Drive and I discover that there are two physical drives used by that volume. Which one did Windows use to boot? Of course, this is assuming that the physical drive Windows used to boot is the same physical drive that contains the MBR.
1. Go into `Control Panel` 2. `System and Security` 3. `Administrative Tools` 4. Launch the `System Configuration` tool If you have multiple copies of Windows installed, the one you are booted with will be named such as: ``` Windows 7 (F:\Windows) Windows 7 (C:\Windows) : Current OS, Default OS ```
40,361
<p>I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone.</p> <p>Is that possible?</p>
[ { "answer_id": 40443, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>Short answer: no. Such a function was considered and explicitly rejected for version 2 of the XPath spec (see the non-nor...
2008/09/02
[ "https://Stackoverflow.com/questions/40361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1019/" ]
I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone. Is that possible?
It can be done but only if the return value when the node does exist is *the string value of the node, not the node itself*. The XPath ``` substring(concat("N/A", /foo/baz), 4 * number(boolean(/foo/baz))) ``` will return the string value of the `baz` element if it exists, otherwise the string "N/A". To generalize the approach: ``` substring(concat($null-value, $node), (string-length($null-value) + 1) * number(boolean($node))) ``` where `$null-value` is the null value string and `$node` the expression to select the node. Note that if `$node` evaluates to a node-set that contains more than one node, the string value of the *first* node is used.
40,402
<p>I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?</p>
[ { "answer_id": 40420, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 8, "selected": false, "text": "<p>In management studio:</p>\n\n<ul>\n<li>Don't do this on a live environment, but to ensure you shrink your dev db as much ...
2008/09/02
[ "https://Stackoverflow.com/questions/40402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1042/" ]
I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?
if I remember well... in query analyzer or equivalent: ``` BACKUP LOG databasename WITH TRUNCATE_ONLY DBCC SHRINKFILE ( databasename_Log, 1) ```
40,422
<p>Ok, so I want an autocomplete dropdown with linkbuttons as selections. So, the user puts the cursor in the "text box" and is greated with a list of options. They can either start typing to narrow down the list, or select one of the options on the list. As soon as they click (or press enter) the dataset this is linked to will be filtered by the selection. </p> <p>Ok, is this as easy as wrapping an AJAX autocomplete around a dropdown? No? (Please?) </p>
[ { "answer_id": 40504, "author": "JasonS", "author_id": 1865, "author_profile": "https://Stackoverflow.com/users/1865", "pm_score": 0, "selected": false, "text": "<p>You'll have to handle the OnSelectedIndexChanged event of your drop down list to rebind your dataset based on the users sel...
2008/09/02
[ "https://Stackoverflow.com/questions/40422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
Ok, so I want an autocomplete dropdown with linkbuttons as selections. So, the user puts the cursor in the "text box" and is greated with a list of options. They can either start typing to narrow down the list, or select one of the options on the list. As soon as they click (or press enter) the dataset this is linked to will be filtered by the selection. Ok, is this as easy as wrapping an AJAX autocomplete around a dropdown? No? (Please?)
This widget can be made with three items: a text input, button input, and an unordered list to hold the results. ``` __________ _ |__________||v|__ <-- text and button | | <-- ul (styled to appear relative to text input) | | | | |______________| ``` ul shown on: * 'keyUp' event of the text input (if value is non-empty) * 'click' event of the button input (if currently not visible) ul hidden on: * 'click' event of the button input (if currently visible) * 'click' event of list items When the ul is shown or the 'keyUp' event of the text input is triggered an AJAX call to the server needs to be made to update the list. On success the results should be placed in the ul. When creating the list items they should have a 'click' event attached to them that sets the text input value and hides the ul (may have to add a link inside the li to attach the event to). The hardest part is really the CSS. The JavaScript is simple especially with a solid library like prototype that supports multiple browsers. You will probably want to support some IDs for the items, so you can add some hidden inputs to each list item with the id and next to the text input to store the selected items ID.
40,423
<p>Actually, this question seems to have two parts:</p> <ul> <li>How to implement pattern matching?</li> <li>How to implement <a href="http://erlang.org/doc/reference_manual/expressions.html#6.9" rel="noreferrer">send and receive</a> (i.e. the Actor model)?</li> </ul> <p>For the pattern matching part, I've been looking into various projects like <a href="http://members.cox.net/nelan/app.html" rel="noreferrer">App</a> and <a href="http://www.cs.nyu.edu/leunga/papers/research/prop/prop.html" rel="noreferrer">Prop</a>. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The <a href="http://felix-lang.org/" rel="noreferrer">Felix</a> language also seems to support pattern matching pretty well, but isn't really C++.</p> <p>As for the <a href="http://en.wikipedia.org/wiki/Actor_model" rel="noreferrer">Actor model</a>, there are existing implementations like ACT++ and <a href="http://theron.ashtonmason.net/" rel="noreferrer">Theron</a>, but I couldn't find anything but papers on the former<strike>, and the latter is single-threaded only</strike> [see answers].</p> <p>Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching.</p> <p>Right now, I can use the following code to send a message:</p> <pre><code>(new Message(this)) ->set("foo", "bar") ->set("baz", 123) ->send(recipient); </code></pre> <p>And the following to do simple pattern matching (<code>qDebug</code> and <code>qPrintable</code> are Qt-specific):</p> <pre><code>receive_and_match(m) match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); } or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); } or_match_ignore end_receive </code></pre> <p>However, this looks a bit hackish to me, and isn't very robust.</p> <p>How would you do it? Did I miss any existing work?</p>
[ { "answer_id": 40616, "author": "1729", "author_id": 4319, "author_profile": "https://Stackoverflow.com/users/4319", "pm_score": 3, "selected": true, "text": "<p>One of the important things about erlang is how the features are used to make robust systems.</p>\n\n<p>The send/recieve model...
2008/09/02
[ "https://Stackoverflow.com/questions/40423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Actually, this question seems to have two parts: * How to implement pattern matching? * How to implement [send and receive](http://erlang.org/doc/reference_manual/expressions.html#6.9) (i.e. the Actor model)? For the pattern matching part, I've been looking into various projects like [App](http://members.cox.net/nelan/app.html) and [Prop](http://www.cs.nyu.edu/leunga/papers/research/prop/prop.html). These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The [Felix](http://felix-lang.org/) language also seems to support pattern matching pretty well, but isn't really C++. As for the [Actor model](http://en.wikipedia.org/wiki/Actor_model), there are existing implementations like ACT++ and [Theron](http://theron.ashtonmason.net/), but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers]. Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching. Right now, I can use the following code to send a message: ``` (new Message(this)) ->set("foo", "bar") ->set("baz", 123) ->send(recipient); ``` And the following to do simple pattern matching (`qDebug` and `qPrintable` are Qt-specific): ``` receive_and_match(m) match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); } or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); } or_match_ignore end_receive ``` However, this looks a bit hackish to me, and isn't very robust. How would you do it? Did I miss any existing work?
One of the important things about erlang is how the features are used to make robust systems. The send/recieve model is no-sharing, and explicitly copying. The processes themselves are lightweight threads. If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads. If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety. Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want. Although if you are not careful you end up with xml over pipes :) Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet. The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.
40,452
<p>I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in <strong>HTTP Headers</strong>.</p> <p>The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like</p> <pre><code>Request.Headers.Add(key,value); </code></pre> <p>but I cannot (exception from the framework); I tried the other way around, using the Response object like</p> <pre><code>Response.AppendHeader("key", "value"); </code></pre> <p>and then redirect to the page... but this doesn't work, as well.</p> <p>It's evident, I think, that I'm stuck there, any help?</p> <hr> <p><strong>EDIT</strong> I forgot to tell you that my environment is .Net 2.0, c#, on Win server 2003. The exception I got is</p> <pre><code>System.PlatformNotSupportedException was unhandled by user code Message="Operation is not supported on this platform." Source="System.Web" </code></pre> <p>This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this. </p>
[ { "answer_id": 40455, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>You should post more information.</p>\n\n<p>For instance, is this C#? It looks like it, but I might be wrong.</p>\n...
2008/09/02
[ "https://Stackoverflow.com/questions/40452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178/" ]
I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in **HTTP Headers**. The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like ``` Request.Headers.Add(key,value); ``` but I cannot (exception from the framework); I tried the other way around, using the Response object like ``` Response.AppendHeader("key", "value"); ``` and then redirect to the page... but this doesn't work, as well. It's evident, I think, that I'm stuck there, any help? --- **EDIT** I forgot to tell you that my environment is .Net 2.0, c#, on Win server 2003. The exception I got is ``` System.PlatformNotSupportedException was unhandled by user code Message="Operation is not supported on this platform." Source="System.Web" ``` This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this.
Like @lassevk said, a redirect won't work. You should use the WebRequest class to do an HTTP POST from your page or application. There's an example [here](http://msdn.microsoft.com/en-us/library/debx8sh9.aspx).
40,456
<p>If I select from a table group by the month, day, year, it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL?</p>
[ { "answer_id": 40462, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 3, "selected": false, "text": "<p>Create a calendar table and outer join on that table</p>\n" }, { "answer_id": 40481, "author": "Tom Mayfield",...
2008/09/02
[ "https://Stackoverflow.com/questions/40456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2477/" ]
If I select from a table group by the month, day, year, it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL?
[My developer](https://stackoverflow.com/users/51836/clark) got back to me with this code, underscores converted to dashes because StackOverflow was mangling underscores -- no numbers table required. Our example is complicated a bit by a join to another table, but maybe the code example will help someone someday. ``` declare @career-fair-id int select @career-fair-id = 125 create table #data ([date] datetime null, [cumulative] int null) declare @event-date datetime, @current-process-date datetime, @day-count int select @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id) select @current-process-date = dateadd(day, -90, @event-date) while @event-date <> @current-process-date begin select @current-process-date = dateadd(day, 1, @current-process-date) select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id) if @current-process-date <= getdate() insert into #data ([date], [cumulative]) values(@current-process-date, @day-count) end select * from #data drop table #data ```
40,465
<p>I have a List of Foo.</p> <p>Foo has a string property named Bar.</p> <p>I'd like to use <strong>LINQ</strong> to get a string[] of <strong>distinct</strong> values for Foo.Bar in List of Foo.</p> <p>How can I do this?</p>
[ { "answer_id": 40477, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>var distinctFooBars = (from foo in foos\n select foo.Bar).Distinc...
2008/09/02
[ "https://Stackoverflow.com/questions/40465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
I have a List of Foo. Foo has a string property named Bar. I'd like to use **LINQ** to get a string[] of **distinct** values for Foo.Bar in List of Foo. How can I do this?
I'd go lambdas... wayyy nicer ``` var bars = Foos.Select(f => f.Bar).Distinct().ToArray(); ``` works the same as what @lassevk posted. I'd also add that you might want to keep from converting to an array until the last minute. LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether. By evaluation I means asking for something that explicitly requires evalution like "Count()" or "ToArray()" etc.
40,480
<p>I always thought Java uses <strong>pass-by-reference</strong>.</p> <p>However, I've seen <a href="http://javadude.com/articles/passbyvalue.htm" rel="noreferrer">a blog post</a> that claims that Java uses <strong>pass-by-value</strong>.</p> <p>I don't think I understand the distinction they're making.</p> <p>What is the explanation?</p>
[ { "answer_id": 40499, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 10, "selected": false, "text": "<p>Java is always pass by value, with no exceptions, <strong>ever</strong>.</p>\n\n<p>So how is it that anyone can be at all co...
2008/09/02
[ "https://Stackoverflow.com/questions/40480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4315/" ]
I always thought Java uses **pass-by-reference**. However, I've seen [a blog post](http://javadude.com/articles/passbyvalue.htm) that claims that Java uses **pass-by-value**. I don't think I understand the distinction they're making. What is the explanation?
The terms "pass-by-value" and "pass-by-reference" have special, [precisely defined](https://en.wikipedia.org/w/index.php?title=Pass-by-value) meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact. The terms "pass-by-value" and "pass-by-reference" are talking about *variables.* Pass-by-value means that the *value* of a variable is passed to a function/method. Pass-by-reference means that a *reference* to that variable is passed to the function. The latter gives the function a way to change the contents of the variable. By those definitions, Java is always **pass-by-value**. Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called *references* which are passed-by-value as well. This terminology and semantics easily confuse many beginners. It goes like this: ``` public static void main(String[] args) { Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(...) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true } public static void foo(Dog d) { d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true } ``` In the example above `aDog.getName()` will still return `"Max"`. The value `aDog` within `main` is not changed in the function `foo` with the `Dog` `"Fifi"` as the object reference is passed by value. If it were passed by reference, then the `aDog.getName()` in `main` would return `"Fifi"` after the call to `foo`. Likewise: ``` public static void main(String[] args) { Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(...) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true } public static void foo(Dog d) { d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); } ``` In the above example, `Fifi` is the dog's name after call to `foo(aDog)` because the object's name was set inside of `foo(...)`. Any operations that `foo` performs on `d` are such that, for all practical purposes, they are performed on `aDog`, but it is **not** possible to change the value of the variable `aDog` itself. For more information on pass by reference and pass by value, consult the following answer: <https://stackoverflow.com/a/430958/6005228>. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.
40,511
<p>As the title already states, I'm trying to declare a nested function and return a pointer to that function. I want this function 'not' to return a new function pointer which will return the negation of whatever the original function was.</p> <p>Here is what I have:</p> <pre><code>someType not( someType original ) { int isNot( ListEntry* entry ) { return !original( entry ); } someType resultFunc = calloc( 1024, 1 ); memcpy( resultFunc, &amp;isNot, 1024 ); return resultFunc; } </code></pre> <p>someType is defined as:</p> <pre><code>typedef int(*someType)(ListEntry* entry) </code></pre>
[ { "answer_id": 40537, "author": "Steve Willard", "author_id": 402, "author_profile": "https://Stackoverflow.com/users/402", "pm_score": 0, "selected": false, "text": "<p>I'm using GCC.</p>\n\n<p>You can turn on nested functions by using the flag:</p>\n\n<pre><code>-fnested-functions\n</c...
2008/09/02
[ "https://Stackoverflow.com/questions/40511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402/" ]
As the title already states, I'm trying to declare a nested function and return a pointer to that function. I want this function 'not' to return a new function pointer which will return the negation of whatever the original function was. Here is what I have: ``` someType not( someType original ) { int isNot( ListEntry* entry ) { return !original( entry ); } someType resultFunc = calloc( 1024, 1 ); memcpy( resultFunc, &isNot, 1024 ); return resultFunc; } ``` someType is defined as: ``` typedef int(*someType)(ListEntry* entry) ```
Steve, you have a completely wrong mental model of what is a C function. ``` someType resultFunc = calloc( 1024, 1 ); memcpy( resultFunc, &isNot, 1024 ); ``` From your code fragment, I can surmise that you think that you can copy function's compiled code into a block of memory, and then reuse it. This kind of thing smells of Lisp, except even in lisp you don't do it that way. In fact, when you say "&isNot", you get a pointer to function. Copying the memory that pointer points at is counterproductive - the memory was initialized when you loaded your executable into memory, and it's not changing. In any case, writing someFunc() would cause a core dump, as the heap memory behing someFunc cannot be executed - this protects you from all sorts of viruses. You seem to expect an implementation of closures in C. That implementation is simply not there. Unlike Lisp or Perl or Ruby, C cannot preserve elements of a stack frame once you exited that frame. Even is nested functions are permitted in some compilers, I am sure that you cannot refer to non-global variables from inside those functions. The closes thing to closures is indeed C++ object that stores the state and implements operator(), but it's a completely different approach, and you'd still have to do things manually. Update: [here](http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Nested-Functions.html#Nested-Functions) is the relevant portion of GCC documentation. Look for "But this technique works only so long as the containing function (hack, in this example) does not exit."
40,525
<p>I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example:</p> <pre><code>//Function Declarations function parentFunction() { function callMe() { textField.text = "lawl"; } } </code></pre> <p>Now, <strong>how do I call the "callMe()" function</strong> in a different part of the code, like an onRelease function?</p> <pre><code>on(release) { callMe(); //doesn't work parentFunction().callMe(); //doesn't work parentFunction.callMe(); //doesn't work } </code></pre> <p>ActionScript 2.0 is just so wonky! Any ideas?</p>
[ { "answer_id": 40617, "author": "Michael Pryor", "author_id": 245, "author_profile": "https://Stackoverflow.com/users/245", "pm_score": 3, "selected": true, "text": "<p>Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do</p>\n\n<p>f...
2008/09/02
[ "https://Stackoverflow.com/questions/40525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/557/" ]
I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example: ``` //Function Declarations function parentFunction() { function callMe() { textField.text = "lawl"; } } ``` Now, **how do I call the "callMe()" function** in a different part of the code, like an onRelease function? ``` on(release) { callMe(); //doesn't work parentFunction().callMe(); //doesn't work parentFunction.callMe(); //doesn't work } ``` ActionScript 2.0 is just so wonky! Any ideas?
Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do function parent() { } function callMe() { } To be clear, a function can't own another function unless you provide some scope for that function to live in. So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned. <http://www.howtocreate.co.uk/tutorials/javascript/objects> For ActionScript, read this article on Adobe's website: <http://www.adobe.com/devnet/flex/articles/as_collections_03.html> EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a **private** function. See this article which should make the whole [private/public javascript issue](http://www.crockford.com/javascript/private.html) a lot more understandable.
40,535
<p>I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?</p>
[ { "answer_id": 40538, "author": "Jim Geurts", "author_id": 3085, "author_profile": "https://Stackoverflow.com/users/3085", "pm_score": 2, "selected": false, "text": "<p>My current solution is with extension methods:</p>\n\n<pre><code>public static class UrlHelperExtensions\n{\n /// &l...
2008/09/02
[ "https://Stackoverflow.com/questions/40535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3085/" ]
I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?
Here what i am using. I think this is actually generated by the MVC project template in VS: ``` public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName) { string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"]; string currentActionName = (string)helper.ViewContext.RouteData.Values["action"]; if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)) return true; return false; } ```
40,545
<p>Is there is any way to change the datasource location for a report and all of it's subreports without having to open each of them manually?</p>
[ { "answer_id": 40704, "author": "David Cumps", "author_id": 4329, "author_profile": "https://Stackoverflow.com/users/4329", "pm_score": -1, "selected": false, "text": "<p>I'm guessing you're talking about .rdl files from Reporting Services? (If not, my answer might be wrong)</p>\n\n<p>Th...
2008/09/02
[ "https://Stackoverflow.com/questions/40545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4286/" ]
Is there is any way to change the datasource location for a report and all of it's subreports without having to open each of them manually?
Here is how I set my connections at runtime. I get the connection info from a config location. ``` #'SET REPORT CONNECTION INFO For i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1 rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword) Next For i = 0 To rsource.ReportDocument.Subreports.Count - 1 For x = 0 To rsource.ReportDocument.Subreports(i).DataSourceConnections.Count - 1 rsource.ReportDocument.OpenSubreport(rsource.ReportDocument.Subreports(i).Name).DataSourceConnections(x).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword) Next Next ```
40,568
<p>Are square brackets in URLs allowed?</p> <p>I noticed that <a href="http://hc.apache.org/httpclient-3.x/index.html" rel="noreferrer">Apache commons HttpClient</a> (3.0.1) throws an IOException, wget and Firefox however accept square brackets.</p> <p>URL example:</p> <pre><code>http://example.com/path/to/file[3].html </code></pre> <p>My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).</p>
[ { "answer_id": 40571, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>Best to URL encode those, as they are clearly not supported in all web servers. Sometimes, even when there is a sta...
2008/09/02
[ "https://Stackoverflow.com/questions/40568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ]
Are square brackets in URLs allowed? I noticed that [Apache commons HttpClient](http://hc.apache.org/httpclient-3.x/index.html) (3.0.1) throws an IOException, wget and Firefox however accept square brackets. URL example: ``` http://example.com/path/to/file[3].html ``` My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).
[RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) states > > A host identified by an Internet > Protocol literal address, version 6 > [RFC3513] or later, is distinguished > by enclosing the IP literal within > square brackets ("[" and "]"). This > is the only place where square bracket > characters are allowed in the URI > syntax. > > > So you should not be seeing such URI's in the wild in theory, as they should arrive encoded.
40,577
<p>In Ruby, I'm trying to do the following.</p> <pre><code>def self.stats(since) return Events.find(:all, :select =&gt; 'count(*) as this_count', :conditions =&gt; ['Date(event_date) &gt;= ?', (Time.now - since)]).first.this_count end </code></pre> <p>where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?</p>
[ { "answer_id": 40580, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>Try using <a href=\"http://chronic.rubyforge.org/\" rel=\"nofollow noreferrer\">Chronic</a> to parse the date string...
2008/09/02
[ "https://Stackoverflow.com/questions/40577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322/" ]
In Ruby, I'm trying to do the following. ``` def self.stats(since) return Events.find(:all, :select => 'count(*) as this_count', :conditions => ['Date(event_date) >= ?', (Time.now - since)]).first.this_count end ``` where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?
I hacked this together with the ActiveSupport gem: ``` require 'active_support' def string_to_date(date_string) parts = date_string.split return parts[0].to_i.send(parts[1]) end sinces = ['1 hour', '1 day', '3 days'] sinces.each do |since| puts "#{since} ago: #{string_to_date(since).ago(Time.now)}" end ``` [edit] To answer your question, you might try it like that: ``` :conditions => ['Date)event_date) >= ?', (string_to_date(since).ago(Time.now))] ```
40,590
<p>Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. </p> <p>For example, in Prototype this works:</p> <pre><code>$$('li')[5].addClassName('active'); </code></pre> <p>But this will not work no matter how I try to cast the variable as a number or integer:</p> <pre><code>$$('li')[currentPage].addClassName('active'); </code></pre> <p>In jQuery I get similar weirdness. This will work:</p> <pre><code>jQuery('li').eq(5).addClass("active"); </code></pre> <p>But this will not work again even though the value of currentPage is 5 and its type is number:</p> <pre><code>jQuery('li').eq(currentPage).addClass("active"); </code></pre> <p>I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.</p>
[ { "answer_id": 40599, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>Are you certain that <code>currentPage</code> is an integer? Try something like:</p>\n\n<pre><code>var currentPage =...
2008/09/02
[ "https://Stackoverflow.com/questions/40590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4320/" ]
Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. For example, in Prototype this works: ``` $$('li')[5].addClassName('active'); ``` But this will not work no matter how I try to cast the variable as a number or integer: ``` $$('li')[currentPage].addClassName('active'); ``` In jQuery I get similar weirdness. This will work: ``` jQuery('li').eq(5).addClass("active"); ``` But this will not work again even though the value of currentPage is 5 and its type is number: ``` jQuery('li').eq(currentPage).addClass("active"); ``` I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.
It looks like I just needed to be more specific in my element selector although it is weird that a hard coded number would work. ``` jQuery('#pagination-digg li').eq(currentPage).addClass("active"); ```
40,637
<p>I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this?</p> <p><strong>Update:</strong> I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.</p>
[ { "answer_id": 40674, "author": "1729", "author_id": 4319, "author_profile": "https://Stackoverflow.com/users/4319", "pm_score": 2, "selected": false, "text": "<p>You can edit the default template for excel - </p>\n\n<p>There is a file called <code>Book.xlt</code> in the <code>XLSTART</c...
2008/09/02
[ "https://Stackoverflow.com/questions/40637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I'm building an excel template (\*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this? **Update:** I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.
You could use the worksheet function =TODAY(), but obviously this would be updated to the current date whenever the workbook is recalculated. The only other method I can think of is, as 1729 said, to code the Workbook\_Open event: ``` Private Sub Workbook_Open() ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Date End Sub ``` You can reduce the problem of needing the user to accept macros each time by digitaly signing the template (in VBA IDE Tools | Digital Signature...) and select a digital certificate, however, you will need to get a certificate from a commercial certification authority (see <http://msdn.microsoft.com/en-us/library/ms995347.aspx>). The user will need to select to always trust this certificate the first time they run the template, but thereafter, they will not be prompted again.
40,651
<p>I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help?</p>
[ { "answer_id": 40659, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>I've always done it with a function like this:</p>\n\n<pre><code>public function keyExists(myCollection as collection, sKe...
2008/09/02
[ "https://Stackoverflow.com/questions/40651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4315/" ]
I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help?
@Mark Biek Your keyExists closely matches my standard Exists() function. To make the class more useful for COM-exposed collections and checking for numeric indexes, I'd recommend changing sKey and myCollection to not be typed. If the function is going to be used with a collection of objects, 'set' is required (on the line where val is set). **EDIT**: It was bugging me that I've never noticed different requirements for an object-based and value-based Exists() function. I very rarely use collections for non-objects, but this seemed such a perfect bottleneck for a bug that would be so hard to track down when I needed to check for existence. Because error handling will fail if an error handler is already active, two functions are required to get a new error scope. Only the Exists() function need ever be called: ``` Public Function Exists(col, index) As Boolean On Error GoTo ExistsTryNonObject Dim o As Object Set o = col(index) Exists = True Exit Function ExistsTryNonObject: Exists = ExistsNonObject(col, index) End Function Private Function ExistsNonObject(col, index) As Boolean On Error GoTo ExistsNonObjectErrorHandler Dim v As Variant v = col(index) ExistsNonObject = True Exit Function ExistsNonObjectErrorHandler: ExistsNonObject = False End Function ``` And to verify the functionality: ``` Public Sub TestExists() Dim c As New Collection Dim b As New Class1 c.Add "a string", "a" c.Add b, "b" Debug.Print "a", Exists(c, "a") ' True ' Debug.Print "b", Exists(c, "b") ' True ' Debug.Print "c", Exists(c, "c") ' False ' Debug.Print 1, Exists(c, 1) ' True ' Debug.Print 2, Exists(c, 2) ' True ' Debug.Print 3, Exists(c, 3) ' False ' End Sub ```
40,663
<p>I'm trying to find a way to validate a large XML file against an XSD. I saw the question <a href="https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file">...best way to validate an XML...</a> but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException.</p> <p>Are there any other tools,libraries, strategies for validating a larger than normal XML file?</p> <p>EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java.</p>
[ { "answer_id": 40678, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 6, "selected": true, "text": "<p>Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk...
2008/09/02
[ "https://Stackoverflow.com/questions/40663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3274/" ]
I'm trying to find a way to validate a large XML file against an XSD. I saw the question [...best way to validate an XML...](https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file) but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException. Are there any other tools,libraries, strategies for validating a larger than normal XML file? EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java.
Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory. ``` SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new SimpleErrorHandler()); reader.parse(new InputSource(new FileReader ("document.xml"))); ```
40,665
<p>I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what *= does? I assume that it is some sort of a join.</p> <pre><code>select * from a, b where a.id *= b.id</code></pre> <p>I can't figure out how this is different from:</p> <pre><code>select * from a, b where a.id = b.id</code></pre>
[ { "answer_id": 40671, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>It means outer join, a simple = means inner join.</p>\n\n<pre><code>*= is LEFT JOIN and =* is RIGHT JOIN.\n</code><...
2008/09/02
[ "https://Stackoverflow.com/questions/40665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
I'm maintaining some code that uses a \*= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what \*= does? I assume that it is some sort of a join. ``` select * from a, b where a.id *= b.id ``` I can't figure out how this is different from: ``` select * from a, b where a.id = b.id ```
From <http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm>: Inner and outer tables The terms outer table and inner table describe the placement of the tables in an outer join: * In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively. * In a right join, the outer table and inner table are the right and left tables respectively. For example, in the queries below, T1 is the outer table and T2 is the inner table: * T1 left join T2 * T2 right join T1 Or, using Transact-SQL syntax: * T1 \*= T2 * T2 =\* T1
40,692
<p>Is it possible to create a REST web service using ASP.NET 2.0? The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET.</p> <p>If it is possible to create REST web services in ASP.NET 2.0 can you provide an example.</p> <p>Thanks!</p>
[ { "answer_id": 40701, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I'm only just beginning to use them, but from what I've seen 2.0 pretty assumes SOAP.</p>\n" }, { "answer_id...
2008/09/02
[ "https://Stackoverflow.com/questions/40692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3498/" ]
Is it possible to create a REST web service using ASP.NET 2.0? The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET. If it is possible to create REST web services in ASP.NET 2.0 can you provide an example. Thanks!
I have actually created a REST web service with asp.net 2.0. Its really no different than creating a web page. When I did it, I really didn't have much time to research how to do it with an asmx file so I did it in a standard aspx file. I know thier is extra overhead by doing it this way but as a first revision it was fine. ``` protected void PageLoad(object sender, EventArgs e) { using (XmlWriter xm = XmlWriter.Create(Response.OutputStream, GetXmlSettings())) { //do your stuff xm.Flush(); } } /// <summary> /// Create Xml Settings object to properly format the output of the xml doc. /// </summary> private static XmlWriterSettings GetXmlSettings() { XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.Indent = true; xmlSettings.IndentChars = " "; return xmlSettings; } ``` That should be enough to get you started, I will try and post more later. Also if you need basic authentication for your web service it can be done, but it needs to be done manually if you aren't using active directory.
40,705
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)" rel="noreferrer">shebang</a> line:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p> <pre><code>if sys.version_info &lt; (2, 4): raise ImportError("Cannot run with Python version &lt; 2.4") </code></pre> <p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p> <pre><code>#!/usr/bin/env python2.4 </code></pre> <p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p> <p>What's the elegant solution?</p> <p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
[ { "answer_id": 40715, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>\"env\" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory fo...
2008/09/02
[ "https://Stackoverflow.com/questions/40705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
At the beginning of all my executable Python scripts I put the [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) line: ``` #!/usr/bin/env python ``` I'm running these scripts on a system where `env python` yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version: ``` if sys.version_info < (2, 4): raise ImportError("Cannot run with Python version < 2.4") ``` I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of `env python` and I don't want to force a particular version, as in: ``` #!/usr/bin/env python2.4 ``` I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4. What's the elegant solution? [Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in `~/bin` and ensuring your PATH has `~/bin` before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?
"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.
40,730
<p>How do you give a C# auto-property an initial value?</p> <p>I either use the constructor, or revert to the old syntax. </p> <p><strong> Using the Constructor:</strong></p> <pre><code>class Person { public Person() { Name = "Initial Name"; } public string Name { get; set; } } </code></pre> <p><strong>Using normal property syntax</strong> (with an initial value)</p> <pre><code>private string name = "Initial Name"; public string Name { get { return name; } set { name = value; } } </code></pre> <p>Is there a better way?</p>
[ { "answer_id": 40734, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": false, "text": "<p>Have you tried using the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx\...
2008/09/02
[ "https://Stackoverflow.com/questions/40730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946/" ]
How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. **Using the Constructor:** ``` class Person { public Person() { Name = "Initial Name"; } public string Name { get; set; } } ``` **Using normal property syntax** (with an initial value) ``` private string name = "Initial Name"; public string Name { get { return name; } set { name = value; } } ``` Is there a better way?
In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor. Since [C# 6.0](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-60), you can specify initial value in-line. The syntax is: ``` public int X { get; set; } = x; // C# 6 or higher ``` [`DefaultValueAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute?view=netframework-4.8) is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value). At compile time `DefaultValueAttribute` will not impact the generated IL and it will not be read to initialize the property to that value (see [DefaultValue attribute is not working with my Auto Property](https://stackoverflow.com/questions/1980520/defaultvalue-attribute-is-not-working-with-my-auto-property)). Example of attributes that impact the IL are [`ThreadStaticAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.threadstaticattribute?view=netframework-4.8), [`CallerMemberNameAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=netframework-4.8), ...
40,737
<p><a href="https://stackoverflow.com/questions/32230/tracking-down-where-disk-space-has-gone-on-linux">In this question</a> someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...</p>
[ { "answer_id": 40862, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 1, "selected": false, "text": "<p>I guess there are a couple of options:</p>\n\n<ol>\n<li><p>For a pure CLI solution, use something like gnuplot. See <a hre...
2008/09/02
[ "https://Stackoverflow.com/questions/40737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4162/" ]
[In this question](https://stackoverflow.com/questions/32230/tracking-down-where-disk-space-has-gone-on-linux) someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...
I would recommend [munin](http://munin.projects.linpro.no/). It is designed for exactly this sort of thing - graphing CPU usage, memory usage, disc-usage and such. sort of like MRTG (but MRTG is primarily aimed at graphing router's traffic, graphing anything but bandwidth with it is very hackish) Writing Munin plugins is very easy (it was one of the projects goals). They can be written in almost anything (shell script, perl/python/ruby/etc, C, anything that can be execute and produce an output). The plugin output format is basically `disc1usage.value 1234`. And debugging the plugins is very easy (compared to MRTG) I've set it up on my laptop to monitor disc-usage, bandwidth usage (by pulling data from my ISP's control panel, it graphs my two download "bins", uploads and newsgroup usage), load average and number of processes. Once I got it installed (currently slightly difficult on OS X, but it's trivial on Linux/FreeBSD), I had written a plugin in a few minutes, and it worked, first time! I would describe how it's setup, but the munin site will do that far better than I could! There's an example installation [here](http://munin.ping.uio.no/) Some alternatives are nagios and cacti. You could also write something similar using rrdtool. Munin, MRTG and Cacti are basically all far-nicer-to-use systems based around this graphing tool. If you want something really, really simple, you could do.. ``` import os import time while True: disc_usage = os.system("df -h / | awk '{print $3}'") log = open("mylog.txt") log.write(disc_usage + "\n") log.close() time.sleep(60*5) ``` Then.. ``` f = open("mylog.txt") lines = f.readlines() # Convert each line to a float number lines = [float(cur_line) for cur_line in lines] # Get the biggest and smallest biggest = max(lines) smallest = min(lines) for cur_line in lines: base = (cur_line - smallest) + 1 # make lowest value 1 normalised = base / (biggest - smallest) # normalise value between 0 and 1 line_length = int(round(normalised * 28)) # make a graph between 0 and 28 characters wide print "#" * line_length ``` That'll make a simple ascii graph of the disc usage. I *really really* don't recommend you use something like this. Why? The log file will get bigger, and bigger, and bigger. The graph will get progressively slower to graph. RRDTool uses a rolling-database system to store it's data, so the file will never get bigger than about 50-100KB, and it's consistently quick to graph as the file is a fixed length. In short. If you want something to easily graph almost anything, use [munin](http://munin.projects.linpro.no/). If you want something smaller and self-contained, write something with RRDTool.
40,787
<p>I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile.</p> <p>How would I go about doing this using the regular Windows command line?</p> <p>I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.</p>
[ { "answer_id": 40826, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>It would be an new shell (but I think it is worth it), but from PowerShell it would be </p>\n\n<pre><code>[int](ge...
2008/09/02
[ "https://Stackoverflow.com/questions/40787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914/" ]
I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile. How would I go about doing this using the regular Windows command line? I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.
You can try a plain old batchfile. ``` @echo off for /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1 echo %temp_counter% > counter.txt ``` assuming the count.bat and counter.txt are located in the same directory.
40,814
<p>I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program.</p> <p>These statements need to be separated by <code>GO</code> statements, but <code>SqlCommand.ExecuteNonQuery()</code> does not like <code>GO</code> statements. My solution, which I suppose I'll post for reference, was to split the SQL string on <code>GO</code> lines, and execute each batch separately.</p> <p>Is there an easier/better way?</p>
[ { "answer_id": 40824, "author": "ila", "author_id": 1178, "author_profile": "https://Stackoverflow.com/users/1178", "pm_score": 2, "selected": false, "text": "<p>I also faced the same problem, and I could not find any other way but splitting the single SQL operation in separate files, th...
2008/09/02
[ "https://Stackoverflow.com/questions/40814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program. These statements need to be separated by `GO` statements, but `SqlCommand.ExecuteNonQuery()` does not like `GO` statements. My solution, which I suppose I'll post for reference, was to split the SQL string on `GO` lines, and execute each batch separately. Is there an easier/better way?
Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: [http://weblogs.asp.net/jongalloway/Handling-\_2200\_GO\_2200\_-Separators-in-SQL-Scripts-*2D00*-the-easy-way](http://weblogs.asp.net/jgalloway/archive/2006/11/07/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-_2D00_-the-easy-way.aspx) Sample code: ``` public static void Main() { string scriptDirectory = "c:\\temp\\sqltest\\"; string sqlConnectionString = "Integrated Security=SSPI;" + "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; DirectoryInfo di = new DirectoryInfo(scriptDirectory); FileInfo[] rgFiles = di.GetFiles("*.sql"); foreach (FileInfo fi in rgFiles) { FileInfo fileInfo = new FileInfo(fi.FullName); string script = fileInfo.OpenText().ReadToEnd(); using (SqlConnection connection = new SqlConnection(sqlConnectionString)) { Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.ExecuteNonQuery(script); } } } ``` If that won't work for you, see Phil Haack's library which handles that: <http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx>
40,816
<p>If I have an HTML helper like so:</p> <pre><code>Name:&lt;br /&gt; &lt;%=Html.TextBox("txtName",20) %&gt;&lt;br /&gt; </code></pre> <p>How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?</p>
[ { "answer_id": 40846, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 6, "selected": true, "text": "<p>You can pass it into the TextBox call as a parameter.</p>\n\n<pre><code>Name:&lt;br/&gt; \n&lt;%= Html.TextBox(\"txtN...
2008/09/02
[ "https://Stackoverflow.com/questions/40816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
If I have an HTML helper like so: ``` Name:<br /> <%=Html.TextBox("txtName",20) %><br /> ``` How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?
You can pass it into the TextBox call as a parameter. ``` Name:<br/> <%= Html.TextBox("txtName", "20", new { @class = "hello" }) %> ``` This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the @ character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.
40,840
<p>I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is:</p> <pre><code> using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); } </code></pre> <p>Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.</p>
[ { "answer_id": 40864, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 1, "selected": false, "text": "<p>What OS is this? Is it on a 64-bit system? What is the nature of the failure: silent or is an exception thrown?</p>\n\...
2008/09/02
[ "https://Stackoverflow.com/questions/40840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is: ``` using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); } ``` Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.
Is there any reason that you have to do it through the registry? If not, you can use Environment.SetEnvironmentVariable() since .NET 2.0. It allows you to set on a machine, process or user basis.
40,853
<p>I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota.</p> <pre><code>DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); </code></pre> <p>No matter what approach I tried (like <code>SecureString</code>), I am easily able to see the password (<strong>m_pwd</strong>) either using Reflector or using strings tab of Process Explorer for the executable.</p> <p>I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account.</p> <p>Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers?</p> <p>Hashing is not possible since I need to know the exact password (not just the hash for matching purpose). Encryption/Decryption mechanisms are not working since they are machine dependent.</p>
[ { "answer_id": 40865, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>If you store it as a secure string and save the secure string to a file (possibly using <a href=\"http://msdn.micr...
2008/09/02
[ "https://Stackoverflow.com/questions/40853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337/" ]
I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota. ``` DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); ``` No matter what approach I tried (like `SecureString`), I am easily able to see the password (**m\_pwd**) either using Reflector or using strings tab of Process Explorer for the executable. I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account. Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers? Hashing is not possible since I need to know the exact password (not just the hash for matching purpose). Encryption/Decryption mechanisms are not working since they are machine dependent.
The sanctified method is to use CryptoAPI and the Data Protection APIs. To encrypt, use something like this (C++): ``` DATA_BLOB blobIn, blobOut; blobIn.pbData=(BYTE*)data; blobIn.cbData=wcslen(data)*sizeof(WCHAR); CryptProtectData(&blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &blobOut); _encrypted=blobOut.pbData; _length=blobOut.cbData; ``` Decryption is the opposite: ``` DATA_BLOB blobIn, blobOut; blobIn.pbData=const_cast<BYTE*>(data); blobIn.cbData=length; CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut); std::wstring _decrypted; _decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR)); ``` If you don't specify CRYPTPROTECT\_LOCAL\_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL\_MACHINE, then anyone with access to the machine can get it.
40,873
<p>I have a table which is full of arbitrarily formatted phone numbers, like this</p> <pre><code>027 123 5644 021 393-5593 (07) 123 456 042123456 </code></pre> <p>I need to search for a phone number in a similarly arbitrary format ( e.g. <code>07123456</code> should find the entry <code>(07) 123 456</code></p> <p>The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby)</p> <pre><code>digits_only = lambda{ |n| n.gsub /[^\d]/, '' } needle = digits_only[input_phone_number] haystack.map(&amp;digits_only).include?(needle) </code></pre> <p>The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want.</p> <p>Currently I can think of 2 'solutions'</p> <ul> <li>Hack together a franken-query of <code>CONCAT</code> and <code>SUBSTR</code></li> <li>Insert a <code>%</code> between every character of the needle ( so it's like this: <code>%0%7%1%2%3%4%5%6%</code> )</li> </ul> <p>However, neither of these seem like particularly elegant solutions.<br /> Hopefully someone can help or I might be forced to use the %%%%%% solution</p> <h3>Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over.</h3> <p>If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback!</p> <hr /> <blockquote> <p>could you use a &quot;replace&quot; function to strip out any instances of &quot;(&quot;, &quot;-&quot; and &quot; &quot;,</p> </blockquote> <p>I'm not concerned about the result being numeric. The main characters I need to consider are <code>+</code>, <code>-</code>, <code>(</code>, <code>)</code> and <code>space</code> So would that solution look like this?</p> <pre><code>SELECT * FROM people WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+') LIKE '123456' </code></pre> <p>Wouldn't that be terribly slow?</p>
[ { "answer_id": 40880, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>An out-of-the-box idea, but could you use a \"replace\" function to strip out any instances of \"(\", \"-\" and \" \",...
2008/09/02
[ "https://Stackoverflow.com/questions/40873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
I have a table which is full of arbitrarily formatted phone numbers, like this ``` 027 123 5644 021 393-5593 (07) 123 456 042123456 ``` I need to search for a phone number in a similarly arbitrary format ( e.g. `07123456` should find the entry `(07) 123 456` The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby) ``` digits_only = lambda{ |n| n.gsub /[^\d]/, '' } needle = digits_only[input_phone_number] haystack.map(&digits_only).include?(needle) ``` The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want. Currently I can think of 2 'solutions' * Hack together a franken-query of `CONCAT` and `SUBSTR` * Insert a `%` between every character of the needle ( so it's like this: `%0%7%1%2%3%4%5%6%` ) However, neither of these seem like particularly elegant solutions. Hopefully someone can help or I might be forced to use the %%%%%% solution ### Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over. If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback! --- > > could you use a "replace" function to strip out any instances of "(", "-" and " ", > > > I'm not concerned about the result being numeric. The main characters I need to consider are `+`, `-`, `(`, `)` and `space` So would that solution look like this? ``` SELECT * FROM people WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+') LIKE '123456' ``` Wouldn't that be terribly slow?
This looks like a problem from the start. Any kind of searching you do will require a table scan and we all know that's bad. How about adding a column with a hash of the current phone numbers after stripping out all formatting characters. Then you can at least index the hash values and avoid a full blown table scan. Or is the amount of data small and not expected to grow much? Then maybe just sucking all the numbers into the client and running a search there.
40,912
<p>I'm looking for a way to check within <code>pageLoad()</code> if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time.</p> <p>This is similar to <code>Page.IsPostback</code> property within code behind page.</p> <p>TIA, Ricky</p>
[ { "answer_id": 40924, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 2, "selected": false, "text": "<p>You could have a hidden input that you set to a known value on the server side if it's a postback/callback - and your jav...
2008/09/02
[ "https://Stackoverflow.com/questions/40912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4191/" ]
I'm looking for a way to check within `pageLoad()` if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time. This is similar to `Page.IsPostback` property within code behind page. TIA, Ricky
One way you could do that is to wire up an Application.Load handler in Application.Init, then have that handler unbind itself after running: ``` Sys.Application.add_init(AppInit); function AppInit() { Sys.Application.add_load(RunOnce); } function RunOnce() { // This will only happen once per GET request to the page. Sys.Application.remove_load(RunOnce); } ``` That will execute after Application.Init. It should be the last thing before pageLoad is called.
40,913
<p>I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: </p> <pre><code>&lt;DataTable&gt; &lt;Row&gt; &lt;text&gt;foo&lt;/text&gt; &lt;/Row&gt; &lt;Row&gt; &lt;text&gt;bar&lt;/text&gt; &lt;/Row&gt; &lt;/DataTable&gt; </code></pre> <p>When the webservice result event is fired I do something like this:</p> <pre><code>for(var i:int=0;i&amp;lt;event.result.DataTable.Row.length;i++) { if(event.result.DataTable.Row[i].text == "foo") mx.controls.Alert.show('foo found!'); } </code></pre> <p>This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the <em>event.DataTable.Row</em> object is not an error and the code subsequently breaks. </p> <p>What is the proper way to loop through the <em>HTTPService</em> result object? Do I need to convert it to some type of <em>XMLList</em> collection or an <em>ArrayCollection</em>? I have tried setting the resultFormat to <em>e4x</em> and that has yet to fix the problem...</p> <p>Thanks.</p>
[ { "answer_id": 40930, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "<p>Row isn't an array unless there are multiple Row elements. It is annoying. You have to do something like this, but I haven'...
2008/09/02
[ "https://Stackoverflow.com/questions/40913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: ``` <DataTable> <Row> <text>foo</text> </Row> <Row> <text>bar</text> </Row> </DataTable> ``` When the webservice result event is fired I do something like this: ``` for(var i:int=0;i&lt;event.result.DataTable.Row.length;i++) { if(event.result.DataTable.Row[i].text == "foo") mx.controls.Alert.show('foo found!'); } ``` This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the *event.DataTable.Row* object is not an error and the code subsequently breaks. What is the proper way to loop through the *HTTPService* result object? Do I need to convert it to some type of *XMLList* collection or an *ArrayCollection*? I have tried setting the resultFormat to *e4x* and that has yet to fix the problem... Thanks.
The problem lies in this statement ``` event.result.DataTable.Row.length ``` `length` is not a property of `XMLList`, but a method: ``` event.result.DataTable.Row.length() ``` it's confusing, but that's the way it is. *Addition:* actually, the safest thing to do is to always use a `for each` loop when iterating over `XMLList`s, that way you never make the mistake, it's less code, and easier to read: ``` for each ( var node : XML in event.result.DataTable.Row ) ```
40,943
<p>What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?</p> <p>I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?</p>
[ { "answer_id": 40945, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 5, "selected": false, "text": "<p>Here is an example of sending back a pdf.</p>\n\n<pre><code>header('Content-type: application/pdf');\nheader('Content-Dispositi...
2008/09/03
[ "https://Stackoverflow.com/questions/40943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited? I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?
Send the following headers before outputting the file: ``` header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); header("Content-Type: application/octet-stream"); header("Content-Length: " . filesize($File)); header("Connection: close"); ``` [@grom](https://stackoverflow.com/users/486/grom): Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)
40,966
<p>I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).</p> <p>Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?</p> <p>For example:</p> <pre><code>function updateDOM(id) { // updates the id element based on form state } </code></pre> <p>should I invoke it via:</p> <pre><code>window.onload = function() { updateDOM("myElement"); }; </code></pre> <p>or:</p> <pre><code>&lt;div id="myElement"&gt;...&lt;/div&gt; &lt;script language="javascript"&gt; updateDOM("myElement"); &lt;/script&gt; </code></pre> <p>The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.</p> <p>Any thoughts? Is one version really better than the other?</p>
[ { "answer_id": 40972, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "<p>Definitely use <code>onload</code>. Keep your scripts separate from your page, or you'll go mad trying to disentangle...
2008/09/03
[ "https://Stackoverflow.com/questions/40966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state). Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better? For example: ``` function updateDOM(id) { // updates the id element based on form state } ``` should I invoke it via: ``` window.onload = function() { updateDOM("myElement"); }; ``` or: ``` <div id="myElement">...</div> <script language="javascript"> updateDOM("myElement"); </script> ``` The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it. Any thoughts? Is one version really better than the other?
Definitely use `onload`. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
40,999
<p>Here's a quick question I've been banging my head against today.</p> <p>I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. </p> <p>Here's the current solution:</p> <pre><code> string transformXML = @"pathToXslDocument"; XmlDocument originalXml = new XmlDocument(); XmlDocument transformedXml = new XmlDocument(); XslCompiledTransform transformer = new XslCompiledTransform(); DataSet ds = new DataSet(); string filepath; originalXml.LoadXml(ds.GetXml()); //data loaded prior StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); transformer.Load(transformXML); transformer.Transform(originalXml, writer); //no need to select the node transformedXml.LoadXml(sb.ToString()); transformedXml.Save(filepath); writer.Close(); </code></pre> <p>Here's the original code:</p> <pre><code>BufferedStream stream = new BufferedStream(new MemoryStream()); DataSet ds = new DataSet(); da.Fill(ds); ds.WriteXml(stream); StreamReader sr = new StreamReader(stream, true); stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset. XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(@"&lt;path to xsl file&gt;"); transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null) </code></pre> <p>For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader.</p> <p>My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML?</p> <p>Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.</p>
[ { "answer_id": 41012, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "<p>I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning...
2008/09/03
[ "https://Stackoverflow.com/questions/40999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2916/" ]
Here's a quick question I've been banging my head against today. I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. Here's the current solution: ``` string transformXML = @"pathToXslDocument"; XmlDocument originalXml = new XmlDocument(); XmlDocument transformedXml = new XmlDocument(); XslCompiledTransform transformer = new XslCompiledTransform(); DataSet ds = new DataSet(); string filepath; originalXml.LoadXml(ds.GetXml()); //data loaded prior StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); transformer.Load(transformXML); transformer.Transform(originalXml, writer); //no need to select the node transformedXml.LoadXml(sb.ToString()); transformedXml.Save(filepath); writer.Close(); ``` Here's the original code: ``` BufferedStream stream = new BufferedStream(new MemoryStream()); DataSet ds = new DataSet(); da.Fill(ds); ds.WriteXml(stream); StreamReader sr = new StreamReader(stream, true); stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset. XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(@"<path to xsl file>"); transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null) ``` For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader. My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML? Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.
I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\flush stream after you wrote some data to it. **EDIT**: Just tried following code and it worked perfectly: ``` BufferedStream stream = new BufferedStream(new MemoryStream()); stream.Write(Encoding.ASCII.GetBytes("<xml>foo</xml>"), 0, "<xml>foo</xml>".Length); stream.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(stream); XmlReader reader = XmlReader.Create(sr); while (reader.Read()) { Console.WriteLine(reader.Value); } stream.Close(); ```
41,045
<p>As a general rule, I prefer using value rather than pointer semantics in C++ (ie using <code>vector&lt;Class&gt;</code> instead of <code>vector&lt;Class*&gt;</code>). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.</p> <p>Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Parent { public: Parent() : parent_mem(1) {} virtual void write() { cout &lt;&lt; "Parent: " &lt;&lt; parent_mem &lt;&lt; endl; } int parent_mem; }; class Child : public Parent { public: Child() : child_mem(2) { parent_mem = 2; } void write() { cout &lt;&lt; "Child: " &lt;&lt; parent_mem &lt;&lt; ", " &lt;&lt; child_mem &lt;&lt; endl; } int child_mem; }; int main(int, char**) { // I can have a polymorphic container with pointer semantics vector&lt;Parent*&gt; pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]-&gt;write(); pointerVec[1]-&gt;write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector&lt;Parent&gt; valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object :( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2 } </code></pre> <p>My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?</p>
[ { "answer_id": 41059, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "<p>Since the objects of different classes will have different sizes, you would end up running into the slicing proble...
2008/09/03
[ "https://Stackoverflow.com/questions/41045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2994/" ]
As a general rule, I prefer using value rather than pointer semantics in C++ (ie using `vector<Class>` instead of `vector<Class*>`). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects. Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below. ``` #include <iostream> using namespace std; class Parent { public: Parent() : parent_mem(1) {} virtual void write() { cout << "Parent: " << parent_mem << endl; } int parent_mem; }; class Child : public Parent { public: Child() : child_mem(2) { parent_mem = 2; } void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; } int child_mem; }; int main(int, char**) { // I can have a polymorphic container with pointer semantics vector<Parent*> pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]->write(); pointerVec[1]->write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector<Parent> valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object :( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2 } ``` My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?
Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values. One reasonable solution is to store container safe smart pointers. I normally use boost::shared\_ptr which is safe to store in a container. Note that std::auto\_ptr is not. ``` vector<shared_ptr<Parent>> vec; vec.push_back(shared_ptr<Parent>(new Child())); ``` shared\_ptr uses reference counting so it will not delete the underlying instance until all references are removed.
41,089
<p>I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this?</p> <p>I have:</p> <pre><code>Dim b As CommandButton Set b = ocx.GetButton("btnPrint") SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd </code></pre> <p>but it doesn't seem to work.</p>
[ { "answer_id": 41123, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "<p>If you have access to the OCX code, you could expose the associated event handler and invoke it directly.<br>\nDon't know if...
2008/09/03
[ "https://Stackoverflow.com/questions/41089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495/" ]
I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this? I have: ``` Dim b As CommandButton Set b = ocx.GetButton("btnPrint") SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd ``` but it doesn't seem to work.
I believe the following will work: ``` Dim b As CommandButton Set b = ocx.GetButton("btnPrint") b = True ``` `CommandButton`s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a `CheckBox`. The default property of the `CommandButton` is actually the `Value` property that indicates whether a button is toggled. By setting the property, the `Click` event is generated. This is done even if the button is not styled as a `ToggleButton` and therefore doesn't change its state.
41,097
<p>The question sort of says it all.</p> <p>Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. </p> <p>Bonus points for parsimonious and readable code samples. </p>
[ { "answer_id": 41123, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "<p>If you have access to the OCX code, you could expose the associated event handler and invoke it directly.<br>\nDon't know if...
2008/09/03
[ "https://Stackoverflow.com/questions/41097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4069/" ]
The question sort of says it all. Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. Bonus points for parsimonious and readable code samples.
I believe the following will work: ``` Dim b As CommandButton Set b = ocx.GetButton("btnPrint") b = True ``` `CommandButton`s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a `CheckBox`. The default property of the `CommandButton` is actually the `Value` property that indicates whether a button is toggled. By setting the property, the `Click` event is generated. This is done even if the button is not styled as a `ToggleButton` and therefore doesn't change its state.
41,107
<p>I've been looking for a <em>simple</em> Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over <code>500K+</code> generation (my needs don't really require anything much more sophisticated). </p> <p>Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like <code>"AEYGF7K0DM1X"</code>. </p>
[ { "answer_id": 41156, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 12, "selected": true, "text": "<h2>Algorithm</h2>\n<p>To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols...
2008/09/03
[ "https://Stackoverflow.com/questions/41107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3803/" ]
I've been looking for a *simple* Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over `500K+` generation (my needs don't really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like `"AEYGF7K0DM1X"`.
Algorithm --------- To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length. Implementation -------------- Here's some fairly simple and very flexible code for generating random identifiers. *Read the information that follows* for important application notes. ``` public class RandomString { /** * Generate a random string. */ public String nextString() { for (int idx = 0; idx < buf.length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); } public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String lower = upper.toLowerCase(Locale.ROOT); public static final String digits = "0123456789"; public static final String alphanum = upper + lower + digits; private final Random random; private final char[] symbols; private final char[] buf; public RandomString(int length, Random random, String symbols) { if (length < 1) throw new IllegalArgumentException(); if (symbols.length() < 2) throw new IllegalArgumentException(); this.random = Objects.requireNonNull(random); this.symbols = symbols.toCharArray(); this.buf = new char[length]; } /** * Create an alphanumeric string generator. */ public RandomString(int length, Random random) { this(length, random, alphanum); } /** * Create an alphanumeric strings from a secure generator. */ public RandomString(int length) { this(length, new SecureRandom()); } /** * Create session identifiers. */ public RandomString() { this(21); } } ``` Usage examples -------------- Create an insecure generator for 8-character identifiers: ``` RandomString gen = new RandomString(8, ThreadLocalRandom.current()); ``` Create a secure generator for session identifiers: ``` RandomString session = new RandomString(); ``` Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols: ``` String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx"; RandomString tickets = new RandomString(23, new SecureRandom(), easy); ``` Use as session identifiers -------------------------- Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used. There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand. The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible. Use as object identifiers ------------------------- Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big. Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission. Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." [The probability of a collision,](https://en.wikipedia.org/wiki/Birthday_problem#Square_approximation) *p*, is approximately n2/(2qx), where *n* is the number of identifiers actually generated, *q* is the number of distinct symbols in the alphabet, and *x* is the length of the identifiers. This should be a very small number, like 2‑50 or less. Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc. Comparison with UUIDs --------------------- According to their specification, [UUIDs](https://www.rfc-editor.org/rfc/rfc4122#section-6) are not designed to be unpredictable, and *should not* be used as session identifiers. UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters. UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.
41,155
<p>In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. </p> <p>I've got my interface set up with the ServiceContract and OperationContract:</p> <pre><code> [OperationContract] void FileUpload(UploadedFile file); </code></pre> <p>Along with the actual method:</p> <pre><code> public void FileUpload(UploadedFile file) {}; </code></pre> <p>To access the Service I enter <a href="http://localhost/project/myService.svc/FileUpload" rel="noreferrer">http://localhost/project/myService.svc/FileUpload</a> but I get the "Method not Allowed" error</p> <p>Am I missing something?</p>
[ { "answer_id": 41205, "author": "Jeremy McGee", "author_id": 3546, "author_profile": "https://Stackoverflow.com/users/3546", "pm_score": 2, "selected": false, "text": "<p>The basic intrinsic types (e.g. <code>byte</code>, <code>int</code>, <code>string</code>, and arrays) will be seriali...
2008/09/03
[ "https://Stackoverflow.com/questions/41155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831/" ]
In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. I've got my interface set up with the ServiceContract and OperationContract: ``` [OperationContract] void FileUpload(UploadedFile file); ``` Along with the actual method: ``` public void FileUpload(UploadedFile file) {}; ``` To access the Service I enter <http://localhost/project/myService.svc/FileUpload> but I get the "Method not Allowed" error Am I missing something?
Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract: ``` [ServiceContract] public interface IUploadService { [WebGet()] [OperationContract] string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser. [OperationContract] void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test. } ```
41,159
<p>Given the following:</p> <pre><code>List&lt;List&lt;Option&gt;&gt; optionLists; </code></pre> <p>what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.</p> <p>So we should end up with <code>List&lt;Option&gt;</code> where each item appears only once.</p>
[ { "answer_id": 41175, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "<p>Ok, this will find the list of Option objects that have a Value appearing in <em>every</em> list.</p>\n\n<pre><code>var...
2008/09/03
[ "https://Stackoverflow.com/questions/41159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3615/" ]
Given the following: ``` List<List<Option>> optionLists; ``` what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value. So we should end up with `List<Option>` where each item appears only once.
Ok, this will find the list of Option objects that have a Value appearing in *every* list. ``` var x = from list in optionLists from option in list where optionLists.All(l => l.Any(o => o.Value == option.Value)) orderby option.Value select option; ``` It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value.
41,185
<p>I'm doing a fair bit of work in Ruby recently, and using</p> <pre><code> ruby script/console </code></pre> <p>Is absolutely critical. However, I'm really disappointed with the default Windows console in Vista, especially in that there's a really annoying bug where moving the cursor back when at the bottom of the screen irregularly causes it to jump back. Anyone have a decent console app they use in Windows?</p>
[ { "answer_id": 41190, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx\" rel=\"nofollow norefer...
2008/09/03
[ "https://Stackoverflow.com/questions/41185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322/" ]
I'm doing a fair bit of work in Ruby recently, and using ``` ruby script/console ``` Is absolutely critical. However, I'm really disappointed with the default Windows console in Vista, especially in that there's a really annoying bug where moving the cursor back when at the bottom of the screen irregularly causes it to jump back. Anyone have a decent console app they use in Windows?
I use [Console2](http://sourceforge.net/projects/console/). I like the tabbed interface and that copy works properly if text breaks at the end of a line.
41,198
<p>How can I get an image to stretch the height of a <code>DIV</code> class?</p> <p>Currently it looks like this:</p> <p><img src="https://i.stack.imgur.com/DcrXC.png" width="650" /></p> <p>However, I would like the <code>DIV</code> to be stretched so the <code>image</code> fits properly, but I do not want to resize the `image.</p> <p>Here is the CSS for the <code>DIV</code> (the grey box):</p> <pre class="lang-css prettyprint-override"><code>.product1 { width: 100%; padding: 5px; margin: 0px 0px 15px -5px; background: #ADA19A; color: #000000; min-height: 100px; } </code></pre> <p>The CSS being applied on the image:</p> <pre class="lang-css prettyprint-override"><code>.product{ display: inline; float: left; } </code></pre> <p>So, how can I fix this?</p>
[ { "answer_id": 41201, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": "<pre><code>display:inline \nfloat:left \n</code></pre>\n\n<p>is your problem</p>\n\n<p>Floating makes the parents w...
2008/09/03
[ "https://Stackoverflow.com/questions/41198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
How can I get an image to stretch the height of a `DIV` class? Currently it looks like this: ![](https://i.stack.imgur.com/DcrXC.png) However, I would like the `DIV` to be stretched so the `image` fits properly, but I do not want to resize the `image. Here is the CSS for the `DIV` (the grey box): ```css .product1 { width: 100%; padding: 5px; margin: 0px 0px 15px -5px; background: #ADA19A; color: #000000; min-height: 100px; } ``` The CSS being applied on the image: ```css .product{ display: inline; float: left; } ``` So, how can I fix this?
Add `overflow:auto;` to `.product1`
41,204
<p>Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts_as_nested_set without using recursion?</p> <p>Here's the recursive solution for reference:</p> <pre><code>class Node &lt; ActiveRecord::Base has_many :products def json_hash if children.size &gt; 0 children.collect { |node| { node.name =&gt; node.json_hash }.to_json else { node.name =&gt; node.products.find(:all).collect(&amp;:name) }.to_json end end end </code></pre>
[ { "answer_id": 41275, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>There is a <a href=\"http://en.wikipedia.org/wiki/Tree_traversal\" rel=\"nofollow noreferrer\">wikipedia article</a> on t...
2008/09/03
[ "https://Stackoverflow.com/questions/41204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499/" ]
Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts\_as\_nested\_set without using recursion? Here's the recursive solution for reference: ``` class Node < ActiveRecord::Base has_many :products def json_hash if children.size > 0 children.collect { |node| { node.name => node.json_hash }.to_json else { node.name => node.products.find(:all).collect(&:name) }.to_json end end end ```
There is a [wikipedia article](http://en.wikipedia.org/wiki/Tree_traversal) on tree traversal which shows different alternatives to the recursive solution you are using. It may be tricky to use them in your specific case, but it should be possible. However, my question to you is, is there a specific reason you want to use iteration instead of recursion? I don't think any of the iterative solutions will be nearly as clean. Are your trees so big that you are running out of stack space (they would have to be pretty big)? Otherwise, I'm not so sure an iterative solution will really be faster. I see one potential for improvement though, if you are seeing performance issues... but I don't know rails, so I'm not sure if it is accurate: Does the find method return a new array? If so, you probably want to invoke .collect! instead of .collect, because if find creates an array, you are just creating an array and then throwing it away to the call to collect (which also creates an array), which surely is not going to be very efficient and may slow you down a lot if you have a big tree there. So ``` { node.name => node.products.find(:all).collect(&:name) }.to_json ``` might become ``` { node.name => node.products.find(:all).collect!(&:name) }.to_json ``` EDIT: Also, it may be more efficient to create your hash of hashes, and then convert the whole thing to json in 1 fell swoop, rather than converting it piecemail like you are doing. So ``` class Node < ActiveRecord::Base has_many :products def json_hash if children.size > 0 children.collect { |node| { node.name => node.json_hash }.to_json else { node.name => node.products.find(:all).collect!(&:name) }.to_json end end end ``` might become ``` class Node < ActiveRecord::Base has_many :products def json_hash to_hash.to_json end def to_hash if children.size > 0 children.collect { |node| { node.name => node.to_hash } else { node.name => node.products.find(:all).collect!(&:name) } end end end ``` Whether this works and is more efficient I leave as an exercise for you ;-)
41,218
<p>I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I <strong>could</strong> configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer.</p> <p>Thanks</p>
[ { "answer_id": 41272, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 2, "selected": false, "text": "<p>There doesn't seem to be an easier way, <a href=\"http://www.rocketwerx.com/blog/8-apple/34-getting-ssl-to-work-with-ma...
2008/09/03
[ "https://Stackoverflow.com/questions/41218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4247/" ]
I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I **could** configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer. Thanks
> > **NOTE: startssl is no longer supported after version 2+ of MAMP. You > have to update the config files (httpd.conf) to enable ssl.** > > > You can modify the free version of MAMP to enable ssl by default very easily. Once you have setup all the SSL parts of apache and have it working so that calling apachectl startssl works, just edit the file ``` /Applications/MAMP/startApache.sh ``` in your favorite text editor and change the **start** argument to **startssl** and you will have the MAMP launcher starting apache in ssl mode for you.
41,239
<p>I am pretty sure that the settings that I am using are correct, so all possible things can be wrong which I should check out so that I can make authentication with our Active Directory work.</p>
[ { "answer_id": 41247, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 1, "selected": false, "text": "<p>Try test if PHP can connect to active directory</p>\n\n<pre><code>&lt;?php\n$ds = ldap_connect('host.ad.lan', 389);\nldap_set_o...
2008/09/03
[ "https://Stackoverflow.com/questions/41239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ]
I am pretty sure that the settings that I am using are correct, so all possible things can be wrong which I should check out so that I can make authentication with our Active Directory work.
Try test if PHP can connect to active directory ``` <?php $ds = ldap_connect('host.ad.lan', 389); ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ds, LDAP_OPT_REFERRALS, 0); ldap_bind($ds, 'admin@ad.lan', 'xxx'); $sr = ldap_search($ds, 'CN=Cameron Zemek,OU=Users,OU=BRC,DC=ad,DC=lan', '(objectclass=*)', array('cn')); $entryID = ldap_first_entry($ds, $sr); $data = ldap_get_attributes($ds, $entryID); print_r($data); ldap_close($ds); ``` What do you have has your $config['ldap\_user'] and $config['ldap\_uid'] ? You want to set $config['ldap\_uid'] to sAMAccountName
41,244
<p>I found an example in the <a href="http://msdn2.microsoft.com/en-us/bb330936.aspx" rel="noreferrer">VS2008 Examples</a> for Dynamic LINQ that allows you to use a SQL-like string (e.g. <code>OrderBy(&quot;Name, Age DESC&quot;))</code> for ordering. Unfortunately, the method included only works on <code>IQueryable&lt;T&gt;</code>. Is there any way to get this functionality on <code>IEnumerable&lt;T&gt;</code>?</p>
[ { "answer_id": 41262, "author": "Kjetil Watnedal", "author_id": 4116, "author_profile": "https://Stackoverflow.com/users/4116", "pm_score": 6, "selected": false, "text": "<p>I guess it would work to use reflection to get whatever property you want to sort on:</p>\n\n<pre><code>IEnumerabl...
2008/09/03
[ "https://Stackoverflow.com/questions/41244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
I found an example in the [VS2008 Examples](http://msdn2.microsoft.com/en-us/bb330936.aspx) for Dynamic LINQ that allows you to use a SQL-like string (e.g. `OrderBy("Name, Age DESC"))` for ordering. Unfortunately, the method included only works on `IQueryable<T>`. Is there any way to get this functionality on `IEnumerable<T>`?
Just stumbled into this oldie... To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties. To get it working with `IEnumerable<T>` you could add some wrapper methods that go via `AsQueryable` - but the code below is the core `Expression` logic needed. ``` public static IOrderedQueryable<T> OrderBy<T>( this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedQueryable<T> OrderByDescending<T>( this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } public static IOrderedQueryable<T> ThenBy<T>( this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenBy"); } public static IOrderedQueryable<T> ThenByDescending<T>( this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenByDescending"); } static IOrderedQueryable<T> ApplyOrder<T>( IQueryable<T> source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach(string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] {source, lambda}); return (IOrderedQueryable<T>)result; } ``` --- Edit: it gets more fun if you want to mix that with `dynamic` - although note that `dynamic` only applies to LINQ-to-Objects (expression-trees for ORMs etc can't really represent `dynamic` queries - `MemberExpression` doesn't support it). But here's a way to do it with LINQ-to-Objects. Note that the choice of `Hashtable` is due to favorable locking semantics: ``` using Microsoft.CSharp.RuntimeBinder; using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Runtime.CompilerServices; static class Program { private static class AccessorCache { private static readonly Hashtable accessors = new Hashtable(); private static readonly Hashtable callSites = new Hashtable(); private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked( string name) { var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name]; if(callSite == null) { callSites[name] = callSite = CallSite<Func<CallSite, object, object>> .Create(Binder.GetMember( CSharpBinderFlags.None, name, typeof(AccessorCache), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.None, null) })); } return callSite; } internal static Func<dynamic,object> GetAccessor(string name) { Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name]; if (accessor == null) { lock (accessors ) { accessor = (Func<dynamic, object>)accessors[name]; if (accessor == null) { if(name.IndexOf('.') >= 0) { string[] props = name.Split('.'); CallSite<Func<CallSite, object, object>>[] arr = Array.ConvertAll(props, GetCallSiteLocked); accessor = target => { object val = (object)target; for (int i = 0; i < arr.Length; i++) { var cs = arr[i]; val = cs.Target(cs, val); } return val; }; } else { var callSite = GetCallSiteLocked(name); accessor = target => { return callSite.Target(callSite, (object)target); }; } accessors[name] = accessor; } } } return accessor; } } public static IOrderedEnumerable<dynamic> OrderBy( this IEnumerable<dynamic> source, string property) { return Enumerable.OrderBy<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } public static IOrderedEnumerable<dynamic> OrderByDescending( this IEnumerable<dynamic> source, string property) { return Enumerable.OrderByDescending<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } public static IOrderedEnumerable<dynamic> ThenBy( this IOrderedEnumerable<dynamic> source, string property) { return Enumerable.ThenBy<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } public static IOrderedEnumerable<dynamic> ThenByDescending( this IOrderedEnumerable<dynamic> source, string property) { return Enumerable.ThenByDescending<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } static void Main() { dynamic a = new ExpandoObject(), b = new ExpandoObject(), c = new ExpandoObject(); a.X = "abc"; b.X = "ghi"; c.X = "def"; dynamic[] data = new[] { new { Y = a }, new { Y = b }, new { Y = c } }; var ordered = data.OrderByDescending("Y.X").ToArray(); foreach (var obj in ordered) { Console.WriteLine(obj.Y.X); } } } ```
41,279
<p>I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish <em>would not</em> be suggested by SpotLight as potential search candidates. I'm not looking for <code>example.log</code>, I'm looking for <code>example.tex</code>!</p> <p>So can Spotlight be configured to ignore, say, all <code>.log</code> files?</p> <p>(I know, I know; I should just use QuickSilver instead…)</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41295">diciu</a> That's an interesting answer. The problem in my case is this:</p> <blockquote> <p>Figure out which importer handles your type of file</p> </blockquote> <p>I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux, .glo, .out, whatever) I think it's improbable that there's an importer that's <em>trying</em> to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.)</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41342">diciu</a> again: <code>TextImporterDontImportList</code> sounds very promising; I'll head off and see if anything comes of it.</p> <p>Like you say, it does seem like the whole UTI system doesn't really allow <em>not</em> searching for something.</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41377">Raynet</a> Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway <code>:)</code> )</p>
[ { "answer_id": 41283, "author": "D2VIANT", "author_id": 4365, "author_profile": "https://Stackoverflow.com/users/4365", "pm_score": 2, "selected": false, "text": "<p>Not sure how to do it on a file type level, but you can do it on a folder level:</p>\n\n<p>Source: <a href=\"http://lists....
2008/09/03
[ "https://Stackoverflow.com/questions/41279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish *would not* be suggested by SpotLight as potential search candidates. I'm not looking for `example.log`, I'm looking for `example.tex`! So can Spotlight be configured to ignore, say, all `.log` files? (I know, I know; I should just use QuickSilver instead…) --- @[diciu](https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41295) That's an interesting answer. The problem in my case is this: > > Figure out which importer handles your type of file > > > I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux, .glo, .out, whatever) I think it's improbable that there's an importer that's *trying* to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.) --- @[diciu](https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41342) again: `TextImporterDontImportList` sounds very promising; I'll head off and see if anything comes of it. Like you say, it does seem like the whole UTI system doesn't really allow *not* searching for something. --- @[Raynet](https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41377) Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway `:)` )
@Will - these things that define types are called [uniform type identifiers](http://developer.apple.com/macosx/uniformtypeidentifiers.html). The problem is they are a combination of extensions (like .txt) and generic types (i.e. public.plain-text matches a txt file without the txt extension based purely on content) so it's not as simple as looking for an extension. RichText.mdimporter is *probably* the importer that imports your text file. This should be easily verified by running mdimport in debug mode on one of the files you don't want indexed: ``` cristi:~ diciu$ echo "All work and no play makes Jack a dull boy" > ~/input.txt cristi:~ diciu$ mdimport -d 4 -n ~/input.txt 2>&1 | grep Imported kMD2008-09-03 12:05:06.342 mdimport[1230:10b] Imported '/Users/diciu/input.txt' of type 'public.plain-text' with plugIn /System/Library/Spotlight/RichText.mdimporter. ``` The type that matches in my example is public.plain-text. I've no idea how you actually write an extension-based exception for an UTI (like public.plain-text except anything ending in .log). Later edit: I've also looked though the RichText mdimporter binary and found a promising string but I can't figure out if it's actually being used (as a preference name or whatever): ``` cristi:FoodBrowser diciu$ strings /System/Library/Spotlight/RichText.mdimporter/Contents/MacOS/RichText |grep Text TextImporterDontImportList ```
41,290
<p>I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is <em>very</em> static, but just <em>might</em> change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt.</p> <p>I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file.</p> <p>This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released?</p> <p>Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part :)</p> <ul> <li><strong>Am I missing something?</strong></li> <li><strong>What is the best file access strategy in a multi-threaded environment?</strong> <hr></li> </ul> <h3>Edit</h3> <p>Sorry - I should have said this is using <strong>ASP.NET 2.0</strong> :)</p>
[ { "answer_id": 41312, "author": "Ubiguchi", "author_id": 2562, "author_profile": "https://Stackoverflow.com/users/2562", "pm_score": 1, "selected": false, "text": "<p>If you're locking on a object stored as a <em>static</em> then the lock should work for all threads in the same Applicati...
2008/09/03
[ "https://Stackoverflow.com/questions/41290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is *very* static, but just *might* change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt. I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file. This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released? Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part :) * **Am I missing something?** * **What is the best file access strategy in a multi-threaded environment?** --- ### Edit Sorry - I should have said this is using **ASP.NET 2.0** :)
Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time: ``` /// <summary> /// Blocks until the file is not locked any more. /// </summary> /// <param name="fullPath"></param> bool WaitForFile(string fullPath) { int numTries = 0; while (true) { ++numTries; try { // Attempt to open the file exclusively. using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100)) { fs.ReadByte(); // If we got this far the file is ready break; } } catch (Exception ex) { Log.LogWarning( "WaitForFile {0} failed to get an exclusive lock: {1}", fullPath, ex.ToString()); if (numTries > 10) { Log.LogWarning( "WaitForFile {0} giving up after 10 tries", fullPath); return false; } // Wait for the lock to be released System.Threading.Thread.Sleep(500); } } Log.LogTrace("WaitForFile {0} returning true after {1} tries", fullPath, numTries); return true; } ``` Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written.
41,304
<p>I know in ASP.NET I can get an item from a DropDownList by using</p> <pre><code>DropDownList1.Items.FindByText </code></pre> <p>Is there a similar method I can use in WPF for a ComboBox?</p> <p>Here's the scenario.</p> <p>I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.</p> <p>In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.</p> <hr> <p>Here's the scenario.</p> <p>I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.</p> <p>In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.</p> <p>Does this make sense?</p>
[ { "answer_id": 41305, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>In WPF you can use FindName method.</p>\n\n<p>XAML:</p>\n\n<pre><code> &lt;ComboBox Name=\"combo\"&gt;\n &lt;ComboBo...
2008/09/03
[ "https://Stackoverflow.com/questions/41304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
I know in ASP.NET I can get an item from a DropDownList by using ``` DropDownList1.Items.FindByText ``` Is there a similar method I can use in WPF for a ComboBox? Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. --- Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Does this make sense?
Can you use ItemContainerGenerator? ItemContainerGenerator contains a ContainerFromItem method that takes an object parameter. If you have a reference to the full object that your comboBox contains (or a way to reconstruct it), you can use the following: ``` ComboBoxItem item = (ComboBoxItem)myComboBox.ItemContainerGenerator.ContainerFromItem(myObject); ```
41,319
<p>What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type <code>IEnumerable&lt;T&gt;</code> and doesn't have a Count property.</p> <p>Right now I'm tossing up between this:</p> <pre><code>if (myList.Count() == 0) { ... } </code></pre> <p>and this:</p> <pre><code>if (!myList.Any()) { ... } </code></pre> <p>My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.</p> <p>That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?</p> <p><strong>Edit</strong> @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:</p> <pre><code>public static bool IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; list) { if (list is ICollection&lt;T&gt;) return ((ICollection&lt;T&gt;)list).Count == 0; return !list.Any(); } </code></pre>
[ { "answer_id": 41324, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 8, "selected": true, "text": "<p>You could do this:</p>\n\n<pre><code>public static Boolean IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n{\n ...
2008/09/03
[ "https://Stackoverflow.com/questions/41319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type `IEnumerable<T>` and doesn't have a Count property. Right now I'm tossing up between this: ``` if (myList.Count() == 0) { ... } ``` and this: ``` if (!myList.Any()) { ... } ``` My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count. That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list? **Edit** @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this: ``` public static bool IsEmpty<T>(this IEnumerable<T> list) { if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0; return !list.Any(); } ```
You could do this: ``` public static Boolean IsEmpty<T>(this IEnumerable<T> source) { if (source == null) return true; // or throw an exception return !source.Any(); } ``` **Edit**: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.
41,330
<p>How do I detect if the system has a default recording device installed? I bet this can be done through some calls to the Win32 API, anyone has any experience with this?</p> <p>I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.</p>
[ { "answer_id": 41346, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>There is an Open Source Audio API called <a href=\"http://www.portaudio.com/\" rel=\"nofollow noreferrer\">PortAudio</a> that...
2008/09/03
[ "https://Stackoverflow.com/questions/41330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509946/" ]
How do I detect if the system has a default recording device installed? I bet this can be done through some calls to the Win32 API, anyone has any experience with this? I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.
Using the [DirectX SDK](https://www.microsoft.com/en-in/download/details.aspx?id=6812), you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the "Address of the GUID that identifies the device being enumerated, or NULL for the primary device". If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs: ``` #include <tchar.h> #include <windows.h> #include "mmsystem.h" int _tmain( int argc, wchar_t *argv[] ) { UINT deviceCount = waveInGetNumDevs(); if ( deviceCount > 0 ) { for ( int i = 0; i < deviceCount; i++ ) { WAVEINCAPSW waveInCaps; waveInGetDevCapsW( i, &waveInCaps, sizeof( WAVEINCAPS ) ); // do some stuff with waveInCaps... } } return 0; } ```
41,397
<p>Right, I know I am totally going to look an idiot with this one, but my brain is just <em>not</em> kicking in to gear this morning.</p> <p>I want to have a method where I can say &quot;if it goes bad, come back with this type of Exception&quot;, right?</p> <p>For example, something like (<strong>and this doesn't work</strong>):</p> <pre><code> static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; } </code></pre> <p>Now whats confusing me is that we <em>KNOW</em> that the generic type is going to be of an Exception type due to the <em>where</em> clause. However, the code fails because we cannot implicitly cast <em>Exception</em> to <em>ExType</em>. We cannot explicitly convert it either, such as:</p> <pre><code> static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; } </code></pre> <p>As that fails too.. So <strong>is this kind of thing possible?</strong> I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P</p> <hr /> <h2>Update</h2> <p>Thanks for the responses guys, looks like it wasn't me being a <em>complete</em> idiot! ;)</p> <p>OK, so <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398">Vegard</a> and <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404">Sam</a> got me on to the point where I could instantiate the correct type, but then obviously got stuck because the <em>message</em> param is read-only following instantiation.</p> <p><a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408">Matt</a> hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code:</p> <pre><code> static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; } </code></pre> <p>Sweet! :)</p> <p>Thanks guys!</p>
[ { "answer_id": 41402, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>Have you tried, instead:</p>\n\n<pre><code>static T TestException&lt;Exception&gt;(string message)\n{}\n</code></pre>\n\n...
2008/09/03
[ "https://Stackoverflow.com/questions/41397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
Right, I know I am totally going to look an idiot with this one, but my brain is just *not* kicking in to gear this morning. I want to have a method where I can say "if it goes bad, come back with this type of Exception", right? For example, something like (**and this doesn't work**): ``` static ExType TestException<ExType>(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; } ``` Now whats confusing me is that we *KNOW* that the generic type is going to be of an Exception type due to the *where* clause. However, the code fails because we cannot implicitly cast *Exception* to *ExType*. We cannot explicitly convert it either, such as: ``` static ExType TestException<ExType>(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; } ``` As that fails too.. So **is this kind of thing possible?** I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P --- Update ------ Thanks for the responses guys, looks like it wasn't me being a *complete* idiot! ;) OK, so [Vegard](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398) and [Sam](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404) got me on to the point where I could instantiate the correct type, but then obviously got stuck because the *message* param is read-only following instantiation. [Matt](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408) hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code: ``` static ExType TestException<ExType>(string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; } ``` Sweet! :) Thanks guys!
You can almost do it like this: ``` static void TestException<E>(string message) where E : Exception, new() { var e = new E(); e.Message = message; throw e; } ``` However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor. I think you'd have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this: ``` static void TestException<E>(string message) where E : Exception { throw Activator.CreateInstance(typeof(E), message) as E; } ``` **Edit** Oops just realised you're wanting to *return* the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements.
41,400
<p>I am looking to do this in C/C++. I came across <a href="http://www.swig.org/Doc1.3/Varargs.html" rel="nofollow noreferrer"><strong>Variable Length Arguments</strong></a>, but this suggests a solution with Python and C using <a href="http://sourceware.org/libffi/" rel="nofollow noreferrer">libffi</a>.</p> <p>Now, if I want to wrap the <code>printf</code> function with <code>myprintf</code>.</p> <p>I do it like below:</p> <pre><code>void myprintf(char* fmt, ...) { va_list args; va_start(args, fmt); printf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf(&quot;This is a number: %d and \nthis is a character: %c and \n another number: %d\n&quot;, a, v, b); return 0; } </code></pre> <p>But the results are not as expected!</p> <pre class="lang-none prettyprint-override"><code>This is a number: 1244780 and this is a character: h and another number: 29953463 </code></pre> <p>What did I miss?</p>
[ { "answer_id": 41413, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "<p>How do you mean a pure C/C++ solution?</p>\n<p>The rest parameter (...) is supported cross platform in the C runtime.</p...
2008/09/03
[ "https://Stackoverflow.com/questions/41400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ]
I am looking to do this in C/C++. I came across [**Variable Length Arguments**](http://www.swig.org/Doc1.3/Varargs.html), but this suggests a solution with Python and C using [libffi](http://sourceware.org/libffi/). Now, if I want to wrap the `printf` function with `myprintf`. I do it like below: ``` void myprintf(char* fmt, ...) { va_list args; va_start(args, fmt); printf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0; } ``` But the results are not as expected! ```none This is a number: 1244780 and this is a character: h and another number: 29953463 ``` What did I miss?
The problem is that you cannot use 'printf' with *va\_args*. You must use **vprintf** if you are using variable argument lists. *vprint*, *vsprintf*, *vfprintf*, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.) You sample works as follows: ``` void myprintf(char* fmt, ...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0; } ```
41,407
<p>I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:</p> <pre><code>(?&lt;date&gt;\d{2}/\d{2}/\d{2})\s(?&lt;time&gt;\d{2}):\d{2}:\d{2}),\d{3})\s(?&lt;message&gt;.+) </code></pre> <p>The log format (which I use for testing the parser) is this:</p> <pre><code>07/23/08 14:17:31,321 log message spanning multiple lines 07/23/08 14:17:31,321 log message on one line </code></pre> <p>When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file).</p> <hr> <p>@samjudson:</p> <p><em>You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).</em></p> <p>I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either).</p> <p>The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on.</p> <hr> <p>I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message.</p> <pre><code>(?&lt;message&gt;(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+) </code></pre>
[ { "answer_id": 41412, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 0, "selected": false, "text": "<p>You need to pass the <code>RegexOptions</code>. Singleline flag in to the regular expression, so that \".\" matches all ...
2008/09/03
[ "https://Stackoverflow.com/questions/41407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909/" ]
I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this: ``` (?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}):\d{2}:\d{2}),\d{3})\s(?<message>.+) ``` The log format (which I use for testing the parser) is this: ``` 07/23/08 14:17:31,321 log message spanning multiple lines 07/23/08 14:17:31,321 log message on one line ``` When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file). --- @samjudson: *You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).* I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either). The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on. --- I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message. ``` (?<message>(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+) ```
This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group: ``` (?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}:\d{2}:\d{2},\d{3})\s(?<message>(.(?!^\d{2}/\d{2}/ \d{2}))+) ``` Note that this requires the use of the RegexOptions.MultiLine flag.
41,479
<p>After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?</p> <p>For example I rather lazily used var in questionable circumstances, e.g.:-</p> <pre><code>foreach(var item in someList) { // ... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear. </code></pre> <p>More legitimate uses of var are as follows:-</p> <pre><code>var l = new List&lt;string&gt;(); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be. </code></pre> <p>Interestingly LINQ seems to be a bit of a grey area, e.g.:-</p> <pre><code>var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. </code></pre> <p>It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.</p> <p>It's even worse when it comes to LINQ to objects, e.g.:-</p> <pre><code>var results = from item in someList where item != 3 select item; </code></pre> <p>This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.</p> <p>There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable&lt;int&gt; and IEnumerable&lt;double&gt; the caller might inadvertently pass in the wrong type.</p> <p><code>var</code> <em>does</em> maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.</p>
[ { "answer_id": 41486, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": false, "text": "<p>I think the use of var should be coupled with wisely-chosen variable names.</p>\n\n<p>I have no problem using var in a...
2008/09/03
[ "https://Stackoverflow.com/questions/41479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var? For example I rather lazily used var in questionable circumstances, e.g.:- ``` foreach(var item in someList) { // ... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear. ``` More legitimate uses of var are as follows:- ``` var l = new List<string>(); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be. ``` Interestingly LINQ seems to be a bit of a grey area, e.g.:- ``` var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. ``` It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is. It's even worse when it comes to LINQ to objects, e.g.:- ``` var results = from item in someList where item != 3 select item; ``` This is no better than the equivilent foreach(var item in someList) { // ... } equivilent. There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type. `var` *does* maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think `var` can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this: ``` var orders = cust.Orders; ``` I don't care if Customer.Orders is `IEnumerable<Order>`, `ObservableCollection<Order>` or `BindingList<Order>` - all I want is to keep that list in memory to iterate over it or get its count or something later on. Contrast the above declaration with: ``` ObservableCollection<Order> orders = cust.Orders; ``` To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from `ObservableCollection<Order>` to `IList<Order>`) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
41,492
<p>Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default!</p> <p><strong>/EDIT:</strong> Without having source to the object itself</p>
[ { "answer_id": 41612, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 1, "selected": false, "text": "<p>I don't use VB, but here it goes.</p>\n\n<p>I found <a href=\"http://msdn.microsoft.com/en-us/library/aa733705%28VS....
2008/09/03
[ "https://Stackoverflow.com/questions/41492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1111/" ]
Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default! **/EDIT:** Without having source to the object itself
Use OLE/Com Object Viewer, which is distributed with Microsoft Visual Studio. Go to type libraries and find the library the control is housed in, for example CommandButton is stored in ***Microsoft Forms 2.0 Object Library***. Right click the library and select view. Find the coclass representing the control and select it: ![alt text](https://i.imgur.com/BervR.png) As can be seen, the default interface for CommandButton is ICommandButton, when you inspect ICommandButton look for a property that has a dispid of 0. The IDL for the dispid 0 property of CommandButton is: ``` [id(00000000), propput, bindable, displaybind, hidden, helpcontext(0x001e8d04)] void Value([in] VARIANT_BOOL rhs); [id(00000000), propget, bindable, displaybind, hidden, helpcontext(0x001e8d04)] VARIANT_BOOL Value(); ``` Showing you the default property.
41,513
<p>I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation?</p>
[ { "answer_id": 41524, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 4, "selected": false, "text": "<p>I usually have</p>\n\n<pre>\nProject Directory\n src - actual source\n doc - documentation\n lib - libraries referenced...
2008/09/03
[ "https://Stackoverflow.com/questions/41513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation?
I usually have ``` Project Directory src - actual source doc - documentation lib - libraries referenced from source dep - installation files for dependencies that don't fit in lib db - database installation script ``` In work with Visual Studio, I'm not sure if this works the same in the java world. But i usually put stuff in different project folders in src. For each source project there's a separate test project. Build files go in the main project directory. I usually put a README there too documenting how to setup the project if it needs more than just checking out. EDIT: This is the structure for a single working checkout of the project. It will be duplicated for each branch/tag in your revision control system (remember, in most SVN system, copies are cheap). The above example under Subversion would look like: ``` /project /trunk /src /doc /... /branches /feature1 /src /doc /... /feature2 /src /doc /... ```
41,562
<p>I've had to do some introspection in python and it wasn't pretty:</p> <pre><code>name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) </code></pre> <p>To get something like</p> <pre><code>foo.py:22 bar() blah blah </code></pre> <p>In our debugging output.</p> <p>I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?</p>
[ { "answer_id": 41574, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": true, "text": "<p>A print statement does its IO through \"sys.stdout.write\" so you can override sys.stdout if you want to manipulate ...
2008/09/03
[ "https://Stackoverflow.com/questions/41562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4319/" ]
I've had to do some introspection in python and it wasn't pretty: ``` name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) ``` To get something like ``` foo.py:22 bar() blah blah ``` In our debugging output. I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?
A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.
41,568
<p>this kind of follows on from another <a href="https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app">question</a> of mine.</p> <p>Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to <strong>test</strong> it?</p> <p>I am thinking of creating a method which just spawns lots of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a>'s or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc.</p> <p>Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :)</p> <h3>Edit</h3> <p>Following <a href="https://stackoverflow.com/questions/41568/whats-the-best-way-to-test-a-method-from-multiple-threads#41572">ajmastrean's</a> post:</p> <p>I am using a console app to test with Debug.Asserts :)</p> <hr /> <h2>Update</h2> <p>I originally rolled with using <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a> to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this.</p> <p>I then followed up on <a href="https://stackoverflow.com/questions/41568/whats-the-best-way-to-unit-test-from-multiple-threads#41589">ajmastrean</a>'s post and realised I should really be using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread(VS.80).aspx" rel="noreferrer">Thread</a> class for working with concurrent operations. I will now refactor using this method (albeit a different approach).</p>
[ { "answer_id": 41578, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": -1, "selected": false, "text": "<p>Your idea should work fine. Basically you just want to spawn a bunch of threads, and make sure the ones writing the...
2008/09/03
[ "https://Stackoverflow.com/questions/41568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
this kind of follows on from another [question](https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app) of mine. Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to **test** it? I am thinking of creating a method which just spawns lots of [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)'s or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc. Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :) ### Edit Following [ajmastrean's](https://stackoverflow.com/questions/41568/whats-the-best-way-to-test-a-method-from-multiple-threads#41572) post: I am using a console app to test with Debug.Asserts :) --- Update ------ I originally rolled with using [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this. I then followed up on [ajmastrean](https://stackoverflow.com/questions/41568/whats-the-best-way-to-unit-test-from-multiple-threads#41589)'s post and realised I should really be using the [Thread](http://msdn.microsoft.com/en-us/library/system.threading.thread(VS.80).aspx) class for working with concurrent operations. I will now refactor using this method (albeit a different approach).
In .NET, `ThreadPool` threads won't return without setting up `ManualResetEvent`s or `AutoResetEvent`s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such. Something I have found that works is 1. Create an array of threads. 2. Setup the `ThreadStart` method of each thread. 3. Start each thread. 4. Join on all threads (blocks the current thread until all other threads complete or abort) ```cs public static void MultiThreadedTest() { Thread[] threads = new Thread[count]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(DoSomeWork()); } foreach(Thread thread in threads) { thread.Start(); } foreach(Thread thread in threads) { thread.Join(); } } ```
41,576
<p>I wonder what the best practice for this scenario is:</p> <p>I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.</p> <p>Two solutions:</p> <ol> <li><p>Change the <code>PageParserPath</code> in <em>web.config</em> as per <a href="http://blogs.msdn.com/kaevans/archive/2007/04/26/code-blocks-are-not-allowed-in-this-file-using-server-side-code-with-sharepoint.aspx" rel="nofollow noreferrer">this site</a> </p> <pre><code>&lt;PageParserPaths&gt; &lt;PageParserPath VirtualPath="/pages/test.aspx" CompilationMode="Always" AllowServerSideScript="true" /&gt; &lt;/PageParserPaths&gt; </code></pre></li> <li><p>Create all the controls and Wire them up to Events in the <em>.CS</em> File, thus completely eliminating some of the benefits of ASP.net</p></li> </ol> <p>I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the <em>web.config</em> is something I want to use sparingly whenever possible.</p>
[ { "answer_id": 42248, "author": "Daniel McPherson", "author_id": 897, "author_profile": "https://Stackoverflow.com/users/897", "pm_score": 1, "selected": false, "text": "<p>What does the ASPX page do? What functionality does it add? How are you adding the page into the site? By the looks...
2008/09/03
[ "https://Stackoverflow.com/questions/41576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I wonder what the best practice for this scenario is: I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default. Two solutions: 1. Change the `PageParserPath` in *web.config* as per [this site](http://blogs.msdn.com/kaevans/archive/2007/04/26/code-blocks-are-not-allowed-in-this-file-using-server-side-code-with-sharepoint.aspx) ``` <PageParserPaths> <PageParserPath VirtualPath="/pages/test.aspx" CompilationMode="Always" AllowServerSideScript="true" /> </PageParserPaths> ``` 2. Create all the controls and Wire them up to Events in the *.CS* File, thus completely eliminating some of the benefits of ASP.net I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the *web.config* is something I want to use sparingly whenever possible.
So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too. You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.
41,590
<p>I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.</p> <p>How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?</p>
[ { "answer_id": 41598, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 8, "selected": true, "text": "<p>Namespaces are packages essentially. They can be used like this:</p>\n\n<pre><code>namespace MyNamespace\n{\n class MyCl...
2008/09/03
[ "https://Stackoverflow.com/questions/41590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
Namespaces are packages essentially. They can be used like this: ``` namespace MyNamespace { class MyClass { }; } ``` Then in code: ``` MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); ``` Or, if you want to always use a specific namespace, you can do this: ``` using namespace MyNamespace; MyClass* pClass = new MyClass(); ``` **Edit:** Following what [bernhardrusch](https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624) has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed). And as you asked [below](https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615), you can use as many namespaces as you like.
41,594
<p>I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on <a href="http://www.plus2net.com/sql_tutorial/access_to_mysql.php" rel="nofollow noreferrer">this site</a> and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt.</p> <p>The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field.</p> <p>Has anyone had this issue before and how did they resolve it ?</p>
[ { "answer_id": 41617, "author": "DAC", "author_id": 1111, "author_profile": "https://Stackoverflow.com/users/1111", "pm_score": 1, "selected": false, "text": "<p>As far as I remember, the Microsoft \"<a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=D842F8B4-C914-4AC7-B2...
2008/09/03
[ "https://Stackoverflow.com/questions/41594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2720/" ]
I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on [this site](http://www.plus2net.com/sql_tutorial/access_to_mysql.php) and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt. The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field. Has anyone had this issue before and how did they resolve it ?
Ok so in the interests of airing my dirty code in public here what i came up with. Note : this is a hack designed to be used once and then thrown away. This Method takes in a datarowview containing 1 row of data from the access table. The Images are wrapped in OLE serialization, im not entirely familiar with how this works but its how Microsoft apps allow any object to be embedded into something else. (eg images into Excel Cells). I needed to remove the serialization junk around the image so i loaded the entire field as a Byte array and searched through it for 3 concurrent entries (FF D8 FF) which represent the beginning of the image data within the field. ``` Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap Dim oImage As Bitmap = New Bitmap("c:\default.jpg") Try If Not IsDBNull(row(columnName)) Then If row(columnName) IsNot Nothing Then Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte())) If mStream.Length > 0 Then Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1)) Dim position As Integer = 0 For index As Integer = 0 To b.Length - 3 If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then position = index Exit For End If Next If position > 0 Then Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position) oImage = New Bitmap(jpgStream) End If End If End If End If Catch ex As Exception Throw New ApplicationException(ex.Message, ex) End Try Return oImage End Function ``` Then its a matter of pulling out this data into a bitmap. So for each row in the access table i extract the bitmap and then update the corresponding MySQL entry. It worked fine but im guessing i could have removed the serialisation stuff in a better way, perhaps theres an API to do it.
41,630
<p>I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.</p> <p>I know that's possible by using keyword <em>system</em> like that :</p> <pre><code>#!/usr/bin/env ruby directory = '/home/paulgreg/' system 'ls ' + directory </code></pre> <p>but is that possible by using the "backquotes or backticks syntax" ? (I mean by using that syntax : <code>ls</code>)</p>
[ { "answer_id": 41635, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 4, "selected": true, "text": "<p>No, that will just concatenate the output from <code>ls</code> and the contents of <code>directory</code>.</p>\n\n<p>...
2008/09/03
[ "https://Stackoverflow.com/questions/41630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable. I know that's possible by using keyword *system* like that : ``` #!/usr/bin/env ruby directory = '/home/paulgreg/' system 'ls ' + directory ``` but is that possible by using the "backquotes or backticks syntax" ? (I mean by using that syntax : `ls`)
No, that will just concatenate the output from `ls` and the contents of `directory`. But you can do this: ``` #!/usr/bin/env ruby directory = '/home/paulgreg/' `ls #{directory}` ```
41,638
<p>The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well!</p> <p>The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens!</p> <p>We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).</p> <p>Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object <strong>Person</strong> will be mapped to say <strong>PersonDTO</strong>. I do not want to do this manually since it is a waste.</p> <p>Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that <em>"cooler"</em> will be suggested.</p> <p>Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord.</p> <hr> <h2>Example code:</h2> <p>By @ajmastrean's request I have <a href="http://www.fryhard.com/downloads/stackoverflow/ActiveRecordAsync.zip" rel="noreferrer">linked</a> to an example that I have (badly) mocked together. The example has a <strong>capture form</strong>, capture form <strong>controller</strong>, <strong>domain</strong> objects, activerecord <strong>repository</strong> and an <strong>async</strong> helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called <em>ActiveRecordAsync</em> on your local machine or just change the .config file.</p> <p>Basic details of example:</p> <p><strong>The Capture Form</strong></p> <p>The capture form has a reference to the contoller</p> <pre><code>private CompanyCaptureController MyController { get; set; } </code></pre> <p>On initialise of the form it calls MyController.Load() private void InitForm () { MyController = new CompanyCaptureController(this); MyController.Load(); } This will return back to a method called LoadComplete()</p> <pre><code>public void LoadCompleted (Company loadCompany) { _context.Post(delegate { CurrentItem = loadCompany; bindingSource.DataSource = CurrentItem; bindingSource.ResetCurrentItem(); //TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone. grdEmployees.DataSource = loadCompany.Employees; }, null); } } </code></pre> <p>this is where the <em>"bad stuff"</em> occurs, since we are using the child list of Company that is set as Lazy load.</p> <p><strong>The Controller</strong></p> <p>The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method.</p> <pre><code>public void Load () { new AsyncListLoad&lt;Company&gt;().BeginLoad(LoadCompany, Form.LoadCompleted); } </code></pre> <p>The LoadCompany() method simply makes use of the Repository to find a know company.</p> <pre><code>public Company LoadCompany() { return ActiveRecordRepository&lt;Company&gt;.Find(Setup.company.Identifier); } </code></pre> <p>The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the <strong>ActiveRecordMediator</strong> abilities.</p>
[ { "answer_id": 169708, "author": "ZeroBugBounce", "author_id": 11314, "author_profile": "https://Stackoverflow.com/users/11314", "pm_score": 3, "selected": false, "text": "<p>I solved a problem very similar to this where I copied the data out of a lot of older web service contracts into ...
2008/09/03
[ "https://Stackoverflow.com/questions/41638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231/" ]
The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well! The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens! We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM). Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object **Person** will be mapped to say **PersonDTO**. I do not want to do this manually since it is a waste. Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that *"cooler"* will be suggested. Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord. --- Example code: ------------- By @ajmastrean's request I have [linked](http://www.fryhard.com/downloads/stackoverflow/ActiveRecordAsync.zip) to an example that I have (badly) mocked together. The example has a **capture form**, capture form **controller**, **domain** objects, activerecord **repository** and an **async** helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called *ActiveRecordAsync* on your local machine or just change the .config file. Basic details of example: **The Capture Form** The capture form has a reference to the contoller ``` private CompanyCaptureController MyController { get; set; } ``` On initialise of the form it calls MyController.Load() private void InitForm () { MyController = new CompanyCaptureController(this); MyController.Load(); } This will return back to a method called LoadComplete() ``` public void LoadCompleted (Company loadCompany) { _context.Post(delegate { CurrentItem = loadCompany; bindingSource.DataSource = CurrentItem; bindingSource.ResetCurrentItem(); //TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone. grdEmployees.DataSource = loadCompany.Employees; }, null); } } ``` this is where the *"bad stuff"* occurs, since we are using the child list of Company that is set as Lazy load. **The Controller** The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method. ``` public void Load () { new AsyncListLoad<Company>().BeginLoad(LoadCompany, Form.LoadCompleted); } ``` The LoadCompany() method simply makes use of the Repository to find a know company. ``` public Company LoadCompany() { return ActiveRecordRepository<Company>.Find(Setup.company.Identifier); } ``` The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the **ActiveRecordMediator** abilities.
I solved a problem very similar to this where I copied the data out of a lot of older web service contracts into WCF data contracts. I created a number of methods that had signatures like this: ``` public static T ChangeType<S, T>(this S source) where T : class, new() ``` The first time this method (or any of the other overloads) executes for two types, it looks at the properties of each type, and decides which ones exist in both based on name and type. It takes this 'member intersection' and uses the DynamicMethod class to emil the IL to copy the source type to the target type, then it caches the resulting delegate in a threadsafe static dictionary. Once the delegate is created, it's obscenely fast and I have provided other overloads to pass in a delegate to copy over properties that don't match the intersection criteria: ``` public static T ChangeType<S, T>(this S source, Action<S, T> additionalOperations) where T : class, new() ``` ... so you could do this for your Person to PersonDTO example: ``` Person p = new Person( /* set whatever */); PersonDTO = p.ChangeType<Person, PersonDTO>(); ``` And any properties on both Person and PersonDTO (again, that have the same name and type) would be copied by a runtime emitted method and any subsequent calls would not have to be emitted, but would reuse the same emitted code *for those types in that order* (i.e. copying PersonDTO to Person would also incur a hit to emit the code). It's too much code to post, but if you are interested I will make the effort to upload a sample to SkyDrive and post the link here. Richard
41,647
<p>When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. </p> <p>At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: (<strong>link no longer working</strong>) <a href="http://driveefficiently.com/testinclude.php" rel="noreferrer">http://driveefficiently.com/testinclude.php</a> this file consists of only: </p> <pre><code>&lt;? include("include.inc"); ?&gt; </code></pre> <p>and include.inc consists of only: </p> <pre><code>&lt;? echo ("hello, world"); ?&gt; </code></pre> <p>and yet, the output is: <em>"?hello, world"</em> where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. </p> <p>Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.</p>
[ { "answer_id": 41655, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 0, "selected": false, "text": "<p>I see <code>hello, world</code> on the page you linked to. No problems that I can see...</p>\n\n<p>I'm using Firefox 3....
2008/09/03
[ "https://Stackoverflow.com/questions/41647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1111/" ]
When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: (**link no longer working**) <http://driveefficiently.com/testinclude.php> this file consists of only: ``` <? include("include.inc"); ?> ``` and include.inc consists of only: ``` <? echo ("hello, world"); ?> ``` and yet, the output is: *"?hello, world"* where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.
What you are seeing is a UTF-8 Byte Order Mark: > > The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8. > > > [Byte Order Mark on Wikipedia](http://en.wikipedia.org/wiki/Byte_Order_Mark) > > > PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM. [You can read more about this problem here](http://juicystudio.com/article/utf-byte-order-mark.php)
41,652
<p>We have got a custom <code>MembershipProvider</code> in <code>ASP.NET</code>. Now there are 2 possible scenario the user can be validated:</p> <ol> <li><p>User login via <code>login.aspx</code> page by entering his username/password. I have used <strong>Login control</strong> and linked it with the <code>MyMembershipProvider</code>. This is working perfectly fine.</p></li> <li><p>An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in <code>MembershipProvider.Validate(string authenticationToken)</code>, which is actually validating the user. In this case we cannot use the <strong>Login control</strong>. Now how can I use the same <code>MembershipProvider</code> to validate the user without actually using the <strong>Login control</strong>? I tried to call <code>Validate</code> manually, but this is not signing the user in.</p></li> </ol> <p>Here is the code snippet I am using </p> <pre><code>if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) { string ticket = Request.QueryString["authenticationToken"]; MyMembershipProvider provider = Membership.Provider as MyMembershipProvider; if (provider != null) { if (provider.ValidateUser(ticket)) // Login Success else // Login Fail } } </code></pre>
[ { "answer_id": 41664, "author": "MartinHN", "author_id": 2972, "author_profile": "https://Stackoverflow.com/users/2972", "pm_score": 5, "selected": true, "text": "<p>After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: <a href=\"http:...
2008/09/03
[ "https://Stackoverflow.com/questions/41652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
We have got a custom `MembershipProvider` in `ASP.NET`. Now there are 2 possible scenario the user can be validated: 1. User login via `login.aspx` page by entering his username/password. I have used **Login control** and linked it with the `MyMembershipProvider`. This is working perfectly fine. 2. An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in `MembershipProvider.Validate(string authenticationToken)`, which is actually validating the user. In this case we cannot use the **Login control**. Now how can I use the same `MembershipProvider` to validate the user without actually using the **Login control**? I tried to call `Validate` manually, but this is not signing the user in. Here is the code snippet I am using ``` if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) { string ticket = Request.QueryString["authenticationToken"]; MyMembershipProvider provider = Membership.Provider as MyMembershipProvider; if (provider != null) { if (provider.ValidateUser(ticket)) // Login Success else // Login Fail } } ```
After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: <http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx> EDIT: It is FormsAuthentication.SetAuthCookie: <http://msdn.microsoft.com/en-us/library/twk5762b.aspx> Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: <http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx> [link text](http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx)
41,659
<p>Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container?</p> <p>For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, </p> <ol> <li>a properties file in the classpath,</li> <li>a web.xml parameter, </li> <li>a system property, or </li> <li>some default logic if nothing else is available. </li> </ol> <p>I'd like to be able to do this without injecting any reference to <code>ServletConfig</code> or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container.</p> <p>This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml.</p> <p>If I recall correctly, .NET has something like <code>Request.GetCurrentRequest()</code> to get a reference to the currently executing <code>Request</code> - but since this is a Java app I'm looking for something simliar that could be used to gain access to <code>ServletConfig</code>.</p>
[ { "answer_id": 41767, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 1, "selected": false, "text": "<p>Have you considered using the Spring framework for this? That way, your beans don't get any extra cruft, and spring ha...
2008/09/03
[ "https://Stackoverflow.com/questions/41659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container? For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, 1. a properties file in the classpath, 2. a web.xml parameter, 3. a system property, or 4. some default logic if nothing else is available. I'd like to be able to do this without injecting any reference to `ServletConfig` or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container. This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml. If I recall correctly, .NET has something like `Request.GetCurrentRequest()` to get a reference to the currently executing `Request` - but since this is a Java app I'm looking for something simliar that could be used to gain access to `ServletConfig`.
One way you could do this is: ``` public class FactoryInitialisingServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { Properties properties = new Properties(); ServletContext servletContext = event.getServletContext(); Enumeration<?> keys = servletContext.getInitParameterNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = servletContext.getInitParameter(key); properties.setProperty(key, value); } Factory.setServletContextProperties(properties); } } public class Factory { static Properties _servletContextProperties = new Properties(); public static void setServletContextProperties(Properties servletContextProperties) { _servletContextProperties = servletContextProperties; } } ``` And then have the following in your web.xml ``` <listener> <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class> </listener> ``` If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the \_servletContextProperties will be replaced with any context-params specified in the web.xml. If your application is running outside a web container, then \_servletContextProperties will be empty.
41,665
<p>Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?</p>
[ { "answer_id": 41672, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>You can try:</p>\n\n<pre><code>Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic;\n</code></pre>\n\n<p>and<...
2008/09/03
[ "https://Stackoverflow.com/questions/41665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?
``` var qualityEncoder = Encoder.Quality; var quality = (long)<desired quality>; var ratio = new EncoderParameter(qualityEncoder, quality ); var codecParams = new EncoderParameters(1); codecParams.Param[0] = ratio; var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">; bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG ```
41,674
<p>In Visual Studio you can create a template XML document from an existing schema. The new <a href="http://msdn.microsoft.com/en-us/library/cc716766.aspx" rel="noreferrer">XML Schema Explorer</a> in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data. Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the <a href="http://msdn.microsoft.com/en-us/library/aa302296.aspx" rel="noreferrer">XmlSampleGenerator</a> article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?</p>
[ { "answer_id": 174148, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 0, "selected": false, "text": "<p>Directly, none that I can think of, other than third party add-ons. You could utilize the <a href=\"http://msdn.microso...
2008/09/03
[ "https://Stackoverflow.com/questions/41674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3873/" ]
In Visual Studio you can create a template XML document from an existing schema. The new [XML Schema Explorer](http://msdn.microsoft.com/en-us/library/cc716766.aspx) in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data. Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the [XmlSampleGenerator](http://msdn.microsoft.com/en-us/library/aa302296.aspx) article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?
some footwork is involved, but you could load the xsd into a DataSet object, iterate over the Tables and add a few rows in each by calling calling NewRow() on each and then adding those rows back into their respective tables.. then save the DataSet out to a file: ``` DataSet ds = new DataSet(); ds.ReadXmlSchema("c:/xsdfile.xsd"); foreach(DataTable t in ds.Tables) { var row = t.NewRow(); t.Rows.Add(row); } ds.WriteXml("c:/example.xml"); ``` P.S. A little extra work, but instead of just iterating over each table type and adding empty rows, you could build a nice winform that would allow you to drop in some data for each of the rows. I built something like this in about an hour a few weeks ago.
41,686
<p>I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code:</p> <p>Servlet</p> <pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String customerPath = "\\leetest\\"; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { // Form field. Ignore for now } else { BufferedInputStream stream = new BufferedInputStream(item .openStream()); if (stream == null) { LOGGER .error("Something went wrong with fetching the stream for field " + name); } byte[] bytes = StreamUtils.getBytes(stream); FileManager.createFile(customerPath, item.getName(), bytes); stream.close(); } } } } catch (Exception e) { throw new UploadException("An error occured during upload: " + e.getMessage()); } } </code></pre> <p>StreamUtils.getBytes(stream) looks like:</p> <pre><code>public static byte[] getBytes(InputStream src, int buffsize) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buff = new byte[buffsize]; while (true) { int nBytesRead = src.read(buff); if (nBytesRead &lt; 0) { break; } byteStream.write(buff); } byte[] result = byteStream.toByteArray(); byteStream.close(); return result; } </code></pre> <p>And finally FileManager.createFile looks like:</p> <pre><code>public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); } </code></pre> <p>Can anyone spot what I'm doing wrong?</p> <p>Cheers, Lee</p>
[ { "answer_id": 41694, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<p>Are you sure that the image isn't coming through garbled or that you aren't dropping some packets on the way in. </p>\n"...
2008/09/03
[ "https://Stackoverflow.com/questions/41686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900/" ]
I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code: Servlet ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String customerPath = "\\leetest\\"; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { // Form field. Ignore for now } else { BufferedInputStream stream = new BufferedInputStream(item .openStream()); if (stream == null) { LOGGER .error("Something went wrong with fetching the stream for field " + name); } byte[] bytes = StreamUtils.getBytes(stream); FileManager.createFile(customerPath, item.getName(), bytes); stream.close(); } } } } catch (Exception e) { throw new UploadException("An error occured during upload: " + e.getMessage()); } } ``` StreamUtils.getBytes(stream) looks like: ``` public static byte[] getBytes(InputStream src, int buffsize) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buff = new byte[buffsize]; while (true) { int nBytesRead = src.read(buff); if (nBytesRead < 0) { break; } byteStream.write(buff); } byte[] result = byteStream.toByteArray(); byteStream.close(); return result; } ``` And finally FileManager.createFile looks like: ``` public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); } ``` Can anyone spot what I'm doing wrong? Cheers, Lee
One thing I don't like is here in this block from StreamUtils.getBytes(): ``` 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } 6 byteStream.write(buff); 7 } ``` At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this: ``` 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } else { 6 byteStream.write(buff, 0, nBytesRead); 7 } 8 } ``` Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6. I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable.