input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Most elegant UI for categorizing items? <p>I have a collection of items that the user needs to group/categorize in several ways. For the sake of an example, let's say it's a collection of cars and the user wants to categorize them in the following ways:</p>
<ul>
<li>Color (red, silver, blue, black, etc.)</li>
<li>Body shape (hatch, sedan, coupe, stationwagon, etc.)</li>
<li>Seats (2, 4, 5, 6, etc.)</li>
<li>etc.</li>
</ul>
<p>Have you ever come across a particularly elegant way of doing this that allows the user full freedom to define their own categories and values?</p>
<p>Obviously, there will many be trade-offs to make in any design. For example, a learnable design might not be efficient, and vice versa. Or some designs may be more demanding of real estate than others. And some will take significantly longer to develop than others.</p>
<p>Regardless, if you've seen -- or designed -- a good pattern for this, I'd be interested to hear about it. If you have screenshots, all the better.</p>
<p><strong>Attempt at clarification</strong>: tags are indeed a great way of categorizing things, but in all implmentations I've seen, there's only ever one level of tagging. The user doesn't generally get to define a category/property and the item's value <em>in that category</em>. To use the example above and StackOverflow's tagging, you'd tag a car as "blue", "sedan", "4", and so on. StackOverflow would have no inherent knowledge that an item couldn't be tagged as both "sedan" and "coupe".</p>
<p>The interface I'm thinking of would need to know that kind of thing, so the user-defined attributes suggestion is more along the lines of what I'm thinking. I'm just keen to find a concrete example of how that kind of system could be elegantly implemented (in a desktop app, if that makes a difference).</p>
<p>Is that any clearer? If not, leave a comment and I'll try to clarify again. :)</p>
| <p>It sounds like you have two tasks: Task 1 Categorize Objects, where for a series of objects, the user assigns each a category (value) on each of multiple dimensions (attributes). Task 2: Create and Modify Dimension and Categories. </p>
<p>Outside of data modelers, object-oriented programmers, and database designers, the idea of dimensions and categories is a very hard concept to grasp. You should be prepared for users not understanding the difference between categories and dimensions. However, users generally will understand tables, where each column is a dimension (that comprises several categories) and each row is an object. As much as possible, work with tables.</p>
<p>The first key question is to figure out through user research is the degree Task 1 and 2 are integrated or separate. </p>
<p>If the tasks are integrated, with users often switching fluidly from one to the other without much thought, then one UI design is to have a objects-by-dimension table, but provide a blank column (or an âInsertâ button) to allow the user to add a dimension. The column header has the dimension name, which the user can edit. Under the header is a space listing the categories of that dimension. Each category name is editable and there is a blank line (or the Insert button) to add a new category. Below that are the objects to categorize, each with a dropdown list in each column for dimension. </p>
<p>In usability testing, watch out for users trying to set an objectâs category by clicking on a category in the category list, rather than selecting from the dropdown list. Make the category list appear visually separate to prevent this.</p>
<p>You may want a button to hide/show the category lists, as this can take a lot of space (even when using scrollbars). Even if Task 1 and 2 are tightly integrated, I think youâll find users may want to get the category lists out of the way sometimes. </p>
<p>If you find that Task 1 and 2 are separate, rarely being done together (e.g., users typically set up their dimensions then categorize a bunch of objects), then youâre better off with a separate window (or page) for each task, although it should be easy to navigate back and forth between them. For example, while users may typically set up their dimensions beforehand then rarely modify them, sometimes a user will realized one needs a new category for a dimension while categorizing an unusual object, so you provide a âAdd categoryâ menu item that takes the user to the Manage Categories window, with a new category inserted for the current dimension awaiting the user to provide a name.</p>
<p>The window for Task 1 is the same as before: table of objects with a column of dropdown lists for each dimension, but exclude the category lists, the editing of the dimension names, and the capacity to add a new dimension. This is most efficient if the user needs to scan for objects needing categorizing or re-categorizing, or if typically the user needs to compare one object against some others (e.g., to decide how to categorize the object). However, if the userâs task is truly limited to just <em>categorizing</em> an object one at a time based on outside information (e.g., transcribing information from paper), then consider a form rather than a table, showing an array of list boxes, one for each attribute. With a single click of each list box to set each category, this is faster than using dropdown lists. </p>
<p>The window for Task 2 could be like the header portion for task one. It is consistent with the table used for Task 1 and allows users to see categories for multiple dimensions at once, helping them figure out the best categorization scheme (e.g., help them find where essentially the same category appears in two different dimensions). If space is a problem, however, then consider a list of dimensions each showing a list of categories in a master-detail relation.</p>
<p>The ultimate in user power and flexibility for Task 2 is a tree-like control. The root level of the tree comprises dimensions and the next step in the hierarchy comprises the categories within each dimension. The main advantage is that it supports dimensions being <em>dependent</em> on categories. For example, one may have a Vehicle Type dimension that includes categories like Car, Boat, Plane, etc. For the Car category, one may then have a Body Type dimension with categories that only apply to that category (Coupe, Hatchback, etc.). Dependent dimensions are represented in the tree by branches off a category. The result is the tree alternates between dimensions and categories with each level in. </p>
<p>Itâs important to visually distinguish the categories from the dimensions, perhaps by different icons, and maybe different font as well âsomething to tell users that alternating steps in the hierarchy are qualitatively different (e.g., if you create a Dimension, then you should create at least two categories). Even then, provide a means of easy recovery if users confuse dimensions with categories (e.g., allow them to move a bunch of âdimensionsâ to under another dimension, converting the former into categories). </p>
<p>I want to emphasize again the difficulty people have with abstractions like dimensions and categories. Even when they do understand it, people generally have great difficulty creating decent dimensions and categories on their own. There are complicated interactions that can result that you need to think through (e.g., what happens to object categorization when a category is moved to a new dimension?). If you are expecting each user to truly create their own novel dimensions, then you may want to seriously re-think your whole approach. It is an inherently complicated task.</p>
<p>User do much better if thereâs already a relevant multi-dimensional scheme in the culture, organization, or domain (such as we have for cars). Of course, if there already is a scheme, then you can research it and install it as a default set of dimensions in your product. Task 2 only needs to be supported to allow expert users to fine-tune it.</p>
|
release configuration management <p>Our windows deliverable has different sets of config files and binary assets for different customers. Right now the configuring is done by hand before packaging and its error prone. What do you think of using branches for each customer, and having the package build/script automerge the customer's branch with trunk?</p>
<p>I'm less concerned with scalability than I am of getting this automated ASAP.</p>
<p>The entire packag contents is in SVN, but SVN branching and merging is so delicate that I don't trust it to work consistently when its automated. If you guys like the idea I might try to use git-svn for this, because it will hopefully make merging less delicate. We don't necessarily have to merge the assets, because they are organized so the installer can just skip inappropriate directory trees, but configuration is not so simple.</p>
| <p>I suppose it depends on how many things have to change. For config files, I like to keep a single file under source control and use a build script to set the environment-specific (or in your case client-specific) items.</p>
<p><a href="http://automaticchainsaw.blogspot.com/2008/02/automate-config-changes-for-different.html" rel="nofollow">http://automaticchainsaw.blogspot.com/2008/02/automate-config-changes-for-different.html</a></p>
<p>For binaries, it probably has more to do with how many of them you have and where they come from. If they are part of a code compile, then the compilation process ideally would create what you need. If they are other resources, such as graphics, perhaps you have a customer-specific set of folders under one directory. The build script would pull in the correct client folder based on a parameter passed to the script. This is basically the branch and merge idea you mentioned in your question.</p>
<p>Regarding your later comment about multi-line config changes - assuming it is xml, you might look at the XmlMassUpdate class in the MSBuild Community Tasks. I've not used it myself, but it looks like it might be what you need.</p>
|
Format Date with fmt:formatDate JSP <p>I am trying to format a date with: </p>
<pre><code><fmt:formatDate value="${newsletter.createdOn}" pattern="MM/dd/yyyy"/>
</code></pre>
<p>newsletter is an object with a <code>createdOn</code> property which is <code>java.util.Date</code>.</p>
<p>When I invoke the previous sentence I get: </p>
<p>According to the TLD, the attribute value does not accept expressions. </p>
<p>I am importing fmt with </p>
<pre><code><%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
</code></pre>
<p>Does anyone know how can I work around this problem?</p>
<p>I am using the jstl.jar coming with tomcat. </p>
<p>Under jstl.jar/META-INF/MANIFEST.MF stays: </p>
<pre><code>Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.3
Created-By: 1.4.2-b28 (Sun Microsystems Inc.)
Specification-Title: JavaServer Pages Standard Tag Library (JSTL)
Specification-Version: 1.1
Implementation-Title: JavaServer Pages Standard Tag Library API Refere
nce Implementation
Implementation-Version: 1.1.0-D13
Implementation-Vendor: Sun Microsystems, Inc.
Implementation-Vendor-Id: com.sun
Extension-Name: javax.servlet.jsp.jstl
</code></pre>
<p>I am using Apache Tomcat Version 6.0.14</p>
| <p>Try </p>
<pre><code><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
</code></pre>
|
What is the best way to know when the UIViewController above me in the stack has been popped? <p>I have a <code>UIViewController</code> that manages the display of some data. When the user wants to edit this data I push an edit <code>UIViewController</code> onto the stack. When the user is finished editing the top view controller is popped off the stack. What is the most elegant way to know that I need to update my display after the edit view is popped off?</p>
<p>I thought that I might be able to put the content update code into the <code>viewDidLoad</code> method of my data view, but this method isn't always called when my view displays, especially not when I'm navigating down the view stack.</p>
<p>I also considered setting up my data view controller as a delegate for the <code>UINavigationController</code> and wait for <code>â navigationController:didShowViewController:animated:</code> to be called, my concern is that there may be other view controllers that need to be notified when they're displayed and it will turn into a minor headache managing which controller should be receiving the <code>didShowViewController</code> message.</p>
| <p>I think viewWillAppear will do the trick.</p>
<p>Otherwise your edit view controller could call a new method of delegate pointing to your parent controller. In there, you can update the data model and display. For instance:</p>
<pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ([delegate respondsToSelector:@selector(editEntryByTitle:)])
[delegate performSelector:@selector(editEntryByTitle:) withObject: textField.text];
[textField resignFirstResponder];
[self dismissModalViewControllerAnimated:YES];
return YES;
}
</code></pre>
|
Is there an ORM for Perl? <pre>
create table person
(
name varchar(15),
attr1 varchar(15),
attr2 varchar(1),
attr3 char(1),
attr4 int
)
</pre>
<p>How I can use basic ORM in Perl by taking a simple table like the one above and mapping it to Perl objects? Next I'd like to perform basic operations like select results using some criteria system Perl like syntax. eg.:</p>
<pre><code>@myResults = findAll(attr1 == 3 && attr2 =~ /abc/);
</code></pre>
| <p>Rule #1, don't write your own.</p>
<p>There are quite a number of ORMs on CPAN, including ...</p>
<ul>
<li><a href="http://search.cpan.org/dist/DBIx-Class">DBIx::Class</a> - probably #1 in popularity at the moment</li>
<li><a href="http://search.cpan.org/dist/Rose-DB-Object">Rose::DB::Object</a></li>
<li><a href="http://search.cpan.org/dist/Fey-ORM">Fey::ORM</a> - my own contribution, most notable for being <a href="http://moose.perl.org/">Moose</a>-based, which means you get all the power of Moose in your ORM-based classes.</li>
</ul>
|
What do I need to write Java-based web applications and test them on my personal computer? <p>I currently have Apache HTTP Server, but I'm guessing I'll need Tomcat (and then have to configure it in a way that makes it not open to the public), a Java JDK (which I already have, but should probably update), and an IDE (I have Eclipse). But what else should I have or know before starting?</p>
| <p>I'd recommend having a database server installed as well- you can go pretty far with the various pure Java implementations, but anything significant will probably benefit from having a copy of MySQL around.</p>
<p>I'd also get some sort of version control going- tortoiseSVN works really well for windows. Even if you're just goofing around for yourself, getting in the habit of using it will save time and heartache down the road.</p>
|
Error: Failed to generate a user instance of SQL Server <p>I'm trying to connect to an MDF. I've even gone to the lengths of re-installing sql server express entirely (it is now the only flavor of SQL installed on my box, where previously I had 05 dev and express). I've verified that the paths are all correct, and thus far my google-fu hasn't helped.</p>
<p>The Full exception message is: </p>
<blockquote>
<p>Failed to generate a user instance of SQL Server due to a failure in
starting the process for the user instance. The connection will be
closed.</p>
</blockquote>
<p>The Connection string is:</p>
<pre><code><add name= "CustomerEntities"
connectionString="metadata=res://*/Data.CustomerModel.csdl|res://*/Data.CustomerModel.ssdl|res://*/Data.CustomerModel.msl;
provider=System.Data.SqlClient;
provider connection string='Data Source=.\SQLEXPRESS;
AttachDbFilename=\App_Data\CustomerDb.mdf;
Integrated Security=True;
User Instance=True'"
providerName="System.Data.EntityClient" />
</code></pre>
<h3>Additional info:</h3>
<p>Several of the references to this error I've found online do not apply to me. For example, one I've seen is where this error occurs when trying to start the user instance over remote desktop (I'm doing this locally). While another suggests that it has to do with leftover files from an old express installation ... I've looked in the prescribed locations and not found those artifacts. I also tried running <code>sp_configure 'user instances enabled', '1'</code>, but it said that it was already set to 1.</p>
| <p>ok, it works now! guess it was a compound problem ... the steps I took to resolve it are as such:</p>
<ol>
<li>Changed the following property in the connection string (note the subtle difference): <code>AttachDbFilename=|DataDirectory|CustomerDb.mdf;</code></li>
<li>Deleted the contents of the following directory: <code>c:\Users\<user name>\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS</code>. I thought I had looked for this before, but I had actually looked in the <code>Microsoft Sql Server</code> folder. Again, a subtle difference.</li>
</ol>
<p>Once I did these two things, the connection started working :-D</p>
|
Visual Studio variable declaration <p>I have a project that has the following line in the additional includes section:</p>
<p>"$(SOMEPATH_SHORTNAME)\include"</p>
<p>Can someone tell me where I can find $(SOMEPATH) defined? I can't find it by simply searching in Visual Studio</p>
| <p>If it's not an environment variable, the place to look is the macros. In the property sheets, click the (...) button beside the "Addition Include Directories" line, and expand the "Macros>>" button in the dialog that pops up. </p>
|
What are the actual performance differences between Int64 and Int32 on 32 and 64 bit MS Windows? <p>What are the actual performance differences between Int64 and Int32 on 32 and 64 bit MS Windows?</p>
<p>It would also be great to see some actual timings of Int64 vs Int32 on each of the two operating system variants. XP or Vista would also be interesting.</p>
<ul>
<li>See also this question about <a href="http://stackoverflow.com/questions/269408/memcpy-performance-differences-between-32-and-64-bit-processes">memcpy</a> performance.</li>
</ul>
| <p>As far as hardware, Int64 will be more efficient on an x64 and IA64 than x86 because the 64-Bit processors have 64-Bit registers to perform the operations on them. </p>
<p>Int32 will be equally as efficient on all x86, x64, and IA64. </p>
<p>On an x64 and on an IA64 both Int32 and Int64 are equally as efficient.</p>
<p>On an x86 Int32 will be more efficient than an Int64. </p>
<p>As far as the OS itself, I don't think you will see any extra performance issues than the performance results mentioned above. </p>
|
How do I get a human-readable file size in bytes abbreviation using .NET? <p>How do I get a human-readable file size in bytes abbreviation using .NET?</p>
<p><strong>Example</strong>:
Take input 7,326,629 and display 6.98 MB</p>
| <p>using Log to solve the problem....</p>
<pre><code>static String BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num).ToString() + suf[place];
}
</code></pre>
<p>Also in c#, but should be a snap to convert. Also I rounded to 1 decimal place for readability. </p>
<p>Basically Determine the number of decimal places in Base 1024 and then divide by 1024^decimalplaces.</p>
<p>And some samples of use and output:</p>
<pre><code>Console.WriteLine(BytesToString(9223372036854775807)); //Results in 8EB
Console.WriteLine(BytesToString(0)); //Results in 0B
Console.WriteLine(BytesToString(1024)); //Results in 1KB
Console.WriteLine(BytesToString(2000000)); //Results in 1.9MB
Console.WriteLine(BytesToString(-9023372036854775807)); //Results in -7.8EB
</code></pre>
<p>Edit:
Was pointed out that I missed a math.floor, so I incorporated it. (Convert.ToInt32 uses rounding, not truncating and that's why Floor is necessary.) Thanks for the catch.</p>
<p>Edit2:
There were a couple of comments about negative sizes and 0 byte sizes, so I updated to handle those 2 cases. </p>
|
Reg-Free COM in an ASP.Net application <p>I am wondering if it is possible to use Reg-Free COM in an ASP.Net application?</p>
| <p>According to this it is: <a href="http://www.mazecomputer.com/sxs/help/iis6aspnet2.htm" rel="nofollow">http://www.mazecomputer.com/sxs/help/iis6aspnet2.htm</a></p>
<p>I haven't tried, it I've just been researching the same idea...</p>
|
Hibernate JPA to DDL command line tools <p>There are Hibernate tools for mapping files to ddl generation; ddl to mapping files and so on, but I can't find any command line tools for simple DDL generation from JPA annotated classes.</p>
<p>Does anyone know an easy way to do this? (Not using Ant or Maven workarounds)</p>
| <p>I'm not sure, whether this is considered a workaround, because you already referred to it in your question. You can use <a href="http://tools.hibernate.org/">Hibernate Tools</a> to generate DDL from JPA annotated classes. You just need hibernate tools and its dependencies on the classpath and should be fine with something like the following:</p>
<pre><code><target name="schemaexport" description="Export schema to DDL file"
depends="compile-jpa"> <!-- compile model classes before running hibernatetool -->
<!-- task definition; project.class.path contains all necessary libs -->
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="project.class.path" />
<hibernatetool destdir="export/db"> <!-- check that directory exists -->
<jpaconfiguration persistenceunit="myPersistenceUnitName" />
<classpath>
<!--
compiled model classes and other configuration files don't forget
to put the parent directory of META-INF/persistence.xml here
-->
</classpath>
<hbm2ddl outputfilename="schemaexport.sql" format="true"
export="false" drop="true" />
</hibernatetool>
</target>
</code></pre>
<p>On the other hand, if you are using Eclipse with Webtools and have configured the project settings correctly, you can just right click and select <em>Generate DDL</em> from the context menu. More information about that on the <a href="http://www.eclipse.org/webtools/dali/">Eclipse Dali website</a>.</p>
|
Are there any Ajax-based UML modeling tools? <p>I'm looking for something like <a href="http://ondras.zarovi.cz/sql/demo/?keyword=default" rel="nofollow">WWW SQL Designer</a> for UML Modeling.</p>
| <p>This one is not in Ajax, it's in flash, at least it is online: <a href="http://www.gskinner.com/gmodeler/launch.html" rel="nofollow">http://www.gskinner.com/gmodeler/launch.html</a></p>
|
How to highlight input text field upon clicking it in Safari? <p>I would like the value of the input text box to be highlighted when it gains focus, either by clicking it or tabbing to it.</p>
<pre><code><html>
<body>
<script>
function focusTest(el)
{
el.select();
}
</script>
<input type="text" value="one" OnFocus="focusTest(this); return false;" />
<br/>
<input type="text" value="two" OnFocus="focusTest(this); return false;" />
</body>
</html>
</code></pre>
<p>When either input field is clicked in Firefox or IE, that field is highlighted. However, this doesn't work in Safari. (NOTE: it works when tabbing between fields.)</p>
| <p>I noticed Safari is actually selecting the text then removing the selection quickly.</p>
<p>So I tried this quick workaround that works in all browsers:</p>
<pre><code>function focusTest(el)
{
setTimeout (function () {el.select();} , 50 );
}
</code></pre>
<p>Edit :<br />
Upon further testing it turns out the OnMouseUp event is clearing the selection so it is enough to add</p>
<pre><code>onMouseUp="return false;"
</code></pre>
<p>to the input element for things to work as they should.</p>
|
What do Streams do when implementing AES encrption in .NET? <p>The Rijndael encryption algorithm is implemented in .NET using 3 streams in the following example: <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx" rel="nofollow">Rinjdael</a>.</p>
<p>Can someone explain to me what these streams are doing? How/Why are they used?</p>
<pre><code>// Declare the streams used
// to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt = null;
CryptoStream csEncrypt = null;
StreamWriter swEncrypt = null;
// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged aesAlg = null;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
msEncrypt = new MemoryStream();
csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
swEncrypt = new StreamWriter(csEncrypt);
//Write all data to the stream.
swEncrypt.Write(plainText);
}
</code></pre>
| <p><code>swEncrypt</code> is a <code>StreamWriter</code> - its job is to convert text into binary data</p>
<p><code>csEncrypt</code> is a <code>CryptoStream</code> - its job is to convert binary data into encrypted binary data</p>
<p><code>msEncrypt</code> is a <code>MemoryStream</code> - its job is to store the data it's given in memory, so you can get it out later</p>
<p>When you put them all together, you basically get something where you can write plain text in one end, and get encrypted binary data out (having stored it in memory temporarily) of the other end.</p>
|
How do I read the value of a checkbox in a word (*.doc) file in VB.net using a Range object? <p>How do I read the value of a checkbox in a word (*.doc) file in VB.net using a range object?</p>
<p>This is what I have so far:</p>
<pre><code>Dim app As New Word.Application
Dim doc As Document
doc = app.Documents.Open("C:\myDoc.doc")
dim chkBox as Bookmark
chkBox = doc.Bookmarks("MyCheckbox")
Dim rng as Range
rng = chkBox.Range
</code></pre>
<p>where "MyCheckbox" is the bookmark of the checkbox in the word document. </p>
| <p>Any particular reason you're not reading the value of the checkbox using the name of the checkbox itself?</p>
<p>If the range defined by your bookmark contains a checkbox, then, depending upon how the checkbox is inserted, it will be found in either the <code>InlineShapes</code> collection (if checkbox inserted inline with the text) or the <code>Shapes</code> collection (if inserted as a floating object.)</p>
<p>You would then need to iterate through the collection of Shapes or InlineShapes looking for the checkbox in question.</p>
<p><i>Iterating through controls in InlineShapes collection</i></p>
<pre><code>Dim ctl As InlineShape
For Each ctl In rng.InlineShapes
If ctl.Type = wdInlineShapeOLEControlObject Then
If ctl.OLEFormat.ClassType Like "Forms.CheckBox*" Then
'current version of ctl is a checkbox, do what you will with it.
End If
End If
Next ctl
...
</code></pre>
<p>This ought to get you closer, but if the name of the checkbox is predictable, it is better to address it directly by name.</p>
|
How do I write unit tests in PHP? <p>I've read everywhere about how great they are, but for some reason I can't seem to figure out how exactly I'm supposed to test something. Could someone perhaps post a piece of example code and how they would test it? If it's not too much trouble :)</p>
| <p>There is a 3rd "framework", which is by far easier to learn - even easier than <em>Simple</em>Test, it's called phpt.</p>
<p>A primer can be found here:
<a href="http://qa.php.net/write-test.php">http://qa.php.net/write-test.php</a></p>
<p><strong>Edit:</strong> Just saw your request for sample code.</p>
<p>Let's assume you have the following function in a file called <em>lib.php</em>:</p>
<pre><code><?php
function foo($bar)
{
return $bar;
}
?>
</code></pre>
<p>Really simple and straight forward, the parameter you pass in, is returned. So let's look at a test for this function, we'll call the test file <em>foo.phpt</em>:</p>
<pre><code>--TEST--
foo() function - A basic test to see if it works. :)
--FILE--
<?php
include 'lib.php'; // might need to adjust path if not in the same dir
$bar = 'Hello World';
var_dump(foo($bar));
?>
--EXPECT--
string(11) "Hello World"
</code></pre>
<p>In a nutshell, we provide the parameter <code>$bar</code> with value <code>"Hello World"</code> and we <code>var_dump()</code> the response of the function call to <code>foo()</code>.</p>
<p>To run this test, use: <code>pear run-test path/to/foo.phpt</code></p>
<p>This requires <a href="http://pear.php.net/manual/en/installation.php">a working install of PEAR</a> on your system, which is pretty common in most circumstances. If you need to install it, I recommend to install the latest version available. In case you need help to set it up, feel free to ask (but provide OS, etc.).</p>
|
Garbage Collector Flash Player <p>Is there a way to force the flash garbage collector to clean up freed memory? I've seen that it takes a lot of time for flash to clean up not referenced memory...</p>
| <p>Unfortunately there isn't. It's something Grant Skinner has written lots about, so check <a href="http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html" rel="nofollow">his blog</a>.</p>
|
How to find out Subversion repository version? <p>How can I determine current version of my repository to see if I need to upgrade it (svnadmin upgrade)?</p>
<p>In reality I'm hosting SVN with 3rd party and I want to find out if I need to ask them to upgrade my repos or not.</p>
<p>I'm asking since 1.5 server will keep repo version at 1.4, unless I miss something?</p>
| <p>Have a look at <code><REPO>/db/format</code>. After upgrading to 1.5 format, my <code>format</code> file shows:</p>
<pre><code>3
layout sharded 1000
</code></pre>
<p>Before it used to be:</p>
<pre><code>2
</code></pre>
|
C++ Opening a file and inputting data to a class object <p>Simple question, hopefully an easy way and just want to verify I'm doing it the correct / efficient way.</p>
<p>I have a class T object, which is typically put into a vector that is created in my main() function. It can be any kind of data, string, int, float.. etc. I'm reading from a file... which is inputted from the user and passed onto the function. Here is my basic read in function:</p>
<pre><code>template <class T, class U>
void get_list(vector<T>& v, const char *inputFile, U)
{
ifstream myFile;
T object;
myFile.open("inputFile")
while(!myFile.eof())
{
myFile >> object;
insert(v, object, U)
}
}
</code></pre>
<p>insert is just another function that will go through and insert the data into my data structure. I just want to make sure this is the best way to pass that data on if it will even work.</p>
| <p>You made the old mistake of testing against eof in the condition.
EOF is not set until you try and read past the end of file. So this method will insert one extra value into the vector that you don't want.</p>
<pre><code>template <class T, class U>
void get_list(vector<T>& v, const char *inputFile, U)
{
ifstream myFile("inputFile"); // Why hard code this?
// When you pass inputFile as a parameter?
T object;
while(myFile >> object) // Get the object here.
// If it fails because of eof() or other
// It will not get inserted.
{
insert(v, object, U)
}
}
</code></pre>
|
Image DPI Explained <p>Attempting to write a definition of DPI has lead me to:</p>
<p>DPI (dots), PPI (points), LPI (lines) all refer to the same concept hereafter referred to as DPI.</p>
<p>DPI is a device dependent measurement. It says, "This is the resolution of this device."</p>
<p>Vector based files are not tied to any one DPI (they expand and contract to conform to a certain resolution).</p>
<p>When that vector based file is rendered to a "bitmap" based format - (bmp, png, tiff, jpg) etc... that "bitmapped" file is created at a certain DPI for printing (or display) on "banding" or "scanline" based devices that output at that specific DPI.</p>
<p>Now, some would argue that DPI does not exist in "bitmapped" based files.</p>
<p>I'm looking for a definition of DPI and how or why it would be considered to not exist in a bitmapped image?</p>
| <p>Because a bitmapped image has no physical size, it has no dpi. If you have a file format where physical size is modeled, you can have a (modeled) dpi.</p>
<p>You might want to make a distinction between addressability and covered area. If a dot is not square but a circle, the covered area is larger.</p>
<p>b.t.w. LPI is a different but related concept. A 100 LPI screen for a 600 DPI printer means there are squares of 6*6 pixels available to create 37 different levels of gray (with a 0 degree rotation). </p>
|
Computing a mean confidence interval without storing all the data points <p>For large <code>n</code> (see below for how to determine what's large enough), it's safe to treat, by the central limit theorem, the distribution of the sample mean as normal (gaussian) but I'd like a procedure that gives a confidence interval for any <code>n</code>. The way to do that is to use a Student T distribution with <code>n-1</code> degrees of freedom.</p>
<p>So the question is, given a stream of data points that you collect or encounter one at a time, how do you compute a <code>c</code> (eg, <code>c=.95</code>) confidence interval on the mean of the data points (without storing all of the previously encountered data)?</p>
<p>Another way to ask this is: How do you keep track of the first and second moments for a stream of data without storing the whole stream?</p>
<p>BONUS QUESTION: Can you keep track of higher moments without storing the whole stream?</p>
| <p>Here's an article on <a href="http://www.johndcook.com/standard_deviation.html" rel="nofollow">how to compute the mean and standard deviation in a single pass</a>, not storing any data. Once you have the these two statistics, you can estimate a confidence interval. A 95% confidence interval would be [mean - 1.96*stdev, mean + 1.96*stdev], assuming a normal distribution for your data and a large number of data points.</p>
<p>For a smaller number of data points, your confidence interval would be [mean - c(n)<em>stdev, mean + c(n)</em>stdev] where c(n) depends on your sample size and your confidence level. For a 95% confidence level, here are your values of c(n) for n = 2, 3, 4, ..., 30</p>
<p>12.70620, 4.302653, 3.182446, 2.776445, 2.570582, 2.446912, 2.364624, 2.306004, 2.262157, 2.228139, 2.200985, 2.178813, 2.160369, 2.144787, 2.131450, 2.119905, 2.109816, 2.100922, 2.093024, 2.085963, 2.079614, 2.073873, 2.068658, 2.063899, 2.059539, 2.055529, 2.051831, 2.048407, 2.045230</p>
<p>These numbers are g(0.025, n-1) where g is the inverse CDF of the t distribution with n degrees of freedom. If you wanted a 99% confidence interval, replace 0.025 with 0.005. In general, for a confidence level of 1-alpha, use alpha/2.</p>
<p>Here's the <a href="http://www.r-project.org/" rel="nofollow">R</a> command that generated the constants above.</p>
<pre><code>n = seq(2, 30); qt(0.025, n-1)
</code></pre>
<p>Here's a <a href="http://www.johndcook.com/blog/2008/11/12/normal-approximation-for-student-t-distribution-isnt-good-enough/" rel="nofollow">blog post</a> explaining why the numbers above are not as close to 1.96 as you might expect.</p>
|
What's the optimal GZIP compression setting for IIS? <p>You can set the HcDynamicCompressionLevel anywhere from 0-10. I've heard 10 is bad (high CPU usage), but what's the magic number that works the best? </p>
| <p>10 was bad when CPUs were two orders of magnitude slower than they are now. The gzip algorithm is pretty fast as far as compression algorithms go these days, so I'd set it to 10 and see what happens.</p>
|
Using varchar instead of date field types in MySQL <p>Is there any reason to use a varchar field instead of a date field in MySQL? I'm looking at an existing site and I see the developer has done this. Is there any reason to?</p>
| <p>Unless it really <em>is</em> acting primarily as a stringâââsay, it wants to preserve date formatting style, locale-named months, named timezones etc. and doesn't care about being computableâââno, varchar would not be a good choice.</p>
<p>Handling real date datatypes can be problematic/non-portable across different DBMSs/data access layers, but the usual solution to that is just to use an integer (Unix-style) timestamp instead.</p>
|
Easiest way to sort DOM nodes? <p>If I have a list like this:</p>
<pre><code><ul id="mylist">
<li id="list-item1">text 1</li>
<li id="list-item2">text 2</li>
<li id="list-item3">text 3</li>
<li id="list-item4">text 4</li>
</ul>
</code></pre>
<p>What's the easiest way to re-arrange the DOM nodes to my preference? (This needs to happen automatically when the page loads, the list-order preference is gained from a cookie)</p>
<p>E.g.</p>
<pre><code><ul id="mylist">
<li id="list-item3">text 3</li>
<li id="list-item4">text 4</li>
<li id="list-item2">text 2</li>
<li id="list-item1">text 1</li>
</ul>
</code></pre>
| <p>Though there's probably an easier way to do this using a JS Library, here's a working solution using vanilla js.</p>
<pre><code>var list = document.getElementById('mylist');
var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
itemsArr.push(items[i]);
}
}
itemsArr.sort(function(a, b) {
return a.innerHTML == b.innerHTML
? 0
: (a.innerHTML > b.innerHTML ? 1 : -1);
});
for (i = 0; i < itemsArr.length; ++i) {
list.appendChild(itemsArr[i]);
}
</code></pre>
|
How do I create a list control with Rich text in FLEX? <p>I am a FLEX newbie, trying to port a Javascript-based prototype into FLEX. One thing my original prototype had was an unordered list (ul) which had list items that had rich text inside it, i.e. I had a mix of differently styled and colored text and some images inside each item. I looked at the List control for FLEX and it only supports displaying a simple string and an icon. How would I go about making a rich text capable list control?</p>
| <p>No help yet? I founded it. It's called ItemRenderers <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=cellrenderer_1.html" rel="nofollow">http://livedocs.adobe.com/flex/3/html/help.html?content=cellrenderer_1.html</a></p>
<p>Much like the renders in Java Swing.</p>
|
ld: duplicate symbol <p>I'm working on a school project and I'm getting some weird errors from Xcode. I'm using TextMate's Command+R function to compile the project. Compilation seems to work okay but linking fails with an error message I don't understand. </p>
<p>ld output:</p>
<blockquote>
<p>ld: duplicate symbol text_field(std::basic_istream >&)in /path/final/build/final.build/Release/final.build/Objects-normal/ppc/generics.o and /path/final/build/final.build/Release/final.build/Objects-normal/ppc/main.o
collect2: ld returned 1 exit status</p>
</blockquote>
<p>Below is my file io_functions.cpp This is the only declaration of text_field in the entire project. </p>
<pre><code>#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
#ifndef ENDF
#define ENDF '|'
#define ENDR '\n'
/**
reads one field from a given input stream
Usage: var = text_field(in)
*/
string text_field(istream &in){
string s;
getline(in, s, ENDF);
return s;
}
long long_field(istream &in){
return atol(text_field(in).c_str());
}
int int_field(istream &in){
return atoi(text_field(in).c_str());
}
double double_field(istream &in){
return atof(text_field(in).c_str());
}
#endif
</code></pre>
<p>What is going wrong? For a number of reasons I don't want to post my project's entire source. </p>
| <p>My first thought was that you're including it twice on the linker command but it appears to be complaining about having the same function in <code>main.o</code> and <code>generics.o</code>.</p>
<p>So it looks like you're including the <code>io_functions.cpp</code> file into the <code>main.cpp</code> and <code>generics.cpp</code> which is a bad idea at the best of times.</p>
<p>You should have a header file (e.g., <code>io_functions.h</code>) that specifies everything contained in <code>io_functions.cpp</code> and include that <em>header</em> file into the other two.</p>
|
How to find whether a Windows user belongs to specified group? <p>Currently we have a DLL that checks whether a username/password is a valid Windows user using the Windows API LogonUser method. We need to enhance it so it checks whether the user belongs to a specified group as well. Is there a Windows method that does that?</p>
<p>Given a Windows username and password, find out whether the user belongs to a specified group.</p>
| <p>you can use "NetUserGetLocalGroups" function in netapi32.dll to get all groups a given user belongs to and then check if specified group name exists in groups name returned by function. you can find function usage <a href="http://www.pinvoke.net/default.aspx/netapi32/NetUserGetLocalGroups.html" rel="nofollow">here</a></p>
|
C++ odd compile error: error: changes meaning of "Object" from class "Object" <p>I don't even know where to go with this. Google wasn't very helpful. As with my previous question. I'm using TextMate's Command+R to compile the project. </p>
<blockquote>
<p>game.h:16:error: declaration of âPlayer* HalfSet::Player() constâ</p>
<p>players.h:11:error: changes meaning of âPlayerâ from âclass Playerâ</p>
<p>game.h:21:error: âPlayerâ is not a type</p>
</blockquote>
<p>player.h file (partial)</p>
<pre><code>#ifndef PLAYERS_H
#define PLAYERS_H
using namespace std;
#include <string>
#include <vector>
#include <istream>
#include <iomanip>
#include "generics.h"
class Player{ //Line 11
public:
//getters
long Id() const;
string FirstName() const;
string LastName() const;
string Country() const;
//setters
void setId(long id);
void setFirstName(string s);
void setLastName(string s);
void setCountry(string s);
//serializing functions
void display(ostream &out);
void read(istream &in);
void write(ostream &out);
//Initalizers
Player();
Player(istream &in);
Player(string firstName, string lastName);
Player(string firstName, string lastName, string country);
Player(long id, string firstName, string lastName, string country);
~Player();
private:
long _id;
string _firstName;
string _lastName;
string _country;
};
</code></pre>
<p>game.h file (partial)</p>
<pre><code>#ifndef GAME_H
#define GAME_H
#include "generics.h"
#include "players.h"
#include <string>
#include <vector>
#include <istream>
#include <iomanip>
using namespace std;
class HalfSet{
public:
//getters
Player* Player() const; //Line 16
int GamesWon() const;
int TotalPoints() const;
int Errors() const;
//setters
void setPlayer(Player* p);
void setGamesWon(int games);
void setTotalPoints(int points);
void setErrors(int errors);
//Serialization
void display(ostream &out) const;
void read(istream &in) const;
void write(ostream &out) const;
//Initalizers
HalfSet();
~HalfSet();
private:
Player* _player;
int _gamesWon;
int _points;
int _errors;
};
</code></pre>
<p>What is going on here?</p>
| <p>In C++ you cannot name a function the same name as a class/struct/typedef. You have a class named "Player" and so the HalfSet class has a function named "Player" ("Player *Player()"). You need to rename one of these (probably changing HalfSet's Player() to getPlayer() or somesuch).</p>
|
Looking for VB.NET open source projects to learn from <p>I'm looking for some small, vb.net open source projects that make good use of unit testing. Similar to <a href="http://stackoverflow.com/questions/236156/could-you-recommend-any-open-source-projects-where-the-source-is-extensively-te">this</a> question, but for VB.NET. </p>
<p>"I would like to improve my unit-testing skills by reading, examining real-world code. Could you recommend any open source projects where the source is extensively tested with unit tests?"</p>
<p>Thanks!</p>
<p>UPDATE: Also asked the question for C# <a href="http://stackoverflow.com/questions/287646/looking-for-small-open-source-c-project-with-extensive-unit-testing">here</a></p>
| <p>For some reason there are not too many VB.NET OSS projects (compared to C#). A good one you can look at however is <a href="http://cthru.codeplex.com/" rel="nofollow">SilverUnit</a>, a testing framework for Silverlight written in VB.NET</p>
|
Is there any popup editor function in iphone? <p>I'd like to popup a simple dialog with an editor box, to let user enter some value then just return. I am wondering whether iPhone SDK has that kind of support.</p>
<p>Thanks.</p>
| <p>I found a solution at :
<a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/1704-uitextfield-inside-uialertview.html" rel="nofollow">http://www.iphonedevsdk.com/forum/iphone-sdk-development/1704-uitextfield-inside-uialertview.html</a></p>
<p>Here is the code which works for me. </p>
<pre><code>UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Your title here" message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 130.0);
[myAlertView setTransform:myTransform];
[myTextField setBackgroundColor:[UIColor whiteColor]];
[myAlertView addSubview:myTextField];
[myAlertView show];
[myAlertView release];
</code></pre>
|
Assign default value to a datacolumn in a select statement <p>I want to assign default values to a column in my select sql query so that if the value of that column is null I get that default value in my recordset. Is there anyway to do this?</p>
<p>Example:</p>
<pre><code>select col1 (some default value) from tblname;
</code></pre>
| <p>The preferable way is to use ANSI compatible function <a href="http://msdn.microsoft.com/en-us/library/ms190349.aspx">COALESCE</a>:</p>
<pre><code>SELECT COALESCE(column_name, default_value) FROM table_name;
</code></pre>
<p>You also could read <a href="http://databases.aspfaq.com/database/coalesce-vs-isnull-sql.html">an article</a> which compares COALESCE and <a href="http://msdn.microsoft.com/ru-ru/library/ms184325.aspx">ISNULL</a>.</p>
|
ASP.NET MVC UpdateModel with a sorta complex data entry field <p>how do i do the following, with an ASP.NET MVC UpdateModel? I'm trying to read in a space delimeted textbox data (exactly like the TAGS textbox in a new StackOverflow question, such as this) into the model.</p>
<p>eg.</p>
<pre><code><input type="Tags" type="text" id="Tags" name="Tags"/>
...
public class Question
{
public string Title { get; set; }
public string Body { get; set; }
public LazyList<string> Tags { get; set; }
}
....
var question = new Question();
this.UpdateModel(question, new [] { "Title", "Body", "Tags" });
</code></pre>
<p>the Tags property does get instantiated, but it contains only one item, which is the entire data that was entered into the Tags input field. If i want to have a single item in the List (based upon Splitting the string via space) .. what's the best practice do handle this, please?</p>
<p>cheers!</p>
| <p>What you need to do is extend the DefaultValueProvider into your own. In your value provider extend GetValue(name) to split the tags and load into your LazyList. You will also need to change your call to UpdateModel: </p>
<pre><code>UpdateModel(q, new[] { "Title", "Body", "Tags" },
new QuestionValueProvider(this.ControllerContext));
</code></pre>
<p>The QuestionValueProvider I wrote is:</p>
<pre><code> public class QuestionValueProvider : DefaultValueProvider
{
public QuestionValueProvider(ControllerContext controllerContext)
: base(controllerContext)
{
}
public override ValueProviderResult GetValue(string name)
{
ValueProviderResult value = base.GetValue(name);
if (name == "Tags")
{
List<string> tags = new List<string>();
string[] splits = value.AttemptedValue.Split(' ');
foreach (string t in splits)
tags.Add(t);
value = new ValueProviderResult(tags, null, value.Culture);
}
return value;
}
}
</code></pre>
<p>Hope this helps</p>
|
Is there a way to put aspx files into a class library in Visual Studio 2008 .NET 3.5? <p>I've got a lot of pages in my site, I'm trying to think of a nice way to separate these into areas that are a little more isolated than just simple directories under my base web project. Is there a way to put my web forms into a separate class library? If so, how is it done?</p>
<p>Thanks in advance.</p>
| <p>At first thought, I don't think this is possible, due to the way ASPX is non-precompiled..</p>
<p>However, you can create classes that inherit from <code>Page</code> and place them into a DLL to re-use code-behind functionality. This can of course include control instantiate logic if required, but there is no designer to work with (if you need it).</p>
|
Asp.net Date Binding Issue with Nulls <p>I have a nullable date in my database. I am connecting to it with a LinqDataSource, and binding with a FormView. It allows you to place dates fine, but if you remove the date I need it to insert the null value to the db. It is instead throwing an exception.</p>
<pre><code><asp:TextBox ID="TxtStartDate" runat="server"
Text='<%# Bind("StartDate", "{0:MM/dd/yyyy}") %>' />
</code></pre>
<p>Works fine if you place a date in it, but if you delete the date out of it and save, you get System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. How do I make it send null?</p>
| <p>I don't know if it was the best way, but I fixed it by subscribing to the FormView Updating event and placed the following code:</p>
<pre><code>object o = e.NewValues["StartDate"];
if (o.ToString() == "")
e.NewValues["StartDate"] = null;
</code></pre>
|
Advice on which language/Framework to choose for web application? <p>I am a c++ developer trying to create a web application using a language or framework that meets the following criteria:</p>
<ol>
<li>Very fast development time</li>
<li>Text searching and other text manipulation</li>
<li>Easy to configure and maintain the application</li>
<li>Tagging system support</li>
<li>Free (as in Beer) IDE</li>
<li>3-4 weekend project</li>
</ol>
<p>Can anyone suggest a language or framework that would be beneficial, giving this criteria?</p>
| <p>I'll go ahead and put the word in for <a href="http://www.djangoproject.com/" rel="nofollow">django</a>.</p>
<p>Which is sometimes called python's answer to rails.<br />
I've recently had the chance to do some ruby programming and if your coming in new to either language I think ruby or python are pretty easy to step into.</p>
<p>Whatever you pick make sure the tools are well documented.
I haven't looked into rails and ruby enough to be familiar with the documentation available, but I've been pretty impressed with the django and python documentation available.</p>
<p><a href="http://www.djangoproject.com/" rel="nofollow">http://www.djangoproject.com/</a></p>
<p><a href="http://www.djangoproject.com/" rel="nofollow">http://docs.python.com</a></p>
<p>Here's a site that lists sites in django, so you can check out what type of sites people are making using django.</p>
<p><a href="http://www.djangosites.org/" rel="nofollow">http://www.djangosites.org/</a></p>
|
how to combine a template from other processed templates? <p>I have a django project pro1 with several apps: app1, app2, app3 and so on. I want to display some top level template that contains blocks from each and every app:</p>
<p>example_base_template.html:</p>
<pre><code>[header /]
[left nav bar]{{ app1 rendered template }}[/left nav bar]
[right nav bar]{{ app2 rendered template }}[/right nav bar]
[center section]{{ app1 main functionality template }}[/center section]
[footer]{{ app3 rendered template }}{{ app4 rendered template }}[/footer]
</code></pre>
<p>All those app templates are dynamic, that use DB. How to do that in the most proper and elegant way? Or maybe the question is how to connect 4 different views to one URL?</p>
| <p>You can use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#include" rel="nofollow">{% include %}</a> tag. But It doesn't help you a lot. The better solution is to write custom <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags" rel="nofollow">inclusion tag</a> with needed template and functionality.</p>
<p>You cannot (in simple way) mix several views into one. Try tags its pretty django solution.</p>
|
Is there a specification of the group leader protocol that handles IO? <p>In Erlang, every process has a group leader, and when a process wants to print something (i.e. it calls the io library or does something similar), it will send a message to its group leader.</p>
<p>My question is, where can I find the specification of these messages? Or in general, the specification of what a group leader should do?</p>
<p>I managed to find out with some experimenting that sometimes the process sends an <code>{io_request, Sender, GroupLeader, Request}</code> term, and the answer is an <code>{io_reply, GroupLeader, ok}</code> term, but there may be other cases.</p>
| <p><a href="https://erlangcentral.org/erlang-rationale-2/" rel="nofollow">The Erlang Rationale (video)</a> or <a href="http://www.erlang-factory.com/upload/presentations/329/EFKR10-ErlangRationale.pdf" rel="nofollow">(slides)</a>; is a good source of information, as is the source code for <a href="http://github.com/mfoemmel/erlang-otp/tree/master/lib/kernel/src/user.erl#L182" rel="nofollow">user.erl</a>.</p>
<p>In short:</p>
<pre><code> {io_request, From, ReplyAs, Request}
%From is the process to send the reply to,
%ReplyAs is any term the caller desires to
%match up the request and the response. (returned verbatim in the reply)
{io_reply, ReplyAs, Reply}
</code></pre>
<p>Some requests in user.erl:</p>
<pre><code> {put_chars, IoList} % puts the iolist
{put_chars, M,F,A} % puts the result of apply(M,F,A)
{get_geometry, 'rows' | 'columns'} % returns the number of rows or columns of the console
{get_line, Prompt} % calls io_lib:collect_line(Prompt)
{get_chars, Prompt, Mod, Func, ExtraArgs}
{get_until, Prompt, Mod, Func, Args}
{setopts, Options} % only option supported by user is 'binary'
% (binary mode if present in Options, list mode otherwise)
</code></pre>
|
How do you organise your STL headers? <p>I am working on a large project that uses the STL and have a question about your preferred way to organise your STL <code>#includes</code>.</p>
<ul>
<li>Do you prefer to #include each header in the source file it is used. For example, if both <code>foo.cpp</code> and <code>bar.cpp</code> require <code>std::string</code>, then both will <code>#include <string></code>.</li>
<li>Do you prefer to have a single header file that includes all the STL headers your project uses (i.e. add them to the MS 'stdafx.h' pre-compiled header).</li>
</ul>
<p>The advantage of the first method is that the .cpp file is an independent unit and can be used in a different project without having to worry that you're missing a <code>#include</code>. The advantages of the second method is that you can take use your compilers pre-compiled header support plus you can wrap STL <code>#includes</code> in <code>pragmas</code> that disable some warnings (for example, some Boost headers will cause warnings when compiling at level 4).</p>
<p>Which do you prefer to use?</p>
| <p>I only include the header files that are really needed in every source, and not 'catch all' headers, to keep dependencies (and hence compile times) as low as possible.</p>
<p>Precompiled headers can work irrespective of this (i.e. I rely on precompiled headers to speed up the compiling process, not to get declarations). So even if something gets declared via the included precompiled headers, I still include the 'regular' header, which will get skipped by the include guard mechanism and won't add anything significant to the compile times.</p>
<p>As precompiled headers are a compiler specific thing. Optimizing / changing precompiled headers should have no effect on the correct functioning of the code in my opinion. </p>
<p>The main advantage of having dependencies as low as possible is that refactoring gets easier (or rather: feasible)</p>
<p>Great book on all this is <a href="http://rads.stackoverflow.com/amzn/click/0201633620" rel="nofollow">Large Scale C++ Design from Lakos</a></p>
|
ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified <p>While connecting .net to sybase server I got this error message:</p>
<blockquote>
<p>[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified</p>
</blockquote>
<p>This has worked properly before. System DSN with same details work and data connection through vs.net also work.</p>
<p>I am using vs.net 2005.</p>
<p>Any suggestions?</p>
| <p>If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:</p>
<pre><code>%windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows)
</code></pre>
<p>When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.</p>
|
IAutomationObject not found when running Flex application <p>i get the following error when trying to run a flex application (which has been working fine!). I was playing around with some different setttings trying to optimize the compiled size. I've put these settings back to the defaults as much as I thought but still getting issues.</p>
<p>I remember getting this error before but cant seem to remember how I fixed it - nor any useful information about how to fix it again! </p>
<p>Anybody know?</p>
<p>VerifyError: Error #1014: Class IAutomationObject could not be found.</p>
<pre><code>at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/deferredNextFrame()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:299]
at mx.managers::SystemManager/preloader_initProgressHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:2225]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\preloaders\Preloader.as:398]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
</code></pre>
| <p>I haven't encountered this, but here are some suggestions on things I would try:</p>
<ul>
<li>Did you exclude any classes in the compiler settings?</li>
<li>If you're using Flex Builder, try doing a clean (Project > Clean...).</li>
<li>If that doesn't help, remove all eclipse and flex builder files from your project and create a new project that points to your existing sources.</li>
</ul>
|
How to build native Mac OS X installer (on a non-Mac platform)? <p>How can I build a native Mac OS X installer for my application, on a non-Mac platform?</p>
<p>For example, I have a windows pc and a Java application. I want the windows pc to build an installer (possibly inside a .dmg archive) that works with Apple installer.</p>
| <p>It is now possible to create a native Mac OS X installer on a non-Mac platform. As Louis Gerbarg, the tricky bit is the BOM (bill-of-materials) file. However an open source version of mkbom (based on the osxbom code by Joseph Coffland) is now available at:</p>
<p><a href="http://hogliux.github.io/bomutils" rel="nofollow">http://hogliux.github.io/bomutils</a></p>
<p>The website also has an easy to follow step-by-step tutorial on creating a Mac OS X installer on Linux ( <a href="http://hogliux.github.io/bomutils/tutorial.html" rel="nofollow">http://hogliux.github.io/bomutils/tutorial.html</a> ).</p>
<p>My company regularly build Mac OS X installers on linux with this method and so far we haven't had any major problems.</p>
|
MSI packaging guidance <p>We're in the process of packaging combinations of our products/modules. Some of them are stand-alone some are interdependent. All versions must be deployable side-by-side. As it is we're considering two choices:</p>
<ol>
<li>One MSI per package and version</li>
<li>One MSI per product/module and version</li>
</ol>
<p>The first alternative would mean that combinations of the same merge modules would be delivered in several packages. The second alternative represents the simpler path.</p>
<p>Can you give some advice on the subject? Will any of the alternatives cause grief in the longer run?</p>
| <p>If you install the same component twice, Windows Installer will just reference-count the first installation, so there's not much in the way of difference between the two. If you're already separating your components into merge modules, you're guaranteed that the components will share their GUIDs, and you will get this behaviour, and the sharing of components won't cause you any problems.</p>
<p>If you make lots of little MSIs, though, such that a "package" installation will require several MSIs, you will lose the Windows Installer transactional capability - a failed installation won't roll back the previous installation - and you will probably have to look at a "chainer" application. I generally try to make as few MSIs as possible.</p>
|
Zend framework; Getting controller to use different viewer <p>I am using the Zend Framework.</p>
<p>I have a controller named 'UserController' that has a public function displayAction().</p>
<p>I would like to know how I can get that action method to use a different viewer than the default display.phtml.</p>
<p>Any help is appreciated.</p>
| <p>You can use </p>
<pre><code>$this->render('actionName');
</code></pre>
<p>or, alternatively, you can call a view script directly by calling</p>
<pre><code>$this->renderScript('path/to/viewscript.phtml');
</code></pre>
<p>For more information, you can take a look at <a href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html">http://framework.zend.com/manual/en/zend.controller.actionhelpers.html</a>, specifically the parts about the <code>render()</code> and <code>renderScript()</code> methods.</p>
|
Acegi Security: How do i add another GrantedAuthority to Authentication to anonymous user <p>i give users special URL with access key in it. users accessing the public page via this special url should be able to see some additional data as compared to simple anonymous user. </p>
<p>i want to give some additional role to anonymous user based on parameters provided in request so i can do something like this in my template:</p>
<pre><code><@sec.authorize ifAnyGranted="ROLE_ADMIN, ROLE_USER, ROLE_INVITED_VISITOR">
...some additional stuff for invited user to see
</@sec.authorize>
</code></pre>
<p>currently i'm implementing Spring's <code>OncePerRequestfilter</code>:</p>
<pre class="lang-java prettyprint-override"><code>protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
if (null != request.getParameter("accessKey")) {
if(isValid(request.getParameter("accessKey"))) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//how do i add additional roles to authenticated (potentially anonymous) user?
}
}
}
</code></pre>
| <p>Why not just create a wrapper class that delegates to the original, but adds on a couple of extra GrantedAuthorities:</p>
<pre class="lang-java prettyprint-override"><code>public class AuthenticationWrapper implements Authentication
{
private Authentication original;
private GrantedAuthority[] extraRoles;
public AuthenticationWrapper( Authentication original, GrantedAuthority[] extraRoles )
{
this.original = original;
this.extraRoles = extraRoles;
}
public GrantedAuthority[] getAuthorities()
{
GrantedAuthority[] originalRoles = original.getAuthorities();
GrantedAuthority[] roles = new GrantedAuthority[originalRoles.length + extraRoles.length];
System.arraycopy( originalRoles, 0, roles, 0, originalRoles.length );
System.arraycopy( extraRoles, 0, roles, originalRoles.length, extraRoles.length );
return roles;
}
public String getName() { return original.getName(); }
public Object getCredentials() { return original.getCredentials(); }
public Object getDetails() { return original.getDetails(); }
public Object getPrincipal() { return original.getPrincipal(); }
public boolean isAuthenticated() { return original.isAuthenticated(); }
public void setAuthenticated( boolean isAuthenticated ) throws IllegalArgumentException
{
original.setAuthenticated( isAuthenticated );
}
}
</code></pre>
<p>and then do this in your filter:</p>
<pre class="lang-java prettyprint-override"><code>Authentication auth = SecurityContextHolder.getContext().getAuthentication();
GrantedAuthority extraRoles = new GrantedAuthority[2];
extraRoles[0] = new GrantedAuthorityImpl( "Role X" );
extraRoles[1] = new GrantedAuthorityImpl( "Role Y" );
AuthenticationWrapper wrapper = new AuthenticationWrapper( auth, extraRoles );
SecurityContextHolder.getContext().setAuthentication( wrapper );
</code></pre>
<p>The Authentication is now replaced by your version with the extra roles. NB You may have to handle the case where the Authentication has not yet been authenticated and so its getAuthorities() returns null. (The wrapper implementation currently assumes that it will always get a non-null array from its wrapped Authentication)</p>
|
Include another MSI file in my setup project <p>I'm trying to make a setup program for an ASP.NET web site. I need to make sure the target machine has sqlxml installed.</p>
<p>I must verify the target machine has the software installed, and if not, launch a .msi file either before or after the main installation.</p>
<p>I'm a complete newbie with setup projects, so maybe this is obvious, but after several hours browsing the web I haven't found a satisfactory solution. I've been reading about <a href="http://en.wikipedia.org/wiki/WiX" rel="nofollow">WiX</a>, etc. but I'm looking (if possible) for a simple solution.</p>
<hr>
<p>Thank you both!</p>
<p>I understand an installer can't run another one. I was thinking in a functionality similar to Prerequisites (in project properties). There I can check a component and it will be automatically installed if it isn't. I don't need to do anything else. But, the most important thing for me is that the installation won't run if it's not needed.</p>
<p>I also tried the .msm solution, but I couldn't find any. Maybe I can make one myself? I haven't tried it yet though.</p>
| <p>Unfortunately, you can't run one installer from another, since only one can be running at a time. You need to chain them together and run one after the other. Google "msi chaining". This is often the reason why products like Visual Studio use an external setup.exe which then runs the installers one after the other.</p>
|
Using foreach (...) syntax while also incrementing an index variable inside the loop <p>When looking at C# code, I often see patterns like this:</p>
<pre><code>DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];
int i = 0;
foreach (DataType item in items)
{
// Do some stuff with item, then finally
itemProps[i] = item.Prop;
i++;
}
</code></pre>
<p>The for-loop iterates over the objects in <code>items</code>, but also keeping a counter (<code>i</code>) for iterating over <code>itemProps</code> as well. I personally don't like this extra <code>i</code> hanging around, and instead would probably do something like:</p>
<pre><code>DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];
for (int i = 0; i < items.Length; i++)
{
// Do some stuff with items[i], then finally
itemProps[i] = items[i].Prop;
}
</code></pre>
<p>Is there perhaps some benfit to the first approach I'm not aware of? Is this a result of everybody trying to use that fancy <code>foreach (...)</code> syntax? I'm interested in your opinions on this.</p>
| <p>If you are using C# 3.0 that will be better;</p>
<pre><code>OtherDataType[] itemProps = items.Select(i=>i.Prop).ToArray();
</code></pre>
|
Transforming selected text with a hotkey <p>I have this code:</p>
<p>myVariable</p>
<p>which I want to change into</p>
<p>trace("myVariable: " + myVariable);</p>
<p>using a direct hotkey like <kbd>alt</kbd> - <kbd>f12</kbd> to do it. I.e not using <kbd>ctrl</kbd> - <kbd>space</kbd> and arrow buttons.</p>
<p>is it possible in eclipse?</p>
| <p>I don't know if it's possible to bind hotkeys for templates. One way for somewhat similar behavior could be using proper template name and "insert automatically".. </p>
<p>That is, you would write <em>trcc</em> (for example) and Eclipse would automatically expand it to a template <em>trace("${name}: " + ${name});</em> (and you would end up editing the name). The drawback is that you should choose such a name that you won't use it otherwise in the code. (So if you would end up writing trcc for other things, you should choose another name)</p>
<p>Regarding to the templates, <a href="http://homepage.mac.com/kelleherk/iblog/C1281128591/E20070302212710/index.html" rel="nofollow">one blog entry on them</a>. (Note the ${enclosing_type} and ${enclosing_method} if you're not familiar with them already)</p>
|
Using Volume Shadow Copy Service (VSS) in Delphi <p>Does anyone have sample code to copy open (in-use and locked by another program) files using Volume Shadow Copy Service (VSS) API?</p>
<p>There was an article about this in The Delphi Magazine (September 2005). But that code is no longer available and even if it was, it's not current.</p>
<p>I am looking for sample code that works with current version of Volume Shadow Copy service libraries.</p>
| <p>there is a digital edition on usb stick of the "The Delphi Magazine".
you can order that on their webpage.</p>
<p>maybe someone has created a torrent of that stick.</p>
<p><strong>update</strong></p>
<p><strike>i found that sample here:
<a href="http://www.google.com/codesearch/p?hl=de#XIdFp1PskBE/VSS/VssAPI.pas" rel="nofollow">http://www.google.com/codesearch/p?hl=de#XIdFp1PskBE/VSS/VssAPI.pas</a></strike></p>
<p>Upper link is outdated, the header-files can also found here:
<a href="http://www.delphipraxis.net/998560-post3.html" rel="nofollow">http://www.delphipraxis.net/998560-post3.html</a></p>
|
How to redirect to the requested URI after authentication using Zend_Auth? <p>I am using a simple <a href="http://framework.zend.com/manual/en/zend.auth.html">Zend_Auth</a> setup to authenticate users for one of my applications, using a check in the preDispatch() method in a <a href="http://framework.zend.com/manual/en/zend.controller.plugins.html">controller plugin</a>. When anonymous users navigate to </p>
<pre><code>/users/view/id/6
</code></pre>
<p>for example, they should be redirected to the above URI after authentication.</p>
<p>What is the best way to do this? I'd prefer not to store <code>$_SERVER['REQUEST_URI']</code> in the session. Personally, I'd find storing the entire Zend Request object to cleanest solution, but I am not sure if this is sensible and if this is the approach I should be taking.</p>
<p>Any thoughts?</p>
| <p>We had the same problem and actually did store request URI in session variable.
If you don't put any specific, unserializable object into Zend Request, I think it also will be ok to persist it. </p>
<p>However it depends on what throughput you're expecting. Serializing objects like Zend Request may not be the best idea if you have a high traffic website. </p>
|
Building my first ASP application <p>I've just been tasked with building a web application using ASP (.net) and am looking for some advice on where to start. In a nutshell the application needs to be able to.</p>
<ul>
<li>Handle user verification / authentication</li>
<li>Handle sessions</li>
<li>Do SOAP messaging</li>
</ul>
<p>The application is intended to act as a front end for system functions that are accessible via web service calls.</p>
<p>I intend to do a lot of work on the client side using JavaScript and am thinking of using ASP solely as the framework for the 3 items I listed above.</p>
<p>Appreciate any suggestions you may have.</p>
| <p>Use Visual Studio 2008 if you can. Its support for Ajax client libraries and javascript intellisense is very good. (Check out the <a href="http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx" rel="nofollow">jQuery add in</a>) </p>
<p>ASP.NET has built in Login controls (and the membership services mentioned by ChrisE), and also has Forms Authentication. Try to leverage these existing components and avoid using session to store user specific objects/data.</p>
<p>---session rant</p>
<p><em>Its sometimes unavoidable, but you should avoid it whenever you can. It incurs a burden on the webserver for each user, and that leads to some very difficult scaling problems. The FormsAuthentication Ticket has a value property that you can store about 4K worth of user data in - try to use that instead.</em> </p>
<p>---End session rant </p>
<p>Try to use a MVC approach (not necessarily an <a href="http://www.asp.net/mvc/" rel="nofollow">ASP.NET MVC</a>), but at least one that seperates your presentation / view layer from the data / model layer. </p>
<p>Create a default theme and use it. Most sites will need to have multiple themes later, and refactoring that will be a PIA.</p>
<p>If you need SOAP to interact with Non-.NET services then by all means use it. If you are only connecting to .NET services then look into WCF clients and services. They will give you more flexibility. </p>
<p>If you are doing the client work in javascript, then dont use the update panel. It adds lots of overhead.</p>
<p>Get FireFox + FireBug + YSlow, and IE8 (yeah its beta still). They will help you when dealing with the client end of debugging / styling. </p>
<p>Take a look at the <a href="http://developer.yahoo.com/performance/rules.html" rel="nofollow">rules for website performance</a>, but take these with a grain of salt. They are intended for very large sites, and some of the items may not be applicable (CDN, DNS lookups, Redirects).</p>
|
How to get a ReadOnlyCollection<T> of the Keys in a Dictionary<T, S> <p>My class contains a <code>Dictionary<T, S> dict</code>, and I want to expose a <code>ReadOnlyCollection<T></code> of the keys. How can I do this without copying the <code>Dictionary<T, S>.KeyCollection dict.Keys</code> to an array and then exposing the array as a <code>ReadOnlyCollection</code>? </p>
<p>I want the <code>ReadOnlyCollection</code> to be a proper wrapper, ie. to reflect changes in the underlying Dictionary, and as I understand it copying the collection to an array will not do this (as well as seeming inefficient - I don't actually want a new collection, just to expose the underlying collection of keys...). Any ideas would be much appreciated!</p>
<p>Edit: I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available. </p>
| <p>DrJokepu said that it might be difficult to implement a wrapper for Keys Collection. But, in this particular case, I think the implementation is not so difficult because, as we know, this is a read-only wrapper. </p>
<p>This allows us to ignore some methods that, in other case, would be hard to implement.</p>
<p>Here's a quick implementation of the wrapper for Dictionary.KeyCollection :</p>
<pre><code>class MyListWrapper<T, TValue> : IList<T>
{
private Dictionary<T, TValue>.KeyCollection keys;
public MyListWrapper(Dictionary<T, TValue>.KeyCollection keys)
{
this.keys = keys;
}
#region IList<T> Members
public int IndexOf(T item)
{
if (item == null)
throw new ArgumentNullException();
IEnumerator<T> e = keys.GetEnumerator();
int i = 0;
while (e.MoveNext())
{
if (e.Current.Equals(item))
return i;
i++;
}
throw new Exception("Item not found!");
}
public void Insert(int index, T item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public T this[int index]
{
get
{
IEnumerator<T> e = keys.GetEnumerator();
if (index < 0 || index > keys.Count)
throw new IndexOutOfRangeException();
int i = 0;
while (e.MoveNext() && i != index)
{
i++;
}
return e.Current;
}
set
{
throw new NotImplementedException();
}
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(T item)
{
return keys.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
keys.CopyTo(array, arrayIndex);
}
public int Count
{
get { return keys.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return keys.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return keys.GetEnumerator();
}
#endregion
}
</code></pre>
<p>This might not be the best implementation for these methods :) but it was just for proving that this might be done.</p>
|
NAnt extension function, Project object <p>Is there a way to access the <code>Project</code> object from a NAnt extension function, as can be done from an extension task?</p>
<p>In this example, I want to use the <code>BaseDirectory</code> property inside the <code>Bar</code> function:</p>
<pre><code>[FunctionSet("foo", "Foo")]
public class FooFunctions : FunctionSetBase
{
public FooFunctions(Project project, PropertyDictionary properties)
: base(project, properties)
{
// When does this constructor gets called?
}
[Function("bar")]
public static string Bar(string name)
{
return "Bar!"; // How to get at project.BaseDirectory?
}
}
</code></pre>
<p>I'm new to NAnt extensions, so I don't know if this is even a valid question or if I should approach the problem differently.</p>
| <p>Great question Tom. The abstract base class, <strong>FunctionSetBase</strong>, has a property called <strong>Project</strong> that you can access from the <strong>Bar</strong> function. However, I noticed that the Bar function is declared static, which is not always necessary (but not wrong).</p>
<p>The following should be completely legal in NAnt world: </p>
<pre><code>Function("bar")]
public string Bar(string name)
{
string baseDirectory = Project.BaseDirectory;
return baseDirectory;
}
</code></pre>
<p>Are you seeing any problems?</p>
|
Is Vista Ultimate 64 w/SP1 okay for a development machine? <p>I am updating my rig and I need to make a decision between staying with XP x64 or going to Vista x64. I do very little development, really just building products from my developers. The other 90% of my work is done with Google Apps, Skype, Office, etc...</p>
<p>I want to upgrade to Vista not only because I will have 3x monitors running on DirectX10, but mostly because iTunes isnt' supported on XP x64!</p>
<p>So, my question...</p>
<p>With all the horror stories about Vista, will Vista Ultimate x64 with 8GB RAM be good for my development machine? </p>
<p>If I can't develop on Vista, I can always fire open a VPC to do the development in. No?</p>
<p><strong>EDIT</strong></p>
<p>I am using all Microsoft development tools... </p>
<ul>
<li>VS.NET 2005</li>
<li>VS.NET 2008</li>
<li>VB6</li>
<li>SQL Server 2005/2008</li>
<li>ASP.NET</li>
<li>(.NET 2.0 & .NET 3.0)</li>
</ul>
<p>I'm sure the software will run, I suppose I am not so sure that the OS will be speedy enough, or stable enough. </p>
| <p>I am fine with Vista 64 bits for .net and php.</p>
<p>A lot of conversation about it are already on SO. Here is some important point your might take in consideration <strong>for .Net</strong>:</p>
<ul>
<li><p><a href="http://stackoverflow.com/questions/208985/nunitexe-cannot-work-on-vista-64bits-if-x86-build">Unit Testing with NUnit</a></p></li>
<li><p><a href="http://stackoverflow.com/questions/128352/when-developing-do-you-turn-off-uac-in-vista#128354">UAC with developpement</a></p></li>
<li><p><a href="http://stackoverflow.com/questions/251460/running-visual-studio-2008-x86-on-windows-vista-x64#251500">VS and Vista</a></p></li>
<li><p>A lot more...</p></li>
</ul>
<p>You can develop for X86 on your new X64 machine without problem.</p>
<p>For <strong>PHP</strong> XAMPP work fine, Eclipse work fine too.</p>
|
Iterate though Generic List in C# <pre><code>public class Item
{
private int _rowID;
private Guid _itemGUID;
public Item() { }
public int Rid
{
get
{
return _rowID;
}
set { }
}
public Guid IetmGuid
{
get
{
return _itemGuid;
}
set
{
_itemGuid= value;
}
}
}
</code></pre>
<p>The above is my custom object.</p>
<p>I have a list:</p>
<pre><code>List<V> myList = someMethod;
</code></pre>
<p>where V is of type Item, my object.</p>
<p>I want to iterate and get the properties as such</p>
<pre><code>foreach(V element in mylist)
{
Guid test = element.IetmGuid;
}
</code></pre>
<p>When I debug and look at the 'element' object I can see all the properties in the 'Quickwatch' but I cannot do element.IetmGuid.</p>
| <p>Are you putting a constraint on the generic type V? You'll need to tell the runtime that V can be any type that is a subtype of your <code>Item</code> type.</p>
<pre><code>public class MyGenericClass<V>
where V : Item //This is a constraint that requires type V to be an Item (or subtype)
{
public void DoSomething()
{
List<V> myList = someMethod();
foreach (V element in myList)
{
//This will now work because you've constrained the generic type V
Guid test = element.IetmGuid;
}
}
}
</code></pre>
<p>Note, it only makes sense to use a generic class in this manner if you need to support multiple kinds of Items (represented by subtypes of Item).</p>
|
How to share config settings between mutiple applications <p>I have a project where there are multiple applications that have some common configuration values. I would like to have a shared .config file that is available to all of the applications using the .Net configuration object model. Each application would also have its own app.config file</p>
<p>How can this best be done. I'd rather avoid using the registry as much as possible. In looking through the documentation, the OpenExeConfiguration(string exePath) method seems promising for accessing a specified config file. Is this a reasonable approach? Any other suggestions?</p>
| <p>Some sections in the app.config allow for a reference to an external file.</p>
<pre><code><appSetting configSource="somefile.config"/>
</code></pre>
|
Compact Framework - System.Threading.Timer stops when the user turns off the screen <p>I have an application that needs to "poll" a webservice to see if the user has any new messages waiting. I have no control over the webservice so I cannot switch to a "push" mechanism, I'm stuck making a request every X number of seconds to see what's available.</p>
<p>I am using a System.Threading.Timer to make the request every so often, but am encountering a few problems. The biggest is that it stops running when the phone is sent into "standby" mode (screen off, but still able to get calls and email/txt notifications). </p>
<p>I'd really like it to behave like other background applications. What can I do to make it work without being too big of a drain on the battery?</p>
| <p>Hate to answer my own question, but I was pointed to <a href="http://blog.opennetcf.com/ctacke/PermaLink,guid,169fcc25-a42f-4a8f-b8af-6b6c85d8819d.aspx" rel="nofollow" title="this">this</a>, which was able to perform even when the device is asleep. Looks like it's working perfectly.</p>
|
Infragistics grid "on-demand" appearance <p>We're using Infragistics grid (most probably, we'll have 8.2 version at the end) and we want to configure row/cells appearances "on-demand" in order to be able to provide sort of "dynamic appearance".</p>
<p>For example, I want some cell to be red or green, depending on its value. We might want to tweak other characteristics as well (font, size, image, etc).</p>
<p>A perfect place to do it would be some event, that happen before a cell gets repainted... But it seems there is no such event in Infragistics...</p>
<p>Or am I wrong? Any help?</p>
<p><strong>Clarification:</strong> I'm talking about WinForms Infragistics UltraGrid</p>
| <p>I had to do exactly this with the IG WebGrid a few years back, and it was ... shall we say ... painful. However, the WebGrid had the advantage of a single render point -- once the HTML was emitted, we were set!</p>
<p>For dealing with this in WinGrid, I tried a variety of different events, both on the grid and the datasource, and met with abject failure every step of the way. The only event I got to work was <code>Paint</code>, which will likely create a performance issue.</p>
<p>For <code>Paint</code>, here's what I hacked together. I'm not proud of this code, and I likely wouldn't put it in production, but here it is anyway (C#):</p>
<pre><code>private void UltraGrid1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
foreach (UltraGridRow r in UltraGrid1.Rows)
{
foreach (UltraGridCell c in r.Cells)
{
if (c.Text == "foo")
c.Appearance.BackColor = Color.Green;
}
}
}
</code></pre>
<p>and VB:</p>
<pre><code>Private Sub UltraGrid1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles UltraGrid1.Paint
For Each r As UltraGridRow In UltraGrid1.Rows
For Each c As UltraGridCell In r.Cells
If c.Text = "foo" Then
c.Appearance.BackColor = Color.Green
End If
Next
Next
End Sub
</code></pre>
|
MOSS SpNavigationNode.Children always empty <p>I'm trying to return all the child nodes of a set of navigation nodes in sharepoint, the SDK implies I should be doing something like this:</p>
<pre><code>NodeColl = objSite.Navigation.TopNavigationBar
Dim Node as SPNavigationNode
For Each Node In NodeColl
if Node.IsVisible then
Response.Write("<siteMapNode url=""" & Node.Url & """ title=""" & Node.Title & """ description=""" & Node.Title & """ >" & Environment.NewLine)
Dim SubChildNodes as SPNavigationNodeCollection = Node.Children
Response.Write(SubChildNodes.Count) 'returns 0 always even though I know theres over 20 nodes in some of the sections
Dim ChildNode as SPNavigationNode
For Each ChildNode in SubChildNodes
if ChildNode.IsVisible then
Response.Write("<siteMapNode url=""" & ChildNode.Url & """ title=""" & ChildNode.Title & """ description=""" & ChildNode.Title & """ />" & Environment.NewLine)
End if
Next
Response.Write("</siteMapNode>" & Environment.NewLine)
End If
Next
</code></pre>
<p>however whenever I do, it lists the top level navigation nodes but I cannot get the children to be displayed.</p>
| <p>I have this same problem, I found the solution as</p>
<pre><code>using (SPSite site = new SPSite("http://server"))
{
using (SPWeb web = site.OpenWeb())
{
SPNavigationNode quicklaunch = web.Navigation.GetNodeById(1025);
if (quicklaunch != null)
{
foreach (SPNavigationNode heading in quicklaunch.Children)
{
PrintNode(heading);
}
}
}
}
static void PrintNode(SPNavigationNode node)
{
foreach (SPNavigationNode item in node.Children)
PrintNode(item);
}
</code></pre>
<p>Make sure you have a <code>SiteMapDataSource</code> associated with your master page quick launch.</p>
|
<assemblyBinding> ignored in parent web.config <p>I have a folder containing several websites, all using the same assemblies in the GAC. Each website also contains some 'custom' assemblies of their own that refer to the common assemblies.</p>
<p>There is a web.config in this folder, defining common settings for the sites, including the assemblies to load in a <strong><em><system.web>/<compilation>/<assemblies></em></strong> element.</p>
<p>What I want to be able to do is add a <strong><em><runtime>/<assemblyBinding></em></strong> section to redirect requests from the older 'custom' assemblies to the newer ones installed in the GAC. (Unfortunately, using machine.config or the GAC redirection policy aren't options as this will affect other sites.)</p>
<p>It seems that the <strong><em><assemblyBinding></em></strong> section is ignored unless it is in the website's own web.config, or the machine.config.</p>
<p>I've already come across the <strong><em><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"></em></strong> problem so I know it's not that.</p>
<p>Does anyone know if this is what is supposed to happen or am I missing something?</p>
| <p>It is supposed to happen. You did nothing wrong. </p>
<p>for more information, please take a look at
<a href="http://msdn.microsoft.com/en-us/library/2fc472t2%28vs.71%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/2fc472t2(vs.71).aspx</a></p>
|
(DataGridView + Binding)How to color line depending of the object binded? <p>I would like to add a backcolor for specific line depending of a Property of the object binded.</p>
<p>The solution I have (and it works) is to use the Event <code>DataBindingComplete</code> but I do not think it's the best solution.</p>
<p>Here is the event:</p>
<pre><code> private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < this.myGrid.Rows.Count; i++)
{
if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
{
this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
}
}
}
</code></pre>
<p>Any other option that would be better?</p>
| <p>You can also attach an event handler to RowPostPaint:</p>
<pre><code>dataGridView1.RowPostPaint += OnRowPostPaint;
void OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;
DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;
// Do whatever you want with style and value
....
}
</code></pre>
|
WindowsPrincipal.IsInRole() not returning the expected result <p>So here's my current code:</p>
<pre><code>List<string> rowGroups = GetFileGroups((int)row.Cells["document_security_type"].Value);
bool found = false;
System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
foreach (string group in rowGroups)
{
if (p.IsInRole(group))
{
found = true;
break;
}
}
</code></pre>
<p>This was done a couple of months ago by someone and I'm having difficulty grasping why its not working. The company has recently just moved from one domain name to another. So I was curious to what domain controller the p.IsInRole("String") function will use. I'm assuming its going to use the default DC by whatever the computer is using.</p>
<p>The odd item is that the computers in the office where this is running could be on 2 seperate domains. In the <code>List<string></code> object, i've got both domains possible. so it could contain items such as "domainA\groupA", "domainA\userB", domainB\groupC", and/or "domainB\userD".</p>
<p>So my major problem is that the IsInRole function is never returning true. i know it should, i even tested it with domainA\Domain users and still get a false returned.</p>
<p>Any ideas? changing the code is possible, but not wanted. i'm not 100% i can even compile it...</p>
| <p>I have to point out, are you actually escaping your '\' character correctly inside your strings? As in "domainA\\groupA"?</p>
|
Is it a bad idea to get rid of the mx: in your Flex code? <p>I am a newbie at Flex, and I don't like the way you have to write the namespace mx: for every control declaration you write. It makes the code cluttery. I would like to write:</p>
<pre><code><Panel ...
</code></pre>
<p>rather than</p>
<pre><code><mx:Panel ...
</code></pre>
<p>I tried writing</p>
<pre><code>xmlns="http://www.adobe.com/2006/mxml"
</code></pre>
<p>for the top level element instead of </p>
<pre><code>xmlns:mx="http://www.adobe.com/2006/mxml"
</code></pre>
<p>In the top level declaration. This work to an extent, but broke some existing code. For one, XML data that are defined in the document are all appended with aaa: as the namespace during runtime. I've also noticed other issues in my very small sample program.</p>
<p>Is there a way to do this that works, or is this a lost cause? And some background information on why would be appreciated.</p>
<p><em>Update: Thanks all for the replies, but I would like to have heard from someone who actually tried this and thought it was important. Although most of you told me it was a bad idea, I was not discouraged. I got a couple of programs working this way smoothly now. And plan to do this in all my flex apps. One trick seemed to work for me although I can't claim it'll work universally. If you need separate namespaces within your doc, take, HTTPService parameters for example, you could create a namespace within that element like so:</em></p>
<pre>
<HTTPService id="service" url="http://blah.com"
method="POST" result="gotResult(event)">
<request xmlns:p="*">
<p:param1>p1</p:param1>
<p:param2>p2</p:param2>
</request>
</HTTPService>
</pre>
<p><em>Hope this helps someone. I am very happy with how clean my code is now, almost as clean as a normal html file. As for people who think writing mx: throughout your code is clearer and what not, I disagree completely. I think languages that require you to repeat the same character sequence excessively in your code - which you should consider a document - have design flaws. Here's an analogy for you: how would you like it if you were reading an article on Barack Obama, and every single sentence contained the words 'Barack Obama', that would get pretty tiresome wouldn't it?</em></p>
| <p>I think that removing the mx namespace will almost certainly cause you trouble with name conflicts as your project gets larger.</p>
<p>Personally I think the mx namespace makes the code clearer rather than more cluttered, especially if you have component based flex development or a lot of your own controls. Having owned a large flex code base for the last two years I find the mx namespace unobtrusive, especially when you have custom objects embedded inline such as item renderers.</p>
<p>My recommendation (unscientifically asserted) is to put up with it, especially if you are finding issues when removing it. I bet you'll stop noticing it after a while.</p>
|
How do I pass a string parameter greater than varchar(8000) in SQL Server 2000? <p>You get a compilation error if you define the string parameter to have a size greater than 8000</p>
<p>e.g. </p>
<pre><code>The size (9000) given to the type 'varchar' exceeds the maximum allowed for any data type (8000).
</code></pre>
<p>Any ideas?</p>
| <p>you need to store it as TEXT instead of varchar for string larger than 8000 in sql 2000</p>
|
How can I insert strings with quotes into Perl DBI queries? <p>What is the preferred way to insert strings that can contain both single and double quotes (",') into MySql using DBI? For example, <code>$val1</code> and <code>$val2</code> can contain quotes:</p>
<pre><code>my $dbh = DBI->connect( ... );
my $sql = "insert into tbl_name(col_one,col_two) values($val1, $val2)";
my $sth = $dbh->prepare($sql);
$sth->execute();
</code></pre>
| <p>Use a bound query using </p>
<pre><code>$sth = $dbh->prepare("insert into tbl_name(col_one,col_two) values(?,?)");
$sth->execute($val1, $val2);
</code></pre>
<p>If you use bound variables, everything is escaped for you.</p>
<p>Update: Changed my example to correspond with the example edited into the question.</p>
<p>Update: I don't know why Adam deleted his answer, but if for some reason you can't use bound variables (aka "placeholders"), you can also use <code>$dbh->quote($var)</code> on the variable. For example:</p>
<pre><code>$sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
$dbh->quote(q("Don't"));
</code></pre>
|
Simple Excel Applescript <p>I am new to Applescripts and Excel 08? I want to write one that colors arbitrarily preselected cells in Excel 08 specific colors. I can get it to write want in an preselected cell and even bold the font...but for some reason it will not change the color of the cell...</p>
<pre><code>print("Tell application "Microsoft Excel"
activate
set formula of active cell to "excellent answer"
set bold of font object of active cell to true
activate cell active cell");
</code></pre>
<p>This part doesn't work for some reason`</p>
<pre><code>print("tell interior object of active cell of active sheet
set color index to 3
set pattern to pattern gray 50
set pattern color index to 13
end tell");
</code></pre>
<p>not sure why</p>
| <p>I was able to set the color of a particular cell in Excel 08 (and 2011 now) using the following AppleScript:</p>
<pre><code>tell sheet "Sheet1" of theWorkbook
set color of interior object of range C2:C2 to {255, 255, 0}
end tell
</code></pre>
<p>I had to specify the color on a particular range and use the Red, Blue, and Green component values (from 0-255).</p>
|
Can MOSS 32 bit and 64 bit exist in the same farm? <p>I am trying to setup a failover location for MOSS. The current farm is built on 32 bit Windows 2003. The servers ar the failover location are all 64 bit Windows 2008.</p>
<p>Is there any way to make these two environments talk and stay in sync? I have considered a "stretched" farm configuration, but that won't work unles the bit width of both locations are the same.</p>
<p>The current database server for MOSS is replicated to our failover location using clustering and is visible at both locations.</p>
| <p>You can mix 32 bits and 64 bits in the same farm, it's fully supported. </p>
<p>However, it's highly recommenced to keep each tiers in the same bit width (for example all WFE 64 bits, application server 32 bits, SQL servers 64 bits).</p>
<p>From msdn @ <a href="http://technet.microsoft.com/en-us/library/cc261700.aspx">http://technet.microsoft.com/en-us/library/cc261700.aspx</a></p>
<blockquote>
<p>You can deploy an Office SharePoint Server 2007 farm on a mix of 32-bit and 64-bit servers, provided that you maintain architecture homogeneity at each topology layer. For example, you should not mix 32-bit and 64-bit Web front-end (WFE) servers, but you may use 64-bit database servers in a farm with 32-bit WFE servers and application servers.</p>
</blockquote>
|
What is the best way to see what files are locked in Subversion? <p>I finally got my group to switch from SourceSafe to Subversion. Unfortunately, my manager still wants to use exclusive locks on every single file. So I set the svn:needs-lock property on every file and created a pre-commit hook to make sure the property stays set.</p>
<p>We are running Subversion on a Linux server. Most of us use Windows machines and a few use Macs. We are using various SVN clients (TortoiseSVN, SmartSVN, Subclipse, etc.). </p>
<p>What we now need is a good/easy method to see all the files that are currently locked in the entire repository (and who has them locked). I have poked around a little in Tortoise and Subclipse, but haven't found what I am looking for. Our projects have many subdirectories that are multiple levels deep, so it would be too time consuming to look at each individual directory. </p>
<p>What I would like is a single report I can run that lists everything that is currently locked and who has it locked. What is the best way to get this type of information?</p>
| <p>What you're looking for is the <a href="http://svnbook.red-bean.com/en/1.8/svn.ref.svnadmin.c.lslocks.html"><code>svnadmin lslocks</code></a> command.</p>
<p>I have this set up at work because we keep some Word documents in our Subversion repository (with <code>svn:needs-lock</code>). I have a cron job set up that every day, checks the list of locks and emails a report of all locks older than 7 days to the whole team. That way we can tell who has been slacking and sitting on a locked copy of a document for a long time.</p>
|
How do you read a byte array from a DataRow in C#? <p>I have a <code>DataSet</code> with a <code>DataTable</code> that correctly fills a single <code>DataRow</code> through a <code>TableAdapter</code>.</p>
<p>I am able to pull data from the DataRow with code like this:</p>
<pre><code>dataFileID = (int)this.dataFileDataRow["DataFileID"];
dataFileName = (string)this.dataFileDataRow["DataFileName"];
dataFileDate = (DateTime)this.dataFileDataRow["DataFileDate"];
</code></pre>
<p>I have another column called DataFile of type <code>varbinary(max)</code>.</p>
<p>When I try to pull that column's data from the same <code>DataRow</code> as above I get nothing.</p>
<pre><code>byte[] fileFromDatabase = (byte[])this.dataFileDataRow["DataFile"];
</code></pre>
<p>If I put a break point at this location, I can look into the dataFileDataRow, look into the ItemArray property and see that the binary data is sitting at position 5 in the ItemArray.</p>
<p>I have tried access the ItemArray directly using its index but the byte array is not being copied to the fileFromDatabase variable. </p>
<p>I have also noticed that adding fileFromDatabase to my watch produces this error: </p>
<blockquote>
<p>"The name 'fileFromDatabase' does not exist in the current context"</p>
</blockquote>
<p>The execution is still in the same block as the definition of fileFromDatabase so I do not understand how it would be out of context.</p>
<p>I had Visual Studio's configuration set to Release instead of Debug. This was causing me to not see the real time debugging information I was looking for when trying to examine fileFromDatabase. After switching from Release to Debug, I am able to see the variable in the watch now and can verify that the code above is working correctly. </p>
| <p>The code above works, make sure you set your debugger to compile for Debug, NOT Release. </p>
<p>Keith</p>
|
Upload large files in .NET <p>I've done a good bit of research to find an upload component for .NET that I can use to upload large files, has a progress bar, and can resume the upload of large files. I've come across some components like <a href="http://ajaxuploader.com">AjaxUploader</a>, <a href="http://krystalware.com/products/slickupload/Default.aspx">SlickUpload</a>, and <a href="http://www.element-it.com/PowUpload.ASPX">PowUpload</a>, to name a few. Each of these options cost money and only PowUpload does the resumable upload, but it does it with a java applet. I'm willing to pay for a component that does those things well, but if I could write it myself that would be best.</p>
<p>I have two questions:</p>
<ol>
<li>Is it possible to resume a file upload on the client without using flash/java/Silverlight?</li>
<li>Does anyone have some code or a link to an article that explains how to write a .NET HTTPHandler that will allow streaming upload and an ajax progress bar?</li>
</ol>
<p>Thank you,<br />
Austin</p>
<p><strong>[Edit]</strong></p>
<p>I realized I do need to be able to do resumable file uploads for my project, any suggestions for components that can do that?</p>
| <blockquote>
<p>1) Is it possible to resume a file upload on the client without using flash/java/Silverlight?</p>
</blockquote>
<p>No. The actual HTTP protocol itself does not support resume of partial uploads, so even if you did use flash or silverlight, you'd still need to use something else like FTP on the server.<br />
I've "solved" this problem in the past by writing a custom client application in C# which broke the file down into small chunks (2meg), transmitted those separately, and then the server combines them all back together.</p>
<blockquote>
<p>2) Does anyone have some code or a link to an article that explains how to write a .NET HTTPHandler that will allow streaming upload and an ajax progress bar?</p>
</blockquote>
<p>While this doesn't solve the 'resume' problem, I've used <a href="http://swfupload.org/">SWFUpload</a> on the client side and it worked brilliantly. It provides a smart file browser (where you can prompt the user for only jpeg files, etc) and upload progress tracking, all without needing to modify your server at all.</p>
|
Open a .BAS DTS Package in SQL 2000? <p>You can save a SQL Server 2000 DTS package as a VB .BAS file. Is is possible to open a .BAS file in SQL Server Enterprise Manager (or some other way) to add the DTS package to the server? Initally, it appears that SQL Server only lets you import .DTS files.</p>
| <p>Actually, it is possible although it's fiddly:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa176248%28SQL.80%29.aspx" rel="nofollow">Running a DTS Package Saved as a Visual Basic File</a></p>
|
Can Boost Spirit be used to parse byte stream data? <p>Can Spirit (part of Boost C++ library) be used to parse out binary data coming from a stream? For example, can it be used to parse data coming from a socket into structures, bytes, and individual bit flags? Thanks!</p>
| <p>Boost Spirit allows for a parser to be defined using <a href="http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form" rel="nofollow">Extended BackusâNaur Form (EBNF)</a> syntax with <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="nofollow">template meta-programming</a>. It is very flexible and uses abstract classes in all phases of the parsing process that can be customized. In order to process a binary data stream, you would need to implement custom scanner classes since the default types are tailored for text input. You can read further in <a href="http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/doc/scanner.html" rel="nofollow">The Scanner and Parsing</a> section of the <a href="http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/index.html" rel="nofollow">Spirit User's Guide</a>.</p>
<p>In my humble opinion, binary data streams are best handled with hand rolled serialization code. Spirit is geared more towards well formed grammars like mark-up or scripting languages. For example, <a href="http://www.lua.org/manual/5.1/manual.html#8" rel="nofollow">The Complete Syntax of Lua</a> is provided in EBNF. So, it might make sense to use Spirit to build a custom parser. On the other hand, a proprietary serial data link with synchronization bytes and CRC bracketing messages would require a lot more work just to define the EBNF if a <a href="http://en.wikipedia.org/wiki/Context-free_grammar" rel="nofollow">context-free grammar</a> even exists for it.</p>
<p><strong>Addendum</strong></p>
<p><a href="http://www.boost.org/doc/libs/1_41_0/libs/spirit/doc/html/spirit/qi/reference/binary.html" rel="nofollow">The latest version of Boost Spirit includes functionality for dealing with binary data.</a></p>
|
Trying to send an HTTP request over sockets <p>I'm having trouble sending out a simple HTTP request using Actionscript 3's Socket() object. My onConnect listener is below:</p>
<pre><code>function sConnect(e:Event):void {
trace('connected');
s.writeUTFBytes('GET /outernet/client/rss/reddit-feeds HTTP/1.1\r\n');
s.writeUTFBytes('Host: 208.43.71.50:8080\r\n');
s.writeUTFBytes('Connection: Keep-alive\r\n');
s.flush();
}
</code></pre>
<p>Using a packet sniffer, I can see the request does indeed get sent to the server, but the packet sniffer doesn't identify the protocol as HTTP like it does with other HTTP services. When I run this, the server just eventually disconnects me. I have tried to connect to other simple Apache Servers and just get a malformed request error.</p>
<p>What am I missing here?</p>
| <p>You have to write another "\r\n" to the stream before the flush to tell the HTTP server that you're finished sending the headers.</p>
|
Converting Plain Text to Clickable link or Link to PlainText in asp.net <p>I need your advice with converting plain text to an URL.</p>
<p>The scenario will be this: The user will select some entry and then click a "convert to link" button. </p>
<p>The entry text the user selected will convert to <code>(link: selected_text)</code>. I do it with JavaScript. And after that, when he clicks the Save button to save all his entry, I don't know how to store <code>(link: selected_text)</code> in tha database.</p>
<p>The URL will be like this: <code>www.mysite.aspx?t=selected_text</code>. </p>
<p>I can convert <code>(link: selected_text)</code> by using replace function in code-behind. But then I don't know how to show user as clickable and also by not showing <code><a href="www.mysite.aspx?t=selected_text"></code></p>
<p>It can be difficult to understand therefore I will show some of my codes to explain.</p>
<pre><code>Private Sub Save(ByVal Entry As String) ' Entry Comes from entry textbox '
Dim elected As String
selected = Entry.Replace("(link: ", "<a href http://www.mysite.com?link=")
selected = Entry.Replace(")", ">")
' then here starts save but not necessary to show '
End Sub
</code></pre>
| <p>If you must save processed input for some reason</p>
<pre><code>(link: here)
</code></pre>
<p>must be converted to</p>
<pre><code>(link: <a href="http://www.mysite.com?t=here">here</a>)
</code></pre>
|
Win32: How to use RegisterTypeLib API from standard user <p>The Win32 API call <a href="http://msdn.microsoft.com/en-us/library/ms221570.aspx" rel="nofollow">RegisterTypeLib()</a> is used to create the registry keys necessary to register a type library.</p>
<p>Unfortunatly, on Windows XP, it tries to write those registry key entries to </p>
<pre><code>HKEY_CLASSES_ROOT\TypeLib
</code></pre>
<p>rather than </p>
<pre><code>HKEY_CURRENT_USER\Software\Classes\TypeLib
</code></pre>
<p>Meaning that a standard user will not be able to run an ActiveX.</p>
<p>In May 2008 Microsoft released a <a href="http://support.microsoft.com/kb/935200" rel="nofollow">hotfix for Vista</a> to correct this issue - but the problem remains on Windows XP.</p>
<p>What's a standard-user friendly developer to do?</p>
<p><hr /></p>
<h2>Answer 1</h2>
<p>Use the API call that is designed for it:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms221504.aspx" rel="nofollow">RegisterTypeLibraryForUser()</a></p>
<h2>Answer 2</h2>
<p>If you can't fix it, hack it:</p>
<pre><code>//begin hack
HKEY key;
RegOpenKeyW(HKEY_CURRENT_USER, @"Software\Classes", out key);
RegOverridePredefKey(HKEY_CLASSES_ROOT, key);
//do original work
RegisterTypeLibrary(...)
//stop hacking
RegOverridePredefKey(HKEY_CLASSES_ROOT, null);
RegCloseKey(key);
</code></pre>
| <p>You can use the <code>RegOverridePredefKey()</code> API to map the <code>HKEY_CLASSES_ROOT</code> regtree to <code>HKEY_CURRENT_USER\Software\Classes</code>:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms724901.aspx"><code>http://msdn.microsoft.com/en-us/library/ms724901.aspx</code></a></li>
</ul>
|
Compact Framework - any implementation of the Image.FromStream (Stream, Boolean, Boolean)? <p>In a .NET CF application I wrote, one of the features is to acquire frames from remote cameras. Frames are acquired as single jpeg images and displayed on the screen when available.</p>
<p>It was a good enough solution, but I don't like the fact that the time needed to convert the stream into an <code>Image</code> object, with the <code>Bitmap()</code> constructor, is <em>far far far larger</em> than the time needed to download the stream.</p>
<p>When I surfed some blogs to search about this issue, I found that some developers were using the <code>Image.FromStream()</code> method which has a <code>validateImageData</code> flag that seems to control some validation code. When <code>validateImageData</code> is false, the conversion gets dramatically faster.</p>
<p>Good, I thought .... but the Compact Framework does not implement this method !</p>
<p>Anyone knows how to get around it, or at least how to convert a stream into an <code>Image</code> without unnecessary delays ?</p>
| <p>If the dimensions of the JPEG are large (like 1200 x 1600 or something), then one of the speed problems you're having on your device with the Bitmap constructor is the size of the Bitmap is has to create in memory (the bitmap would be 1200 x 1600 also, even if it's then displayed on a 240 X 320 screen). If you can retrieve an already-sized JPEG of 320 X 240 instead of a full-sized one, the bitmap creation time should be much less.</p>
<p>I couldn't find any alternatives to the missing FromStream method other than the Bitmap constructor. If you're familiar with the JPEG format, I don't think it would be too hard to write your own JPEG-to-BMP converter, but I'd guess that it wouldn't be faster than Bitmap().</p>
<p>Edit: sorry, I meant your own-rolled converter wouldn't be any faster at converting a 240 X 320 JPEG into a 240 X 320 bitmap. I think it could be made a lot faster at converting a much larger JPEG into a 240 X 320 bitmap because it could skip the step of creating the full-size bitmap first.</p>
|
How to create a 'global event' in actionscript / flex? <p>What is the best way to create a 'global event' in flex/actionscript - preferably using a static class?</p>
<p>I want to raise an event to indicate that a stylesheet is loaded in order to show components that require that stylesheet. So I want each portion of the application that requires a style from the stylesheet to listen to an event telling it that the styles are all loaded.</p>
| <p>Make a <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">Singleton</a> and add listeners to it, nice and simple.</p>
|
Is there any good replacement for SharePoint Designer? <p>If you've ever used SharePoint Designer, you'll know it's bad. Really bad.</p>
<p>Is there any good replacement for that? Is there any consideration I must take account of if I want to build my own Visual Studio Add-in connector to connect to it?</p>
<p>Anything you know that I should be aware of?</p>
<p>I just hate the slowness and the way SPD (SharePoint Designer) just keeps reformating all my stuff.</p>
| <p>You can get the Sharepoint Explorer add-in for Visual Studio which will allow you to browse around sites:</p>
<p><a href="http://blog.thekid.me.uk/archive/2007/10/29/vs-net-developer-add-in-for-sharepoint-available-for-download.aspx" rel="nofollow">http://blog.thekid.me.uk/archive/2007/10/29/vs-net-developer-add-in-for-sharepoint-available-for-download.aspx</a></p>
|
Automatically wrapping I-search? <p>In Vim I can <code>:set wrapscan</code> so that when I do an incremental search, the cursor jumps to the first match whether the first match is above or below the cursor.</p>
<p>In Emacs, if I start a search via <code>C-s</code>, the search fails saying <em>Failing I-search</em> if the first match is above the cursor. If I hit <code>C-s</code> again it then wraps the search, saying <em>Wrapped I-search</em>. How do I wrap and jump the cursor by default as in Vim, without having to <code>C-s</code> a second time?</p>
| <p>The easiest way to do this is to use the following defadvice:</p>
<pre><code>(defadvice isearch-repeat (after isearch-no-fail activate)
(unless isearch-success
(ad-disable-advice 'isearch-repeat 'after 'isearch-no-fail)
(ad-activate 'isearch-repeat)
(isearch-repeat (if isearch-forward 'forward))
(ad-enable-advice 'isearch-repeat 'after 'isearch-no-fail)
(ad-activate 'isearch-repeat)))
</code></pre>
<p>When Isearch fails, it immediately tries again with wrapping. Note that it is important to temporarily disable this defadvice to prevent an infinite loop when there are no matches.</p>
|
Representing Monetary Values in Java <p>I understand that BigDecimal is recommended best practice for representing monetary values in Java. What do you use? Is there a better library that you prefer to use instead?</p>
| <p><code>BigDecimal</code> all the way. I've heard of some folks creating their own <code>Cash</code> or <code>Money</code> classes which encapsulate a cash value with the currency, but under the skin it's still a <code>BigDecimal</code>, probably with <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#ROUND%5FHALF%5FEVEN"><code>BigDecimal.ROUND_HALF_EVEN</code></a> rounding.</p>
<p><strong>Edit:</strong> As Don mentions in <a href="http://stackoverflow.com/questions/285680/representing-monetary-values-in-java#286228">his answer</a>, there are open sourced projects like <a href="http://timeandmoney.sourceforge.net/">timeandmoney</a>, and whilst I applaud them for trying to prevent developers from having to reinvent the wheel, I just don't have enough confidence in a pre-alpha library to use it in a production environment. Besides, if you dig around under the hood, you'll see <a href="http://timeandmoney.svn.sourceforge.net/viewvc/timeandmoney/timeandmoney/trunk/src/main/java/com/domainlanguage/money/Money.java?view=markup">they use <code>BigDecimal</code> too</a>.</p>
|
programatically convert word docx to doc without using ole automation <p>i'm looking for a way to programatically convert word documents in docx format to doc format without using ole automation. i already have a windows service that does this but it means installing office on a server and it is a little unreliable and not supported. i am aware of the aspose.words product, and i will try it out, but has anyone any recommendations for how to do this as simply, reliably, and cheaply as possible?</p>
| <p>One option without using OLE automation would be to wrap the converter dlls coming with compatibility pack in order to convert from docx to doc without automating Office.</p>
<p>This requires only that the Compatibility Pack of Office is installed on the machine.</p>
<p>The Office converter dlls convert from the document format that they support to RTF and/or from RTF to their document format using the interface ForeignToRtf/RtfToForeign. You can chain converters as you wish to convert from one format to another, e.g. to do a conversion DOCX -> RTF -> DOC.</p>
<p>You can get the SDK from Microsoft: <a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B111716&x=16&y=7">http://support.microsoft.com/?scid=kb%3Ben-us%3B111716&x=16&y=7</a> which includes several samples on how to use existing converters. If I remember correctly there is already a command line wrapper sample included. Everything is C/C++ stuff.</p>
<p>You can find out which of the converter dlls are responsible for OpenXML conversion by looking at the following registry key: </p>
<pre><code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Text Converters\Import\Word12
</code></pre>
<p>Let me know if you need further details on this.</p>
<p>Regards,
divo</p>
|
What techniques can you use to profile your code <p>Some of the platforms that I develop on, don't have profiling tools. I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.</p>
<p>The target language is C++.</p>
<p>I am interested in what you have personally used.</p>
| <p>No joke: In addition to dumping timings to std::cout and other text/data oriented approaches I also use the Beep() function. There's something about hearing the gap of silence between two "Beep" checkpoints that makes a different kind of impression.</p>
<p>It's like the difference between looking at a written sheet music, and actually HEARING the music. It's like the difference between reading rgb(255,0,0) and seeing fire-engine red.</p>
<p>So, right now, I have a client/server app and with Beeps of different frequencies, marking where the client sends the message, where the server starts its reply, finishes its reply, where reply first enters the client, etc, I can very naturally get a feel for where the time is spent.</p>
|
WPF Binding to Grid Column Width <p>I'm attempting to bind a <code>DependancyProperty</code> in one of my usercontrols to the <code>Width</code> property of a <code>Column</code> in a <code>Grid</code>. </p>
<p>I have code similar to this:</p>
<pre><code><Grid x:Name="MyGridName">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="TitleSection" Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>...</Grid.RowDefinitions>
<GridSplitter x:Name="MyGridSplitter" Grid.Row="0" Grid.Column="0" ... />
</Grid>
</code></pre>
<p>In a separate Usercontrol I have the following<code>DependancyProperty</code> defined.</p>
<pre><code>public static readonly DependencyProperty TitleWidthProperty = DependencyProperty.Register("TitleWidth", typeof(int), typeof(MyUserControl));
public int TitleWidth
{
get { return (int)base.GetValue(TitleWidthProperty); }
set { base.SetValue(TitleWidthProperty, value); }
}
</code></pre>
<p>I am creating instances of the Usercontrol in code, hence I have a binding statement similar to this :</p>
<pre><code>MyUserControl Cntrl = new MyUserControl(/* Construction Params */);
BindingOperations.SetBinding(Cntrl , MyUserControl.AnotherProperty, new Binding { ElementName = "objZoomSlider", Path = new PropertyPath("Value"), Mode = BindingMode.OneWay });
BindingOperations.SetBinding(Cntrl , MyUserControl.TitleWidthProperty, new Binding { ElementName = "TitleSection", Path = new PropertyPath("ActualWidth"), Mode = BindingMode.OneWay });
/* Other operations on Cntrl */
</code></pre>
<p>The first binding defined works fantastically, although that is binding to an actual UIElement (in this case a Slider), but the Binding to "TitleSection" (which is the ColumnDefinition defined in the Grid) fails. Putting a breakpoint in the code and doing a watch on "TitleSection" returns the expected object. </p>
<p>I am beginning to suspect that a x:Name'd ColumnDefinition can't be bound to. <strong>Can anyone suggest how I might be able to bind to the changing width of the first column in my grid?</strong></p>
<p><strong>EDIT #1 - To answer comments</strong></p>
<p>The databinding 'fails' in the sense that with a breakpoint set on the setter for the <code>TitleWidth</code> property, and using the GridSplitter control to resize the first column, the breakpoint is never hit. Additionally, code I would expect to be fired when the DependancyProperty <code>TitleWidth</code> changes does not get executed.</p>
<p>The usercontrol is being created and added to a Stackpanel within the Grid in the <code>Window_Loaded</code> function. I would expect that the Grid has been rendered by the time the Usercontrols are being constructed. Certainly the x:Name'd Element <code>TitleSection</code> is watchable and has a value of <code>100</code> when they are being constructed / before the binding is happening.</p>
<p><strong>EDIT #2 - Possibly something to do with this?</strong></p>
<p>I've been having a sniff round the MSDN pages for the Grid ColumnDefinition documentation and have come across <a href="http://msdn.microsoft.com/en-us/library/system.windows.gridlength.aspx" rel="nofollow">GridLength()</a> but I can't get my head around how I can use this in a binding expression. I cannot use the associated GridLengthConverter as a converter in the binding code as it does not derive from IValueConverter. </p>
<p>I am leaning towards somehow binding to the ActualWidth property of one of the cells in the Grid object. It doesn't seem as clean as binding to the column definition, but at the moment I cannot get that to work.</p>
| <p>Well I have got a bit of a kludge working, I'll explain how for future generations:</p>
<p>Essentially I have a 2 column, multi row grid with a splitter right aligned in the first column so it can be resized by the user if the content it contains requires more space. To complicate things I have a user control being loaded programatically into some of the rows which has a columnSpan of 2 for rendering purposes (content 'bleeds' from one cell into the next).</p>
<p>When the first column is resized I need this to be reflected in the usercontrol. Firstly I tried binding to the ColumnDefinition but it really wasn't playing ball.</p>
<p><strong>How I fixed/Kludged it</strong></p>
<p>In a spare cell in the first column I added a <code><Label></code> with an x:Name to make it accessible. As it is in a cell it has default properties of 'Stretch' and fills the cell completely. It gets resized as the column is resized using the splitter. Binding to the Label's <code>ActualWidth</code> property means that changes to the size of the column are communicated to the DependancyProperty in my columnSpanned usercontrol correctly.</p>
<p><strong>Thoughts</strong></p>
<p>Obviously, despite ColumnDefinition having an <code>ActualWidth</code> property when it changes it doesn't appear to fire the <code>PropertyChanged</code> event internally (or thats my best guess). This may be a bug, or by design, but for me it means I've had to use a less clean solution.</p>
|
How to spawn a process and capture its STDOUT in .NET? <p>I need to spawn a child process that is a console application, and capture its output.</p>
<p>I wrote up the following code for a method:</p>
<pre><code>string retMessage = String.Empty;
ProcessStartInfo startInfo = new ProcessStartInfo();
Process p = new Process();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = command;
startInfo.FileName = exec;
p.StartInfo = startInfo;
p.Start();
p.OutputDataReceived += new DataReceivedEventHandler
(
delegate(object sender, DataReceivedEventArgs e)
{
using (StreamReader output = p.StandardOutput)
{
retMessage = output.ReadToEnd();
}
}
);
p.WaitForExit();
return retMessage;
</code></pre>
<p>However, this does not return anything. I don't believe the <code>OutputDataReceived</code> event is being called back, or the <code>WaitForExit()</code> command may be blocking the thread so it will never callback.</p>
<p>Any advice?</p>
<p><strong>EDIT:</strong> Looks like I was trying too hard with the callback. Doing:</p>
<pre><code>return p.StandardOutput.ReadToEnd();
</code></pre>
<p>Appears to work fine.</p>
| <p>Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:</p>
<pre><code>process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();
</code></pre>
|
irritating select() behaviour in c <pre><code>while (xxx) {
timeout.tv_sec=TIMEOUT;
timeout.tv_usec=0;
FD_ZERO(&set);
FD_SET(sd,&set);
switch (select(FD_SETSIZE,&set,NULL,NULL,&timeout))
xxxxx
}
</code></pre>
<p>works fine, however</p>
<pre><code>FD_ZERO(&set);
FD_SET(sd,&set);
while (xxx) {
timeout.tv_sec=TIMEOUT;
timeout.tv_usec=0;
switch (select(FD_SETSIZE,&set,NULL,NULL,&timeout))
xxxxx
}
</code></pre>
<p>doesn't. It works the first time around, but the next time it runs through the while loop it gets a timeout even if the sd socket receives data. It seems to me to be a waste of resources to have to empty and fill set every time.</p>
<p>Anybody have a good explanation why this is, and even better, perhaps a suggestion how to avoid it?</p>
| <p>select modifies its arguments. You really do have to re-initialize it each time.</p>
<p>If you're concerned about overhead, the cost of processing the complete FD_SET in the kernel is somewhat more significant than the cost of FD_ZERO. You'd want to only pass in your maximum fd, not FD_SETSZIZE, to minimize the kernel processing. In your example:</p>
<pre><code>switch (select((sd + 1),&set,NULL,NULL,&timeout))
</code></pre>
<p>For a more complex case with multiple fds, you typically end up maintaining a max variable:</p>
<pre><code>FD_SET(sd,&set);
if (sd > max) max = sd;
... repeat many times...
switch (select((max + 1),&set,NULL,NULL,&timeout))
</code></pre>
<p><br>
If you will have a large number of file descriptors and are concerned about the overhead of schlepping them about, you should look at some of the alternatives to select(). You don't mention the OS you're using, but for Unix-like OSes there are a few:</p>
<ul>
<li>for Linux, epoll()</li>
<li>for FreeBSD/NetBSD/OpenBSD/MacOS X, kqueue()</li>
<li>for Solaris, /dev/poll</li>
</ul>
<p>The APIs are different, but they are all essentially a stateful kernel interface to maintain a set of active file descriptions. Once an fd is added to the set, you will be notified of events on that fd without having to continually pass it in again.</p>
|
How can I programmatically test an HTTP connection? <p>Using Java, how can I test that a URL is contactable, and returns a valid response?</p>
<pre><code>http://stackoverflow.com/about
</code></pre>
| <p>The solution as a unit test:</p>
<pre><code>public void testURL() throws Exception {
String strUrl = "http://stackoverflow.com/about";
try {
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
} catch (IOException e) {
System.err.println("Error creating HTTP connection");
e.printStackTrace();
throw e;
}
}
</code></pre>
|
How to avoid, that URL.equals needs access to the internet in Java? <p>The <code>equals()</code> method of the URL class in the Java class library makes a DNS request to get the IP for the hostname, to check the two IP's for equality. This happens even for URLs that are created from the same <code>String</code>. Is there a way to avoid this internet access?</p>
| <p>Use <a href="http://docs.oracle.com/javase/8/docs/api/java/net/URI.html" rel="nofollow">java.net.URI</a> instead of URL.</p>
|
Parse HTML via XPath <p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
| <p>I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries.</p>
<p>Here's how <a href="http://codespeak.net/lxml/xpathxslt.html">you can parse HTML via XPATH using lxml</a>.</p>
<pre><code>>>> from lxml import etree
>>> doc = '<foo><bar></bar></foo>'
>>> tree = etree.HTML(doc)
>>> r = tree.xpath('/foo/bar')
>>> len(r)
1
>>> r[0].tag
'bar'
>>> r = tree.xpath('bar')
>>> r[0].tag
'bar'
</code></pre>
|
What do I need to change to allow my IIS7 ASP.Net 3.5 application to create an event source and log events to Windows EventLog? <p>ASP.Net 3.5 running under IIS 7 doesn't seem to allow this out of the box.</p>
<pre><code> if (!EventLog.SourceExists("MyAppLog"))
EventLog.CreateEventSource("MyAppLog", "Application");
EventLog myLog = new EventLog();
myLog.Source = "MyAppLog";
myLog.WriteEntry("Message");
</code></pre>
| <p>I've copied this answer from <a href="http://stackoverflow.com/questions/2587453/log4net-eventlogappender-does-not-work-for-asp-net-2-0-website">here</a> (the question was Log4Net but the answer still applies). The technet link misses a vital step.</p>
<h3>Create a registry key</h3>
<p><code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MY-AWESOME-APP</code></p>
<h3>Create a string value inside this</h3>
<p>Name it <code>EventMessageFile</code>, set its value to</p>
<blockquote>
<p>C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll</p>
</blockquote>
<p>That path appears to work in both 64 bit and 32 bit environments.</p>
<p>With this technique you don't need to set permissions in the registry, and once the key above is created it should just work.</p>
<p><strong>Alternatively</strong><br>
If you don't have a large server farm but just a small "web garden" you could run a console application on each server that creates the event log source using <a href="http://msdn.microsoft.com/en-us/library/5zbwd3s3.aspx"><code>EventLog.CreateEventSource</code></a>, make sure the console application is run by an administrator.</p>
|
Stack Overflow Exploit in C <p>The question is actually about stack overflows in C.
I have an assigment that I can not get done for the life of me, I've looked at everything in the gdb and I just cant figure it.</p>
<p>The question is the following:</p>
<pre><code>int i,n;
void confused()
{
printf("who called me");
exit(0);
}
void shell_call(char *c)
{
printf(" ***Now calling \"%s\" shell command *** \n",c);
system(c);
exit(0);
}
void victim_func()
{
int a[4];
printf("[8]:%x\n", &a[8]);
printf("Enter n: "); scanf("%d",&n);
printf("Enter %d HEX Values \n",n);
for(i=0;i<n;i++) scanf("%x",&a[i]);
printf("Done reading junk numbers\n");
}
int main()
{
printf("ls=736c --- ps = 7370 --- cal = 6c6163\n");
printf("location of confused %x \n", confused);
printf("location of shell_call %x \n", shell_call);
victim_func();
printf("Done, thank you\n");
}
</code></pre>
<p>Ok, so I managed to get the first question correctly, which is to arbitrarily call one of the two functions not explicitly called in the main path. By the way, this has to be done while running the program without any modifications.
I did this by running the program, setting <code>N</code> to <code>7</code>, which gets me to the Function Pointer of the <code>victim_func</code> frame, I write <code>a[7]</code> with the memory address of confused or <code>shell_call</code>, and it works. (I have a 64 bit machine, thats why I have to get it to 7, since the EBI pointer is 2 ints wide, instead of 1)</p>
<p>My question is the following, how could I control which argument gets passed to the <code>shell_code</code> funcion? ie. how do I write a <code>string</code> to <code>char* c</code>.
The whole point is executing unix commands like <strong>ps</strong> etc, by running only the program.</p>
<p>I figured writing the EBI pointer with the hex representation of <strong>ps</strong> and setting the arg list of <code>shell_call</code> to that, but that didn't work. I also tried inputing <code>argsv</code> arguments and setting the arg list of <code>shell_call</code> to the <code>arg_list</code> of main, but didn't work either. </p>
<p>I think the second version should work, but I believe I'm not setting the arg list of the new stack frame correctly ( I did it by writing <code>a[8]</code> to <code>0</code>, since its the first part of the function pointer, and writing <code>a[9]=736c</code> and <code>a[10]=0000</code>, but its probably not right since those are the parameters of <code>victim_func</code>. So how do I access the parameters of <code>shell_call</code>? </p>
| <p>I probably shouldn't do your homework for you. But the basically:</p>
<p>You need to get a character buffer somewhere in memory to store the string you want to execute. Obviously, you can do this the same way you are getting the other functions called (i.e. you put the text on the stack as well). After you have that written, you need to write a pointer to it on to the stack in the location that the shell_code function expects to find its arguments.</p>
<p>The best way to figure this out without me doing <em>all</em> of the work for you is to write down your stack/memory contents on a piece of paper/whiteboard. Write down how it would look if you called shell_code normally from inside the program. Then write down what the stack looks like inside victum_func and figure out which things to change to get it to look like it would look "naturally" (of course keeping in mind some things are "don't cares" like the return address).</p>
<p>That's all the charity you're gonna get from me today! :-P</p>
|
How to split a web address <p>So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address <a href="http://www.stackoverflow.com/questions/ask" rel="nofollow">http://www.stackoverflow.com/questions/ask</a>. I would need the protocol and domain (e.g. <a href="http://www.stackoverflow.com" rel="nofollow">http://www.stackoverflow.com</a>) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?</p>
| <p>Dan is right: urlparse is your friend:</p>
<pre><code>>>> from urlparse import urlparse
>>>
>>> parts = urlparse("http://www.stackoverflow.com/questions/ask")
>>> parts.scheme + "://" + parts.netloc
'http://www.stackoverflow.com'
>>> parts.path
'/questions/ask'
</code></pre>
|
Alternative to StyleCop for Visual Studio? <p>I like <a href="http://code.msdn.microsoft.com/sourceanalysis">StyleCop</a>'s static code analysis and rules enforcement. However, it is severely lacking in several key departments. </p>
<ul>
<li>Adding new rules isn't officially supported and from what I hear pretty difficult.</li>
<li>Automatic "fixing" of trivial rules violations would be nice! Perhaps not with variable naming but with method ordering (static, etc) this would be a huge time saver.</li>
<li>Microsofts "one-size-fits-all" approach to StyleCop is kind of restrictive. I would like to have a custom set of rules for our in-house standards.</li>
</ul>
<p>Is there such a commercial product out there?</p>
<p><img src="http://blogs.interakting.co.uk/images/blogs_interakting_co_uk/dominicz/WindowsLiveWriter/MicrosoftStyleCopSourcecodeanalysisforfo_D8EF/styleCopErrors_6.gif" alt="alt text" /></p>
| <p>Adding rules is, or is going to be, <a href="http://blogs.msdn.com/sourceanalysis/archive/2008/08/19/stylecop-4-3-is-released.aspx">officially supported</a>:</p>
<blockquote>
<p>As promised, we will also be releasing
SDK documentation for StyleCop
explaining how to author custom rules
and how to integrate the tool into
custom build environments. The SDK
documentation is currently under final
review and we hope to release it very
soon.
-- <a href="http://blogs.msdn.com/sourceanalysis/archive/2008/08/19/stylecop-4-3-is-released.aspx">JasonAll</a></p>
</blockquote>
<p>In terms of our "in-house" style, I got pretty close by disabling a handful of StyleCop rules:</p>
<ul>
<li>File Headers (SA1633-SA-1640)</li>
<li>Code ordering (SA1200-SA1202)</li>
<li>Requiring "this" (SA1101)</li>
</ul>
<p>You can do this globally by modifying the Settings.StyleCop file in the installation directory, though I've taken the approach of putting one at the root of our source tree in each project.</p>
<p>The end effect is much what we want. There are a handful of "in-house" choices that would be nice to flag, but even without them StyleCop is delivering a lot of value for us.</p>
|
Importance of closing SQLConnection objects when using the SQLDataReader object <p>My present contract engagement is at a large E-Commerce company. Their code base which has origins going back to .Net 1.0 has caught me by surprise to contain many issues that raise the level of smell beyond the last crap I took. </p>
<p>That notwithstanding and trying to diffuse my level of distraction from it, I go along merrily trying to add in features to either fix other problems or extend more crap. Where I touch the DAL/BLL the time it will take to fix the aforementioned will be done. However I wanted to get a vote of confidence from the experts to get some assurance of not wasting the clients time or worse having my credibility voted down by touching "stuff that works". Of course unit testing would solve or at least soften this worry. Perhaps this should also be added to the wtf.com?</p>
<pre><code>Public Function GetSizeInfoBySite(ByVal siteID As String) As IList
Dim strSQL As String = "YES INLINE SQL!! :)"
Dim ci As CrapInfo
Dim alAnArrayList As ArrayList
Dim cn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim cmd As New SqlCommand(strSQL, cn)
cmd.Parameters.Add(New SqlParameter("@MySiteID", SqlDbType.NVarChar, 2)).Value = siteID
cn.Open()
Dim rs As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While rs.Read()
ci = New CategoryInfo(rs("someID"), rs("someName"))
If IsNothing(alAnArrayList) Then
alAnArrayList = New ArrayList
End If
alAnArrayList.Add(ci)
End While
rs.Close()
Return CType(alAnArrayList, IList)
End Function
</code></pre>
<p>Does anyone see problems with this aside from the inline SQL which makes my gut churn? At the least wouldn't you ordinarily wrap the above in a try/catch/finally which most of us knows has been around since .Net v1.0? Even better would'nt it be wise to fix with Using statements? Does the SQLDataReader close really encapsulate the connection close automagically? </p>
| <p>Nothing wrong with inline sql if the user input is properly parameterized, and this looks like it is. </p>
<p>Other than that, yes you do need to close the connections. On a busy web site you could hit your limit and that would cause all kinds of weirdness.</p>
<p>I also noticed it's still using an arraylist. Since they've moved on from .Net 1.0 it's time to update those to generic <code>List<T></code>'s (and avoid the call to CType- you should be able to DirectCast() that instead).</p>
|
Is there a time when && (AndAlso) does not matter over & (And) <p>If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&"</p>
<pre><code>//some logic that sets bool values
boolean X = true;
boolean Y = true;
if (X & Y){
// perform some operation
}
if (X && Y){
// perform some operation
}
</code></pre>
<p>Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the && operator, is the & operator going away?</p>
| <p>Always use && if you are performing a true/false logic test. A single & performs a bit-wise 'and'. It make work like a logic test in some cases but it is not guaranteed to work for all logic cases. The most common use of a single & is when applying a bit-mask.</p>
<p>Examples (&&):</p>
<pre><code>true && true == true
</code></pre>
<p>Example (&):</p>
<pre><code>00101001 & 00100001 = 00100001
</code></pre>
|
How to password protect streaming videos with php <p>What is the best way to password protect quicktime streaming videos using php/.htaccess. They are being streamed using rtsp, but I can use other formats if necessary.</p>
<p>I know how to do authentication with php, but I'm not sure how to setup authentication so that will protect the streaming files urls so that a user can't just copy the url and share it.</p>
<p>Or am I overthinking this and I can just use a normal authentication scheme and place the files in a protected directory?</p>
| <p>Both nginx and lighttpd web servers have X-Send-File headers you can return from PHP. So you can do your checks in PHP and then conditionally server out the file.</p>
<pre><code>if (check_user_can_access()){
header('X-sendfile: /path/to/file');
} else {
header('HTTP/1.1 403 Fail!');
}
</code></pre>
<p>Lighttpd also has a neat module called <a href="http://redmine.lighttpd.net/wiki/lighttpd/Docs#mod_secure_download" rel="nofollow">mod_secure_download</a> that allows you to programatically generate a URL that will only be valid for a short time period.</p>
<p>Nginx, and possibly lighttpd, allow you to cap the download speed, so you're not sending out streaming data faster than it can be consumed.</p>
<p>Either way, you want to use your web server for serving files. Serving them through PHP is possible, but slow. </p>
|
How to create an automated way of monitoring to see if this application is running <p>We have a application that should always be running. Does anyone know of a way to create an automated way of monitoring to see if this application is running (possibly using a batch file)? If it is not running, then send an email notification and start the application?</p>
| <p><a href="http://www.nagios.org/" rel="nofollow">Nagios</a> is generally what's used by systems administrators that I've come across. You can script it to do whatever check you need and alert based on a variety of conditions. Works well with cacti so you can graph stuff too :)</p>
<p>If you want to ensure that your service always restarts should it die you could use <a href="http://cr.yp.to/daemontools/supervise.html" rel="nofollow">supervise</a> from daemontools.</p>
|
How do I translate init.d scripts from Ubuntu/Debian Linux to Solaris? <p>I have several init.d scripts that I'm using to start some daemons. Most of these scripts I've found on the internet and they all use start-stop-daemon. My understanding is that "start-stop-daemon" is a command that is specific to Linux or BSD distros and is not available on Solaris.</p>
<p>What is the best way to translate my init.d scripts from Linux to Solaris? Is there a command equivalent to start-stop-daemon that I can use, roughly?</p>
<p>Since I'm not much of a Solaris user, I'm willing to admit upfront that I don't even know if my question is inherently invalid or not.</p>
| <p>start-stop-daemon is a Linux thing, and not used that much on Solaris. I guess you can port the command though, if you want to reuse your init scripts.</p>
<p>Otherwise it depends on what version of Solaris you are using. Starting with Solaris 10 and also OpenSolaris they use a new startup script framework "Solaris Service Management Facility", which you configure with the commands <code>svcs</code>, <code>svccfg</code> and <code>svcadm</code>.</p>
<p>See <a href="http://www.sun.com/bigadmin/content/selfheal/smf-quickstart.jsp" rel="nofollow">http://www.oracle.com/technetwork/server-storage/solaris/overview/servicemgmthowto-jsp-135655.html</a> for more information.</p>
<p>For older Solaris releases most init scripts are written in pure shell without any helper commands like start-stop-daemon.</p>
|
How can I print the lines in STDIN in random order in Perl? <p>I want to do the inverse of <a href="http://www.manpagez.com/man/1/sort/" rel="nofollow">sort(1)</a> : randomize every line of <strong>stdin</strong> to <strong>stdout</strong> in Perl. </p>
| <p>I bet real Perl hackers will tear this apart, but here it goes nonetheless.</p>
<pre><code>use strict;
use warnings;
use List::Util 'shuffle';
my @lines = ();
my $bufsize = 512;
while(<STDIN>) {
push @lines, $_;
if (@lines == $bufsize) {
print shuffle(@lines);
undef @lines;
}
}
print shuffle(@lines);
</code></pre>
<p>Difference between this and the other solution:</p>
<ul>
<li>Will not consume all the input and then randomize it (memory hog), but will randomize every $bufsize lines (not truly random and slow as a dog compared to the other option).</li>
<li>Uses a module which returns a new list instead of a in place editing Fisher - Yates implementation. They are interchangeable (except that you would have to separate the print from the shuffle). For more information type perldoc -q rand on your shell.</li>
</ul>
|
Setting focus to a button from from text box? <p>I have a few text boxes and buttons on my form.</p>
<p>Lets say txtBox1 is next to btnSubmit1,
txtBox2 is next to btnSubmit2,
txtBox3 is next to btnSubmit3.</p>
<p>How can I set the focus on btnSubmit3 when the user starts to type something in txtBox3.
Meaning..... if a user type in a text box the program will know what button to fire when the user press the enter key.</p>
| <p>If you use a panel, you should be able to set a defaultbutton. I´m not sure if it´s an win forms application or a web forms application, but this is how you should do it with web forms:</p>
<pre><code><asp:Panel id="panel1" runat="server" DefaultButton="Button1">
<asp:TextBox id="textbox1" runat="server" />
<asp:Button id="Button1" runat="server" Text="Button 1" />
</asp:Panel>
<asp:Panel id="panel2" runat="server" DefaultButton="Button2">
<asp:TextBox id="textbox2" runat="server" />
<asp:Button id="Button2" runat="server" Text="Button 2" />
</asp:Panel>
<asp:Panel id="panel3" runat="server" DefaultButton="Button3">
<asp:TextBox id="textbox3" runat="server" />
<asp:Button id="Button3" runat="server" Text="Button 3" />
</asp:Panel>
</code></pre>
|
How to add CardSpace support to your ASP.NET application <p>I like the idea of CardSpace but unlike OpenID it seems like a real PITA
to support it in your ASP.NET web application. I've found many examples, even a tutorial
in one of the books I own... but it would seem a lot more is required than what they suggest.</p>
<p>Changes to the server and such? </p>
<p>Can someone tell me:</p>
<ul>
<li>What I need to configure in IIS7</li>
<li>How to implement CardSpace support without using to many 3rd party components</li>
<li>Have you managed to get it working?</li>
</ul>
<p>I think the complexity (or poor documentation) is one of the reasons CardSpace is lagging behind.</p>
<p>(I'm interested in what others think about this, but lets not turn this into a flame war, I just want a solution and perhaps your thoughs in short)</p>
| <p>For card space take a look at the open source library SharpSTS a https://sharpsts.com/</p>
<p>They also have links to a number of card space resources that might help you get started at: https://sharpsts.com/resources.aspx </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.