input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
How should I get started learning about ADO.NET Entity Framework? <p>So here I am just about to start a big project using LINQ to SQL and then I read this:</p>
<p><a href="http://www.infoq.com/news/2008/11/DLINQ-Future" rel="nofollow">Is LINQ to SQL Truly Dead?</a> by Jonathan Allen for InfoQ.com</p>
<p>Well, I don't want to be supporting LINQ to SQL indefinitely if it's a dead end. So, how should I get started learning about ADO.NET Entity Framework?</p>
|
<p>How Do I...? Videos</p>
<ul>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx">How Do I Get Started with the Entity Framework?</a> </li>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx">How Do I Use the new Entity Data Source?</a> </li>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx">How Do I Serialize a Graph with the Entity Framework?</a> </li>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx">How do I use Entity Client?</a> </li>
<li><a href="http://www.asp.net/learn/3.5-SP1/video-245.aspx">ADO.NET Entity Designer Video - CTP 2</a></li>
</ul>
<p>Webcasts</p>
<ul>
<li><a href="http://www.asp.net/learn/webcasts/webcast-181.aspx">MSDN Webcast: Framework Masterclass: LINQ to Entities (Level 200)</a></li>
</ul>
|
How to serialize an object to XML without getting xmlns="..."? <p>Is there a way for me to serialize an object in .NET without the XML Namespaces automatically serializing also? It seems that by default .NET believes the XSI and XSD namespaces should be included, but I don't want them there.</p>
|
<p>Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is <code>obj</code> and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.</p>
<p>In VB like this:</p>
<pre><code>Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")
Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True
Using ms As New MemoryStream(), _
sw As XmlWriter = XmlWriter.Create(ms, settings), _
sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using
</code></pre>
<p>in C# like this:</p>
<pre><code>//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);
</code></pre>
|
Phone number normalization: Any pre-existing libraries? <p>I have a system which is using phone numbers as unique identifiers. For this reason, I want to format all phone numbers as they come in using a normalized format. Because I have no control over my source data, I need to parse out these numbers myself and format them before adding them to my DB.</p>
<p>I'm about to write a parser that can read phone numbers in and output a normalized phone format, but before I do I was wondering if anyone knew of any pre-existing libraries I could use to format phone numbers.</p>
<p>If there are no pre-existing libraries out there, what things should I be keeping in mind when creating this feature that may not be obvious?</p>
<p>Although my system is only dealing with US numbers right now, I plan to try to include support for international numbers just in case since there is a chance it will be needed.</p>
<p><strong>Edit</strong> I forgot to mention I'm using C#.NET 2.0.</p>
|
<p>You could use <code>libphonenumber</code> from Google. Here's a blog post: </p>
<p><a href="http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber" rel="nofollow">http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber</a></p>
<p>Parsing numbers is as easy as installing the <a href="http://nuget.org/packages/libphonenumber-csharp" rel="nofollow">NuGet package</a> and then doing this:</p>
<pre><code>var util = PhoneNumberUtil.GetInstance();
var number = util.Parse("555-555-5555", "US");
</code></pre>
<p>You can then format the number like this:</p>
<pre><code>util.Format(number, PhoneNumberFormat.E164);
</code></pre>
<p><code>libphonenumber</code> supports several formats other than E.164.</p>
|
Why would I choose Powershell over WMI to develop management interfaces? <p>We are discussing development of an improved management infrastructure for our distributed system.
We use COM, web services and .NET components. Since we're based on Microsoft Windows Server XP/2003, I guess, we basically have two options:</p>
<ol>
<li>Powershell cmdlets
<li>WMI classes using System.Management and WMI providers for native code (class, instance, method, event)
</ol>
<p>Why would we choose Powershell over WMI?</p>
|
<p>I would choose PowerShell over WMI for the following reasons:</p>
<ol>
<li>Writing a cmdlet is only adding a .NET Class.</li>
<li>The PowerShell runtime provides command line parsing built in.</li>
<li>Writing your management interface in PowerShell allows administrators the ability to integrate management of your application with that of other applications and services (like Exchange, Active Directory, or SQL Server).</li>
<li>The PowerShell environment makes the pipeline available to administrators, enabling management tasks for your application to be done more efficiently.</li>
<li>Discoverability. PowerShell, via Get-Command, Get-Member, and Get-Help, provides an extremely discoverable environment for admins to work in, resulting in a shorter learning curve to maintaining your application.</li>
</ol>
<p>Even if you go the WMI route, PowerShell does have support for working with WMI (though there are a few glitches).</p>
<p>To me, PowerShell is the best way to surface a <strong>task oriented</strong> interface to an application. With the support Microsoft has been providing PowerShell, it is and will be a consistent interface to managing applications and services throughout the enterprise.</p>
<p>My day job is as an admin and I'm pushing all the vendors I work with towards surfacing a PowerShell management API, as this makes the learning curve and context switching for managing applications much lower. On the development side, I have written (and am still working on) a series of PowerShell cmdlets for one open source product I work with and am working on another set for a separate application.</p>
|
Scanning Java annotations at runtime <p>What is the best way of searching the whole classpath for an annotated class?</p>
<p>I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.</p>
<p>Do you know a library or a Java facility to do this?</p>
<p>Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with <code>@WebService</code> or <code>@EJB</code> and the system finds these classes while loading so they are accessible remotely.</p>
|
<p>Use <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html">org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider</a> </p>
<p>API</p>
<blockquote>
<p>A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates. </p>
</blockquote>
<pre><code>ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);
scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));
for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
System.out.println(bd.getBeanClassName());
</code></pre>
|
How to cut out a part from a stream in Delphi7 <p>I have an incoming soap message wich form is TStream (Delphi7), server that send this soap is in development mode and adds a html header to the message for debugging purposes. Now i need to cut out the html header part from it before i can pass it to soap converter. It starts from the beginning with 'pre' tag and ends with '/pre' tag. Im thinking it should be fairly easy to but i havent done it before in Delphi7, so can someone help me? </p>
|
<p>Another solution, more in line with Lars' suggestion and somehow more worked out.<br />
It's faster, especially when the size of the Stream is above 100, and even more so on really big ones. It avoids copying to an intermediate string.<br />
<strong>FilterBeginStream</strong> is simpler and follows the "specs" in removing everything up until the end of the header.<br />
<strong>FilterMiddleStream</strong> does the same as DepreStream, leaving what's before and after the header.</p>
<p><strong>Warning</strong>: this code is for Delphi up to D2007, not D2009. </p>
<pre><code>// returns position of a string token (its 1st char) into a Stream. 0 if not found
function StreamPos(Token: string; AStream: TStream): Int64;
var
TokenLength: Integer;
StringToMatch: string;
begin
Result := 0;
TokenLength := Length(Token);
if TokenLength > 0 then
begin
SetLength(StringToMatch, TokenLength);
while AStream.Read(StringToMatch[1], 1) > 0 do
begin
if (StringToMatch[1] = Token[1]) and
((TokenLength = 1) or
((AStream.Read(StringToMatch[2], Length(Token)-1) = Length(Token)-1) and
(Token = StringToMatch))) then
begin
Result := AStream.Seek(0, soCurrent) - (Length(Token) - 1); // i.e. AStream.Position - (Length(Token) - 1);
Break;
end;
end;
end;
end;
// Returns portion of a stream after the end of a tag delimited header. Works for 1st header.
// Everything preceding the header is removed too. Returns same stream if no valid header detected.
// Result is True if valid header found and stream has been filtered.
function FilterBeginStream(const AStartTag, AEndTag: string; const AStreamIn, AStreamOut: TStream): Boolean;
begin
AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;
Result := (StreamPos(AStartTag, TStream(AStreamIn)) > 0) and (StreamPos(AEndTag, AStreamIn) > 0);
if Result then
AStreamOut.CopyFrom(AStreamIn, AStreamIn.Size - AStreamIn.Position)
else
AStreamOut.CopyFrom(AStreamIn, 0);
end;
// Returns a stream after removal of a tag delimited portion. Works for 1st encountered tag.
// Returns same stream if no valid tag detected.
// Result is True if valid tag found and stream has been filtered.
function FilterMiddleStream(const AStartTag, AEndTag: string; const AStreamIn, AStreamOut: TStream): Boolean;
var
StartPos, EndPos: Int64;
begin
Result := False;
AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;
StartPos := StreamPos(AStartTag, TStream(AStreamIn));
if StartPos > 0 then
begin
EndPos := StreamPos(AEndTag, AStreamIn);
Result := EndPos > 0;
end;
if Result then
begin
if StartPos > 1 then
begin
AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;
AStreamOut.CopyFrom(AStreamIn, StartPos - 1);
AStreamIn.Seek(EndPos - StartPos + Length(AEndTag), soCurrent);
end;
AStreamOut.CopyFrom(AStreamIn, AStreamIn.Size - AStreamIn.Position);
end
else
AStreamOut.CopyFrom(AStreamIn, 0);
end;
</code></pre>
|
Why is tomcat looking for JSF classes? <p>I am trying to get my development environment up and running, and I am having trouble with Tomcat trying to load JSF classes for some reason. My application does not use JSF; in fact, I haven't even deployed my application to tomcat yet. I am getting a number of stack traces in the startup logs and I cannot load the default tomcat homepage when I try to open <a href="http://localhost:8080" rel="nofollow">http://localhost:8080</a> (I just get the tomcat 404 page).</p>
<p>Here is what the first stack trace is:</p>
<pre><code>SEVERE: Error configuring application listener of class com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener
java.lang.ClassNotFoundException: com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3712)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4216)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
</code></pre>
<p>I also get similar stack traces for the following other classes:</p>
<pre><code>com.sun.faces.config.ConfigureListener
com.sun.faces.application.WebappLifecycleListener
</code></pre>
<p>I'm not sure if this is relevant, but I am running Tomcat 5.5.27 with the 1.4 compatibility pack installed, with Java 1.4.2, on Mas OS 10.5.</p>
<p>Thanks for any ideas!</p>
<p><strong>EDIT:</strong> It seems that each of the default applications that come with Tomcat (host-manager, balancer, tomcat-docs, jsp-examples, etc) was relying on these JSF classes. I removed these default applications, and everything seems to be working.</p>
<p>So, my question is now:
<strong>Why does tomcat come with applications that don't include their dependencies, and what do I need to do to make those default applicaitons work?</strong></p>
|
<p>Is your tomcat installation totally clean, or is it one you have inherited?</p>
<p>Check if the webapps contains existing wars/directories which may be referencing JSF classes?</p>
<p>UPDATE: Ah -- I see you found this was the case :-)</p>
<p>Not sure why tomcat doesn't include all its dependencies. Perhaps you downloaded a developer release instead of a stable one?</p>
|
iterator adapter to iterate just the values in a map? <p>I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C.</p>
<p>One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this facility with its Keys and Values properties of its Dictionary class. Objective-C's NSDictionary, similarly, has allKeys and allValues.</p>
<p>Since I've been "away", Boost has acquired the Range and ForEach libraries, which I am now using extensively. I wondered if between the two there was some facility to do the same, but I haven't been able to find anything.</p>
<p>I'm thinking of knocking something up using Boost's iterator adapters, but before I go down that route I thought I'd ask here if anyone knows of such a facility in Boost, or somewhere else ready made?</p>
|
<p>Replacing the previous answer, in case anybody else finds this like I did. As of boost 1.43, there are some commonly used range adaptors provided. In this case, you want boost::adaptors::map_values. The relevant example:
<a href="http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html#range.reference.adaptors.reference.map_values.map_values_example">http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html#range.reference.adaptors.reference.map_values.map_values_example</a></p>
|
Disappearing bullet points <p><a href="http://biochrom.fivesite.co.uk/catalogue4.asp" rel="nofollow">http://biochrom.fivesite.co.uk/catalogue4.asp</a></p>
<p>On the page above there is an image floated to the left. To the right of it is a list, titled "features". The list items have a background image, however, it isn't appearing. List 2 shows how the background image looks.</p>
<p>Does anyone know how I can make the bullets visible?</p>
|
<p>I know this is a year old post but others may want to know...</p>
<p>What happens if you are using a content management system and some pages have images & some don't you wouldn't want your list items to be 200px in the content?</p>
<p>You can add this CSS to your UL/OL element:</p>
<pre><code>overflow:hidden;
</code></pre>
<p>I hope that helps.</p>
|
How to display image in grails GSP? <p>I'm still learning Grails and seem to have hit a stumbling block.</p>
<p><strong>Here are the 2 domain classes:</strong></p>
<pre><code>class Photo {
byte[] file
static belongsTo = Profile
}
class Profile {
String fullName
Set photos
static hasMany = [photos:Photo]
}
</code></pre>
<p><strong>The relevant controller snippet:</strong> </p>
<pre><code>class PhotoController {
.....
def viewImage = {
def photo = Photo.get( params.id )
byte[] image = photo.file
response.outputStream << image
}
......
}
</code></pre>
<p><strong>Finally the GSP snippet:</strong></p>
<pre><code><img class="Photo" src="${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}" />
</code></pre>
<p>Now how do I access the photo so that it will be shown on the GSP? I'm pretty sure that
<strong>profileInstance.photos.get(1).id</strong> is not correct. Thanks!!</p>
|
<p>If you have a url for the image, you just have to make sure you return the appropriate anser in the controller:</p>
<pre><code> def viewImage= {
//retrieve photo code here
response.setHeader("Content-disposition", "attachment; filename=${photo.name}")
response.contentType = photo.fileType //'image/jpeg' will do too
response.outputStream << photo.file //'myphoto.jpg' will do too
response.outputStream.flush()
return;
}
</code></pre>
|
What do you use to test the handheld css on your website? <p>I've been adding css support for <strong>handheld</strong> to my website but haven't been able to find a good tool for testing. </p>
<p>I tried using the webdeveloper plugin for Firefox but it doesn't work for me. Maybe that is because all my css is in the html and not a seperate css file.</p>
<p>Are there any other testing tools available aside from going out and buying a handheld device?</p>
|
<p>With a bit of hunting I found what I was looking for, thanks for the leads guys.</p>
<p>Opera will display the <strong>handheld</strong> css if you select "Small Screen" from the View menu.</p>
|
Calling internal methods in Medium Trust <p>I have the requirement to call an internal method of a 3rd party object (I cannot make it public for example). I can do that via reflection. Unfortunately this does not work in ASP.NET Medium trust due to insufficient rights:</p>
<pre><code><IPermission class="ReflectionPermission" version="1" Flags="RestrictedMemberAccess"/></PermissionSet>
</code></pre>
<p>Is there any way I can internal methods in this case? I've heard that LINQ expressions can be used to call private/internal methods. Would expression methods somehow override the ReflectionPermission? </p>
|
<p>I don't see a way to call it. The .NET security/trust model is designed to prevent exactly this sort of thing. If you could somehow circumvent it, you would have to file a security bug with Microsoft which would then (hopefully) be fixed and make your solution useless again ;-)</p>
<p>Can't you negotiate a higher trust level with the deployer/operator of your solution?</p>
|
How do I best display CheckBoxes in SQL Server Reporting Services? <p>One of the many quirks of Reporting Services we've run across is the complete and utter lack of a CheckBox control or even something remotely similar.</p>
<p>We have a form that should appear automatically filled out based on information pulled from a database. We have several bit datatype fields. Printing out "True" or "False" just looks silly, as this is supposed to look like a form that has been auto-filled out, so we want to have a series of checkboxes and labels that are either checked or unchecked.</p>
<p>We are running SSRS 2005 but I'm not aware of SSRS 2008 having added a CheckBox control. Even if it did, we'd need to have an alternative for the time being. The best we've found so far is:</p>
<ol>
<li>use Wingdings</li>
<li>use images</li>
<li>use text boxes with borders and print a blank/space or a capital X</li>
</ol>
<p>All three approaches require <code>IIF</code> expression shenanigans.</p>
<p>The Wingdings approach seemed to work acceptably, and was the most aesthetically pleasing except that for whatever reason it didn't always print correctly. More importantly, PDF exports, also for whatever reason, converted all fonts (generally) to Arial and so we got funky letters instead of the Windings dingbats.</p>
<p>Images, being a pixel-based raster, don't do so well when printed along side vector stuff like text. Unless handled carefully, they tend to stretch, pixelate, and do other unprofessional looking things.</p>
<p>While these methods do work (some with limitations as mentioned above) none of them are particularly elegant.</p>
<p><strong>Are we missing something obvious?</strong> Not so obvious? Does someone at Microsoft have a good reason why such a control was not provided in SSRS 2000, let alone 2 versions and 8 years later? This can't be the first time this issue has come up...</p>
|
<p>I, along with others in my shop, have used images, toggling the hidden attribute based on the field value (true or false). We haven't had any problems with blurring or scaling, unless we tried to increase the scale of the image beyond 100% obviously.</p>
<p>Another option I've used is similar to the wingdings idea, but I just use a plain old "X". On our forms at least, it is not uncommon for someone to use an X in a box instead of a check mark, so it looks completely acceptable. Plus, you don't have to worry about strange characters when printing.</p>
<p>As for why Microsoft does not include a checkbox control, I can't answer that as I've been wondering the same thing myself for a long time now.</p>
|
Using nullable types in C# <p>I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:</p>
<pre><code>bool isNull = (i == null);
</code></pre>
<p>or</p>
<pre><code>bool isNull = !i.HasValue;
</code></pre>
<p>Also when assigning to a non-null type is this:</p>
<pre><code>long? i = 1;
long j = (long)i;
</code></pre>
<p>better than:</p>
<pre><code>long? i = 1;
long j = i.Value;
</code></pre>
|
<p>I would use this:</p>
<pre><code>long? i = 1;
...some code...
long j = i ?? 0;
</code></pre>
<p>That means, if <em>i</em> is <strong>null</strong>, than 0 will be assigned.</p>
|
<base target="FrameName"> doesn't work on IE7 <p>It seems that the following piece of HTML is ignored in IE7 but works ok in IE6/FF. It supposes to override all the html links to be opened in the desired frame</p>
<pre><code><HEAD>
<title>LeftPane</title>
<base target="rightFrame">
</HEAD>
</code></pre>
<p>The above code is the header of a left frame that holds an Infragistics UltraWebTree (tree menu) which doesn't support the TargetFrame property.</p>
<p>Is there another way to add the target attribute to all the links elements on the desired page. </p>
<p>Any server or client-side code workarounds?</p>
<p>The site is built on ASP.Net 1.1 and Infragistics V 2.0</p>
<p><strong>Update</strong>
the web page is aspx an the doctype is </p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
</code></pre>
|
<p>The <code>href=""</code> attibute is <a href="http://www.w3schools.com/TAGS/tag_base.asp" rel="nofollow">mandatory on the base tag</a> - that's one possible explanation. You don't say what doctype you're using, but <a href="http://www.devguru.com/Technologies/xhtml/quickref/xhtml_base.html" rel="nofollow">target is not allowed in strict XHTML</a>.</p>
<p>Edit: tested it without href and it worked ok... that leaves the doctype, or something else.</p>
|
Is this the correct step-by-step and organization for creating an SVN repo with multiple projects and vendors? <p>I've read quite a bit of the Red Bean Software SVN Book, and some of the questions here on SO, but I want to make sure I'm going about this in the right way the first time around step-by-step before I begin using it. Is this correct?</p>
<ol>
<li>Install SVN.</li>
<li><p>Create SVN repository at /usr/local/svn. Directory structure looks like this:</p>
<pre><code>-- conf
-- db
-- format
-- hooks
-- locks
-- README.txt
</code></pre></li>
<li><p>Create folders through command line for repository organization (including projects and vendors).</p>
<pre><code>-- conf
-- db
-- format
-- hooks
-- locks
-- projects
-- project_name
-- vendor
-- trunk
-- branches
-- tags
-- project_name
-- vendor
-- trunk
-- branches
-- tags
-- README.txt
</code></pre></li>
<li><p>Checkout vendor code into vendor folder under the correct project name.</p></li>
<li>Export vendor code into trunk under the correct project name (no merge necessary, as I have no project trunk files yet).</li>
<li>Create users/permissions in /svnroot/conf/passwd and /svnroot/conf/svnserve.conf.</li>
<li>Make sure that svnserve is running, and on my local SVN client (TortoiseSVN), checkout the trunk for the project that I need.</li>
</ol>
<p>I don't need to serve this up by public URL, so I'm not configuring for Apache. The server is not in our network, but is a dedicated CentOS box we rent. Thanks for any thoughts and advice.</p>
<p><strong>EDIT:</strong></p>
<p>I guess I'm confused because I don't have code or a project to begin with, so I am starting fresh from the vendor's code. Do I need to create a directory structure somewhere on the server that includes my project_name w/ vendor, trunk, branches and tags subfolders, import that into my repo, and then import the code from the vendor into the vendor folder? The idea is that I can get updates from the vendor, and then merge those updates with any changes I made to my trunk.</p>
|
<blockquote>
<p>Create folders through command line for repository organization (including projects and vendors).</p>
</blockquote>
<p>Do you mean creating the repository structure by making directories inside the subversion intallation directory? That's very wrong.</p>
<p>You have to create the necessary folders via the <code>svn mkdir</code> command and not via filesystem.</p>
<p>In <code>/usr/local/svn</code> you have the physical implementation of the Subversion repository, and you must access it only via a client, and never touch it "by hand".</p>
<p>For example, using the file:// URL scheme</p>
<pre><code>svn mkdir file:///usr/local/svn/projects -m "Parent dir for projects created"
</code></pre>
|
Is there danger of corruption in SQL Server 2000 databases when using SQL Server 2005 Management Studio? <p>In an interview for a SQL DBA position a while back, I mentioned I prefer the SQL 2005 Management Studio app vs. the old 2000 versions of Enterprise Manager / Query Analyzer. The DBA who was interviewing me said that they had experienced some sort of database corruption in their 2000 databases when making changes from the 2005 MS, so they always use Enterprise Manager now. </p>
<p>He was a bit vague, but I got the impression he was talking about some sort of corruption experienced when making server-wide or database-level setting changes, and not just routine SQL updates or something.</p>
<p>Anyone heard of anything like this? I didn't end up taking that position, so I can't follow up to get more info.</p>
|
<p>Sounds like he was just was using that as an excuse for lack of experience with SQL 2005 Management Studio. DBA's hate change. lol.</p>
|
Painless 'Analysis of Algorithms' Training? <p>I had a painful experience with the "Analysis of Algorithms" classes back in college but have recently found a need for it in the <em>real world</em>. -- Anyway, I'm looking for a simple-yet-effective crash course. Any ideas?</p>
<p><em>Related Sidenote:</em> It sure would be nice if there were a "Cartoon Guide to Algorithm Analysis", taught by Dilbert.</p>
<p><strong>UPDATE:</strong> A very similar question can be found at: <a href="http://stackoverflow.com/questions/366418/how-to-get-started-on-algorithms">How to get started on ALGORITHMS?</a></p>
|
<p>There are a lot of good books on the subject. I like <a href="http://rads.stackoverflow.com/amzn/click/020140009X">An Introduction to the Analysis of Algorithms</a>. Also check out the algorithms course on <a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-046JFall-2005/CourseHome/">MIT OpenCourseWare</a> (using <a href="http://rads.stackoverflow.com/amzn/click/0262032937">CLRS</a> as the course text). It's a little bit deep, but having it online allows you to go at your own pace.</p>
<p>A couple of other books that I've started reading recently are <a href="http://oreilly.com/catalog/9780596516246/">Algorithms in a Nutshell</a> and the <a href="http://rads.stackoverflow.com/amzn/click/0387948600">Algorithm Design Manual</a>. They both take a lighter approach than most algorithms books. Instead of heavy math and formal proofs these books give you realistic problem statements and show you the steps taken to refine an algorithm. They also show you how to <em>estimate</em> and <em>measure</em> the complexity of a solution. I would highly recommend either book.</p>
|
Exposing inherited members of a COM vb.net class <p>I have two vb.net class:</p>
<pre><code>Public MustInherit Class Class1
Private m_sProperty1 As String = ""
Public Property sProperty1() As String
Get
Return m_sProperty1
End Get
Set(ByVal value As String)
m_sProperty1 = value
End Set
End Property
End Class
<ComClass("classid","interfaceid","eventid")> _
Public Class Class2
Inherits Class1
Private m_sProperty2 As String = ""
Public Property sProperty2() As String
Get
Return m_sProperty2
End Get
Set(ByVal value As String)
m_sProperty2 = value
End Set
End Property
End Class
</code></pre>
<p>When I reference the compiled DLL through VB6, Class2 only exposes sProperty2. How can I access the inherited property of the base class (sProperty1) through COM?</p>
|
<p>This seems to answer your question:</p>
<p><strong>Exporting Inheritance Hierarchies</strong></p>
<p>Managed class hierarchies flatten out when exposed as COM objects. For example, if you define a base class with a member, and then inherit the base class in a derived class that is exposed as a COM object, clients that use the derived class in the COM object will not be able to use the inherited members. Base class members are accessible from COM objects only as instances of a base class, and then only if the base class is also created as a COM object.</p>
<p>Taken from here: <a href="http://msdn.microsoft.com/en-us/library/8877bdk6(VS.80).aspx" rel="nofollow">Troubleshooting Interoperability</a></p>
|
Is there a built in .NET exception that indicates an illegal object state? <p>What exception should I throw if I encounter an illegal state - for instance, an initialization method that should only be called once being called a second time? I don't really see any built-in exception that makes sense. This seems like something that should be in the framework - am I not poking in the right spot?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx">InvalidOperationException</a> maybe?</p>
<blockquote>
<p>The exception that is thrown when a method call is invalid for the object's current state. </p>
</blockquote>
|
Javascript - multiple client-side validations on same event <p>I am performing two validations on the client side on the samve event.
I have defined my validations as shown below</p>
<pre><code>btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();"
</code></pre>
<p>Pseudo code for </p>
<pre><code>prepareSave():
{
if (bPendingchanges)
{
return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first')
}
else
{return true}
}
</code></pre>
<p>Pseudo code for </p>
<pre><code>prepareSearch():
{
if (bNoSearchText)
{
alert('Please specify search criteria before proceeding')
return false;
}
else
{return true;}
}
</code></pre>
<p>When <code>bPendingchanges=false</code>, I never get the second validation running.
Anyone who can quickly spot what I have overlooked here? Please?</p>
|
<p><code>return</code>, as the name implies, returns control back to whatever called the code in question. Therefore, anything that's after a return statement</p>
<pre><code>return prepareSave(); return prepareSearch();
// ^^^^^^^^^^^^^^^^^^^^^^^ e.g. this part
</code></pre>
<p>never executes. Try <code>return (prepareSave() && prepareSearch());</code></p>
|
Oracle single-table constant merge with CLOB using JDBC <p>As a follow-up to <a href="http://stackoverflow.com/questions/167471/">this question</a>, I need help with the following scenario:</p>
<p>In Oracle, given a simple data table:</p>
<pre><code>create table data (
id VARCHAR2(255),
key VARCHAR2(255),
value CLOB);
</code></pre>
<p>I am using the following merge command:</p>
<pre><code>merge into data
using (
select
? id,
? key,
? value
from
dual
) val on (
data.id=val.id
and data.key=val.key
)
when matched then
update set data.value = val.value
when not matched then
insert (id, key, value) values (val.id, val.key, val.value);
</code></pre>
<p>I am invoking the query via JDBC from a Java application.</p>
<p>When the "value" string is large, the above query results in the following Oracle error:</p>
<pre><code>ORA-01461: cannot bind a LONG value for insert into a long column
</code></pre>
<p>I even set the "SetBigStringTryClob" property as documented <a href="http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/clob10g/handlingclobsinoraclejdbc10g.html" rel="nofollow">here</a> with the same result.</p>
<p>Is it possible to achieve the behavior I want given that "value" is a CLOB?</p>
<p>EDIT: Client environment is Java</p>
|
<p>You haven't mentioned specifically in your post, but judging by the tags for the question, I'm assuming you're doing this from Java.</p>
<p>I've had success with code like this in a project I just finished. This application used Unicode, so there may be simpler solutions if your problem domain is limited to a standard ASCII character set.</p>
<p>Are you currently using the OracleStatement.setCLOB() method? It's a terribly awkward thing to have to do, but we couldn't get around it any other way. You have to actually create a temporary CLOB, and then use that temporary CLOB in the setCLOB() method call.</p>
<p>Now, I've ripped this from a working system, and had to make a few ad-hoc adjustments, so if this doesn't appear to work in your situation, let me know and I'll go back to see if I can get a smaller working example. </p>
<p>This of course assumes you're using the Oracle Corp. JDBC drivers (ojdbc14.jar or ojdbc5.jar) which are found in $ORACLE_HOME/jdbc/lib</p>
<pre><code>CLOB tempClob = CLOB.createTemporary(conn, true, CLOB.DURATION_SESSION);
// Open the temporary CLOB in readwrite mode to enable writing
tempClob.open(CLOB.MODE_READWRITE);
// Get the output stream to write
Writer tempClobWriter = tempClob.getCharacterOutputStream();
// Write the data into the temporary CLOB
tempClobWriter.write(stringData);
// Flush and close the stream
tempClobWriter.flush();
tempClobWriter.close();
// Close the temporary CLOB
tempClob.close();
myStatement.setCLOB(column.order, tempClob);
</code></pre>
<p>Regards,
Dwayne King</p>
|
OpenGL glDrawPixels on dynamic 3D arrays <p>How do you draw the following dynamic <strong>3D</strong> array with OpenGL <strong>glDrawPixels()</strong>?
You can find the documentation here: <a href="http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html" rel="nofollow">http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html</a></p>
<pre><code>float ***array3d;
void InitScreenArray()
{
int i, j;
int screenX = scene.camera.vres;
int screenY = scene.camera.hres;
array3d = (float ***)malloc(sizeof(float **) * screenX);
for (i = 0 ; i < screenX; i++) {
array3d[i] = (float **)malloc(sizeof(float *) * screenY);
for (j = 0; j < screenY; j++)
array3d[i][j] = (float *)malloc(sizeof(float) * /*Z_SIZE*/ 3);
}
}
</code></pre>
<p>I can use only the following header files:</p>
<pre><code>#include <math.h>
#include <stdlib.h>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
</code></pre>
|
<p>Uh ... Since you're allocating <i>each single pixel</i> with a separate <code>malloc()</code>, you will have to draw each pixel with a separate call to <code>glDrawPixels()</code>, too. This is (obviously) insane; the idea of bitmapped graphics is that the pixels are stored in an adjacent, compact, format, so that it is quick and fast (<i>O(1)</i>) to move from one pixel to another. This looks very confused to me.</p>
<p>A more sensible approach would be to allocate the "3D array" (which is often referred to as a 2D array of pixels, where each pixel happens to consist of a red, green and blue component) with a single call to <code>malloc()</code>, like so (in C):</p>
<pre><code>float *array3d;
array3d = malloc(scene.camera.hres * scene.camera.vres * 3 * sizeof *array3d);
</code></pre>
|
.NET bug when converting float to integer? <p>Check it out: this little .NET Console Program yields interesting results...notice how I'm converting a float to an integer in two different ways:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CastVsConvert
{
class Program
{
static void Main(string[] args)
{
int newWidth = 0;
CalculateResizeSizes(600, 500, out newWidth);
}
static void CalculateResizeSizes(int originalWidth, int maxWidth, out int newWidth)
{
float percentage = 1.0F;
percentage = maxWidth / (float)originalWidth;
newWidth = (int)((float)originalWidth * percentage);
int newWidthConvert = Convert.ToInt32((float)originalWidth * percentage);
Console.Write("Percentage: {0}\n", percentage.ToString());
Console.Write("Cast: {0}\n", newWidth.ToString());
Console.Write("Convert: {0}\n", newWidthConvert.ToString());
}
}
}
</code></pre>
<p>I would expect the output for "Cast" and "Convert" to be the same, but they're not...here's the output:</p>
<pre><code>C:\Documents and Settings\Scott\My Documents\Visual Studio 2008\Projects\CastVsC
onvert\CastVsConvert\bin\Debug>CastVsConvert.exe
Percentage: 0.8333333
Cast: 499
Convert: 500
</code></pre>
<p>Does anybody know why .NET is returning different values here? </p>
|
<p>Its not a bug, <code>cast</code> truncates, <code>convert</code> rounds.</p>
<p>See <a href="http://stackoverflow.com/questions/104063/systemconverttoint-vs-int">this</a></p>
|
HttpWebRequest, known problems with canceling requests? <p>Are there any known issues with canceling HttpWebRequest HTTP requests? We find that when we cancel 4-5 requests, the next request hangs indefinitely.</p>
<p>If there are no known problems with this, then I'm probably doing something wrong... where is a good resource example that shows how this works (a complete solution, not a couple of code snippets)?</p>
<p>If there are known problems, what can I do to work around them, in order to effectively cancel as many requests as I need to?</p>
|
<p>After you cancel the request, take care to close the response stream, otherwise you will have leaks.</p>
<p>I usually use "using" when obtain the response from the web request to ensure that the response is closed:</p>
<pre><code>WebRequest request = WebRequest.Create("http://google.com");
using (WebResponse response = request.GetResponse())
{
//do my job
}
</code></pre>
<p>That way, even if you cancel the request, or it throws an exception during response reading, the resposne and it's stream will be closed.</p>
|
Updating a Database from DataBound Controls <p>I'm currently creating a WinForm in VB.NET bound to an access database.</p>
<p>Basically what i have are two forms: one is a search form used to search the database, and the other is a details form. You run a search on the searchForm and it returns a list of Primary Keys and a few other identifying values. You then double click on the entry you want to view, and it loads the details form.</p>
<p>The Details form has a collection of databound controls to display the data: mostly text boxes and checkboxs. The way i've set it up is i used the UI to build the form and then set the DataBindings Property of each control to "TblPropertiesBindingSource - " where value name is one of the values in the table (such as PropertyID or HasWoodFloor).</p>
<p>Then, when you double click an entry in the searchform, I handle the event by parsing the Primary Key (PropertyID) out of the selected row and then storing this to the details form:</p>
<p>Note: Detail is the details form that is opened to display the info</p>
<pre><code>Private Sub propView_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles propView.CellDoubleClick
Dim detail As frmPropertiesDetail = New frmPropertiesDetail
detail.id = propView.Rows(e.RowIndex).Cells(0).Value
detail.Show()
End Sub
</code></pre>
<p>Then, upon loading the details form, it set's the filter on the BindSource as such:</p>
<pre><code>TblPropertiesBindingSource.Filter() = "PropertyID=" & id
</code></pre>
<p>This works great so far. All the controls on the details form will display the correct info. The problem is updating changes. </p>
<p>Scenario:
If i have the user load the details for say, property 10001, it will show a description in a textBox named descriptionBox which is identical to the value of the description value of for that entry in the database. I want the user to then be able to change the text of the text box (which they can currently do) and click the save button (saveBut) and have the form update all the values in the controls to the database.</p>
<p>Theorectically, it should do this as the controls are DataBound, thus i can avoid writing code that tells each entry in the database row to take the value of the aligned control.</p>
<p>I've tried calleding PropertiesTableAdapter.Update(PropertiesBindingSource.DataSource), but that doesnt seem to do it.</p>
|
<p>The site is down, so use the google cached version of the following link:</p>
<p><a href="http://www.paulstovell.com/blog/binding-oriented-programming" rel="nofollow">http://www.paulstovell.com/blog/binding-oriented-programming</a></p>
<p>It's near exact to what you're trying to do.</p>
|
Is it possible to get the matching string from an SQL query? <p>If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. <code>SELECT * FROM table WHERE column LIKE %news%</code>), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a teaser, if you will.</p>
|
<pre><code>select substring(column,
CHARINDEX ('news',lower(column))-10,
20)
FROM table
WHERE column LIKE %news%
</code></pre>
<p>basically substring the column starting 10 characters before where the word 'news' is and continuing for 20.</p>
<p>Edit: You'll need to make sure that 'news' isn't in the first 10 characters and adjust the start position accordingly.</p>
|
How to make the group-box text background transparent <p>I want to make a transparent dialog. I capture the OnCtlColor message in a CDialog derived class...this is the code:</p>
<pre><code>HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if(bSetBkTransparent_)
{
pDC->SetBkMode(TRANSPARENT);
hbr = (HBRUSH)GetStockObject(NULL_BRUSH);
}
return hbr;
}
</code></pre>
<p>It works fine for all the controls but the group-box (CStatic). All the labels (CStatic) are been painted with a transparent text background but the text of the group box it is not transparent.</p>
<p>I already googled for this but I didn't find a solutions. Does anybody know how to make a real transparent group-box?</p>
<p>By the way, I am working in Windows XP. And I don't want to fully draw the control to avoid having to change the code if the application is migrated to another OS.</p>
<p>Thanks,</p>
<p>Javier</p>
<p>Note: I finally changed the dialog so that I don't need to make it transparent. Anyway, I add this information because maybe someone is still trying to do it. The groupbox isn't a CStatic but a CButton (I know this is not new). I changed the Windows XP theme to Windows classic and then the groupbox backgraund was transparent. The bad new is that in this case the frame line gets visible beneath the text...so if someone is following this approach I think maybe he/she would better follow the Adzm's advice. </p>
|
<p>You have two options.</p>
<p>You can not use Common Controls v6 (the XP-Styled controls), which will make your app lose the fanciness of newer windows versions. However IIRC the groupbox will respect the CTLCOLOR issue. If you are not using that anyway, and it is still not respecting your color, then you only have one option...</p>
<p>Which is to draw it yourself. I know you said you don't want to, but sometimes you have to. Thankfully a group box is a very simple control to draw. This page has an example for drawing a classic-style group box: <a href="http://www.codeguru.com/cpp/controls/controls/groupbox/article.php/c2273/" rel="nofollow">http://www.codeguru.com/cpp/controls/controls/groupbox/article.php/c2273/</a> You can also draw it very simply using the UxTheme libraries that come with XP+.</p>
<p>If the application will be migrated to another OS, you will have plenty to deal with migrating over an MFC application in general. If that is your goal, then you should really look into developing with a cross-platform UI toolkit.</p>
|
Download file with Resume capability for windows servers <p>I am building an Auto Updater for a winforms desktop application.</p>
<p>When the update is downloading, how can I provide a <b>Resume download</b> capability in case the customers internet connection breaks?</p>
|
<p>If you are doing a windows-only application, and you are targeting windows XP and later OSes, you can use BITS: the Background Intelligent Transfert Service.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb968799%28v=VS.85%29.aspx" rel="nofollow">MSDN page on BITS</a></li>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc188766.aspx" rel="nofollow">Interfacing BITS with .NET</a></li>
</ul>
<p>It is the same service used by WindowsUpdate.</p>
<p>Otherwise rolling out your solution in C# using the HTTP auto-resume capabilities should not be too difficult, (using the Accept-Range directive in the HTTP request)</p>
<ul>
<li><a href="http://www.csharp-station.com/HowTo/HttpWebFetch.aspx" rel="nofollow">How To: Fetching Web Pages with HTTP</a></li>
<li><a href="http://bytes.com/forum/thread446201.html" rel="nofollow">downloading a large file</a></li>
</ul>
|
How should I treat strings of digits in XML::RPC and Drupal? <p>I am trying to use an XML-RPC server on my Drupal (PHP) backend to make it easier for my Perl backend to talk to it. However, I've run into an issue and I'm not sure which parts, if any, are bugs. Essentially, some of the variables I need to pass to Drupal are strings that sometimes are strings full of numbers and the Drupal XML-RPC server is returning an error that when a string is full of numbers it is not properly formed.</p>
<p>My Perl code looks something like this at the moment.</p>
<pre><code>use strict;
use warnings;
use XML::RPC;
use Data::Dumper;
my $xmlrpc = XML::RPC->new(URL);
my $result = $xmlrpc->call( FUNCTION, 'hello world', '9876352345');
print Dumper $result;
</code></pre>
<p>The output is:</p>
<pre><code>$VAR1 = {
'faultString' => 'Server error. Invalid method parameters.',
'faultCode' => '-32602'
};
</code></pre>
<p>When I have the Drupal XML-RPC server print out the data it receives, I notice that the second argument is typed as i4:</p>
<pre><code><param>
<value>
<i4>9876352345</i4>
</value>
</code></pre>
<p>I think when Drupal then finishes processing the item, it is typing that variable as an int instead of a string. This means when Drupal later tries to check that the variable value is properly formed for a string, the is_string PHP function returns false.</p>
<pre><code>foreach ($signature as $key => $type) {
$arg = $args[$key];
switch ($type) {
case 'int':
case 'i4':
if (is_array($arg) || !is_int($arg)) {
$ok = FALSE;
}
break;
case 'base64':
case 'string':
if (!is_string($arg)) {
$ok = FALSE;
}
break;
case 'boolean':
if ($arg !== FALSE && $arg !== TRUE) {
$ok = FALSE;
}
break;
case 'float':
case 'double':
if (!is_float($arg)) {
$ok = FALSE;
}
break;
case 'date':
case 'dateTime.iso8601':
if (!$arg->is_date) {
$ok = FALSE;
}
break;
}
if (!$ok) {
return xmlrpc_error(-32602, t('Server error. Invalid method parameters.'));
}
}
</code></pre>
<p>What I'm not sure about is on which side of the divide the issue lies or if there is something else I should be using. Should the request from the Perl side be typing the content as a string instead of i4 or is the Drupal side of the request too stringent for the string type? My guess is that the issue is the latter, but I don't know enough about how an XML-RPC server is supposed to work to know for sure.</p>
|
<p>The number <code>9876352345</code> is too big to fit in a 32bit integer. That might cause the problem.</p>
|
How to justify more ram for SQL Server 2005 <p>We have SQL Server 2005 running on Win2003/64, and we push it hard. We generate real time reports on several tables with a couple million records using asp.net 3.5, and they will periodically time out.</p>
<p>I'd like to increase our memory from 8GB to 16GB or even 32GB to see how that helps, but I need to justify this to the pencil pushers before they will spend the money. Can someone point me to some resources that will help me make my case and will get me some hard numbers to use?</p>
|
<p>First find out what is really the problem and that the server is properly tuned for the queries you are running. It's very sad to waste the money on RAM to find out you are I/O bound.</p>
<p>After you gather data about the cause of the timeouts you should be able to convince the pencil wielders easily.</p>
<p>Some tuning/monitoring links:</p>
<p><a href="http://www.brentozar.com/archive/2008/03/sql-server-2005-setup-checklist-part-1-before-the-install/" rel="nofollow">http://www.brentozar.com/archive/2008/03/sql-server-2005-setup-checklist-part-1-before-the-install/</a> (check both articles)</p>
<p><a href="http://www.sql-server-performance.com/" rel="nofollow">http://www.sql-server-performance.com/</a></p>
<p>About I/O specifically:</p>
<p><a href="http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/pdpliobp.mspx" rel="nofollow">http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/pdpliobp.mspx</a></p>
<p><a href="http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1307990,00.html" rel="nofollow">http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1307990,00.html</a></p>
<p><a href="http://www.novicksoftware.com/Articles/sql-server-io-statistics.htm" rel="nofollow">http://www.novicksoftware.com/Articles/sql-server-io-statistics.htm</a></p>
|
Is anybody using OBIEE (formerly Siebel Analytics) ? What is your experience <p>We are in the process of selecting BI stack for our data warehouse. The top contenders are OBIEE = Oracle BI Enterprise Edition (formerly Siebel Analytics) and Microstrategy.</p>
<p>Has anyone worked with OBIEE? Lessons learned? General impressions? Flaws, strengths?</p>
|
<p>I've been involved in 20 OBIEE projects for the past 6 years. It's a good ROLAP product. It has a flexible, mostly intuitive UI that end users typically like. HTML, Javascript, and some Flash (charts) is used for presentation. There is a presentation server that runs under a web server (or app server) and the core of the tool, the analytics engine runs separately. Generally speaking the tool generates efficient SQL. Performance overall is generally good, but is dependent on the source data structures and the types of reporting being attempted.</p>
<p>The metadata layer is well designed and extremely (almost to a fault) flexible, though it could stand to be much better documented. The tool expects to work with traditional star schemas. It works well with all the major RDBMSs. It has multi-level caching and is very flexible with authentication, functionality access, and data security. It doesn't do everything I'd like it to do, but taken as a whole, it's a first class application. Most of it's flaws are little things, there really isn't anything major. I'd say from a presentation perspective it's prompting is far weaker than it could be. </p>
<p>It's not a cube tool (though it can source data from cubes) and it's not meant to be a tool for generating massive reports (long lists and massive data sets presented to end users) though it does get used that way. If anything its biggest flaw is probably the cost, but it's probably comparable to all the other enterprise players. </p>
<p>I don't know a lot about Microstrategy, but a friend who has worked with both says it has a great front end and a weak back end. He prefers OBIEE considerably, though he's developer biased. It really is quite easy to build physical, logical, and presentation metadata in the tool. As with all warehouses, the hard work is mostly in the ETL, followed by good BA work and good performance tuning in the DB. </p>
|
After clicking the nth item, how do I manipulate another nth element? <p>I'm using jQuery and wanting to target the nth <li> in a list after clicking the nth link.</p>
<pre><code><ul id="targetedArea">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div id="clickedItems">
<a></a>
<a></a>
<a></a>
<a></a>
</div>
</code></pre>
<p>I can target them individually, but I know there must be a faster way by passing which <a> element I clicked on.</p>
<pre><code>$("#clickedItem a:eq(2)").click(function() {
$("#targetedArea:eq(2)").addClass('active');
return false;
});
</code></pre>
<p>Cheers,<br />
Steve </p>
|
<p>how about something like this:</p>
<pre><code>$('#clickedItems a').click(function() {
// figure out what position this element is in
var n = $('#clickedItems a').index($(this) );
// update the targetedArea
$('#targetedArea li:eq('+n+')').html('updated!');
return false;
});
</code></pre>
<p>assuming a 1:1 relationship between your <code><a></code> and <code><li></code> elements it will update the appropriate <code><li></code></p>
|
import data from a webpage to excel <p>I'm in need of a macro that will enter data into a webpage search field and than copy the results to excel.</p>
|
<p>It's just a simple "File Open". No need for a macro.</p>
<p>Excel can open URLs directly. If the URL contains any tables, those will be formatted appropriately.</p>
<p>Try this: </p>
<ul>
<li>Run Excel</li>
<li>File | Open</li>
<li>Type <code>http://finance.yahoo.com/q?s=MSFT</code> as the file name</li>
<li>Ignore the warning</li>
</ul>
|
Display HTML in an Actionscript 3 project <p>Folks,</p>
<p>I am pulling all my Flash (pure AS3 project, not Flash CS3) content from a Drupal back-end for SEO purposes. This works great, except the HTML rendering built into the TextField object leaves a lot to be desired. Could anyone recommend any libraries that would allow me to display HTML elements? At this stage, commercial or open-source libraries are welcome.</p>
<p>Thanks,
Marcus</p>
|
<p>you might also want to try:
<a href="http://code.google.com/p/htmlwrapper/" rel="nofollow">http://code.google.com/p/htmlwrapper/</a></p>
<p>I haven't used it but it looks like it does what you want.</p>
|
How to get partition ranges in SQL 2005 <p>I have a partitioned table in SQL Enterprise 2005. I need to query the PARTITION FUNCTION to find it's partition ranges. What SQL query will give me those values?</p>
|
<p>Got this from the SQL profiler watching the management studio generate the script for creating the function</p>
<p>SELECT
sprv.value AS [Value],
sprv.boundary_id AS [ID]
FROM
sys.partition_functions AS spf
INNER JOIN sys.partition_range_values sprv ON sprv.function_id=spf.function_id
WHERE
(spf.name=N'fnPartitionLast30Days')
ORDER BY
[ID] ASC</p>
|
Are non-pure virtual functions with parameters bad practice? <p>I have a base class with an optional virtual function</p>
<pre><code>class Base {
virtual void OnlyImplementThisSometimes(int x) {}
};
</code></pre>
<p>When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this:</p>
<pre><code>class Base {
virtual void OnlyImplementThisSometimes(int x)
{
x = 0;
}
};
</code></pre>
<p>I also have the problem that if I'm not careful, the subclass I make can implement the wrong function and then I don't notice because of overloading: e.g.</p>
<pre><code>class Derived : public Base {
void OnlyImplementThisSometimes(int x, int y) { // some code }
};
Derived d;
Base *b = dynamic_cast<Base *>(&d);
b->OnlyImplementThisSometimes(x); // calls the method in the base class
</code></pre>
<p>The base class method was called because I implemented the derived function with an "int y" param but there is no warning about this. Are these just common pitfalls in C++ or have I misunderstood virtual functions?</p>
|
<p>Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example:</p>
<pre><code>virtual void OnlyImplementThisSometimes(int ) { }
</code></pre>
<p>Mistakenly implementing the wrong method signature when trying to override the virtual function is just something you need to be careful about in C++. Languages like C# get around this with the 'override' keyword.</p>
|
How do you scrape AJAX pages? <p>The title says it all. Please advise how to scrape AJAX pages.</p>
|
<p><strong>Overview:</strong></p>
<p>All screen scraping first requires manual review of the page you want to extract resources from. When dealing with AJAX you usually just need to analyze a bit more than just simply the HTML. </p>
<p>When dealing with AJAX this just means that the value you want is not in the initial HTML document that you requested, but that javascript will be exectued which asks the server for the extra information you want. </p>
<p>You can therefore usually simply analyze the javascript and see which request the javascript makes and just call this URL instead from the start. </p>
<p><hr /></p>
<p><strong>Example:</strong></p>
<p>Take this as an example, assume the page you want to scrape from has the following script:</p>
<pre><code><script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
}
</script>
</code></pre>
<p>Then all you need to do is instead do an HTTP request to time.asp of the same server instead. <a href="http://www.w3schools.com/Ajax/ajax_server.asp">Example from w3schools</a>.</p>
<p><hr /></p>
<p><strong>Advanced scraping with C++:</strong> </p>
<p>For complex usage, and if you're using C++ you could also consider using the firefox javascript engine <a href="http://www.mozilla.org/js/spidermonkey/">SpiderMonkey</a> to execute the javascript on a page. </p>
<p><strong>Advanced scraping with Java:</strong></p>
<p>For complex usage, and if you're using Java you could also consider using the firefox javascript engine for Java <a href="http://www.mozilla.org/rhino/">Rhino</a></p>
<p><strong>Advanced scraping with .NET:</strong></p>
<p>For complex usage, and if you're using .Net you could also consider using the Microsoft.vsa assembly. Recently replaced with ICodeCompiler/CodeDOM.</p>
|
Required Field Validator Not Firing <p>I'm having an issue with a standard ASP.NET page that has a TextBox and a RequiredFieldValidator. The steps to reproduce are quite simple:</p>
<ol>
<li>Place a TextBox on a page</li>
<li>Place a RequiredFieldValidator on the page</li>
<li>Point the RequiredFieldValidator at the TextBox</li>
<li>Run the app</li>
<li>Tab away from the TextBox the RequiredFieldValidator does not show</li>
<li>Enter text, then delete the text and THEN tab away, the RequiredFieldValidator does show</li>
</ol>
<p>The RequiredFieldValidator works fine in both cases after a postback, however it seems the client-side code isn't firing until something is entered into the textbox (and then deleted).</p>
<p>Does anyone have a solution to this without hacking away at JavaScript myself?</p>
|
<p>A follow-up to my previous answer:</p>
<p>Validation occurs in the onchange event, rather than the onblur. onchange fires when the focus is lost AND the control value has changed.</p>
<p>To trigger validation in the onblur event, I added the following code in the Page_Load():</p>
<pre><code>ScriptManager.RegisterStartupScript(this, GetType(), "js" + myTextBox.ClientID,
"ValidatorHookupEvent(document.getElementById(\"" + myTextBox.ClientID +
"\"), \"onblur\", \"ValidatorOnChange(event);\");", true);
</code></pre>
<p>Works in ASP.Net 2.</p>
|
Resizable Java component <p>I would like to have a Java component which has a resize icon on the bottom right of the component so that when I drag that icon, the component will automatically resize with it.</p>
<p>By resize icon, I mean the following:</p>
<p><img src="http://lh5.ggpht.com/%5F7dfPdX2BP6o/SQ%5FsPvvHpTI/AAAAAAAAAKU/vRWKb%5FpLVvc/s144/resize%20icon.jpg" alt="resize icon in Google Talk" /></p>
<p>The above image contains the resize icon in the Google Talk messenger's main window. Is there any Java component which provides this facility?</p>
|
<p>You will find in this article how to add an icon looking like the resize icon you are referring to.</p>
<p><img src="http://i.stack.imgur.com/uyYo4.gif" alt="PixelPushing"> <a href="http://today.java.net/pub/a/today/2005/06/07/pixelpushing.html" rel="nofollow">PixelPushing</a></p>
<p><img src="http://i.stack.imgur.com/shuJJ.gif" alt="Google Talk Styled Form"></p>
|
conditional formating in rails partials <p>I am rendering a rails partial and I want to alternate the background color when it renders the partial. I know that is not super clear so here is an example of what I want to do:</p>
Row One grey Background
Row Two yellow background
Row Three grey Background
Row Four yellow background
<ul>
<li>sorry stackoverflow seams to prevent the background colors from being shown but I think this makes my idea clear</li>
</ul>
<p>This is the view code that I am using </p>
<pre><code><table>
<%= render :partial => 'row' :collection => @rows %>
</table>
</code></pre>
<p>the _row.html.erb partial looks like this</p>
<pre><code><tr bgcolor="#AAAAAA">
<td><%= row.name %></td>
</tr>
</code></pre>
<p>The problem is I do not know how to change the background color for every other row. Is there away to do this?</p>
|
<p>You could use the Cycle helper. Something like this:</p>
<pre><code><tr class="<%= cycle("even", "odd") %>">
<td><%= row.name %></td>
</tr>
</code></pre>
<p>Or in your case use bgcolor instead, although i would recomend using css classes.</p>
<p>You can cycle through more than two values: cycle(âfirstâ, âsecondâ, âthirdâ, âand_moreâ). </p>
<p>There is also: reset_cycle(âcycle_nameâ) This makes sure that on each iteration, you will start again with your first value of the cycle list.</p>
<p>Check the rails <a href="http://apidock.com/rails/ActionView/Helpers/TextHelper/cycle">documentation</a> for more examples.</p>
|
Userland autoboxing? <p>Is it possible to implement autoboxing for your own classes?</p>
<p>To illustrate my example, this is what I might want to write:</p>
<pre><code>Foo foo = "lolcat";
</code></pre>
<p>And this is what Java would do (as per my own definitions, somewhere, somehow), under the hood:</p>
<pre><code>Foo foo = new Foo();
foo.setLolcat("lolcat");
</code></pre>
<p>So, is this possible somehow, or is it a JVM-feature only?</p>
|
<p>No, java does not support operator overloading (<a href="http://en.wikipedia.org/wiki/Operator_overloading">http://en.wikipedia.org/wiki/Operator_overloading</a>).</p>
<p>Autoboxing is a compiler feature and not available for your own classes.</p>
<p>The reasoning is explained here:
<a href="http://www.cafeaulait.org/javafaq.html#xtocid1902938">http://www.cafeaulait.org/javafaq.html#xtocid1902938</a></p>
|
How do I use MSTest without Visual Studio? <p>Does MSTest have standalone GUI similar to nUnit that lets me use it and run test without visual studio? What is the official site for MSTest where I can learn more about how to use it?</p>
|
<p>MSTest can be used without installing Visual Studio. You will need to install Visual Studio Test Agent, which is a free download from Microsoft:
<a href="http://www.microsoft.com/download/en/details.aspx?id=1334">http://www.microsoft.com/download/en/details.aspx?id=1334</a>.</p>
<p>I think this approach is better from a licensing perspective than manually copying MSTest.exe and its dependencies onto the build server.</p>
<p>See this blog for reference:
<a href="http://blogs.msdn.com/b/anutthara/archive/2009/12/16/running-tests-in-mstest-without-installing-the-vs-ide.aspx">http://blogs.msdn.com/b/anutthara/archive/2009/12/16/running-tests-in-mstest-without-installing-the-vs-ide.aspx</a></p>
|
MDI Parent Menu and Child Menu <p>I am using VB.Net on Winforms Development developing an MDI application.</p>
<p>In my Parent form, I have a menu strip. In my child forms, I also have a menu strip attached to each form, which invokes a different set of command when accessed. Is it possible then that in an MDI form, the child form which is currently active be the menu that would display in the parent form?</p>
|
<p>It's easy. Just add a MenuStrip to the parent but leave it empty. The built-in support for menu merging ensures that the active child's menu appears in the empty parent strip.</p>
|
start specific iis 6.0 website via script <p>I've googled around and can't find a clear answer.</p>
<p>I simply want to start some of my iis 6.0 websites via a script that will be run on start up.</p>
<p>anyone got any tips for that?</p>
|
<p>Well, I've googled around, and <a href="http://windowsitpro.com/article/articleid/22971/iis-scripting-solutions.html" rel="nofollow">this is what I've found</a>.
Snippet :</p>
<pre><code>cd \inetpub\adminscripts
Cscript.exe adsutil.vbs START_SERVER W3SVC/1
</code></pre>
|
Detect whether adobe reader is installed using VB code <p>I want to detect whether adobe reader is installed using VB6. Also if detected that it's not installed, what would be the best solution?</p>
|
<p>There are crude ways (checking for files on Program files directory), but I'd recommend you declare full-registry functions (not getSetting from vb) as in <a href="http://www.windowsdevcenter.com/pub/a/windows/2004/06/15/VB_Registry_Keys.html" rel="nofollow">http://www.windowsdevcenter.com/pub/a/windows/2004/06/15/VB_Registry_Keys.html</a> and fetch </p>
<p>*HKEY_CLASSES_ROOT\.pdf*</p>
<p>If that's there, something capable of reading pdfs is there (which is what you want, right?).</p>
<p>As a bonus, *HKEY_CLASSES_ROOT\.pdf\OpenWithList* has a list (wow) of registered applications that open .pdf files... the key names on that list are programs you can invoke from vb using <em>shell("start "+ OpenAppName)</em></p>
|
What's the best way to perform system tasks from Ruby on Rails? <p>I am building a small system administration web application (think Web-Min, but in RoR) and I need to be able to access system parameters from my Ruby code. For instance, I want to allow the user to change the hostname, time zone, or network config of the server. </p>
<p>My current thoughts are to have a separate setuid script (Perl, Ruby, ??) so that I can call it from my RoR code and it will perform the actions. That is quite cumbersome and not very elegant. I'm a Ruby newbie and would like to know if there is a better way to accomplish this type of thing.</p>
<p>Thanks!</p>
|
<p>You can use <a href="http://backgroundrb.rubyforge.org/" rel="nofollow">BackgrounDRb</a>. Its purpose is to offload tasks from rails apps, and you can run the server under a different user.</p>
|
How to build Python C extension modules with autotools <p>Most of the documentation available for building Python extension modules
uses distutils, but I would like to achieve this by using the appropriate
python autoconf & automake macros instead.</p>
<p>I'd like to know if there is an open source project out there that does
exactly this. Most of the ones I've found end up relying on a setup.py file.
Using that approach works, but unfortunately ends up rebuilding the entire
source tree any time I make a modification to the module source files.</p>
|
<p>Supposing that you have a project with a directory called <code>src</code>, so let's follow the follow steps to get a python extension built and packaged using autotools:</p>
<h2>Create the Makefile.am files</h2>
<p>First, you need to create one Makefile.am in the root of your project, basically (but not exclusively) listing the subdirectories that should also be processed. You will end up with something like this:</p>
<pre><code>SUBDIRS = src
</code></pre>
<p>The second one, inside the <code>src</code> directory will hold the instructions to actually compile your python extension. It will look like this:</p>
<pre><code>myextdir = $(pkgpythondir)
myext_PYTHON = file1.py file2.py
pyexec_LTLIBRARIES = _myext.la
_myext_la_SOURCES = myext.cpp
_myext_la_CPPFLAGS = $(PYTHON_CFLAGS)
_myext_la_LDFLAGS = -module -avoid-version -export-symbols-regex initmyext
_myext_la_LIBADD = $(top_builddir)/lib/libhollow.la
EXTRA_DIST = myext.h
</code></pre>
<h2>Write the configure.ac</h2>
<p>This file must be created in the root directory of the project and must list all libraries, programs or any kind of tool that your project needs to be built, such as a compiler, linker, libraries, etc.</p>
<p>Lazy people, like me, usually don't create it from scratch, I prefer to use the <code>autoscan</code> tool, that looks for things that you are using and generate a <code>configure.scan</code> file that can be used as the basis for your real <code>configure.ac</code>.</p>
<p>To inform <code>automake</code> that you will need python stuff, you can add this to your <code>configure.ac</code>:</p>
<pre><code>dnl python checks (you can change the required python version bellow)
AM_PATH_PYTHON(2.7.0)
PY_PREFIX=`$PYTHON -c 'import sys ; print sys.prefix'`
PYTHON_LIBS="-lpython$PYTHON_VERSION"
PYTHON_CFLAGS="-I$PY_PREFIX/include/python$PYTHON_VERSION"
AC_SUBST([PYTHON_LIBS])
AC_SUBST([PYTHON_CFLAGS])
</code></pre>
<h2>Wrap up</h2>
<p>Basically, <code>automake</code> has a built-in extension that knows how to deal with python stuff, you just need to add it to your <code>configure.ac</code> file and then take the advantage of this feature in your <code>Makefile.am</code>.</p>
<p>PyGtk is definitely an awesome example, but it's pretty big, so maybe you will want to check another project, like <a href="http://github.com/Guake/Guake">Guake</a></p>
|
IPC with Message Passing <p>I'm looking for suggestions on possible IPC mechanisms that I can implement in my self-made OS for an AVR32 board. </p>
<p>My current choice is implementing the massage passing mechanism described in the books written by Tanenbaum. </p>
<p>Is this a good choice? Are there easier way to implement IPC?</p>
<p>Thanks </p>
|
<p>My suggestion is to review the message passing primitives that QNX RTOS (www.qnx.com) supports before making any decisions. I spent several years programming a complex multi-process system in that environment, and it stands out as the best message-based O/S I have ever encountered.</p>
<p>Some specific points that spring to mind (it's been a while now):</p>
<ol>
<li>Message data copied between process memory space by the kernel so that a bug in one process cannot affect another.</li>
<li>Ability to send and block for a reply.</li>
<li>Ability to drop a message on a queue and move on immediately.</li>
<li>Ability to send a message an block indefinitely until the receiver responds; the receiver may receive and process other messages in the meantime - this is way more valuable than you at first think it will be.</li>
</ol>
|
Overflow when calculating a const in VBA <p>This declaration causes an overflow in VBA:</p>
<pre><code>Const OVERFLOWS As Long = 10 * 60 * 60
</code></pre>
<p>whereas setting the value directly is fine:</p>
<pre><code>Const COMPILES_OK As Long = 36000
</code></pre>
<p>How do you persuade VBA to treat literal integers as longs?</p>
<p>Thanks</p>
|
<p>Add the <code>long</code> suffix <code>&</code> to at least one number:</p>
<pre><code>Const OVERFLOWS As Long = 10& * 60 * 60
</code></pre>
<p>Note that using the <code>CLNG</code> function to convert the values to <code>long</code> will not work, because VBA does not allow assigning the return value of a function to a constant.</p>
|
How do I set an image for some but not all nodes in a TreeView? <p>I have a <code>TreeView</code> windows forms control with an <code>ImageList</code>, and I want some of the nodes to display images, but the others to not have images.</p>
<p>I <em>don't</em> want a blank space where the image should be. I <em>don't</em> want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList. How do I get it to draw images for some items and not others, without resorting to clumsy hacks like that?</p>
|
<p>You need to set <code>ImageIndex</code> and <code>SelectedImageIndex</code> to a number that is higher than the number of values in your <code>ImageList</code>. For example, if you create this node and add it to your <code>TreeView</code>:</p>
<pre><code>TreeNode node1 = new TreeNode(string.Empty, 12, 12); // imageList1.Count = 5
</code></pre>
<p>you will have an invisible <code>TreeNode</code> inserted into your <code>TreeView</code>. I changed the background color of my <code>TreeView</code> and it was still invisible.</p>
<p>(I googled this for some time, and I eventually found the answer here: <a href="http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2006-09/msg00322.html" rel="nofollow">http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2006-09/msg00322.html</a>)</p>
|
NSDateFormatter won't parse dates using locale settings? <p>I'm trying to parse dates using the user's date preferences</p>
<pre><code>[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [ dateFormatter dateFromString:@"7/4/2008" ];
NSLog(@"string from date %@: %@ for locale %@", date, [dateFormatter stringFromDate:date], [[dateFormatter locale] localeIdentifier]);
</code></pre>
<p>When I set my region (in the International system preferences) to be United States, it prints:</p>
<pre><code>2008-08-14 20:20:31.117 Date Difference17226:10b string from date 2008-07-04 00:00:00 -0400: 7/4/08 for locale en_US
</code></pre>
<p>And when my region is United Kingdom, it prints:</p>
<pre><code>2008-08-14 20:19:23.441 Date Difference17199:10b string from date 2008-04-07 00:00:00 -0400: 07/04/2008 for locale en_GB
</code></pre>
<p>It looks like the NSDateFormatter is insensitive to the change of regions. Notice that the raw printing of the date is properly switching with the region, though.</p>
<p>What do I have to do to get the NSDateFormatter to respect the region setting? </p>
|
<blockquote>
<p>It looks like the NSDateFormatter is insensitive to the change of regions.</p>
</blockquote>
<p>No, it is using the locale in both directions.</p>
<p>You can see how the formatter interpreted the date by looking at the date's description (the first <code>%@</code> in your <code>NSLog</code> format).<br />
With the region as US, the formatter interpreted the date as 2008-<strong>07-04 (July 4)</strong>.<br />
With the region as GB, the formatter interpreted the date as 2008-<strong>04-07 (April 7)</strong>.</p>
<p>Then, you asked the same formatter in the same region to display that date.<br />
July 4 using US format is 07/04/2008 (MM/DD/YYYY).<br />
April 7 using GB format is 07/04/2008 (DD/MM/YYYY).</p>
|
rollover effect using Jquery <p>Would you please help me in making a rollover effect using jquery, what i want to do is when someone hover over any of the menu items the text slide down and disappear and a picture slides from the top down to the center (e.g. you could see this effect here <a href="http://www.iviewcom.com/panda" rel="nofollow">panda</a> as you can see the picture slide down from the top but the text does not slide down which is not what want).</p>
<p>I know it can be easily done using flash but i don't want my menu in flash as that would be a bad practice. </p>
<p>can you tell me what do i need to change in my menu HTML and what jquery functions should i use.</p>
<p><strong>Thanks So much for your help</strong></p>
<p>P.S. this my menu HTML and you can see my menu here </p>
<pre><code><ul class="nav">
<li class="active first"><a href="#" class="home">Home</a></li>
<li><a href="#" class="news">News</a></li>
<li><a href="#" class="offers">Special offers</a></li>
<li><a href="#" class="private">Private label</a></li>
<li><a href="#" class="locations">Locations</a></li>
<li><a href="#" class="about">About us</a></li>
<li><a href="#" class="jobs">Jobs</a></li>
<li><a href="#" class="contact">Contact us</a></li>
<li><a href="#" class="mm">Multimedia</a></li>
</ul>
</code></pre>
<p>MENU: </p>
<p><img src="http://i.stack.imgur.com/8ANuL.jpg" alt="alt text"></p>
|
<p>Instead of doing it for you, I'll offer some places to start looking.. </p>
<p>Here is an example that could be easily modified to use 'rollover' instead of 'click': <a href="http://css-tricks.com/examples/MenuFader/">http://css-tricks.com/examples/MenuFader/</a></p>
<p>Details on how the above example was put together (the tutorial):
<a href="http://css-tricks.com/learning-jquery-fading-menu-replacing-content/">http://css-tricks.com/learning-jquery-fading-menu-replacing-content/</a></p>
<p>I found this tutorial by searching on Google for "jquery effects examples":
<a href="http://www.google.com/search?hl=en&q=jquery+effects+examples&btnG=Google+Search&aq=f&oq=">http://www.google.com/search?hl=en&q=jquery+effects+examples&btnG=Google+Search&aq=f&oq=</a> and clicking on the first and second links.</p>
<p>Good luck with your Jquery project. </p>
|
ASP.NET removing an item from Session? <p>Which method is preferred?</p>
<pre><code>Session.Remove("foo");
Session["foo"] = null;
</code></pre>
<p>Is there a difference?</p>
|
<blockquote>
<p>Is there a difference?</p>
</blockquote>
<p>There is.
<code>Session.Remove(key)</code> deletes the entry (both key & value) from the dictionary while <code>Session[key] = null</code> assigns a value (which happens to be null) to a key. After the former call, the key won't appear in the <code>Session#Keys</code> collection. But after the latter, the key can still be found in the key collection.</p>
|
Best algorithm to check whether a vector is sorted <p>What would be the best way to check that a <code>std::vector</code> is sorted? Is there something faster than a loop checking that <code>v[i]<=v[i+1]</code>? Is it faster/cleaner with iterators? Or is it actually better to just call <code>sort</code> every time (though the "v is already sorted" case is quite common)?</p>
<p>We can safely assume the vector only contains PODs, usually <code>float</code>s and sometimes <code>double</code>s and <code>int</code>s.</p>
<p>The size of the vector is non-trivial (usually a few thousands items) but not extreme (not gigabyte-sized).</p>
<ul>
<li>in some instances we'll sort the vector immediately afterwards, however there are other instances where we don't (it's an error case of our algorithm).</li>
<li>we already use a flag "IsSorted" whenever possible.</li>
</ul>
|
<blockquote>
<p>Is there something faster than a loop
checking that v[i]<=v[i+1] ?</p>
</blockquote>
<p>No.</p>
<p>If this is something you wish to check often, you might want to make a wrapper class that keeps a "sorted" flag which starts out False, is set to False whenever an item is added, and add a member function sort() that sets the flag to True after sorting.</p>
|
Find JPEG resolution with PHP <p>Calling all PHP gurus!</p>
<p>I understand that you can use getimagesize() to get the actual pixel height and width of an image in PHP. However, if you open an image in photoshop and look at the image size dialog, you notice that there is a resolution value that determines the print size of the image.</p>
<p>Given an arbitrary jpg image file, I need to use PHP to determine this resolution number. It appears that this information is stored in the jpg file somewhere, so how do I get to it?</p>
<p>One other requirement - I only have gdlib available to me. I need to do this without the use of other php libraries (imagemagick, etc.)</p>
<p>Thanks for the help!</p>
|
<p>You could just read the JPEG file directly, bytes 14-18 specify:</p>
<ul>
<li>byte 14: 01, X and Y density unit specifier (00: none, pixel ratios, 01: DPI,02: DPC)</li>
<li>bytes 15-16: horizontal pixel density,</li>
<li>byte 16-18: vertical pixel densit</li>
</ul>
<p>Also see: <a href="http://www.obrador.com/essentialjpeg/headerinfo.htm">http://www.obrador.com/essentialjpeg/headerinfo.htm</a></p>
|
Addicted to LINQ <p>Ok, the more I use LINQ, the more I like it! I recently found myself working in some legacy code at work. It is your classic DataSet and DataTable rich application. Well, when adding a bit of functionality I found myself <em>really</em> wanting to just query the rows of a DataTable for the results I was looking for.</p>
<p>Let me repeat that... instead of looping and adding to a temp collection, I just wanted to ask the Rows collection for what I needed. No looping, no temp variables, just give me what I want.</p>
<pre><code>var customerOrderIds = table.Rows.Cast<DataRow>()
.Where(x => (string)x["CUSTOMER_ID"] == customerId)
.Select(x => (string)x["CUSTOMER_ORDER_ID"])
.Distinct();
</code></pre>
<p><strong>My question is whether or not this is a good thing, or am getting carried away with LINQ?</strong> It does seem to me that this declarative style of pulling a subset of data out of a collection is a good thing and more readable in the end. But then again, maybe I'm just smitten :)</p>
|
<p>One other observation; if you aren't using typed datasets, you might also want to know about the <code>Field<></code> extension method:</p>
<pre><code> var customerOrderIds = table.Rows.Cast<DataRow>()
.Where(x => x.Field<string>("CUSTOMER_ID") == customerId)
.Select(x => x.Field<string>("CUSTOMER_ORDER_ID"))
.Distinct();
</code></pre>
<p>Or using the query syntax:</p>
<pre><code> var customerOrderIds = (
from row in table.Rows.Cast<DataRow>()
where row.Field<string>("CUSTOMER_ID") == customerId
select row.Field<string>("CUSTOMER_ORDER_ID")
).Distinct();
</code></pre>
<p>I'm not saying it is better or worse - just another viable option.</p>
<p>(Actually, I don't use <code>DataTable</code> very much, so YMMV)</p>
|
Good Javascript Combo Box replacement for combo boxes with tons of elements? <p>I have a page where my combo box has hundreds of elements which makes it very hard to pick the one item I want. Is there a good Javascript replacement that would do better than</p>
<pre><code><select id="field-component" name="field_component">
<option selected="selected">1</option><option>2</option>...
</select>
</code></pre>
<p>Is there something with "Intellisense"-like auto-complete?</p>
|
<p>In HTML 5 there's standard combo box. </p>
<p>Currently only Opera supports it, but if you happen to be time traveller or writing Opera-only application, it's a nice solution :)</p>
<pre><code><input type=text list=listid>
<datalist id=listid>
<select><option>1<option>2</select>
</datalist>
</code></pre>
|
how to keep inline items from wrapping? <p>I've got menu items that look like this</p>
<pre><code><ul>
<li>Item1<span class="context-trigger"></span></li>
<li>Item2<span class="context-trigger"></span></li>
<li>Item3<span class="context-trigger"></span></li>
</ul>
</code></pre>
<p>with CSS that turns the above into a horizontal menu, and JS that turns the [spans] into buttons that bring up contextual menus. Vaguely like this:</p>
<pre>
Item1^ Item2^ Item3^
</pre>
<p>If the menu gets too wide for the browser width, it wraps, which is what I want. The problem is that sometimes it's putting in line-breaks before the [spans]. I only want it to break between [li]s. Any ideas?</p>
|
<p>try using </p>
<pre><code>white-space: nowrap;
</code></pre>
<p>in the css definition of your context-trigger class.</p>
<p>Edit: I think patmortech is correct though, putting nowrap on the span does not work, because there is no "white space" content. It might also be that sticking the style on the LI element does not work either, because the browser might breakup the parts because the span is a nested element in li. You might reconsider your code, drop the SPAN element and use css on the LI elements.</p>
|
How can I know if a process is running? <p>When I get a reference to a <code>System.Diagnostics.Process</code>, how can I know if a process is currently running?</p>
|
<p>This is a way to do it with the name:</p>
<pre><code>Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
MessageBox.Show("nothing");
else
MessageBox.Show("run");
</code></pre>
<p>You can loop all process to get the ID for later manipulation:</p>
<pre><code>Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
</code></pre>
|
Negotiating a common "network-channel" in a peer-to-peer system <p>Is there a common or established algorithm for peer-nodes in a network to decide on a unique "network-channel" (or any other form of semi-secret identifier)?</p>
<p>The environment I'm working in is SecondLife. I am trying to figure out how to get many identical peer scripted objects to agree on a "channel" number which allows them to form a network, without interfering with other existing networks of the same kind of objects.</p>
<p>All objects get instantiated at roughly the same time, and have access to the (common) system time.</p>
<p>Approaches I've thought of:</p>
<ol>
<li><p>Time-of-instantiation based. Channel is derived (by md5) from the unix time. Problem is the "<strong>roughly</strong> the same time" part. They may get instantiated right on the cusp of a new second.</p></li>
<li><p>Random wait. Make objects wait a random amount, and announce a (randomly generated) channel number decided upon by the first one to wake. Problem is, the system has a low time granularity, and more than one object can wake before the announcement was processed.</p></li>
<li><p>Combine 1 and 2. Announce a high-res timestamp after waiting a random amount, and derive channel from the lowest announced timestamp.</p></li>
</ol>
<p>This has to be something smarter people than me have thought about. Any better way of doing this?</p>
|
<p>How would a new object know which network to join (new or existing)? Depending on what exactly you need, there are number of approaches.</p>
<h2>First method</h2>
<p>You can use less precise timer than every second, for example something like this:</p>
<pre><code>integer time = llGetUnixTime();
integer channel = time - (time % 1000);
</code></pre>
<p>All the objects rezzed at nearly the same time are likely to have same channel according to the above code, although you'd probably want to make sure that time % 1000 is not near 0 or 1000 and perhaps use time % 10000 in that case.</p>
<h2>Second method</h2>
<p>Other than that, you can create some sort of discovery protocol. For example:</p>
<ol>
<li>newly rezzed object says hello on hard-coded control channel</li>
<li>main server for each network in area responds with channel number of its network</li>
<li>object chooses network he wants to join</li>
<li>if nobody responds, object becomes server for its own network, by incrementing control channel by some number (for example +1)</li>
<li>if object wants to create its own network anyway, it increments highest channel in use by +1 and creates its own channel/network</li>
</ol>
<h2>Combination</h2>
<p>Of course, you can combine both methods - use llGetUnixTime() to derive channel, say hello, and if server responds become node, otherwise become server. Also, you can check appropriate higher and lower channel to avoid having two networks because of time rollover differences in rezzing of objects.</p>
|
Qt: how to make a shadow to main window widget? <p>How to make a shadow to main window widget on windows using Qt?</p>
|
<p>Applications normally do not create shadows, that is up to the window manager. You could fake it by all sorts of evil hacks such as creating another borderless window that is the shadow color and put it under your main window.</p>
|
Secure file transfers <p>We are using a custom FTP application (which encrypts the files) for secure transfers. We send the application to end users and they use it to send us confidential data. We also use it to send information back to the end users.</p>
<p>The application is in need of an update - some things are no longer working consistently. As the end users get more restrictive security environments, as OS updates are released, etc.</p>
<p>We have several options:</p>
<ol>
<li>Update the application, use SFTP, etc.</li>
<li>Write a new custom web application to add to our aspx website.</li>
<li>Purchase or download SFTP software</li>
<li>Purchase or download web software</li>
<li>Setup an external sharepoint site</li>
<li>Use a service which is hosted elsewhere - preferably in Canada so that our laws apply</li>
</ol>
<p>Some of features which would be nice:</p>
<ol>
<li>We would not want decrypted files sitting on a server outside the firewall.</li>
<li>Resumable transfers.</li>
<li>Ability to move the files automatically to a specific place inside our firewall. Though this could be easily done outside the file transfer.</li>
<li>Notifications for both sender and recipient by email.</li>
</ol>
<p>Suggestions/comments?</p>
|
<p>I've had good results using <a href="http://www.freesshd.com/" rel="nofollow">Free SSHd</a> on windows machines; it runs on the standard SSH port (22), supports SFTP, and is encrypted end to end. It also lets you set up authorization systems in parallel with your windows permissions, so you can exercise pretty fine-grained control of who gets access and what they can do.</p>
|
Why is using '*' to build a view bad? <p>Why is using '*' to build a view bad ?</p>
<p>Suppose that you have a complex join and all fields may be used somewhere.</p>
<p>Then you just have to chose fields needed.</p>
<pre><code>SELECT field1, field2 FROM aview WHERE ...
</code></pre>
<p>The view "aview" could be <code>SELECT table1.*, table2.* ... FROM table1 INNER JOIN table2 ...</code></p>
<p>We have a problem if 2 fields have the same name in table1 and table2.</p>
<p>Is this only the reason why using '*' in a view is bad?</p>
<p>With '*', you may use the view in a different context because the information is there.</p>
<p>What am I missing ?</p>
<p>Regards</p>
|
<p>I don't think there's much in software that is "just bad", but there's plenty of stuff that is misused in bad ways :-)</p>
<p>The example you give is a reason why * might not give you what you expect, and I think there are others. For example, if the underlying tables change, maybe columns are added or removed, a view that uses * will continue to be valid, but might break any applications that use it. If your view had named the columns explicitly then there was more chance that someone would spot the problem when making the schema change.</p>
<p><strike>On the other hand, you might actually <em>want</em> your view to blithely
accept all changes to the underlying tables, in which case a * would
be just what you want.</strike></p>
<p><em>Update:</em> I don't know if the OP had a specific database vendor in mind, but it is now clear that my last remark does not hold true for all types. I am indebted to user12861 and Jonny Leeds for pointing this out, and sorry it's taken over 6 years for me to edit my answer.</p>
|
making a programme run indefinitely in python <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
|
<p>The simplest way is just to write a program with an infinite loop, and then hit control-C to stop it. Without more description it's hard to know if this works for you.</p>
<p>If you do it time-based, you don't need a generator. You can just have it pause for user input, something like a "Continue? [y/n]", read from stdin, and depending on what you get either exit the loop or not.</p>
|
what's the quickest way to extract a 5 digit number from a string in c# <p>what's the quickest way to extract a 5 digit number from a string in c#. </p>
<p>I've got </p>
<pre><code>string.Join(null, System.Text.RegularExpressions.Regex.Split(expression, "[^\\d]"));
</code></pre>
<p>Any others?</p>
|
<p>The regex approach is probably the quickest to implement but not the quickest to run. I compared a simple regex solution to the following manual search code and found that the manual search code is ~2x-2.5x faster for large input strings and up to 4x faster for small strings:</p>
<pre><code>static string Search(string expression)
{
int run = 0;
for (int i = 0; i < expression.Length; i++)
{
char c = expression[i];
if (Char.IsDigit(c))
run++;
else if (run == 5)
return expression.Substring(i - run, run);
else
run = 0;
}
return null;
}
const string pattern = @"\d{5}";
static string NotCached(string expression)
{
return Regex.Match(expression, pattern, RegexOptions.Compiled).Value;
}
static Regex regex = new Regex(pattern, RegexOptions.Compiled);
static string Cached(string expression)
{
return regex.Match(expression).Value;
}
</code></pre>
<p>Results for a ~50-char string with a 5-digit string in the middle, over 10^6 iterations, latency per call in microseconds (smaller number is faster):</p>
<p>Simple search: 0.648396us</p>
<p>Cached Regex: 2.1414645us</p>
<p>Non-cached Regex: 3.070116us</p>
<p>Results for a ~40K string with a 5-digit string in the middle over 10^4 iterations, latency per call in microseconds (smaller number is faster):</p>
<p>Simple search: 423.801us</p>
<p>Cached Regex: 1155.3948us</p>
<p>Non-cached Regex: 1220.625us</p>
<p>A little surprising: I would have expected Regex -- which is compiled to IL -- to be comparable to the manual search, at least for very large strings.</p>
|
SourceSafe Label Search <p>Is there a way to search Microsoft Visual SourceSafe 6.0d for all files tagged with a specific label?</p>
|
<p>AJ had the right idea, but you just need to use the "dir" command instead of get:</p>
<pre><code>ss dir -v"LABEL" $\PROJECT -R
</code></pre>
<p>This will output each file with version that is at that label in the format of:</p>
<pre><code>someFile.c;23
someOtherFile.h;3
<filename>;<version>
</code></pre>
<p>For those interested if you want to quickly tell what the latest version of a file is you can do:</p>
<pre><code>ss dir -v. $\PROJECT -R
</code></pre>
<p>Have a great time!</p>
|
.Net 2.0 Winform Label Tool Tip <p>This has got to be something I just missed, but how do I add a tool tip to a label?</p>
<p>I saw something on the web about handling the mouse hover event, but how would I even handle it in code?</p>
|
<p>Add in your form the TooTip from the ToolBox than click once in your label and you'll see ToolTip in the property box.</p>
|
Variable opacity within a WPF application <p>My problem is:</p>
<p>I have a Canvas which covers part of my Window. The Opacity of the canvas is set to less than 1, i.e. I can view the controls under the Canvas. What I would like to do is place a control, any control, say a Button, on the canvas and not have that Button semitransparent. Is this possible using WPF?</p>
|
<p>Try the alpha in the color of the canvas.</p>
|
Javascript onHover event <p>Is there a canonical way to set up a JS onHover event with the existing onmouseover, onmouseout and some kind of timers? Or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time.</p>
|
<p>How about something like this?</p>
<pre><code><html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
</code></pre>
|
Agile 40-hour week <p>Have you ever worked on a (full-time) project where using Agile methodologies actually allowed you to accomplish a 40-hour work-week? If so, what were the most valuable agile practices?</p>
|
<p>Yes, I'm on a 40 hour (actually it's 37.5 hours or so, that's what my contract says) on a project that was run with SCRUM from the beginning. That was about 2 years ago and the first time we implemented SCRUM. It's the project with the least amount of overtime for me personally, and it's also a PC game we're developing. I'm not even in "crunch" mode right now even though we're shipping an open beta on Friday.</p>
<p>We have learned a lot since then about SCRUM and agile. The single most valuable lesson from my point of view is: pod sizes must be reasonable ... we started out with pods with 12-20 members, that didn't work out well at all. A maximum of 10 should not be exceeded. It's too easy to agree on "flaky" and "vague" tasks because otherwise the standup & task planning meetings would take too long. So keep the pod size small and the tasks specific and get the product owner or sign-off's together with those who will work on the task.</p>
<p>Also, with a bi-weekly task planning schedule you have to get every Product Owner to agree on the task list and priorities for the current sprint, and new task requests should be issued before that planning meeting or else it will be ignored for the current sprint. This forced us to improve on inter-pod communication.</p>
|
openbd cfloop over a date <p>I'm trying to convert my sites from CF8 to openBD. I have a cfloop in a site that loops over a date range.</p>
<p>In essence, I want to insert a new record into the db for every 2 weeks (step) of a date range (from and to)</p>
<p>my loop looks like this... </p>
<pre><code><cfloop
from = "#form.startDate#"
to = "#form.endDate#"
index = "i"
step = "#theStep#"
>
</code></pre>
<p>This works perfectly in CF8, in openBD, I get this error...
Data not supported: value [11/05/09] is not a number</p>
<p>Any ideas of a work around?</p>
<p>Thx</p>
|
<p>Your problem lies in not checking for ambiguous locale dependent date strings from your FORM.</p>
<p>A more robust version would be this:</p>
<pre><code><cfset SetLocale("English (US)")> <!--- set expected input locale here --->
<cfif LSIsDate(form.startDate) and LSIsDate(form.endDate)>
<cfset theStep = 14>
<cfloop
from = "#LSParseDate(form.startDate)#"
to = "#LSParseDate(form.endDate)#"
index = "i"
step = "#theStep#"
>
<!--- do stuff --->
</cfloop>
<cfelse>
<!--- output some error message --->
</cfif>
</code></pre>
<p>It would be helpful to restrict people to entering unambiguous date formats into the FORM, like "yyyy-mm-dd".</p>
<p>The "value is not a number" error comes from the fact that the loop still goes over numbers, even if you feed it dates. It uses a numerical representation of these dates then, but they must be <em>valid</em> and intelligible for that to work. </p>
|
Can my web server be at one hosting company, and my email hosted by a 3rd party? <p>I have a web server that runs my web application.</p>
<p>If I want to outsource my email to another provider, is it possible if they are on their on network/data center?</p>
|
<p>Yes. To do this, you will need access to the DNS records for your domain. The MX record allows you to set up a mail server that's separate from the web server.</p>
<p>Google offers a service that will manage your domain's email through GMail, and the instructions on how to reconfigure your DNS for this service can be found <a href="http://www.google.com/support/a/bin/answer.py?answer=33352&src=top5&lev=index">here</a>.</p>
|
What's your favorite cross domain cookie sharing approach? <p>I see iframe/p3p trick is the most popular one around, but I personally don't like it because javascript + hidden fields + frame really make it look like a hack job. I've also come across a master-slave approach using web service to communicate (<a href="http://www.15seconds.com/issue/971108.htm">http://www.15seconds.com/issue/971108.htm</a>) and it seems better because it's transparent to the user and it's robust against different browsers. </p>
<p>Is there any better approaches, and what are the pros and cons of each?</p>
|
<p>My approach designates one domain as the 'central' domain and any others as 'satellite' domains.</p>
<p>When someone clicks a 'sign in' link (or presents a persistent login cookie), the sign in form ultimately sends its data to a URL that is on the central domain, along with a hidden form element saying which domain it came from (just for convenience, so the user is redirected back afterwards).</p>
<p>This page at the central domain then proceeds to set a session cookie (if the login went well) and redirect back to whatever domain the user logged in from, with a specially generated token in the URL which is unique for that session.</p>
<p>The page at the satellite URL then checks that token to see if it does correspond to a token that was generated for a session, and if so, it redirects to itself without the token, and sets a local cookie. Now that satellite domain has a session cookie as well. This redirect clears the token from the URL, so that it is unlikely that the user or any crawler will record the URL containing that token (although if they did, it shouldn't matter, the token can be a single-use token).</p>
<p>Now, the user has a session cookie at both the central domain and the satellite domain. But what if they visit another satellite? Well, normally, they would appear to the satellite as unauthenticated.</p>
<p>However, throughout my application, whenever a user is in a valid session, all links to pages on the other satellite domains have a ?s or &s appended to them. I reserve this 's' query string to mean "check with the central server because we reckon this user has a session". That is, no token or session id is shown on any HTML page, only the letter 's' which cannot identify someone.</p>
<p>A URL receiving such an 's' query tag will, if there is no valid session yet, do a redirect to the central domain saying "can you tell me who this is?" by putting something in the query string.</p>
<p>When the user arrives at the central server, if they are authenticated there the central server will simply receive their session cookie. It will then send the user back to the satellite with another single use token, which the satellite will treat just as a satellite would after logging in (see above). Ie, the satellite will now set up a session cookie on that domain, and redirect to itself to remove the token from the query string.</p>
<p>My solution works without script, or iframe support. It does require '?s' to be added to any cross-domain URLs where the user may not yet have a cookie at that URL. I did think of a way of getting around this: when the user first logs in, set up a chain of redirects around every single domain, setting a session cookie at each one. The only reason I haven't implemented this is that it would be complicated in that you would need to be able to have a set order that these redirects would happen in and when to stop, and would prevent you from expanding beyond 15 domains or so (too many more and you become dangerously close to the 'redirect limit' of many browsers and proxies).</p>
|
range for integer values of chars in c++ <p>I'm reading <em>The C++ Programming Language</em> and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127. If not, why are their only 255 possible values in the second implementation possibility, not 256.</p>
|
<p>You're stuck in <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement</a> thinking - The C++ standard does not define the representation used for negative numbers!</p>
<p>If your computer (god forbid) uses <a href="http://en.wikipedia.org/wiki/Ones_complement#Ones.27_complement">ones's complement</a> to represent negative numbers, you have a range of -127 to + 127 in an 8-bit byte. On the upside, you have two different possible representations for zero... </p>
<p>However, in the real world, <a href="http://stackoverflow.com/questions/161797/is-ones-complement-a-real-world-issue-or-just-a-historical-one">you're unlikely to meet a one's complement computer</a>.</p>
|
Showing too much 'skin' detection in software <p>I am building an ASP.NET web site where the users may upload photos of themselves. There could be thousands of photos uploaded every day. One thing my boss has asked a few time is if there is any way we could detect if any of the photos are showing too much 'skin' and automatically move flag these as 'Adults Only' before the editors make the final decision. </p>
|
<p>Your best bet is to deal with the image in the HSV colour space (see <a href="http://www.cs.rit.edu/~ncs/color/t_convert.html">here</a> for rgb - hsv conversion). The colour of skin is pretty much the same between all races, its just the saturation that changes. By dealing with the image in HSV you can simply search for the colour of skin.</p>
<p>You might do this by simply counting the number of pixel within a colour range, or you could <a href="http://www.cse.unr.edu/~bebis/CS791E/Notes/RegionGrowing.pdf">perform region</a> growing around pixel to calculate the size of the areas the colour.</p>
<p>Edit: for dealing with grainy images, you might want to perform a <a href="http://en.wikipedia.org/wiki/Median_filter">median filter</a> on the image first, and then reduce the number of colours to segment the image first, you will have to play around with the settings on a large set of pre-classifed (adult or not) images and see how the values behave to get a satisfactory level of detection.</p>
<p>EDIT: Heres some code that should do a simple count (not tested it, its a quick mashup of some code from <a href="http://www.obnoxiouslyverbose.com/8/c-image-processing-performance-unsafe-vs-safe-code-part-i">here</a> and rgb to hsl <a href="http://en.wikipedia.org/wiki/HSL_color_space">here</a>)</p>
<pre><code>Bitmap b = new Bitmap(_image);
BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat);
byte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat);
byte* scan0 = (byte*)bData.Scan0.ToPointer();
int count;
for (int i = 0; i < bData.Height; ++i)
{
for (int j = 0; j < bData.Width; ++j)
{
byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8;
byte r = data[2];
byte g = data[1];
byte b = data[0];
byte max = (byte)Math.Max(r, Math.Max(g, b));
byte min = (byte)Math.Min(r, Math.Min(g, b));
int h;
if(max == min)
h = 0;
else if(r > g && r > b)
h = (60 * ((g - b) / (max - min))) % 360;
else if (g > r && g > b)
h = 60 * ((b - r)/max - min) + 120;
else if (b > r && b > g)
h = 60 * ((r - g) / max - min) + 240;
if(h > _lowerThresh && h < _upperThresh)
count++;
}
}
b.UnlockBits(bData);
</code></pre>
|
What is the best algorithm for an overridden System.Object.GetHashCode? <p>In .NET <code>System.Object.GetHashCode</code> method is used in a lot of places, throughout the .NET base class libraries. Especially when finding items in a collection fast or to determine equality. Is there a standard algorithm/ best practice on how to implement the <code>GetHashCode</code> override for my custom classes so I don't degrade performance?</p>
|
<p>I usually go with something like the implementation given in Josh Bloch's <em>fabulous</em> <a href="http://rads.stackoverflow.com/amzn/click/0321356683">Effective Java</a>. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:</p>
<pre><code>public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
}
</code></pre>
<p>EDIT: As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-FNV example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant <em>is</em> prime though. I don't know quite how important that is.)</p>
<p>This is better than the common practice of <code>XOR</code>ing hashcodes for two main reasons. Suppose we have a type with two <code>int</code> fields:</p>
<pre><code>XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y
</code></pre>
<p>By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.</p>
<p>EDIT: <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx">This page</a> gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx#fnv">FNV</a> alternative is similarly simple, but uses different constants and XOR instead of ADD as a combining operation. It looks <em>something</em> like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.</p>
<pre><code>// Note: Not quite FNV!
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = (int) 2166136261;
// Suitable nullity checks etc, of course :)
hash = (hash * 16777619) ^ field1.GetHashCode();
hash = (hash * 16777619) ^ field2.GetHashCode();
hash = (hash * 16777619) ^ field3.GetHashCode();
return hash;
}
}
</code></pre>
<p>EDIT: Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.</p>
<p>As per the <a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode%28v=vs.110%29.aspx">documentation</a>:</p>
<blockquote>
<p>You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:</p>
<ul>
<li>You can compute the hash code from fields that are not mutable; or</li>
<li>You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.</li>
</ul>
</blockquote>
|
We have a graphical designer, now they want a text based designer. Suggestions? <p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
|
<p>From what i think i've understood you have two options</p>
<p>you could either use an XML style "markup" to let them define entities and their groupings, but that may not be best.</p>
<p>Your alternatives are yes, yoou could embedd a language, but do you really need to, wouldnt that be overkill, and how can you control it?</p>
<p>If you only need really simple syntax then perhaps write your own language. Its actually not that hard to create a simple interpreter, as long as you have a strict, unambiguous language. Have a look for some examples of compilers in whatever youre using, c#?</p>
<p>I wrote a very simple interperter in java at uni, it wasnt as hard as you'd think.</p>
|
Is there a performance hit when "Windows" authentication is enabled on an anonymous website? <p>I've been having performance issues with a high traffic ASP.NET 2.0 site running on Windows 2000. While editing the web.config file I noticed that the authentication mode was set to 'Windows'. I changed it to 'None'. The only users this site has are anonymous and it gets 25,000+ page views at day. Could this have been a caused performance issues?</p>
|
<p>There is a small potential, but if you are not securing any folders, it shouldn't be an issue.</p>
<p>In reality it would mostly be an issue if you needed to secure a folder path. </p>
<p>There might be a SMALL performance hit but I can't imagine it would be that bad.</p>
|
launching VS2008 build from python <p>if I paste this into the command prompt by hand, it works, but if I run it from python, I get <code>The filename, directgory name, or volume label syntax is incorrect</code>.</p>
<pre><code>os.system('%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system('devenv Immersica.sln /rebuild Debug /Out last-build.txt')
</code></pre>
|
<p>I think the backslashes are messing you up. You need to use an R string (raw)</p>
<p>r"string"</p>
<p>See <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">https://docs.python.org/2/reference/lexical_analysis.html#string-literals</a> for reference</p>
|
fragment was not found at expected path (eclipse jsp) <p>In eclipse, I have a javaproject (not a web project), though it does provide reusable tag files.</p>
<p>layout</p>
<p>+src<br>
+++META-INF<br>
----my.tld<br>
+++++++++++tags<br>
---------------include.jsp<br></p>
<p>I keep on getting Fragment "/META-INF/tags/include.jsp" was not be found at expected path /Project/META-INF/tags/taginclude.jsp</p>
<p>How can I modify the path eclipse is looking for? I need to tell it to include "src" in the lookup</p>
|
<p>Josh, if you're working with .jsp and .tld files, then you really shouldn't be doing this as a "Java Project", but instead a "Dynamic Web Project" in Eclipse. Nonetheless, I'll try to answer your question.</p>
<p>Based on the diagram of your file system, your files are laid out incorrectly. If you're trying to create a web app (a .war file), then you need a WEB-INF directory. Under the WEB-INF directory you'll need a web.xml file (google for web.xml to see what needs to be in there), a tags directory, and a classes and lib directory.</p>
<p>Compiled class files must go in the WEB-INF/classes directory.
Jar files that you depend on must go in the WEB-INF/lib directory.
Tablibs must go in the WEB-INF/tags directory.
Finally, your .jsp files must go in src directory (the parent dir of WEB-INF).</p>
<p>So, your layout should look like this:</p>
<pre>
myproject/
`-- src
|-- WEB-INF
| |-- classes
| | `-- MyClass.class
| |-- lib
| | `-- my.jar
| |-- tags
| | `-- my.tld
| `-- web.xml
`-- include.jsp
</pre>
<p>Hope this helps.</p>
<p>-Bryan</p>
|
What is the best way to add user ID to RubyOnRails log entries? <p>I am looking for the best way to customize my Rails log entries (I want to add the user ID in there). I am using Rails 2.1.2. The only way I've found so far is to override method "add" of class BufferedLogger (as defined in active_support/lib/active_support). </p>
<p>But it ain't pretty: I have to copy all the code in there and it is
closely tied to the current implementation. Is there a better way?
I found this on the Google: <a href="http://pandejo.blogspot.com/2007/08/customize-logger-message-format.html" rel="nofollow">http://pandejo.blogspot.com/2007/08/customize-logger-message-format.html</a> but it seems outdated.
One day, I might create a specific audit log, but it is overkill for
what I need: <a href="http://maintainable.com/articles/rails_logging_tips#audit-logs" rel="nofollow">http://maintainable.com/articles/rails_logging_tips#audit-logs</a>
Cheers.</p>
|
<p>Have you seen the <a href="http://github.com/ffmike/user_event_logger/tree/master" rel="nofollow">user_event_logger</a> plugin?</p>
|
How to move documents and list items in Windows SharePoint Services? <p>I need to provide users with an easy way to move documents and lists items in WSS 3.0. They want to be able to move across lists, sites and site collections without loss of version history, metadata, and author/date info. This functionality is unfortunately not available OOB. Anyone know a good solution/product?</p>
|
<p>None of the products out there can do it and even if they do, all of them would modify the dates and the by's (modified by). We developed a custom solution to do that.</p>
|
launching vs2008 build from python <p>The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?</p>
<p>As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes <code>devenv</code> without the necessary context.</p>
<pre><code>os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
</code></pre>
<p>think of it as in i'm in bash, and i need to execute a command in a perl context, so i type <code>perl -c 'asdf'</code>. executing perl and asdf back to back won't work, i need to get the <code>devenv</code> inside of the perl context.</p>
|
<p>I think that the proper way for achieving this would be running this command:</p>
<pre><code>%comspec% /C "%VCINSTALLDIR%\vcvarsall.bat" x86 && vcbuild "project.sln"
</code></pre>
<p>Below you'll see the Python version of the same command:</p>
<pre><code>os.system('%comspec% /C "%VCINSTALLDIR%\\vcvarsall.bat" x86 && vcbuild "project.sln"')
</code></pre>
<p>This should work with any Visual Studio so it would be a good idea to edit the question to make it more generic.</p>
<p>There is a small problem I found regarding the location of vcvarsall.bat - Because VCINSTALLDIR is not always set, you have to use the registry entries in order to detect the location where it is installer:</p>
<pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0]
"InstallDir"="c:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\"
</code></pre>
<p>Add <code>..\..\VC\vcvarsall.bat</code> to this path. Also is a good idea to test for other versions of Visual Studio.</p>
|
How do you create a Distinct query in HQL <p>Is there a way to create a Distinct query in HQL. Either by using the "distinct" keyword or some other method. I am not sure if distinct is a valid keywork for HQL, but I am looking for the HQL equivalent of the SQL keyword "distinct".</p>
|
<p>Here's a snippet of hql that we use. (Names have been changed to protect identities)</p>
<pre><code>String queryString = "select distinct f from Foo f inner join foo.bars as b" +
" where f.creationDate >= ? and f.creationDate < ? and b.bar = ?";
return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar});
</code></pre>
|
How do I find the width & height of a terminal window? <p>As a simple example, I want to write a CLI script which can print '=' across the entire width of the terminal window.</p>
<pre><code>#!/usr/bin/env php
<?php
echo str_repeat('=', ???);
</code></pre>
<p>or</p>
<pre><code>#!/usr/bin/env python
print '=' * ???
</code></pre>
<p>or</p>
<pre><code>#!/usr/bin/env bash
x=0
while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo
</code></pre>
|
<ul>
<li><code>tput cols</code> tells you the number of columns.</li>
<li><code>tput lines</code> tells you the number of rows.</li>
</ul>
|
Fastest possible XML handling in Delphi for very large documents <p>I need recommendations on what to use in Delphi (I use Delphi 2009) to handle very large XML files (e.g. 100 MB) as fast as possible. </p>
<p>I need to input the XML, access and update the data in it from my program, and then export the modified XML again.</p>
<p>Hopefully the input and output could be done within a few seconds on a fast Windows machine.</p>
<p><hr /></p>
<p>Clarification. I expect I will need to use DOM, because access to the data structure for developing reports and making updates to the data is important, and I need this functionality to be very fast.</p>
<p>The input is only done once for File Loading and the output done only for File saving, usually just once upon exit. These should be quick as well, but are not as important as the in-memory data access and update.</p>
<p>My understanding is that 3rd party parsers only help with input and output, but not on using and modifying the data once loaded into memory. Or am I mistaken on this?</p>
|
<p>If I understood your question correctly, you have known data structure and you are modifying data - not XML structure of file. </p>
<p>Under these condition <em>and if performance is crucial</em>, then you could try with direct text manipulation - skip XML parsing. </p>
<p>Read from stream, use some fast text search algorithm e.g. <a href="http://en.wikipedia.org/wiki/Boyer-Moore%5Fstring%5Fsearch%5Falgorithm">Boyer-Moore</a>, to find places where you need to modify data, do your modification and output data into another stream.</p>
<p>This would be one-pass, no XML parsing, no in-memory XML tree building. </p>
|
Have you used a traveling salesman algorithm to solve a problem? <p>I studied TSP in college in the context of NP Completeness. I have never actually had a situation where it would apply to a practical problem. A little bit of research shows that it has been used to pick the cheapest path to move a drill around, that is making holes in circuit boards. That is pretty much all I could find.</p>
<p>Are you using it? What other practical applications does the TSA have?</p>
|
<p>I was once given the task of writing a program to fill a rectangular area fairly uniformly with a "squiggle" - a curved line which doesn't self-intersect. My first attempt was to generate random points within the rectangle and try to find a tour of them (not necessarily the absolute shortest). Unfortunately this approach just didn't work very well and I abandoned it. </p>
<p>I did solve the problem in the end though:</p>
<p><img src="http://imgur.com/BMWnQ.png" alt="alt text"></p>
<p>My successful method was not related to the TSP but for the curious I will summarize it:</p>
<p>Start with a single line segment. Now loop: if a line is "too long", divide it in two. Move each point a bit at random, but make points repel each other. End the loop when little progress can be made. There are details but hopefully you get the idea.</p>
<p>Of course this produces an angular path (which would have been acceptable) but it is easy to turn the corners into smooth arcs.</p>
<p>And yes I did keep the code.</p>
|
How do I calculate the closest power of 2 or 10 a number is? <p>What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.</p>
<p>3.5 would return 4 for power of 2 and 1 for power of 10</p>
<p>123 would return 128 for power of 2 and 100 for power of 10</p>
<p>0.24 would return 0.25 for power of 2 and 0.1 for power of 10</p>
<p>I'm just looking for the algorithm and don't mind the language.</p>
|
<pre><code>n^round(log_n(x))
</code></pre>
<p>where log_n is the logarithm to base n. You may have to modify the round() depending on how you define "closest".</p>
<p>Note that <code>log_n(x)</code> can be implemented as:</p>
<pre><code>log_n(x) = log(x) / log(n)
</code></pre>
<p>where <code>log</code> is a logarithm to any convenient base.</p>
|
In SQL, how to delete a row from one table if it doesn't have a corresponding row in another table? <p>How can I make:</p>
<p>DELETE FROM foo WHERE id=1 AND <strong>bar not contains id==1</strong></p>
<p>To elaborate, how can I remove a row with <code>id = 1</code>, from table <code>foo</code>, only if there is not a row in table <code>bar</code> with <code>id = 1</code>.</p>
|
<pre><code>DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1)
</code></pre>
<p>I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar.</p>
|
How to move build task into parent POM <p>I have a POM for my ejb project. In it I have added a maven-antrun-plugin execution step to build websphere ejb stubs during the verify phase. This works but is quite verbose, and as I need to add similiar steps to a number of other ejb projects I want to move the common section to a parent POM for all our ejbs. </p>
<p>My first try was to just move the entire build tag to the parent POM but this failed during install/deploy of the parent as the verify step was executed for the parent POM instead of just for the child POM.</p>
<p>My second try involved specifying ejb:verify for the phase. This partially succeeded in that the parent POM was deployable. However the verify step was not executed for the child POM.</p>
<p>I have tried several other variations including specifying a phase of ejb, ejb:ejb and specifying true in the plugin definition.</p>
<p>What is the correct way to do this?</p>
|
<p>If you put the configuration inside a pluginManagement section of your parent, then it won't run there. Then in the children you just need to bind the antrun plugin and it will inherit the execution config and run. This is nice because you can then control which of the children inherit the values.</p>
<p>You can see examples in the chapter I wrote here: <a href="http://www.sonatype.com/book/reference/optimizing.html#d0e8621" rel="nofollow">http://www.sonatype.com/book/reference/optimizing.html#d0e8621</a></p>
|
How do I make HTTP post request for getting JSON object in response for iPhone application? <p>I've a web service running on server which return data either in XML format or JSON format.
I wanted to request a JSON format but using HTTP Post method.</p>
<p>any help greatly appreciated.</p>
<p>thanks in advance.</p>
|
<p>This is the code which work for JSON post request,
TouchJSON Framework is used for parsing the JSON, thanks 'schwa'.</p>
<pre><code>NSArray *keys = [NSArray arrayWithObjects:@"username", @"password", @"preference", @"uid", nil];
NSArray *objects = [NSArray arrayWithObjects:@"accuser", @"accpass", @"abc_region", @"100", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *theURL = [NSURL URLWithString:@"http://url.com/request.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"];
NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
NSLog(@"%@", theBodyString);
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"%@", theBodyData);
[theRequest setHTTPBody:theBodyData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(theResponseString);
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString];
NSLog(@"%@", theResponseDictionary);
NSString *theGreeting = [theResponseDictionary objectForKey:@"greeting"];
[self setValue:theGreeting forKey:@"greeting"];
</code></pre>
|
Are real-time linux extensions obsolete? <p>Do the new real-time and low latency patches from Ingo Molnar render previous real-time extensions for Linux (such as RTAI, Xenomai) obsolete?</p>
|
<p>Doesn't look like it to me, although I've not endeavoured to build a real-time system on Linux (yet). RTAI look like APIs. POSIX.4 would be similar (and of course <em>infinitely superior</em> in my humble opinion as the former vice-chair of that committee and author of the book :) .</p>
<p>Molnar's work looks to me as if it is designed to actually provide real-time <em>performance</em> to Linux. So to write a real, real-time application, you're probably talking about (1) using real-time APIs as well as the standard *nix calls, and (2) building your application very carefully, taking account of techniques mentioned on the <a href="http://rt.wiki.kernel.org/index.php/Main_Page" rel="nofollow">Real-Time Linux Wiki</a>. So in general, I'd say you need both. And probably even more than those two!</p>
|
Spell checking city names? <p>I figure this problem is easier than just a regular spell checker since the list of U.S cities is small compared to all known English words.</p>
<p>Anyhow, here's the problem:
I have text files with full of city names; some of which are spelled correctly and some which aren't. </p>
<p>What kind of algorithm can I use to correct all the misspellings of city names?</p>
|
<p>Do you actually need to correct the misspellings or just flag them as with a normal spell checker? If the latter, you just need to obtain a list of correct spellings and make sure each name is the same as one in your list.</p>
<p>If you want to actually correct them, you probably want to use the concept of <a href="http://en.wikipedia.org/wiki/Edit_distance" rel="nofollow">edit distance</a> to compare the similarity of misspelled strings to those in your reference list. Then you can replace the misspelled word with the closest match. You may also want to handle the possibility that the intended city is not in your list.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow">Levenshtein distance</a> Wikipedia article is another good resource.</p>
|
How to discover what Linux distribution is in use <p>Sometimes I need to access some servers running Linux (or maybe another Unix-like SO), but I don't know how to verify which <a href="http://en.wikipedia.org/wiki/Linux_distribution">distribution</a> is in use on the server (there are times that even the "responsible" person for the server doesn't know). </p>
<p>Is there an easy and reliable way to discover that, one that is uniform and consistent across all of them?</p>
|
<p><code>lsb_release -i</code> may work for you.</p>
<p>More detail is available with <code>lsb_release -a</code></p>
<p>Some discussion at <a href="http://etbe.coker.com.au/2007/08/30/identifying-the-distribution-of-a-linux-system/">http://etbe.coker.com.au/2007/08/30/identifying-the-distribution-of-a-linux-system/</a></p>
|
Is there an alternative for sleep() in C? <p>In traditional embedded programming, we will give a delay function like so:</p>
<pre><code>for(i=0;i<255;i++)
for(j=0;j<255;j++);
</code></pre>
<p>In the microprocessor's view, is this how the sleep() function works?</p>
<p>Is there an alternative for the sleep() function in C?</p>
|
<p>The kind of loop you describe is called a "busy wait". In real operating systems, sleeping does not cause a busy wait; it tells the operating system to not schedule the process in until the sleep period is over.</p>
|
DataList, Conditional statements in <ItemTemplate>? <p>I am trying to do the following in ASP.NET 3.5. Basically, I am binding a LINQDataSource to a DataList. There is a property called "Deleted" and if it is true, I want to display different markup. The following code throws errors:</p>
<pre><code><asp:DataList runat="server">
<ItemTemplate>
<% If CBool(Eval("Deleted")) Then%>
...
<% Else%>
...
<% End If%>
</ItemTemplate>
</asp:DataList>
</code></pre>
<p>Is this possible? If not, what are the alternatives?</p>
|
<p>I might suggest keeping the code-front lean and writing out the desired text via a function result:</p>
<pre><code><asp:DataList runat="server">
<ItemTemplate>
<%# GetText(Container.DataItem) %>
</ItemTemplate>
</asp:DataList>
</code></pre>
<p>And the code-behind:</p>
<pre><code>protected static string GetText(object dataItem)
{
if (Convert.ToBoolean(DataBinder.Eval(dataItem, "Deleted"))
return "Deleted";
return "Not Deleted";
}
</code></pre>
<p>I hope it helps.</p>
|
How can I get a list of the differences between two JavaScript object graphs? <p>I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur. </p>
<p>For what it is worth, these objects are usually retrieved from the server as JSON and typically are no more than a handful of layers deep (i.e. it may be an array of objects that themselves have data and then arrays with other data objects).</p>
<p>I want to not only see the changes to basic properties, but differences in the number of members of an array, etc. etc.</p>
<p>If I don't get an answer, I will probably end up writing this myself, but hope someone has already done this work or know of someone who has.</p>
<p><hr /></p>
<p>EDIT: These objects will typically be very close in structure to one another, so we are not talking about objects that are utterly different from one another, but may have 3 or 4 deltas.</p>
|
<p>Here is a partial, naïve solution to my problem - I will update this as I further develop it.</p>
<pre><code>function findDifferences(objectA, objectB) {
var propertyChanges = [];
var objectGraphPath = ["this"];
(function(a, b) {
if(a.constructor == Array) {
// BIG assumptions here: That both arrays are same length, that
// the members of those arrays are _essentially_ the same, and
// that those array members are in the same order...
for(var i = 0; i < a.length; i++) {
objectGraphPath.push("[" + i.toString() + "]");
arguments.callee(a[i], b[i]);
objectGraphPath.pop();
}
} else if(a.constructor == Object || (a.constructor != Number &&
a.constructor != String && a.constructor != Date &&
a.constructor != RegExp && a.constructor != Function &&
a.constructor != Boolean)) {
// we can safely assume that the objects have the
// same property lists, else why compare them?
for(var property in a) {
objectGraphPath.push(("." + property));
if(a[property].constructor != Function) {
arguments.callee(a[property], b[property]);
}
objectGraphPath.pop();
}
} else if(a.constructor != Function) { // filter out functions
if(a != b) {
propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b });
}
}
})(objectA, objectB);
return propertyChanges;
}
</code></pre>
<p>And here is a sample of how it would be used and the data it would provide (please excuse the long example, but I want to use something relatively non-trivial):</p>
<pre><code>var person1 = {
FirstName : "John",
LastName : "Doh",
Age : 30,
EMailAddresses : [
"john.doe@gmail.com",
"jd@initials.com"
],
Children : [
{
FirstName : "Sara",
LastName : "Doe",
Age : 2
}, {
FirstName : "Beth",
LastName : "Doe",
Age : 5
}
]
};
var person2 = {
FirstName : "John",
LastName : "Doe",
Age : 33,
EMailAddresses : [
"john.doe@gmail.com",
"jdoe@hotmail.com"
],
Children : [
{
FirstName : "Sara",
LastName : "Doe",
Age : 3
}, {
FirstName : "Bethany",
LastName : "Doe",
Age : 5
}
]
};
var differences = findDifferences(person1, person2);
</code></pre>
<p>At this point, here is what the <code>differences</code> array would look like if you serialized it to JSON:</p>
<pre><code>[
{
"Property":"this.LastName",
"ObjectA":"Doh",
"ObjectB":"Doe"
}, {
"Property":"this.Age",
"ObjectA":30,
"ObjectB":33
}, {
"Property":"this.EMailAddresses[1]",
"ObjectA":"jd@initials.com",
"ObjectB":"jdoe@hotmail.com"
}, {
"Property":"this.Children[0].Age",
"ObjectA":2,
"ObjectB":3
}, {
"Property":"this.Children[1].FirstName",
"ObjectA":"Beth",
"ObjectB":"Bethany"
}
]
</code></pre>
<p>The <code>this</code> in the <code>Property</code> value refers to the root of the object that was compared. So, this solution is not yet <em>exactly</em> what I need, but it is pretty darn close. </p>
<p>Hope this is useful to someone out there, and if you have any suggestions for improvement, I am all-ears; I wrote this very late last night (i.e. early this morning) and there may be things I am completely overlooking.</p>
<p>Thanks.</p>
|
Converting plist to binary plist <p>Apple strongly recommends using the binary plist format when reading large XML-based data sets into iPhone apps. Among their reasoning is the fact that XML parsing is very taxing on the iPhone. However, this requires that files residing on the remote web server be converted first.</p>
<p>For frequently-changing content, it is not acceptable to do this manually. If at all possible, I'd like to avoid having a web based app call the command line to perform the conversion (i.e., plutil). </p>
<p>Are there publicly available algorithms to perform this conversion?</p>
|
<p>Yes. All the plist code is part of CoreFoundation, which is opensource. CoreFoundation can be directly built and run on Linux and Windows, so you can write a CF tool using the normal APIs you would use on Mac OS X, but build and run it on other platforms.</p>
<p>The particular API you want to be looking at is <a href="http://developer.apple.com/documentation/CoreFoundation/Reference/CFPropertyListRef/Reference/reference.html#//apple_ref/c/func/CFPropertyListWriteToStream">CFPropertyListWriteToStream()</a>. The code for CoreFoundation is available from <a href="http://www.opensource.apple.com/darwinsource/10.5.5/CF-476.15/">Apple</a> (<a href="http://www.opensource.apple.com/darwinsource/tarballs/apsl/CF-476.15.tar.gz">tarball</a>), among other places. </p>
<p>Finally depending on how often you update the file, how much processor you have to spare on the server, and how much repetition there is your data there may be one significant enhancement left that you can do. By default certain elements in binary plists are uniqued (such as strings). Other elements are not (such as arrays and dictionarts). The binary plist format allows them to be uniqued, the issue is that it is expensive to actually walk through and unique arrays and dictionaries. If you have a lot of identical arrays or dicts in your content you may see a significant size reduction by uniquing them. You can enable that by hacking up _flattenPlist() in <a href="http://www.opensource.apple.com/darwinsource/10.5.5/CF-476.15/CFBinaryPList.c">CFBinaryPlist.c</a>.</p>
<p>If you do that make sure to test it very thoroughly, and do not do on any files you cannot update over the network, just in case a future release makes any optimizations that break that. Also, make sure you are ready to turn it off at a moments notice.</p>
|
PHP removing a character in a string <p>My php is weak and I'm trying to change this string:</p>
<p><a href="http://www.site.com/backend.php?/c=crud&m=index&t=care">http://www.site.com/backend.php?/c=crud&m=index&t=care</a></p>
<p>to be:</p>
<p><a href="http://www.site.com/backend.php?c=crud&m=index&t=care">http://www.site.com/backend.php?c=crud&m=index&t=care</a></p>
<p>removing the / after the ? on backend.php. Any ideas on the best way to do this?</p>
<p>Thanks!</p>
|
<p>I think that it's better to use simply <a href="http://www.php.net/str_replace">str_replace</a>, like the manual says:</p>
<blockquote>
<p>If you don't need fancy replacing
rules (like regular expressions), you
should always use this function
instead of ereg_replace() or
preg_replace().</p>
</blockquote>
<pre><code><?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.