input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Can i get the key of a style in code-behind? (WPF) <p>If I have the following code:</p>
<pre><code>Style defaultStyle = (Style)FindResource("MyTestStyle");
</code></pre>
<p>Is there a way to get the name of the style (i.e. reverse-lookup)? Something like:</p>
<pre><code>string name = defaultStyle.SomeMagicLookUpFunction()
</code></pre>
<p>Where name would evaluate to "MyTestStyle."</p>
<p>Is this possible?</p>
| <p>I've created a small helper class with a single method to do the reverse lookup that you require.</p>
<pre><code>public static class ResourceHelper
{
static public string FindNameFromResource(ResourceDictionary dictionary, object resourceItem)
{
foreach (object key in dictionary.Keys)
{
if (dictionary[key] == resourceItem)
{
return key.ToString();
}
}
return null;
}
}
</code></pre>
<p>you can call it using the following</p>
<pre><code>string name = ResourceHelper.FindNameFromResource(this.Resources, defaultStyle);
</code></pre>
<p>Every <code>FrameworkElement</code> has it's own <code>.Resources</code> dictionary, using 'this' assumes you're in the right place for where MyTestStyle is defined. If needs be you could add more methods to the static class to recursively traverse all the dictionaries in a window (application ?)</p>
|
IsAjaxRequest is always false after upgrade to RC MVC <p>I updated the AJAX scripts and assembly referenced as per release notes. However, IsAjaxRequest still always returns false despite it actually being such a request. How do I resolve this?</p>
| <p>As I understand you are using MS Ajax library. You should update your MicrosoftMvcAjax.js too. It was changed. </p>
|
How do I get the current mouse position in C++ / OpenGL? <p>I know that I can use a Mouse callback function for when a user clicks the mouse, but what if I want to know the current x/y position without the user clicking?</p>
<p>Will I have to use a different callback that gets called on any mouse movement and keep track of the x/y myself or is there a function I can call within GLUT/OpenGL to get it?</p>
| <p>Register a glutPassiveMotionFunc callback function</p>
<p>See info about <a href="http://titanium.mountunion.edu/cs/cs480/sp07/glutcallbackhints.html" rel="nofollow">callbacks</a></p>
|
Deploying Ruby on Rails with Apache and Mongrel <p>I'm fairly new to ruby on rails and web development. Here is my setup which I followed from this link <a href="http://tonyrose023.blogspot.com/2007/01/multiple-rails-apps-with-mongrel.html" rel="nofollow">http://tonyrose023.blogspot.com/2007/01/multiple-rails-apps-with-mongrel.html</a>
I run multiple rails applications on Apache2 with Mongrel clusters.</p>
<p><a href="http://services.abc.edu/app1" rel="nofollow">http://services.abc.edu/app1</a>
<a href="http://services.abc.edu/app2" rel="nofollow">http://services.abc.edu/app2</a>
<a href="http://services.abc.edu/app3" rel="nofollow">http://services.abc.edu/app3</a></p>
<p>This is what my 'virtual host' (/etc/apache2/sites-availabe/services.abc.edu) file looks like</p>
<pre><code>--------------
<Proxy balancer://app1>
BalancerMember http://services.abc.edu:8000
BalancerMember http://services.abc.edu:8001
BalancerMember http://services.abc.edu:8002
Order deny,allow
Deny from all
Allow from all
</Proxy>
<Proxy balancer://app2>
BalancerMember http://services.abc.edu:8004
BalancerMember http://services.abc.edu:8005
Order deny,allow
Deny from all
Allow from all
</Proxy>
<Proxy balancer://app3>
BalancerMember http://services.abc.edu:8006
BalancerMember http://services.abc.edu:8007
Order deny,allow
Deny from all
Allow from all
</Proxy>
<VirtualHost *:80>
ServerName services.abc.edu
DocumentRoot /home/joe/projects/app1/public
<Directory "/home/joe/projects/app1/public">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<Directory "/home/joe/projects/app2/public">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<Directory "/home/joe/projects/app3/public">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
RewriteEngine On
# Rewrite index to check for static
#RewriteRule ^/$ /index.html [QSA]
# Rewrite to check for Rails cached page
RewriteRule ^([^.]+)$ $1.html [QSA]
# Redirect all non-static requests to cluster
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
#RewriteRule ^/(.*)$ balancer://mongrel_cluster%{REQUEST_URI} [P,QSA,L]
RewriteRule ^/app1(.*)$ balancer://app1%{REQUEST_URI} [P,QSA,L]
RewriteRule ^/app2(.*)$ balancer://app2%{REQUEST_URI} [P,QSA,L]
RewriteRule ^/app3(.*)$ balancer://app3%{REQUEST_URI} [P,QSA,L]
</VirtualHost>
-----------------------------------------
</code></pre>
<p>My questions are</p>
<p>1) If anybody can comment on my setup and offer any suggestions would be great.</p>
<p>2) As you can see I have one DocumentRoot, although right now all the 3 apps work since they use same images but I think in the future I need to have DocumentRoot for each app </p>
<p>3) I need to get the apps running securely so I need to make this run with SSL (port 443) and I need some help with making it run with SSL. Any pointers would be helpful since I never installed a cert. I created the csr and the key and I have the cert with me. I'm researching on what are the next steps.</p>
<p>Thanks!</p>
| <p>I would advise you to look into <a href="http://www.modrails.com/" rel="nofollow">Passenger</a>. It's really easy to set up, lets Rails apps share memory, removes the burden of managing a cluster of mongrels and requires virtually no configuration. All you need are a special 'config.ru' file with a <a href="http://www.modrails.com/documentation/Users%20guide.html#_rackup_specifications_for_various_web_frameworks" rel="nofollow">RackUp config</a> and a DocumentRoot pointing to RAILS_ROOT/public set in Apache.</p>
<p>The problem with running multiple apps in mongrel is that you need a seperate mongrel instance for each of them.</p>
<p>As for your SSL question, I have found it really easy to set up SSL for some parts of my sites in <a href="http://nginx.net/" rel="nofollow">Nginx</a>. I don't remember how to do it in Apache, but there are most likely some <a href="http://www.sitepoint.com/article/securing-apache-2-server-ssl/" rel="nofollow">good howtos out there</a>.</p>
|
Should private helper methods be static if they can be static <p>Let's say I have a class designed to be instantiated. I have several private "helper" methods inside the class that do not require access to any of the class members, and operate solely on their arguments, returning a result.</p>
<pre><code>public class Example {
private Something member;
public double compute() {
double total = 0;
total += computeOne(member);
total += computeMore(member);
return total;
}
private double computeOne(Something arg) { ... }
private double computeMore(Something arg) {... }
}
</code></pre>
<p>Is there any particular reason to specify <code>computeOne</code> and <code>computeMore</code> as static methods - or any particular reason not to?</p>
<p>It is certainly easiest to leave them as non-static, even though they could certainly be static without causing any problems.</p>
| <p>I prefer such helper methods to be <code>private static</code>; which will make it clear to the reader that they will not modify the state of the object. My IDE will also show calls to static methods in italics, so I will know the method is static without looking the signature.</p>
|
StarTeam view/branching approach <p>We're looking for some advice on our StarTeam configuration. We have a project that is used by two main customers. We share a common code base but we want to be able to do development for one customer at a time. Does anyone know what the best way to do this is using StarTeam?</p>
<p>I would think you would want to do something like this:</p>
<pre><code>->Main branch (1.0)
-->Cust #1 Release (1.1)
-->Cust #2 Release (1.2)
</code></pre>
<p>As 1.1 is done, you would merge this code into 2.0. Same for 1.2. Then you would create 2.1 or 2.2.</p>
<p>Does this make sense? Just looking for some common sense configuration management solutions that would work for our scenario and would work easily with StarTeam.</p>
<p>Thanks.</p>
<p><strong>Update</strong>: I found an ST <a href="http://dn.codegear.com/article/images/31869/StarTeam_Configuration_Best_Practices.pdf" rel="nofollow">best practices guide</a> that contains useful info regarding this question (see chapter 5). The recommendations are inline with Craig's ST usage (see below). Note that this guide was published Dec 2003.</p>
| <p>You may not want to hear this, but there is no single best way. Having said that, I will tell you what we do.</p>
<p>We do nearly all development in the default view. When we are close enough to releasing one version of a product that we want to start working on the next version, whenever that happens to be, we make a derived view for the version to be released. The derived view is set to branch on change.</p>
<p>We continue development of both the version to be released and the next version in the default view. When there is a bug fix or feature which needs to be included in the version to be released, there are two possibilities:</p>
<ol>
<li>The only thing which has changed in that file is the bug fix or feature which we want in both the version to be released and the next version.</li>
<li>There have been changes made to the file which are intended to be included in the next version, but not in the version to be released.</li>
</ol>
<p>In the case of (1), we go into the derived view, right-click the file, choose Advanced->Behavior, and change the Configuration such that the file includes the changes we've just made. In the case of (2), we check the file into the default view (so that the changes will be included in the next version) and into the derived view (so that the changes will be included in the version to be released, and, of course, only including these changes), causing it to branch.</p>
<p><strong>To be clear,</strong> we do nearly all of our work in the default view. We rarely have to manually branch or change the configuration of files in derived views, because we do not create the derived views at all until we are very close to release.</p>
<p>This is not too far from what you propose doing for your customers, but the important point is to work in the default view and avoid having to do bulk merges up or down into the derived views. StarTeam's view compare/merge tool is just not that great. (We are using 2005; it may have improved since then.)</p>
|
How can I report on files with pending changes in TFS? <p>I'd like to create a simple report that shows files that currently have pending changes (checked out) from a TFS 2008 server. I know that I can use the "Find in Source Control" option from Team Explorer, but I would rather generate a reporting services report. Ideally, I'd be able to show when the file was checked out and the user that checked it out, but that's not imperative.</p>
<p>If the data isn't pushed to the TFS data warehouse by default, then I'd like to find the relational table(s) in the SQL Server instance that would need to be queried.</p>
<p>I've spent some time digging around the TFS data warehouse and looking at all of the canned Reporting Services reports that I can get my hands on, but everything seems to be geared towards work items, check-ins associated with work items, etc... </p>
| <p>If you're looking for some easy to read data and not too worried about print outs, have a look at the TFS sidekick application by Attrice. Very helpful and if you have the correct permissions, you'll be able to see all the checked out files.</p>
<p><a href="http://www.attrice.info/cm/tfs/" rel="nofollow">http://www.attrice.info/cm/tfs/</a></p>
|
Unable to access bluetooth device via COM port on dell axim pda with J2ME <p>I'm trying to write part of a J2ME application and I'm responsible for reading NMEA data from a GPS device attached via bluetooth (to a Dell Axim X51 PDA).</p>
<p>I've paired the gps device with the PDA and I can run the sample program that comes with the gps device and it succesfully streams NMEA strings. </p>
<p>In system settings, in GPS settings, I've set up a COM port (8) for programs to use to obtain GPS data, however, when providing the details for the GPS hardware port there doesn't seem to be a matching baud rate to the one I had to use in the sample program? Does this matter? What does baud rate actually mean?</p>
<p>Now, as far as I understand the settings, I should now be able to read NMEA data over COM 8?</p>
<p>However, when I print out:</p>
<pre><code>System.getProperty("microedition.commports")
</code></pre>
<p>COM8 does not appear in the list returned and if I try and open a connection on that port I get the following error:</p>
<pre><code>java.io.IOException: GetCommState() failed; error code=21, (21) The device is not ready.
</code></pre>
<p>Any pointers on successfully setting up the COM port for reading, and actually reading from it would be most welcome. I'm pretty stumped and clueless as to what to do.</p>
| <p>There is a good chance the j2me implementation on your device doesn't support bluetooth COM ports at all. I would suggest confirming that first. It could be worth comparing the result of the system property call on other (recent) handsets.</p>
|
Is there a simple way to change the text of the 'Open' button on the windows file dialog to 'Select'? <p>We're using the file picker dialog to allow users to add documents into our application. The word 'Open' doesn't make a lot of sense in this case.</p>
<p>Thanks.</p>
| <p>I would browse the <a href="http://www.codeproject.com/KB/dialog/OpenFileDialogEx.aspx" rel="nofollow">code found here</a>, which shows how someone extended the OpenFileDialog. Admittedly, this is overkill for you. But I think there is code within to change the button label.</p>
|
Connecting to MS SQL Server using python on linux with 'Windows Credentials' <p>Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials?</p>
<p>I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc </p>
<pre><code>>>import pyodbc
>>conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname")
</code></pre>
<p>results in this error:</p>
<pre><code>class 'pyodbc.Error'>: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)')
</code></pre>
<p>I'm sure the password is written correctly, but I've tried many different combinations of username:</p>
<pre><code>DOMAIN\username
DOMAIN\\username
</code></pre>
<p>or even</p>
<pre><code>UID=username;DOMAIN=domain
</code></pre>
<p>to no avail. Any ideas?</p>
| <p><strong>As pointed out in one of the comments, this answer is quite stale by now. I regularly and routinely use GSSAPI to authenticate from Linux to SQL Server 2008 R2 but mostly with the EasySoft ODBC manager and the (commercial) EasySoft ODBC SQL Server driver.</strong></p>
<p>In early 2009, a colleague and I managed to connect to a SQL Server 2005 instance from Solaris 10 using GSSAPI (Kerberos credentials) using DBB::Perl over a FreeTDS build linked against a particular version of the MIT kerberos libraries. The trick was -- and this is a little bit difficult to believe but I have verified it by looking through the FreeTDS source code -- to specify a <em>zero-length</em> user_name. If the length of the user_name string is 0 then the FreeTDS code will attempt to use GSSAPI (if that support has been compiled in). I have not been able to do this via Python and pyodbc as I could not figure out a way of getting ODBC to pass down a zero-length user_name.</p>
<p>Here in the perl code .. there are multiple opportunities for breakage wrt configuration files such as .freetds.conf etc. I seem to recall that the principal had to be in uppercase but my notes seem to be in disagreement with that.</p>
<pre>
$serverprincipal = 'MSSQLSvc/foo.bar.yourdomain.com:1433@YOURDOMAIN.COM';
$dbh = DBI->connect("dbi:Sybase:server=THESERVERNAME;kerberos=$serverprincipal", '', '');
</pre>
<p>You will have to know how to use the setspn utility in order to get the SQL Server server to use the appropriate security principal name.</p>
<p>I do not have any knowledge of the kerberos side of things because our environment was set up by an out and out Kerberos guru and has fancy stuff like mutual trust set up between the AD domain that the SQL Server is running in and the Kerberos domain that my client was running in.</p>
<p>There is some code <a href="http://code.google.com/p/libsqljdbc-auth/" rel="nofollow">http://code.google.com/p/libsqljdbc-auth/</a> which does GSSAPI authentication from Linux to SQL Server but it is Java only. The author (who seems to know his stuff) also has contributed a similar patch to the jTDS project which works with more recent versions of Java that have GSSAPI built in.</p>
<p>So the pieces are all there, it is just a big tangled mess trying to get them all to work together. I found the pyodbc to unixODBC to FreeTDS odbc to TDS integration pretty hard to trace/debug. The perl stuff because it was a pretty thin wrapper on top to CT-Lib was much easier to get going.</p>
|
MGTwitterEngine - Status updates <p>I find that randomly I get a EXC_BAD_ACCESS error on the iPhone when updating the status. This occurs pretty randomly.</p>
<p>Anyone have any idea to how this make be fixed?</p>
<pre><code>#import "TwitterViewController.h"
NSString *_testUID = nil;
NSString *sImageName;
@implementation TwitterViewController
//Turns NSLogs into comments
//#define NSLog //
- (void)viewDidLoad {
self.title = @"Twitter";
arrayEmotes = [[NSMutableArray alloc] init];
[arrayEmotes addObject:@"Happy"];
[arrayEmotes addObject:@"Sad"];
[arrayEmotes addObject:@"Tongue"];
[arrayEmotes addObject:@"Drunk"];
[arrayEmotes addObject:@"Bored"];
[arrayEmotes addObject:@"Love"];
[arrayEmotes addObject:@"Sleepy"];
[arrayEmotes addObject:@"Sick"];
[arrayEmotes addObject:@"Awake"];
[arrayEmotes addObject:@"Shocked"];
[arrayEmotes addObject:@"Angry"];
[arrayEmotes addObject:@"Laughing"];
[arrayEmotes addObject:@"Dancing"];
[arrayEmotes addObject:@"Confused"];
[activityView startAnimating];
[currentActivity setText:@"Logging In"];
NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"username_preference"];
NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"password_preference"];
// Make sure you entered your login details before running this code... ;)
if ([username isEqualToString:@""] || [password isEqualToString:@""]) {
//Show the UIAlert if no username or password is stored in the settings
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Incorrect username/password stored in the settings." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(@"You forgot to specify your username/password in settings.bundle!");
}
// Create a TwitterEngine and set our login details.
twitterEngine = [[[MGTwitterEngine alloc] initWithDelegate:self] retain];
[twitterEngine setUsername:username password:password];
// Get updates from people the authenticated user follows.
//[twitterEngine getFollowedTimelineFor:username since:nil startingAtPage:0];
_testUID = [twitterEngine testService];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [arrayEmotes count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [arrayEmotes objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayEmotes objectAtIndex:row], row);
[btnUpdateMood setEnabled:YES];
}
- (IBAction)updateMood:(id)sender
{
NSLog(@"Tried to send status.");
NSInteger selectedindex = [pickerView selectedRowInComponent:0];
switch(selectedindex){
case 0:
//Happy
sImageName = @"Happy";
break;
case 1:
//Sad
sImageName = @"Sad";
break;
case 2:
//Tongue
sImageName = @"Tounge";
break;
case 3:
//Drunk
sImageName = @"Drunk";
break;
case 4:
//Bored
sImageName = @"Bored";
break;
case 5:
//Love
sImageName = @"Love";
break;
case 6:
//Sleepy
sImageName = @"Sleepy";
break;
case 7:
//Sick
sImageName = @"Sick";
break;
case 8:
//Awake
sImageName = @"Awake";
break;
case 9:
//Shocked
sImageName = @"Shocked";
break;
case 10:
//Angry
sImageName = @"Angry";
break;
case 11:
//Laughing
sImageName = @"Laughing";
break;
case 12:
//Dancing
sImageName = @"Dancing";
break;
case 13:
//Confused
sImageName = @"Confused";
break;
default: break;
}
[twitterEngine sendUpdate:[@"has changed his/her iMood to " stringByAppendingString:sImageName]];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
//Releasing seems to sometimes cause complete errors.
//[twitterEngine release];
[super dealloc];
}
#pragma mark MGTwitterEngineDelegate methods
- (void)requestSucceeded:(NSString *)requestIdentifier
{
[activityView stopAnimating];
//Some animations
[UIView beginAnimations:@"redToWhite" context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:1];
[UIView setAnimationRepeatCount:0];
//Change background colour of the activity area over 1 second
[activityArea setBackgroundColor:[UIColor whiteColor]];
[currentActivity setText:@"Logged In"];
[UIView commitAnimations];
//End of animations
NSLog(@"Request succeeded (%@)", requestIdentifier);
if ([requestIdentifier isEqualToString:_testUID])
{
NSLog(@"[TWITTER UP]");
}
}
- (void)requestFailed:(NSString *)requestIdentifier withError:(NSError *)error
{
currentActivity.text = [NSString stringWithFormat:@"Error: %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]];
NSLog(@"Twitter request failed! (%@) Error: %@ (%@)",
requestIdentifier,
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)statusesReceived:(NSArray *)statuses forRequest:(NSString *)identifier
{
NSLog(@"Got statuses:\r%@", statuses);
}
- (void)directMessagesReceived:(NSArray *)messages forRequest:(NSString *)identifier
{
NSLog(@"Got direct messages:\r%@", messages);
}
- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)identifier
{
NSLog(@"Got user info:\r%@", userInfo);
}
- (void)miscInfoReceived:(NSArray *)miscInfo forRequest:(NSString *)identifier
{
NSLog(@"Got misc info:\r%@", miscInfo);
}
- (void)imageReceived:(UIImage *)image forRequest:(NSString *)identifier
{
NSLog(@"Got an image: %@", image);
}
@end
</code></pre>
| <p>You have a few leaks (twitterEngine (you are retaining it when alloc/init does the job fine) and arrayEmotes (never gets released) to name the two I spotted right away), and you could have another issue related to sImageName when you send the update (notice how it isn't defined on a scope other than inside the switch statement - I don't really know if this would definitely cause issues, it's just something I always try to avoid. I can see it potentially causing an EXC_BAD_ACCESS).</p>
<p>Anyway, try using GDB to step through your program to figure out what object exactly is being released early. A lot of headaches can be solved simply with GDB.</p>
|
How to get a window handle to a COM Single-Threaded Apartment (STA)? <p>CoInitialize(NULL) creates an STA by creating a hidden window. How to get an HWND handle for this window?</p>
<p>Function EnumThreadWindows does not work, in an example I tried:</p>
<pre><code>...
CoInitialize(NULL);
EnumThreadWindows(GetCurrentThreadId(), EnumThreadWndProc, 0);
...
BOOL CALLBACK EnumThreadWndProc(HWND hwnd, LPARAM lParam)
{
m_hwnd = hwnd;
return FALSE;
}
</code></pre>
<p>Nothing ever enters the EnumThreadWndProc.</p>
<p>Any ideas?</p>
| <p>This hidden window is Message-Only Window, It is not visible, has no z-order, cannot be enumerated, and does not receive broadcast messages. The window simply dispatches messages.</p>
<p>To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function. In addition, FindWindowEx searches message-only windows as well as top-level windows if both the hwndParent and hwndChildAfter parameters are NULL.</p>
<p>Source:
<a href="http://msdn.microsoft.com/en-us/library/ms632599(VS.85).aspx#message_only" rel="nofollow">MSDN</a></p>
|
Can we publish two versions of an iphone application? <p>HI,</p>
<p>I am developing an application for an esteemed client in Australia. They have certain copyright issues when it comes to uses outside Australia accessing the content via the app.</p>
<p>Is it possible to have a local and an international version of the app, both available via iTunes Store? The international version will only have permissible content. If not, please advice the best option to deal with this issue.</p>
<p>Thanking you in anticipation</p>
<p>Cheers,</p>
<p>Amit</p>
| <p>Yes, you can create two versions of the application with different SKUs. The best way to do this would by by using a wildcard certificate and using a different project identifier in the application's plist file.</p>
<p>Using the administrative panel on iTunes Connect you can then restrict the sale of the SKUs to different territories.</p>
<p>These options become available when you have paid the $99 for a development certificate, and and when you upload your application to iTunes.</p>
|
What can cause a UIView to be arbitrarily removed from the hierarchy? <p>I have an iPhone app that, for some users, sometimes behaves as if with the main UIView has been removed from the view hierarchy. It always happens coincident with a significant event in the game. Other Core Graphics-drawn UIViews that are above it in the z-order remain, but the main one (an OpenGL view) appears to be gone, leaving the background (a solid color).</p>
<p>The app does not crash (it keeps running, without the view), and this seems to happen very consistently for affected users. Unfortunately I am not able to reproduce it.</p>
<p>I suspect a memory issue -- that would be the easiest explanation -- but based on my reading it looks like didReceiveMemoryWarning only deallocs views that aren't visible, and aside from that the memory usage for my app is pretty small. Also, the "significant event" only results in OpenGL drawing and a SoundEngine call -- no view manipulation.</p>
<p>Anybody out there seen something like this before?</p>
| <p>Yes, infact one of my applications very occasionally exhibits this problem and it does seem to be memory related.</p>
<p>I have had no success tracking it down either by debugging or analyzing the program flow. I have verified that the view in question is destroyed and not just hidden in some way.</p>
<p>It happens so infrequently that I haven't looked into it to deeply, but I do think it's caused by something in the OS in some way,</p>
|
why can't i change my regional settings? <p>for about 2 hours i've been trying to find solutions on how to change my advanced regional settings(the one for language used in non-unicode programs) ..because everytime i try to change the language ...the system gives me an error that says:
Setup was unable to install the chosen locale. Please contact your system Administrator.</p>
<p>So what do i have to do?</p>
| <p>Sounds to me like you may need to be an admin to do that. Have you tried that?</p>
|
OCI connection string... need help <p>Does anyone know the OCI connection string used for the dbname parameter in the function OCILogon() for the oracle 10g C API ?</p>
<p>I know you can specify the tnsnames.ora entry for the service, but does it have the ability to take something like: oci:connect:myserver.com:1521/myservicename ?</p>
| <p>You may use the following format for dbname:</p>
<p><code>[//]host[:port][/service name]</code></p>
<p>You can read more on subject here:
<a href="http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10646/oci01int.htm#LNOCI16167" rel="nofollow">Database Connection Strings for OCI Instant Client</a></p>
|
Google Bookmark Export date format? <p>I been working on parsing out bookmarks from an export file generated by google bookmarks. This file contains the following date attributes:</p>
<p>ADD_DATE="1231721701079000"</p>
<p>ADD_DATE="1227217588219000"</p>
<p>These are not standard unix style timestamps. Can someone point me in the right direction here? I'll be parsing them using c# if you are feeling like really helping me out.</p>
| <p>Chrome uses a modified form of the Windows Time format (â<a href="http://blogs.msdn.com/b/oldnewthing/archive/2009/03/06/9461176.aspx">Windows epoch</a>â) for its timestamps, both in the <code>Bookmarks</code> file and the history files. The Windows Time format is the number of 100ns-es since January 1, 1601. The Chrome format is the number of microseconds since the same date, and thus 1/10 as large.</p>
<p>To convert a Chrome timestamp to and from the Unix epoch, you must convert to seconds and compensate for the difference between the two base date-times (11644473600).</p>
<p>Hereâs the conversion formulas for Unix, JavaScript (Unix in milliseconds), Windows, and Chrome timestamps (you can rearrange the +/à and -/÷, but youâll lose a little precision):</p>
<pre><code>u : Unix timestamp eg: 1378615325
j : JavaScript timestamp eg: 1378615325177
c : Chrome timestamp eg: 13902597987770000
w : Windows timestamp eg: 139025979877700000
u = (j / 1000)
u = (c - 116444736000000) / 10000000
u = (w - 1164447360000000) / 100000000
j = (u * 1000)
j = (c - 116444736000000) / 10000
j = (w - 1164447360000000) / 100000
c = (u * 10000000) + 116444736000000
c = (j * 10000) + 116444736000000
c = (w / 10)
w = (u * 100000000) + 1164447360000000
w = (j * 100000) + 1164447360000000
w = (c * 10)
</code></pre>
<p>Note that these are pretty big numbers, so youâll need to use 64-bit numbers or else handle them as strings like with PHPâs BC-math module.</p>
|
What is the best way to clean a string for placement in a URL, like the question name on SO? <p>I'm looking to create a URL string like the one SO uses for the links to the questions. I am not looking at rewriting the url (mod_rewrite). I am looking at generating the link on the page.</p>
<p>Example: The question name is:</p>
<pre><code>Is it better to use ob_get_contents() or $text .= âtestâ;
</code></pre>
<p>The URL ends up being:</p>
<pre><code>http://stackoverflow.com/questions/292068/is-it-better-to-use-obgetcontents-or-text-test
</code></pre>
<p>The part I'm interested in is:</p>
<pre><code>is-it-better-to-use-obgetcontents-or-text-test
</code></pre>
<p>So basically I'm looking to clean out anything that is not alphanumeric while still keeping the URL readable. I have the following created, but I'm not sure if it's the best way or if it covers all the possibilities:</p>
<pre><code>$str = urlencode(
strtolower(
str_replace('--', '-',
preg_replace(array('/[^a-z0-9 ]/i', '/[^a-z0-9]/i'), array('', '-'),
trim($urlPart)))));
</code></pre>
<p>So basically:</p>
<ol>
<li>trim</li>
<li>replace any non alphanumeric plus the space with nothing</li>
<li>then replace everything not alphanumeric with a dash</li>
<li>replace -- with -. </li>
<li><code>strtolower()</code></li>
<li><code>urlencode()</code> -- probably not needed, but just for good measure.</li>
</ol>
| <p>As you pointed out already, urlencode() is not needed in this case and neither is trim(). If I understand correctly, step 4 is to avoid multiple dashes in a row, but it will not prevent more than two dashes. On the other hand, dashes connecting two words (like in "large-scale") will be removed by your solution while they seem to be preserved on SO.</p>
<p>I'm not sure that this is really the <em>best</em> way to do it, but here's my suggestion:</p>
<pre><code>$str = strtolower(
preg_replace( array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'),
$urlPart ) );
</code></pre>
<p>So:</p>
<ol>
<li>remove any character that is neither space, dash, nor alphanumeric </li>
<li>replace any consecutive number of spaces or dashes with a single dash</li>
<li>strtolower()</li>
</ol>
|
How does .NET make use of IO Threads or IO Completion Ports? <p>We have a .NET application that makes several concurrent calls to various web services, collects their responses and then makes a few calculations off those responses. In attempting to derive additional performance, I've been investigating the use of approaches that make use of .NET's IO threading via the use of IO completion ports. I've read through several resources including Joe Duffy's recent book Concurrent Programming on Windows and while I "get" their usefulness, I'm a little unclear as to their behavior within .NET and am looking for a concise explanation.</p>
| <p>Chances are that you don't have to do anything if you are using the asynchronous methods already. Depending on the technology that you are using for the call to the web service, ultimately, it's going to drop down to the Win32 API to make the call to get bytes from the network, and to that end, it will use I/O Completion Ports in order to handle asynchronous calls.</p>
<p>The basic premise behind I/O completion ports is that when waiting on I/O operations, there is a thread pool that is kept waiting for when the I/O operations complete (assuming you registered to use I/O completion ports). When your registered operation completes, the thread from the I/O completion port thread pool is used to handle the callback.</p>
<p>Of course, after calling out to the I/O completion port, your thread can move on to do more work, or terminate, the choice is up to you.</p>
<p>The following should help describe it more:</p>
<p>I/O Completion Ports:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa365198%28VS.85%29.aspx">http://msdn.microsoft.com/en-us/library/aa365198(VS.85).aspx</a></p>
<p>Inside I/O Completion Ports (WayBack Machine):</p>
<p><a href="https://web.archive.org/web/20101101112358/http://doc.sch130.nsc.ru/www.sysinternals.com/ntw2k/info/comport.shtml">https://web.archive.org/web/20101101112358/http://doc.sch130.nsc.ru/www.sysinternals.com/ntw2k/info/comport.shtml</a></p>
|
Questions about Php and Mysql Hash Table <p>I am a new php and mysql programmer. I am handling quite large amount of data, and in future it will grow slowly, thus I am using hash table. I have couple of questions:</p>
<ol>
<li><p>Does mysql have hash table built in function? If yes, how to use that?</p></li>
<li><p>After couple of days doing research about hash table. I briefly know what hash table is but I just could not understand how to start creating one. I saw a lot of hash table codes over the internet. Most of them, in the first step in to create a hashtable class. Does it mean, they store the hash table value in the temporary table instead of insert into mysql database?</p></li>
</ol>
<p>For questions 3,4 & 5, example scenario:
User can collect items in the website. I would like to use hash table to insert and retrieve the items that the user collected.</p>
<ol>
<li><p>[Important] What are the possible mysql database structure looks like?</p>
<p>e.g, create items and users table</p>
<p>in items table have: item_id, item_name, and item_hash_value</p>
<p>in users table have: user_id, username, item_name, item_hash_value</p>
<p>I am not sure if the users table is correct?</p></li>
<li><p>[Important] What are the steps of creating hash table in php and mysql?
(If there is any sample code would be great :))</p></li>
<li><p>[Important] How to insert and retrieve data from hash table? I am talking about php and mysql, so I hope the answers can be like: "you can use mysql query i.e SELECT * from blabla..."</p></li>
</ol>
| <p>(sorry about the italics, underscores can trigger them but I can't find a good way to disable that in the middle of a paragraph. Ignore the italics, I didn't mean to put them there)</p>
<p>You don't need to worry about using a hashtable with MySQL. If you intend to have a large number of items in memory while you operate on them a hashtable is a good data structure to use since it can find things much faster than a simple list.</p>
<p>But at the database level, you don't need to worry about the hashtable. Figuring out how to best hold and access records is MySQL's job, so as long as you give it the correct information it will be happy.</p>
<h2>Database Structure</h2>
<pre><code>items table would be: item_id, item_name
Primary key is item_id
users table would be: user_id, username
Primary key is user_id
user_items table would be: user_id, item_id
Primary key is the combination of user_id and item_id
Index on item_id
</code></pre>
<p>Each item gets one (and only one) entry in the items table. Each user gets one (and only one) entry in the users table. When a user selects an item, it goes in the user items table. Example:</p>
<pre><code>Users:
1 | Bob
2 | Alice
3 | Robert
Items
1 | Headphones
2 | Computer
3 | Beanie Baby
</code></pre>
<p>So if Bob has selected the headphones and Robert has selected the computer and beanie baby, the user_items table would look like this:</p>
<pre><code>User_items (user_id, item_id)
1 | 1 (This shows Bob (user 1) selected headphones (item 1))
3 | 2 (This shows Robert (user 3) selected a computer (item 2))
3 | 3 (This shows Robert (user 3) selected a beanie baby (item 3))
</code></pre>
<p>Since the user_id and item_id on the users and items tables are primary keys, MySQL will let you access them very fast, just like a hashmap. On the user_items table having both the user_id and item_id in the primary key means you won't have duplicates and you should be able to get fast access (an index on item_id wouldn't hurt).</p>
<h2>Example Queries</h2>
<p>With this setup, it's really easy to find out what you want to know. Here are some examples:</p>
<p>Who has selected item 2?</p>
<pre><code>SELECT users.user_id, users.user_name FROM users, user_items
WHERE users.user_id = user_items.user_id AND user_items.item_id = 2
</code></pre>
<p>How many things has Robert selected?</p>
<pre><code>SELECT COUNT(user_items.item_id) FROM user_items, users
WHERE users.user_id = user_items.user_id AND users.user_name = 'Robert'
</code></pre>
<p>I want a list of each user and what they've selected, ordered by the user name</p>
<pre><code>SELECT user.user_name, item.item_name FROM users, items, user_items
WHERE users.user_id = user_items.user_id AND items.item_id = user_items.item_id
ORDER BY user_name, item_name
</code></pre>
<p>There are many guides to SQL on the internet, such as the <a href="http://www.w3schools.com/sql/default.asp" rel="nofollow">W3C's tutorial</a>.</p>
|
Scrum: Unfinished products and sprint velocity <p>Letâs say product X is worth 10 story points. Development starts in sprint Y, but is not completed in time. What do you with the story points when calculating sprint Yâs velocity?</p>
<p>Would you:</p>
<p>a. Allocate 0 story points for sprint Y and 10 points for the sprint it is eventually completed in;</p>
<p>b. Determine the story points for the remaining work (letâs say 3) and allocate the difference to sprint Y (7 in our example); or</p>
<p>c. Something else?</p>
<p>Thanks in advance!</p>
| <p>Depends on whether you care about your "instantaneous" or "average" velocity. Personally, I wouldn't make it more complicated than necessary and just add it into the sprint where it was completed. Calculate your average velocity by looking at the average number of points completed per sprint over the last 3, 6, and 12 months. Hopefully, these will eventually converge and you'll have a good idea of how much you can get done in one sprint. </p>
|
Script SQL Server login with Windows authentication without machine name <p>I want to write a SQL 2005 script to create a new login that uses Windows authentication. The Windows user is a local account (not a domain one). A local account with the same name exists on many SQL Server machines and I want to run the same script on all of them.</p>
<p>It seemed simple enough:</p>
<pre><code>CREATE LOGIN [MyUser]
FROM WINDOWS
</code></pre>
<p>However, that doesn't work! SQL returns an error, saying <code>Give the complete name: <domain\username>.</code></p>
<p>Of course, I can do that for one machine and it works, but the same script will not work on other machines.</p>
| <p>Looks like sp_executesql is the answer, as beach posted. I'll post mine as well, because @@SERVERNAME doesn't work correctly if you use named SQL instances, as we do.</p>
<pre><code>DECLARE @loginName SYSNAME
SET @loginName = CAST(SERVERPROPERTY('MachineName') AS SYSNAME) + '\MyUser'
IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE [name] = @loginName)
BEGIN
DECLARE @sql NVARCHAR(1000)
SET @sql = 'CREATE LOGIN [' + @loginName + '] FROM WINDOWS'
EXEC sp_executesql @sql
END
</code></pre>
|
What is the best way to meditate to increase programming productivity? <p>Recently, I've added regular exercise to my life. It has given me more overall energy and I have been more productive at work. However, I have also heard that meditation can help you be more focused, and, consequently, more productive. There is a lot of different advice out there, but it is difficult to tell which route go: music, silence, brain-wave sounds, eyes open, eyes closed, seated, laying down, kata. What has worked for you?</p>
<p>To clarify, I am not asking what you do specifically while you are working. Similar to exercise being done before or after work that helps me have more energy during the work hours, I'm looking for meditation to help train my brain to be more focused and creative during the day with deep thought tasks, like programming.</p>
| <p>The Pragmatic Programmers wrote a great book <a href="http://www.pragprog.com/titles/ahptl/pragmatic-thinking-and-learning">Pragmatic Thinking and Learning</a> which suggests the Vipassana meditation technique:</p>
<blockquote>
<p>What you want to attain here is not a trance or to fall asleep or to
relax or to contemplate the Great Mystery or any of that (there are
other for ms of meditation for those particular activities). Instead,
what you want is to sink into a sort of relaxed awareness where you
can be aware of your - self and your environment without rendering
judgment or making responses. This is known as Vipassana meditation.
You want to catch that moment of bare attention where you ï¬rst notice
some- thing but do not give it any additional thought. Let it go. In
this style of meditation, âallâ you have to do is pay attention to
your breath. Itâs not as easy as it sounds, but it does have the
advantage of not requiring any props or special equipment.</p>
</blockquote>
<p>I don't feel comfortable quoting more of the book as they have a full 4 pages on it and I recommend getting it anyway!</p>
|
XmlSerializer can't find EntityObject even though its referenced <p>I hope that someone can help me with this problem that I've been having with XmlSerializer. </p>
<p>I've already looked through this thread: <a href="http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/551cee76-fd80-48f8-ac6b-5c22c234fecf/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/551cee76-fd80-48f8-ac6b-5c22c234fecf/</a></p>
<p>The error I am getting is:</p>
<p>System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.</p>
<p>I've made sure that my unit test has a reference to System.Data.Entity, so it is able to compile at least. I've also in the app.config made an assembly binding to System.Data.Entity.</p>
<p>Here's my rough class structure</p>
<pre><code>[Serializable]
[XmlRoot(Namespace = XmlSupport.MyNamespace, ElementName = XmlSupport.WantToSerialize)]
[XmlInclude(typeof(WantToSerializeBaseClass)]
[XmlInclude(typeof(EntityObject)]
[XmlInclude(typeof(MyEntityObjectSubClass)]
public class WantToSerialize : WantToSerializeBaseClass, IXmlSerializable (I've tried putting this on the baseclass and the current class)
{
// methods and classes
// I've included XmlIncludes for all the classes that this class has a reference too
// even though in the WriteXml it just uses .NET base classes
}
</code></pre>
<p>The WantToSerializeBaseClass makes use of some generics, but I've decorated it with XmlIncludes for (EntityObject, and any other classes it makes reference to as well).</p>
<p>the calling code:</p>
<pre><code>var serializerWrite = new XmlSerializer(typeof (WantToSerialize), XmlSupport.ITNNamespace);
</code></pre>
<p>fails</p>
<p>However if I do:</p>
<pre><code>var serializerWrite = new XmlSerializer(typeof (WantToSerialize), new Type[] {typeof(EntityObject)});
</code></pre>
<p>it is succesfull.</p>
<p>Any thoughts would be most helpful.</p>
<p><strong>UPDATED</strong>
I've tracked the problem down to a method in the WantToSerializeBaseClass</p>
<pre><code>public abstract void ConvertFromEntity<TtoCopy>(TtoCopy toCopy) where TtoCopy : MyEntityObjectSubClass;
</code></pre>
<p>Where MyEntityObjectSubClass is a subclass of EntityObject, that adds a few methods that I want on my entity objects. The MyEntityObjectSubClass looks like this:</p>
<pre><code>[Serializable]
[XmlInclude(typeof(EntityObject))]
public abstract class MyEntityObjectSubClass : EntityObject, IMyEntityObjectSubClass
</code></pre>
<p>Again any thoughts would be great</p>
| <p>If you don't have any code that requires a reference at compile time then that reference won't be included in the built assembly. You can use a tool like <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">Reflector</a> to check whether the reference is making it into your assembly.</p>
<p>One thing you can try is adding a static method to WantToSerialize that creates the XmlSerializer. The assembly containing WantToSerialize must already have a good reference to EntityObject, so this should solve the problem.</p>
|
Good Domain Driven Design samples <p>I'm learning about Domain Driven Design and enjoying every minute of it. However, there are some practical issues that are confusing to me that I think seeing some good samples might clear up.</p>
<p>So being at peace with those issues, does anyone know of some good working code samples that do a good job of modeling basic DDD concepts?</p>
<p>Particularly interested in</p>
<ul>
<li>An illustrative Domain Model</li>
<li>Repositories</li>
<li>Use of Domain/Application Services</li>
<li>Value Objects</li>
<li>Aggregate Roots</li>
</ul>
<p>I know I'm probably asking for too much, but anything close will help.</p>
| <p>The difficulty with DDD samples is that they're often very domain specific and the technical implementation of the resulting system doesn't always show the design decisions and transitions that were made in modelling the domain, which is really at the core of DDD. DDD is much more about the process than it is the code. (as some say, the best DDD sample is the book itself!)</p>
<p>That said, a well commented sample app should at least reveal some of these decisions and give you some direction in terms of matching up your domain model with the technical patterns used to implement it.</p>
<p>You haven't specified which language you're using, but I'll give you a few in a few different languages:</p>
<p><a href="https://github.com/citerus/dddsample-core">DDDSample</a> - a Java sample that reflects the examples Eric Evans talks about in <a href="http://www.domaindrivendesign.org/books/index.html#DDD">his book</a>. This is well commented and shows a number of different methods of solving various problems with separate bounded contexts (ie, the presentation layer). It's being actively worked on, so check it regularly for updates.</p>
<p><a href="http://www.codeplex.com/dddpds">dddps</a> - Tim McCarthy's sample C# app for his book, .NET Domain-Driven Design with C#</p>
<p><a href="http://code.google.com/p/sharp-architecture/">S#arp Architecture</a> - a pragmatic C# example, not as "pure" a DDD approach perhaps due to its lack of a real domain problem, but still a nice clean approach.</p>
<p>With all of these sample apps, it's probably best to check out the latest trunk versions from SVN/whatever to really get an idea of the thinking and technology patterns as they should be updated regularly.</p>
|
What is the conventions for headers and cpp files in C++? <p>In C++, what is the convention for including headers for class files in the "main" file. e.g.</p>
<pre><code>myclass.h
class MyClass {
doSomething();
}
myclass.cpp
doSomething() {
cout << "doing something";
}
run.cpp
#include "myclass.h"
#include "myclass.cpp"
etc..
</code></pre>
<p>Is this relatively standard? </p>
| <p>You don't include the .cpp file, only the .h file. The function definitions in the .cpp will be compiled to .obj files, which will then be linked into the final binary. If you include the .cpp file in other .cpp files, you will get two different .obj files with the same funciton definition compiled, which will lead to linker error.</p>
|
Java Class Loaders <p>Can anyone point me a good resource or explain me about the concept behind Class Loaders? I found the following resource on class loaders <a href="http://www.onjava.com/lpt/a/5586">http://www.onjava.com/lpt/a/5586</a> but still no help. The following questions may look silly but trying to answer them always confuses me.</p>
<ul>
<li>Why do developers write Custom class loaders, why not invoke a Bootstrap class loader to invoke your custom classes? What is the need to define custom class loaders?</li>
<li><p>Why there are so many varieties of class loaders? eg: Bootsrap, Comman, Catalina class loader etc.,</p>
<p>Thanks in advance.</p></li>
</ul>
| <p>I found the following, valid reasons to create custom classloaders:</p>
<ol>
<li><p>You want to load a class from an unconventional source (For example, the bytecode for one class is stored in a database, across the network or <a href="http://www.ietf.org/rfc/rfc1149.txt?number=1149">carried as 0 and 1s by pidgeons</a> - MessengerPidgeonClassLoader). There is some ClassLoader implementations already in the API for such cases, such as <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/net/URLClassLoader.html">URLClassLoader</a>.</p></li>
<li><p>You need to define a different hierarchy to load classes. Default implementations of the ClassLoader delegate the search first to the parent, then they try to load the class themselves. Maybe you want a different hierarchy. This is the reason why OSGI and Eclipse have its own ClassLoaders as the Manifest .MF files define all types of weird hierarchy paths (buddy-classloading, for example). All Eclipse classloaders implement the BundleClassLoader interface and have some extra code to find resources within Eclipse Plugins.</p></li>
<li><p>You need to do some modification to the bytecode. Maybe the bytecode is encrypted, and you will unencrypt it on the fly (<a href="http://www.javaworld.com/javaworld/javaqa/2003-05/01-qa-0509-jcrypt.html">Not that it helps, really, but has been tried</a>). Maybe you want to "patch" the classes loaded on the fly (A la JDO bytecode enhancement).</p></li>
</ol>
<p>Using a different classloader than the System Classloader is required if you need to unload classes from memory, or to load classes than could change their definition at runtime. A typical case is an application that generates a class on the fly from an XML file, for example, and then tries to reload this class. Once a class is in the System Classloader, there is no way to unload it and have a new definition.</p>
|
Eclipse RCP Plugin development - Can't get new menuContribution option <p>I am using Eclipse 3.2. For an RCP application, I am trying to extend from org.eclipse.ui.menus. When I right-click and pick new option, "menu Contribution" isn't appearing. I only see options 'item', 'menu', 'group', 'widget' under 'New'. There is no option named "menu Contribution". Am I missing anything in target platform? If so, which jar?</p>
| <p>I confirm it can not work.</p>
<p>Consider the <strong>Extension Points Reference</strong> help from:</p>
<ul>
<li><p><a href="http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/extension-points/org_eclipse_ui_menus.html" rel="nofollow">org.eclipse.ui.menus in 3.2.1</a></p>
<p><!ELEMENT extension (item* , menu* , group* , widget*)></p></li>
<li><p><a href="http://help.eclipse.org/ganymede/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/extension-points/org_eclipse_ui_menus.html" rel="nofollow">org.eclipse.ui.menus in 3.4 Ganymede</a></p>
<p><!ELEMENT extension (group* , widget* , menuContribution*)></p></li>
</ul>
<p>That is why you do not see <code>menuContribution</code></p>
<p><img src="http://www.vogella.de/articles/RichClientPlatform/images/command70.gif" alt="alt text" /></p>
|
Fix for 'return' in cakePHP to return Value from view controller function <p>I have a function inside of a view function inside of a model class in the model.php file that looks like this</p>
<pre><code>function sqlToUnix($date){
$YMDThenHMS = explode(" ", $date);
$YMD = explode("-", $YMDThenHMS[0]);
$HMS = explode(":", $YMDThenHMS[1]);
$UnixTime = mktime($HMS[0], $HMS[1], $HMS[2], $YMD[1], $YMD[2], $YMD[0]);
return $UnixTime;
}
</code></pre>
<p>The problem is, when it returns $UnixTime, The return value is usable inside the model controller specific view function but it won't render my view (stops script propogation)</p>
<p>Is there a place where I can build functions like this up for use ANYWHERE in ANY Controller?</p>
<p>Such as the function time() built into PHP itself, I want to be able to use sqlToUnix anywhere</p>
| <p>If you want to call this function from anywhere, i.e. in models, controllers, views, behaviors, components and helpers, you can put it in your app/config/bootstrap.php file. That's what it's for. Once the it's available globally simply as sqlToUnix();</p>
|
jquery sortable - how to prevent item from dragging from one list to another <p>There are two sortable UL elements which are linked to each other via 'connectWith' options so that items from one list can be moved to another list and vice versa. I'm in need to prohibit from moving/dragging some items to another list while still letting them to be draggable within their own list. Is there any way to implement such behavior?</p>
<p>For now I can only restrict items from dragging using 'items' option of those sortable lists but while this prevents the desired items from dragging to another list this also prevents those items from dragging within their own lists (which is bad).</p>
| <p>The way I was able to get around this is by using the <code>li</code> elements <code>onMouseDown</code> and <code>onMouseUp</code> events. When the mouse is clicked, I changed my CSS class (or whatever else) so that it falls out of the items list.</p>
|
WCF Recommend approaches for serializing multiple objects <p>I am attempting to optimise around a possible bottleneck.</p>
<p>I have a server application that is serving objects from a database to applications remotely, who can work with 1 - n objects of 1 - n different types (where n can be a relatively high number) that all implement a common interface but may contain many unique properties on different types.</p>
<p>The client applications store the server objects in a local cache, until they are ready to persist them back, through the server, to the database.</p>
<p>This is being done currently in WCF with each class defining a DataContract.</p>
<p>Due to the possibly large amount of objects that may need to be passed back to the server (it changes depending on implementation), I would prefer not to do these all as individual calls any more, rather wrap all the objects in a single serialized (or better still compressed) stream and send them through as one connection to the server. </p>
<p>I can quite simply roll my own, but would prefer to use a recommended approach, and hoping someone may suggest one. If you can convince me, I am also willing to accept that my approach is probably not the best idea.</p>
| <p>How high is "relatively high"?</p>
<p>For example, one option that occurs is to use a wrapper object:</p>
<pre><code>[DataContract]
public class Wrapper {
[DataMember(Order = 1)]
public List<Foo> Foos {get {...}}
[DataMember(Order = 2)]
public List<Bar> Bars {get {...}}
[DataMember(Order = 3)]
public List<Blop> Blops {get {...}}
}
</code></pre>
<p>Then you should be able to send a single message with any number of <code>Foo</code>, <code>Bar</code> and/or <code>Blop</code> records. My inclusion of the <code>Order</code> attribute was deliberate - if you want to reduce the size of the stream, you might consider <a href="http://code.google.com/p/protobuf-net/" rel="nofollow">protobuf-net</a> - with the above layout, protobuf-net can hook into WCF simply by including <code>[ProtoBehavior]</code> on the method (in the operation-contract interface) that you want to attack (at both client and server). This switches the transfer to use google's "protocol buffers" binary format, using base-64 to encode. If you are using the basic-http binding, this can also use MTOM if enabled, so even the base-64 isn't an issue. Using this, you can get <a href="http://code.google.com/p/protobuf-net/wiki/Performance" rel="nofollow">significant data transfer savings</a> (~1/5th the space based on the numbers shown).</p>
<p>(edit 1 - protobuf-net assumes that <code>Foo</code>, <code>Bar</code> and <code>Blop</code> <em>also</em> use the <code>Order</code> attribute)</p>
<p>(edit 2 - note that you could always break up the request into a number of mid-size <code>Wrapper</code> messages, then call a method to apply all the changes once you have them at the server (presumably in a staging table in the database))</p>
|
dynamically generate textboxes using JavaScript <p>I want generate textboxes dynamically according to user input. If user enter the integer value in the textbox, if he/she enter 5 i want generate 5 textboxes. This code is working in Firefox but not working in IE and Netscape; please help me how to do this or point out any other mistake in this code to me. Also, the technology we are using is Struts 2.<br />
Please help me.</p>
<p>JavaScript code:</p>
<pre><code>function generate()
{
var tot = document.getElementById("totmob").value;
var tbl = document.getElementById("sim");
for(var i =1;i<=tot;i++)
{
tbl.innerHTML = 'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno> <br> \n';
}
</code></pre>
<p>HTML code:</p>
<pre><code><td>
<s:textfield id="totmob" label="Total Mobile Number" />
<td>
<td>
<input type="button" value="ADD" onclick="generate()"/>
</td>
</tr>
</table>
<div id="sim">
</div>
</code></pre>
| <pre><code>for(var i =1;i<=tot;i++)
{
tbl.innerHTML = 'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno> <br> \n';
}
</code></pre>
<p>should be</p>
<pre><code>for(var i =1;i<=tot;i++)
{
tbl.innerHTML += 'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno> <br> \n';
}
</code></pre>
<p>because you need to append to the inner HTML, rather than replace it.</p>
<p>You've also used a <td> instead of a </td></p>
|
How can I turn off current line highlighting in Netbeans? <p>I've been looking for half an hour over all the options several times but I can't find it; googling also fails me at the moment. This is on Netbeans 6.0.1</p>
| <p>Tools > options > highlighting > highlight caret row : [change background to inherited]</p>
<p><img src="http://i.stack.imgur.com/tjZcP.png" alt="enter image description here">
Screenshot : <a href="http://d.pr/wZpr">http://d.pr/wZpr</a></p>
|
assembly.GetExportedTypes() show different result <p>Why does assembly.GetExportedTypes() show different result in C# and VB.NET?</p>
<p>These two give different results </p>
<pre><code>var v = from a in AppDomain.CurrentDomain.GetAssemblies() from b in a.GetExportedTypes() select b;
v.Count();
Dim v = From a In AppDomain.CurrentDomain.GetAssemblies(), b In a.GetExportedTypes() Select b v.Count()
</code></pre>
| <p>When you compile a VB.NET assembly, it includes some extra "helper" types. Use <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">Reflector</a> to have a look at your compiled assembly to see what I mean.</p>
<p>I'm pretty sure you'll find that the only assembly with any differences in is the one you're using to do the reflection - i.e. the one which is built with either C# or VB.NET, depending on your scenario.</p>
<p>EDIT: It depends on exactly how you define your classes.</p>
<p>However, again this is <em>only</em> relevant to the code being compiled <em>by the C# or VB compiler</em>. When you call <code>GetExportedTypes</code> it doesn't matter what language you're calling from. You're getting confused by the fact that you're only writing out the total count. Here are two short but complete programs to show the difference:</p>
<p><strong>C#</strong></p>
<pre><code>using System;
using System.Reflection;
public class ShowTypeCounts
{
static void Main()
{
AppDomain domain = AppDomain.CurrentDomain;
foreach (Assembly assembly in domain.GetAssemblies())
{
Console.WriteLine("{0}: {1}",
assembly.GetName().Name,
assembly.GetExportedTypes().Length);
}
}
}
</code></pre>
<p>Results:</p>
<pre><code>mscorlib: 1282
ShowTypeCounts: 1
</code></pre>
<p><strong>VB</strong></p>
<pre><code>Imports System
Imports System.Reflection
Public Module ShowCounts
Sub Main()
Dim domain As AppDomain = AppDomain.CurrentDomain
For Each assembly As Assembly in domain.GetAssemblies
Console.WriteLine("{0}: {1}", _
assembly.GetName.Name, _
assembly.GetExportedTypes.Length)
Next
End Sub
End Module
</code></pre>
<p>Results:</p>
<pre><code>mscorlib: 1282
ShowTypeCounts: 1
</code></pre>
<p>As you can see, the results are the same - but if you remove "public" from either piece of code, the ShowTypeCounts result goes down to 0. This isn't a difference of how GetExportedTypes works between languages - it just depends on what types you're actually exporting.</p>
<p>My guess is that in your console apps, one had a public type and the other didn't.</p>
|
When is it acceptable to break CLS compliance? <p>I was wondering which edge cases exist that could make <a href="http://www.devarticles.com/c/a/C-Sharp/Making-Your-Code-CLS-Compliant/" rel="nofollow">Common Language Specification compliance</a> acceptable. Even when not intending to be accessed from other languages, I think that the tenets asserted by the <a href="http://msdn.microsoft.com/en-us/library/system.clscompliantattribute.aspx" rel="nofollow"><code>CLSCompliantAttribute</code></a> are good best practices.</p>
<p>Do you have encountered / know of cases where <a href="http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It" rel="nofollow">YAGNI</a> outweighs the best practices?</p>
| <p>Well, "params" arrays on attributes are sometimes just so tempting (but non-compliant). But I'd recommend using CLS-compliant approaches whenever possible.</p>
|
Remote database connection with my iPhone application using Cocos2d <p>MCPResult *theResult;
MCPConnection *mySQLConnection;</p>
<pre><code>//initialize connection string vars
NSString *dbURL = @"192.168.0.16";
NSString *userName = @"";
NSString *pass = @"";
int port = 3306;
//open connection to database
mySQLConnection = [[MCPConnection alloc] initToHost: dbURL
withLogin:userName
password:pass
usingPort:port];
if ([mySQLConnection isConnected])
{
NSLog(@"The connection to database was successfull");
}
else
{
NSLog(@"The connection to database was failed");
}
//selection to database
if([mySQLConnection selectDB:@"blackjack_DB"])
{
NSLog(@"Database found");
}
else
{
NSLog(@"Database not found");
}
//selection to Table
theResult = [mySQLConnection queryString:@"select * from test"];
//theResult = [mySQLConnection queryString:@"select * from test where id='1'"];
//theResult = [mySQLConnection queryString:@"select id from test"];
//theResult = [mySQLConnection queryString:@"select name from test where pass='main_pass'"];
NSArray *m= [theResult fetchRowAsArray];
NSLog(@"%@", m);
NSLog(@"%@", [m objectAtIndex:2]);
</code></pre>
<p>Use this code for connecting & receive information from remotedatabase.
And also use some framework. AppKit.framework, Cocoa.framework, Carbon.framework, MCPKit_bundled.framework. But stile i didn't connect my application with remort database.</p>
| <p>A little more info is needed, specifically, what is the IP of your iPhone? The reason I ask is because unless it's IP address is in a private C network (192.168.x.x) it's not going to be able to find the DB.</p>
<p>I would recommend setting the dbUrl to a publicly accessible IP address. This may take a little work (firewall, learning what your IP address is, etc.) but it should work then.</p>
<p>Also, printing the results of the failed connection would be useful (I assume that MCPConnection has this capability, beyond just success/failure)</p>
|
How can I install a CPAN module into a local directory? <p>I'm using a hosted Linux machine so I don't have permissions to write
into the <code>/usr/lib</code> directory.</p>
<p>When I try to install a CPAN module by doing the usual:</p>
<pre><code>perl Makefile.PL
make test
make install
</code></pre>
<p>That module is extracted to a <code>blib/lib/</code> folder. I have kept <code>use
blib/lib/ModuleName</code> but it still the compiler says module can not be
found. I have tried copying the .pm file into local directory and kept
<code>require ModuleName</code> but still it gives me some error.</p>
<p>How can I install a module into some other directory and use it?</p>
| <p>Other answers already on Stackoverflow:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/102850/how-can-i-install-cpan-modules-locally-without-root-access-dynaloader-pm-line-22">How do I install modules locally without root access...</a></li>
<li><a href="http://stackoverflow.com/questions/251705/how-can-i-use-a-new-perl-module-without-install-permissions">How can I use a new Perl module without install permissions?</a></li>
</ul>
<p>From perlfaq8:</p>
<p><hr>
<a href="http://learn.perl.org/faq/perlfaq8.html#How-do-I-keep-my-own-module-library-directory">How do I keep my own module/library directory?</a></p>
<p>When you build modules, tell Perl where to install the modules.</p>
<p>For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:</p>
<pre><code>perl Makefile.PL INSTALL_BASE=/mydir/perl
</code></pre>
<p>You can set this in your CPAN.pm configuration so modules automatically install in your private library directory when you use the CPAN.pm shell:</p>
<pre><code>% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit
</code></pre>
<p>For Build.PL-based distributions, use the --install_base option:</p>
<pre><code>perl Build.PL --install_base /mydir/perl
</code></pre>
<p>You can configure CPAN.pm to automatically use this option too:</p>
<pre><code>% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit
</code></pre>
|
Runtime dependency for std::string concatenation <pre><code>std::string sAttr("");
sAttr = sAttr+VAL_TAG_OPEN+sVal->c_str()+VAL_TAG_CLOSE;
</code></pre>
<p>else where in the code I have defined</p>
<pre><code>const char VAL_TAG_OPEN[] = "<value>";
</code></pre>
<p><code>sVal</code> is a variable that is retrieved off of a array of string pointers. This works fine in most of the system, windows and linux. However at a customer site, where to my belief has a version of linux on which we had done some extensive testing, produce a result as if I have never used the <code>VAL_TAG_OPEN</code> and <code>VAL_TAG_CLOSE</code>. The results I recieve is for</p>
<pre><code>sAttr = sAttr+sVal->c_str();
</code></pre>
<p>Whats going on ?. Does std::string concatenation varies across runtime ?</p>
| <p>Why the <code>->c_str()</code>? If <code>sVal</code> is a <code>std::string</code>, try removing this call. Remember that the order of evaluation is undefined, so you may end up adding pointers instead of concatenating strings, because <code>VAL_TAG_OPEN</code>, <code>sVal->c_str()</code> and <code>VAL_TAG_CLOSE</code> are all plain C strings. I suggest you use the addition assignment operator <code>+=</code>, e.g. :</p>
<pre><code>sAttr += VAL_TAG_OPEN;
sAttr += *sVal; /* sVal->c_str() ? */
sAttr += VAL_TAG_CLOSE;
</code></pre>
<p>(which should be faster anyway).</p>
|
MonoRail redirect to # anchor <p>I'm using <a href="http://www.castleproject.org/monorail/" rel="nofollow">Castle Monorail</a> with <a href="http://docs.jquery.com/UI/Tabs" rel="nofollow">jQuery tabbed navigation</a>.</p>
<p>When handling a controller action, I would like to redirect to a view, and control which tab is visible. Therefore, I'd like to have my controller redirecting to a specific anchor in a view, something along the lines of:</p>
<pre><code>RedirectToAction("Edit", "id=1", "#roles"));
</code></pre>
<p>Resulting in the url:</p>
<pre><code>http://localhost/MyApp/User/edit.rails?id=1#roles
</code></pre>
<p>However, the actual result encodes the <strong>#</strong> sign to <strong>%23</strong></p>
<pre><code>http://localhost/MyApp/User/edit.rails?id=1&%23roles=&
</code></pre>
<p>I'm surely missing a basic concept here. What do I need to do to solve this?</p>
| <p>It does not only encode the '#' sign, it simply refer to it as another query string parameter (adds '&' and '=')</p>
<p>I'd advise you to post this question to the <a href="http://groups.google.com/group/castle-project-users" rel="nofollow">users group of Castle Project</a>, and even better - open issue on <a href="http://support.castleproject.org/" rel="nofollow">Castle's issue tracker</a>.</p>
|
ListView MouseClick Event <p>I have a ListView whereby I want to display one context menu if an item is right-clicked, and another if the click occurs in the ListView control. The problem I'm getting is the MouseClick event is only firing when an item is right-clicked, not the control. What's causing this and how can I get around it?</p>
| <p>Use MouseUp instead of MouseClick! Sorry about that. Should have googled harder.</p>
|
Multi-level grouping using a CollectionViewSources <p>When databinding a <code>TreeView</code>, how would you create multiple levels of grouping for the items displayed?</p>
<p>Imagine you are binding to a Shop class which, among others, has the properties <code>Region</code> and <code>RetailChain</code>. The desired effect is to have a <code>TreeView</code> that displays the shops in the following topology:</p>
<pre><code>+ Region: California
| + Walmart
| + Walmart Pacific Beach
| + Walmart Orange County
| + Walmart San Diego
+ Region: New Jersey
+ Frys
| + Frys Electronics NJ
+ Walmart
+ Walmart New Jersey
</code></pre>
<p>The clincher is this: <code>Region</code>s aren't related to <code>Retailer</code>s, and vice versa, so the <code>Shop</code> (the leaf node) is the only common denominator.</p>
<p>Using <code>CollectionViewSource</code> only allows for a single level of grouping (despite the fact that the <code>CollectionView</code> class has properties that suggest multi-level grouping).</p>
<p>Using the <code>HierarchicalDataTemplate</code> only works for top-down topologies, which this scenario doesn't lend itself to.</p>
<p>Any suggestions on how to solve this?</p>
| <p>The answer to my problem turned out to be this:</p>
<p>Add multiple groupings (via PropertyGroupDescriptor) to the CollectionViewSource, then use a ListBox / DataGrid with multiple GroupStyles. The nett effect of this is that the leaf items (in my example, the stores) are grouped at two distinct levels. </p>
<p>Switching which PropertyGroupDescriptor appears first in the CollectionViewSource will change which property is the "root" level in the resulting tree.</p>
|
Which version of safe_delete is better? <pre><code>#define SAFE_DELETE(a) if( (a) != NULL ) delete (a); (a) = NULL;
</code></pre>
<p>OR</p>
<pre><code>template<typename T> void safe_delete(T*& a) {
delete a;
a = NULL;
}
</code></pre>
<p>or any other better way</p>
| <p>I would say neither, as both will give you a false sense of security. For example, suppose you have a function:</p>
<pre><code>void Func( SomePtr * p ) {
// stuff
SafeDelete( p );
}
</code></pre>
<p>You set p to NULL, but the copies of p outside the function are unaffected.</p>
<p>However, if you must do this, go with the template - macros will always have the potential for tromping on other names.</p>
|
Variable initial value in delphi <p>I believe that local integer variables are not initialized to zero in delphi. The initial value is whatever happens to be at that memory location.
So in the code below the first time the button is clicked the first message shows a integer value.
How come the second time it's clicked it doesn't show 3 but instead shows the same integer
value? It continues to show the same integer value each time I click the button. The value is different only when I stop and restart the program.
Where is 3 being stored as it looks like the same memory location is used each time the button is clicked in the same run of the program?</p>
<pre><code>procedure TForm1.Button1Click(Sender: TObject);
var
int1 : integer;
begin
showmessage(inttostr(int1)) ;
int1 := 3;
end;
end.
</code></pre>
| <p>kjack, </p>
<p>It contains whatever value is in the stack frame at that time. In your case, this will be Sender. If you'd take the integer and typecast it to an object you'll notice the "pattern".</p>
<pre><code>procedure TForm1.Button1Click(Sender: TObject);
var
int1 : integer;
begin
ShowMessage(TObject(int1).ClassName);
showmessage(inttostr(int1)) ;
int1 := 3;
end;
end.
</code></pre>
|
Finding top-level xml comments using Python's ElementTree <p>I'm parsing an xml file using Python's ElementTree, like that: </p>
<pre><code>et = ElementTree(file=file("test.xml"))
</code></pre>
<p>test.xml starts with a few lines of xml comments. </p>
<p>Is there a way to get those comments from et?</p>
| <p>For ElementTree 1.2.X there is an article on <a href="http://effbot.org/zone/element-pi.htm" rel="nofollow">Reading processing instructions and comments with ElementTree
</a> (<a href="http://effbot.org/zone/element-pi.htm" rel="nofollow">http://effbot.org/zone/element-pi.htm</a>).</p>
<p><hr /></p>
<p><em>EDIT:</em></p>
<p>The alternative would be using <strong>lxml.etree</strong> which implements the ElementTree API. A quote from <a href="http://codespeak.net/lxml/compatibility.html" rel="nofollow">ElementTree compatibility of lxml.etree
</a>:</p>
<blockquote>
<p><strong>ElementTree ignores comments</strong> and
processing instructions when parsing
XML, while <strong>etree will read them in</strong> and
treat them as Comment or
ProcessingInstruction elements
respectively.</p>
</blockquote>
|
Entire website hijacked! How to prevent from being hijacked? <p><em>The technical solution can be found here</em>: <a href="http://stackoverflow.com/questions/548355/entire-website-hijacked-part-2-how-to-configure-virtual-hosting">Entire website hijacked! Part 2: How to configure name-based virtual hosting?</a>
<hr /></p>
<p>The original domain is <a href="http://neteditr.com" rel="nofollow">http://neteditr.com</a></p>
<p>The offending copycat site is <a href="http://kitchen.co.jp" rel="nofollow">http://kitchen.co.jp</a></p>
<p>After reading upon some articles it seems like this kind of website hijacking is done by proxy servers, but how in the world is the link to "neteditr.com" removed from Google's search pages and theirs "kitchen.co.jp" is high up on the list? About a month ago, I could still do a "neteditr" search and have neteditr.com come up on 1st place.</p>
<p>As of now, I've used Google's SearchWiki to remove all of their entries and added the original URL hoping to give more weight back to the original domain. But this is only for my own Google account. If I do a generic search without being logged in, the problem still persists.</p>
<p>Anyhow my questions are:</p>
<ol>
<li>Technically, how do you prevent your website from being mirrored on another domain, I'm using Apache and serving HTML/JS/PHP/CSS files.</li>
</ol>
<p><em>Short Answer: You can't prevent it</em></p>
<ol>
<li>What do you do if you are currently mirrored?</li>
</ol>
<p><em>Short Answer: Set up name-based virtual hosting. See techinical solution above.</em></p>
<ol>
<li>Google deleted your original domain from their search rank and has ranked your offender's site on Google's first page. Can we[victims] complain to Google about this?</li>
</ol>
<p><em>Answer: After name-based virtual hosting is set up and the offending domain is disallowed HTTP access, given time Google should automatically remove their domain name</em></p>
<p>***EDIT</p>
<p>Using stackoverflow.com as an example:</p>
<p>stackoverflow.com IP = 69.59.196.211</p>
<p>It would be the same as registering a domain named stackunderflow.com and pointing it to 69.59.196.211. And while doing a search for stackoverflow in Google, stackunderflow.com is on Google's first page and stackoverflow.com is nowhere to be found. How did they do this?</p>
<p>***EDIT 2</p>
<p>After learning kitchen.go.jp is pointing to my original IP I've concluded that the offender is not using a proxy server. Usually in malevolent mirroring cases, the offender will add their own ads and porn links on top of the mirrored content. Such is not the case in my situation. So it could be either:</p>
<p>A) To be honest I think someone just wanted to have your editor on a Japanese domain (company webfilter policy maybe?), nothing malvolent -DrJokepu</p>
<p>B) Could be someone wanting to build search engine rank before switching it out to different content (i.e. theirs) -Roland Shaw</p>
| <p>In Apache, set up <a href="http://httpd.apache.org/docs/2.2/vhosts/" rel="nofollow">virtual hosting</a>. You can disallow access to your site from <code>http://kitchen.co.jp/</code> or disallow from anything except <code>http://neteditr.com/</code>.</p>
|
Connect two Line Segments <p>Given two 2D line segments, A and B, how do I calculate the length of the shortest 2D line segment, C, which connects A and B?</p>
| <p>Consider your two line segments A and B to be represented by two points each:</p>
<p>line A represented by A1(x,y), A2(x,y) </p>
<p>Line B represented by B1(x,y) B2(x,y)</p>
<p>First check if the two lines intersect using this algorithm. </p>
<p><strong>If they do intersect</strong>, then the distance between the two lines is zero, and the line segment joining them is the intersection point.</p>
<p><strong>If they do not intersect</strong>, Use this method: <a href="http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/" rel="nofollow">http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/</a> to calculate the shortest distance between:</p>
<ol>
<li>point A1 and line B</li>
<li>Point A2 and line B </li>
<li>Point B1 and line A </li>
<li>Point B2 and line A</li>
</ol>
<p>The shortest of those four line segments is your answer.</p>
|
Migrating applications from Dev to QA to Prod <p>I have a number of webservices and clients (click-once deployment) that I am wondering how to deploy efficiently. We have a QA department that reviews and tests releases as well as an operations group that currently does the 'deployment' which basically consists of copying tested releases from QA boxes to Prod boxes. The process is quite error prone as config files are not copied correctly and feedback on if/when/how deployment was done is not being given and therefore I consider this method of deploying a not-so-best-practice method.</p>
<p>We are using a build machine for doing our builds and I don't want to use publish from my dev machine.</p>
<p>I have been wondering if scripted deployment is anything I should look into and if there are any standard ways of doing this. I have experimented a little with TFSDeployer which is a utility that lives on boxes to be deployed to and pick up events from team foundation server that can be then be acted upon via powershell scripts. I can see something like that working on dev/test machines but for production servers I don't know. </p>
<p>How do you deploy your webservices/clients?</p>
| <p>I use TFSDeployer for the push to production as well, as you can set TFSDeployer up to push so you don't have to install it on the production boxes (it just means that you need to configure permissions for you build account/machine to access production).</p>
<p>One useful tip is to restrict permissions on who can change build qualities and only allow the push to production script to fire once the build quality is at the UAT passed level (or whatever the equivalent is for your organistion).</p>
|
Entity Framework: Model doesn't reflect DB <p>I'm probably thinking about this all wrong but I have the following db tables:</p>
<p><img src="http://1ponbw.bay.livefilestore.com/y1pUw3xaKZ7RhtNS3GiC5F1NYMad5ZeYI8Wh-jZ8CDajt7MiKO-6vhVmEm8VhlXMkDZTQz9t5gP4gnskgbvDtAYTA/DBImage.jpg" alt="alt text" /></p>
<p>When I run the EF Wizard in VS2008 I get the following model:</p>
<p><img src="http://1ponbw.bay.livefilestore.com/y1pY5xK0aw6ckqcY5IPaIc45Rfjhy-CSMpdd_l4z-4mMGKbhd5N9VIySd72t-0LXBkYseQY0D2W5mEUUaDzhntcQA/EFImage.jpg" alt="alt text" /></p>
<p>You'll notice that in the EF model shows that the Entity has no field for EntityTypeID or EntityStatusId. Instead it shows it as a navigation property, so the field appears to not be addressable when I instantiate an Entity (pardon the terminology confusion: Entity is a Table/Class in my name space not in the EF namespace). How can I assign an EntityTypeID and StatusTypeID when instantiating an Entity?</p>
| <p>Yes, the entity framework hides foreign key ID properties and shows navigation properties instead. There is a lengthy discussion about why it does that, <a href="http://blogs.msdn.com/efdesign/archive/2008/10/27/foreign-keys-in-the-conceptual-and-object-models.aspx" rel="nofollow" title="Foreign Keys in the Conceptual and Object Models">here</a>. The usual means of assigning a reference to another entity is to assign the entity instance, rather than the foreign key ID value, like this:</p>
<pre><code>var foo = new Entity();
var status = (from .... select ...).FirstOrDefault();
foo.StatusCodes = status;
</code></pre>
<p>However, it is possible to assign a foreign key ID directly, if you happen to know what it is:</p>
<pre><code>foo.StatusCodesReference = new EntityKey(
"MyEntityContextName.StatusCodesEntitySetName", "StatusCodeId", value);
</code></pre>
<p>Obviously, substitute the real values in the above.</p>
|
XSLT - How to select XML Attribute by Attribute? <p>this is the structure of my source xml:</p>
<pre><code><root>
<DataSet Value="A">
<Data Value1="1" Value2="anythingA1" />
<Data Value1="2" Value2="anythingA2" />
<Data Value1="3" Value2="anythingA3" />
<Data Value1="4" Value2="anythingA4" />
<Data Value1="5" Value2="anythingA5" />
</DataSet>
</root>
</code></pre>
<p>from which I like to create some variables e.g. from all with Value1="2" and all with Value1="5" should result myVar1 with anythingA2 and myVar2 with anythingA5</p>
<p>My approch looks like this</p>
<pre><code><xsl:variable name="myVarA" select="/DataSet/Data/[@Value1='2']/@Value2" />
</code></pre>
<p>but of course is not working since Value2 is no child of Value1.</p>
<p>thanks for any hints in advance!</p>
| <p>Just remove the slash after <code>Data</code> and prepend the root:</p>
<pre><code><xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
</code></pre>
|
Extracting extension from filename in Python <p>Is there a function to extract the extension from a filename?</p>
| <p>Yes. Use <a href="https://docs.python.org/2/library/os.path.html#os.path.splitext"><code>os.path.splitext</code></a>:</p>
<pre><code>>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
</code></pre>
|
How to I access an attached property in code behind? <p>I have a rectangle in my XAML and want to change its <code>Canvas.Left</code> property in code behind:</p>
<pre class="lang-xml prettyprint-override"><code><UserControl x:Class="Second90.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300" KeyDown="txt_KeyDown">
<Canvas>
<Rectangle
Name="theObject"
Canvas.Top="20"
Canvas.Left="20"
Width="10"
Height="10"
Fill="Gray"/>
</Canvas>
</UserControl>
</code></pre>
<p>But this doesn't work:</p>
<pre><code>private void txt_KeyDown(object sender, KeyEventArgs e)
{
theObject.Canvas.Left = 50;
}
</code></pre>
<p>Does anyone know what the syntax is to do this?</p>
| <pre><code>Canvas.SetLeft(theObject, 50)
</code></pre>
<p></p>
|
How do I read any request header in PHP <p>How should I read any header in PHP?</p>
<p>For example the custom header: <code>X-Requested-With</code>.</p>
| <pre><code>$_SERVER['HTTP_X_REQUESTED_WITH']
</code></pre>
<p><a href="http://www.faqs.org/rfcs/rfc3875.html">RFC3875</a>, 4.1.18:</p>
<blockquote>
<p>Meta-variables with names beginning with <code>HTTP_</code> contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of <code>-</code> replaced with <code>_</code> and has <code>HTTP_</code> prepended to give the meta-variable name.</p>
</blockquote>
|
PHP readdir() not returning files in alphabetical order <p>I am reading through a directory with some pictures and such using a pretty simple implementation of readdir() like the following:</p>
<pre><code>if ($handle = opendir($path)) {
while (false !== ($szFilename = readdir($handle))) {
if ($szFilename[0] !== '.') {
if (is_file($path.$szFilename)) {
// do stuff
}
}
}
}
</code></pre>
<p>The problem that I am having is that the files are not being read in alphabetical order as the docs for readdir() state:</p>
<blockquote>
<p>Returns the filename of the next file
from the directory. The filenames are
returned in the order in which they
are stored by the filesystem.</p>
</blockquote>
<p>Another weird thing is that, on the local testing server, the same code works great. This is running on a server using the LAMP stack in both cases.</p>
<p>I know that I can build an array and just sort it, but I was wondering if I was missing something in what I was doing.</p>
| <p>Alphabetical order :: I think you misread the snippet you quoted...</p>
<blockquote>
<p>Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.</p>
</blockquote>
<p>The fact that 'ls' would display the files in (usually) alphabetical order does not mean that's how they are stored on the filesystem. PHP is behaving as spec, I'm afraid.</p>
<p>You may want to consider using <a href="http://uk3.php.net/manual/en/function.scandir.php">scandir</a> as the basis for your efforts, if alphabetical sorting is a must. :)</p>
|
Focus issues, focus sometimes goes to unknown object <blockquote>
<p>[FocusEvent type="focusIn" bubbles=true cancelable=false eventPhase=3 relatedObject=null shiftKey=false keyCode=0]</p>
</blockquote>
<p>When I click with a mouse an TextField, I would like that another (editable) field gets focus, but currently focus is lost somewhere.. I dont know where focus is.</p>
<p>I made a listener to textfield which tries to set focus back to another filed with stage.focus = editfield but its not working.</p>
<p>I have also same focus listener in stage, but no difference.</p>
| <p>Since you list a "FocusEvent" in your example, I will focus on Flex solutions. That is not a Flash AS3 class.</p>
<p>I will wager that Flex is trying to manage the focus by itself and that is screwing with your attempts to set it. There are, however, a number of ways around this.</p>
<p><strong>Is Flex trying to work against you?</strong><br/>
First, you may want to either use FocusManager class or the UIComponent setFocus method (this depends on what you specifically need to do, I believe the FocusManager allows you to have multiple objects targeted, while the setFocus method is a good deal simpler) instead of stage.focus. This has the benefit of working natively within the Flex component system.</p>
<p><strong>Are you listening to the right event?</strong><br/>
Failing that, try making sure that the target of the FocusEvent you're looking for is neither your textfield nor a child of your textfield. (Just for sanity's sake). If that does not work, make sure you are only getting the event dispatched once.Next, I would try using MouseEvent.CLICK instead of a FocusEvent.</p>
<p><strong>Has everything else failed?</strong><br/>
Unfortunately, Flex is often far from perfect. I find that sometimes I have to use setTimeout to get around the fact that it does not fire events in the "right order" -- you resize something, but "RESIZE" is dispatched before it has re-rendered, you change the font, and a TextArea's TextWidth property doesn't return the right number. The workaround</p>
<pre><code>private function myListener( event:FocusEvent ):null
{
setTimeout( function(){ editfield.setFocus(); }, 35 );
}
</code></pre>
|
How to get a regular expression to match items with spaces <p>The following regular expression works if there is no space character, but if the input has a space character, it doesn't work (it seems like a link but JavaScript doesn't work).</p>
<p>How can I change it? </p>
<p>The regular expression should work for both <code>World</code> and <code>The World</code>.</p>
<pre><code> Dim makebkz As String
Dim pattern As String = "\(bkz: ([a-z0-9$&.öıÅçÄü\s]+)\)"
Dim regex As New Regex(pattern, RegexOptions.IgnoreCase)
Dim myAnchor As New System.Web.UI.HtmlControls.HtmlAnchor()
Dim postbackRef As String = Page.GetPostBackEventReference(myAnchor, "$1")
myAnchor.HRef = postbackRef
str = regex.Replace(str, "(bkz: <a href=javascript:" & myAnchor.HRef & "><font color=""#CC0000"">$1</font></a> )")
makebkz = str
Return makebkz
</code></pre>
| <p>Actually, there is a space 'character'. It is a '\s' (minus the quotes).</p>
|
SQL Injection in .NET <p>Hi I was wondering if anyone knew of some good websites detailing prevention for SQL injection for .NET web applications. Any resources would be greatly appricated, thank you.</p>
| <p>I think that, if you google a bit on 'preventing sql injection in .NET', you'll find lots of good resources. :)</p>
<p>Anyway, one very important thing, is to not use string-concatenation in order to build your queries.
Instead, use parametrized queries. ADO.NET allows to do this, in a very easy way:</p>
<pre><code>string sql = "SELECT * FROM Persons WHERE Persons.Lastname LIKE @p_Name";
SqlCommand cmd = new SqlCommand (sql);
cmd.Parameters.Add ("@p_Name", SqlDbType.Varchar).Value = textBox1.Text + "%";
</code></pre>
|
Return day int value from function <p>I try to write any code about days:</p>
<pre><code>function xyz("13.02.2009")
{
return value= 6;
}
function xyz("12.02.2009")
{
return value= 5;
}
function xyz("14.02.2009")
{
return value= 7;
}
</code></pre>
<p>But how?</p>
<p>This method is good but I need C# times specific codes (like timespan...)</p>
<pre><code>DayOfWeek day = DateTime.ParseExact("13.02.2008", "dd.MM.yyyy", CultureInfo.InvariantCulture).DayOfWeek;
int days = ((int)day - (int)DateTime.Now.DayOfWeek);
if (days &#60;= 0) days += 7;
Console.Write(days);
</code></pre>
| <p>Note that DateTime.DayOfWeek depends on your regional settings.</p>
|
problems once uploaded to server <p>This all works fine in MAMP but i've uploaded and now the problems start.</p>
<p>heres an image of the code for the link and a grab of the result</p>
<p><a href="http://dl.getdropbox.com/u/236383/link-to-file.tiff" rel="nofollow">First image</a></p>
<p><a href="http://dl.getdropbox.com/u/236383/result-of-link.tiff" rel="nofollow">Second image </a></p>
<p>any ideas?</p>
| <p>You seem to be POSTing to a static HTML file. Try changing the file extension to php, asp, jsp etc. depending on what you're using on the server-side.</p>
<p>Also, for textual content like this, you could simply copy-paste the text intead of capturing screenshots.</p>
|
Velocity named parameters for a macro <p>I have a macro taking several parameters. Some of these are optional and if a parameter is left empty it will replaced with default.</p>
<p>Now the question is how to make this as easy as possible for ordinary web designer. Is there any other possibity apart from my examples to handle this case?</p>
<p>Example 1: </p>
<p>The obvious problem here is the optional values.</p>
<pre><code>#macro (myTag $param1 $param2 $param3)
...
#end
</code></pre>
<p>Example 2:</p>
<p>And here the problem is a possible issue when same macro is used more than once and all variables are not set again.</p>
<pre><code>#set ($param1="value1")
#set ($param2="value2")
#set ($param3="value3")
#macro (myTag)
...
#end
</code></pre>
| <p>As of Velocity 1.6, optional or named parameters are not supported. There was a recent patch submitted with this feature so we might see it available in a future release.</p>
<p>In the meantime, consider passing in a list or a map of values. For example you can pass in a map of params as follows (requires Velocity 1.5 or greater):</p>
<pre><code>#macro(myMacro $p)
item 1: $p.param1
item 2: $p.param2
#end
#set($params = {"param1" : "val1", "param2":"val2"})
#myMacro($params)
</code></pre>
<p>displays:</p>
<pre><code>item 1: val1
item 2: val2
</code></pre>
<p>To handle optional parameters, use an #if within the macro to check for the parameter. Adding new elements to the map is a little messy. Since the Java method "put" returns a value, you have to use #set to dispose of the return value. (Otherwise it's displayed in the resulting text).</p>
<pre><code>#macro(myMacro $p)
#if(!$p.param1)#set($dummy = $p.put("param1", "default1"))#end
#if(!$p.param2)#set($dummy = $p.put("param2", "default2"))#end
#if(!$p.param3)#set($dummy = $p.put("param3", "default3"))#end
item 1: $p.param1
item 2: $p.param2
item 3: $p.param3
#end
#set($params = {"param1" : "val1", "param2":"val2"})
#myMacro($params)
</code></pre>
<p>displays</p>
<pre><code>item 1: val1
item 2: val2
item 3: default3
</code></pre>
|
Is it possible manage developers with high turnover if you can't lower the turnover rate? <p>I lead a small group of programmers in a university setting, having just moved into this position last year. While the majority of our team are full time employees, we have a couple of people who are traditionally graduate assistants.</p>
<p>The competition for these assistantships is fairly intense, as they get free graduate school tuition on top of their salary while they have the job. We require that they sign up for at least a year, though we consider ourselves lucky if they stay for two. After that, they get their master's degree and move on to bigger and better things.</p>
<p>As you can imagine, hiring and re-training these positions is time- and resource-intensive. To make matters worse, up to now they have typically been the sole developer working on their respective projects, with me acting in an advisory and supervisory role, so wrangling the projects themselves to fight the entropy as we switch from developer to developer is a task unto itself.</p>
<p>I'm tempted to bring up to the administrators the possibility of hiring a full- (and long-haul) developer to replace these two positions, but for a school in a budget crisis, paying for two half-time graduate assistants is far cheaper (in terms of salary and benefits) than paying for one full-time developer. Also, since I'm new to this position, I'd like to avoid seeming as though I'm not able to deal with what I signed up for. For the forseeable future, I don't think the practice of hiring short-term graduate assistants is going to change.</p>
<p>My question: <strong>What can I do to create an effective training program considering that the employees may be gone after as little as a year on the job?</strong> </p>
<ul>
<li>How much time should I invest in training them, and how much would simply be a waste of time?</li>
<li>How much time should they take simply getting acclamated to our process and the project?</li>
<li>Are there any specific training practices or techniques that can help with this kind of situation?</li>
<li>Has anyone dealt with a similar situation before?</li>
<li>Do I worry too much, or not enough?</li>
</ul>
<p>By the way, and for the record, we do the vast majority of our development in Perl. It's hard to find grad students who know Perl, while on the other hand everybody seems to have at least an academic understanding of Java. Hence <a href="http://stackoverflow.com/questions/141641/what-constitutes-effective-perl-training-for-non-perl-developers">this question</a> which I asked a while back.</p>
| <p>Why don't you ask the students what they find difficult and make cheat sheets, lectures, etc. for the parts of the job that they have trouble with? Maybe you need to create some introductory Perl lectures or purchase some dead trees. How about a Safari subscription at O'Reilly? I'd ask the students how they prefer to learn, though, before embarking on a training project. Everyone has different learning styles.</p>
<p>I'd also spend some time and capital creating a culture of professional software development at work. It'll be tough since academic programmers are often neophytes and used to kludging up solutions (I'm an academic programmer, btw) but the students will thank you in the long run. Maybe you can all go out to lunch once a week to discuss programming and other topics. You might also want to take some time to do code reviews so people can learn from each other.</p>
<p>With high turnover you definitely need to ensure that knowledge transfer occurs. Make sure you are using source code control and that your students understand proper commenting. I'd also make the students create brief documentation for posterity. If they are getting credit, make them turn in a writeup of their progress once a semester. You can put this in a directory in the project's repository for anyone who inherits it. As mentioned in other posts, a group wiki can really help with knowledge transfer. We use Mediawiki in our group and like it a lot.</p>
<p>One last thing I should add is that I find it helps to keep a list of projects for new developers that relatively easy and can be completed in a month or so. They are a great way for new people to get acclimated to your development environment.</p>
|
XML XSL Transform From Stream <p>Hi I have a memory stream in which I use XMLTextWriter to write out some XML. What I want to do is transform this XML using the XSL.transform feature. The thing is I don't want to create a temp. XML file, I want to somehow use the stream to Transform it into the XSL. Thank you for any suggestions.</p>
| <p>Just use an XmlReader and pass it to the Transform method. You'll need to seek to the start of the stream first.</p>
<pre><code> stream.Seek(0, SeekOrigin.Begin);
XmlReader reader = XmlReader.Create(stream, settings);
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(...load your transform...);
transform.Transform(reader, resultsWriter);
</code></pre>
<p>I've obviously removed certain elements here to simplify the code, but you should get the idea.</p>
|
Multiple line code example in Javadoc comment <p>I have a small code example I want to include in the Javadoc comment for a method. </p>
<pre><code>/**
* -- ex: looping through List of Map objects --
* <code>
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get("wordID"));
* System.out.println(map.get("word"));
* }
* </code>
*
* @param query - select statement
* @return List of Map objects
*/
</code></pre>
<p>The problem is the code example shows up in the Javadoc with no line breaks making it hard to read. </p>
<pre><code>-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }
Parameters
query - - select statement
Returns:
List of Map objects
</code></pre>
<p>I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ?</p>
| <p>In addition to the already mentioned <code><pre></code> tags, you should also use the <code>@code</code> JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:</p>
<pre><code>* <pre>
* {@code
* Set<String> s;
* System.out.println(s);
* }
* </pre>
</code></pre>
<p>Will give correct HTML output:</p>
<pre><code>Set<String> s;
System.out.println(s);
</code></pre>
<p>While omitting the <code>@code</code> block (or using a <code><code></code> tag) will result in HTML like this:</p>
<pre><code>Set s;
System.out.println(s);
</code></pre>
|
Create a cache dependancy on a folder and its sub-folder <p>In ASP.NET I would like to store an object in the cache which has a dependancy on all the files in specific folder and its sub-folders. Just adding the object with a dependancy on the root folder doesn't work. Is there in any reasonable way to do this other than creating a chain of dependancies on all the files?</p>
| <p>I believe you can roll your own cache dependency and use FileSystemMonitor to monitor the filesystem changes.</p>
<p>Update: Sample code below</p>
<pre><code>public class FolderCacheDependency : CacheDependency
{
public FolderCacheDependency(string dirName)
{
FileSystemWatcher watcher = new FileSystemWatcher(dirName);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Changed);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
}
void watcher_Renamed(object sender, RenamedEventArgs e)
{
this.NotifyDependencyChanged(this, e);
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
this.NotifyDependencyChanged(this, e);
}
}
</code></pre>
|
Apple's Singleton example <p>Used the MyGizmoClass example in a iPhone app where I have an object that sets and maintain db info. </p>
<p>How do I eliminate the
'MyGizmoClass' may not respond to '+sharedManager'</p>
<p>Warning</p>
<p>The offending line of code is:
NSString *databasePath = [[MyGizmoClass sharedManager]databasePath];</p>
| <p>It sounds like the +sharedManager method is not declared in the header. You've mentioned importing the header a couple of times but haven't said whether +sharedManager is part of that header. The error you're seeing indicates that either (a) the header's not being imported (and you've said that it is) or (b) the header is being imported but doesn't contain the method in question.</p>
|
inheritance in controllers <p>I use inheritance in my model. An event has different types:</p>
<pre><code>Event < activity
Event < training
Event < game
</code></pre>
<p>I want to set session data to every event type like</p>
<pre><code>game.user_id = session[:user_id]
training.user_id = session[:user_id]
activity.user_id = session[:user_id]
</code></pre>
<p>I want to avoid writing @game.user_id = session[:user_id] , ..., ... in every create method in the controller of activity, game and training</p>
<p>Someone knows how to approach this best.</p>
<p>Thanks</p>
| <p>Perhaps you are looking for a before_filter that resides in your ApplicationController? Then in each controller, you can set the before_filter to run on create actions.</p>
<pre><code>ApplicationController
def set_user_ids
game.user_id = session[:user_id]
training.user_id = session[:user_id]
activity.user_id = session[:user_id]
end
...
end
OneController < ApplicationController
before_filter :set_user_ids, :only => [:create]
...
end
TwoController < ApplicationController
before_filter :set_user_ids, :only => [:create]
...
end
</code></pre>
|
How do I intercept a NotImplementedException in a WPF application? <p>How do I intercept a NotImplementedException in a WPF application?</p>
<p>I'll occasionally throw a NotImplementedException while testing my in-progress WPF application:</p>
<pre><code>Private Sub ButtonDoSomething_Click(...) Handles ButtonDoSomething.Click
Throw New NotImplementedException( _
"ButtonDoSomething_Click() not implemented.")
End Sub
</code></pre>
<p>But, I'd rather these not crash the program.</p>
<p>I could replace all such exception throws with:</p>
<pre><code>MessageBox.Show("ButtonDoSomething_Click() not implemented.", _
"Not Implemented", MessageBoxButton.OK, MessageBoxImage.Information)
</code></pre>
<p>But that seems inellegant somehow and wouldn't work if the NotImplementedException was buried away from the interface.</p>
<p>How can I capture all such exceptions and display a message box?</p>
| <p>You can attach to the DispatcherUnhandledException event on the Application class, which will be raised anytime an unhandled exception occurs. In there, you can check the Exception property on the DispatcherUnhandledExceptionEventArgs instance passed to the event handler to see if it is of type NotImplementedException. If it is, then set the Handled property to true, and then return.</p>
<p>It should be noted that if you called MsgBox instead of throwing the exception, you would have the problem of having to actually return something and set all out/ref parameters as well, which would have been additional overhead. </p>
|
JSP - Saving a collection <p>[Warning] I'm new to JSP/Struts/JSTL. This is probably a newbie question :)</p>
<p>I have a form that contains a collection:</p>
<pre><code>public class ServiceForm extends AbstractForm
{
private List<SrvDO> allSrv = new ArrayList<SrvDO> ();
}
</code></pre>
<p>I can see the object data correctly in my form using the JSP. The page displays 5 input box with the data from the database correctly:</p>
<pre><code><c:forEach items="${serviceForm.allSrv}" var="srv">
<html:text name="srv" property="nbDays"/>
</c:forEach>
<html:submit/>
</code></pre>
<p>But when I press the submit button, the form does not contains the updated data for "nbDays". I still see the same data as it was shown before the update. What am I missing that says to struts: for each srv, update the "nbDays" data?</p>
| <p>Found the answer on <a href="http://forum.springframework.org/showthread.php?t=54509" rel="nofollow">the spring forum</a>: </p>
<blockquote>
<p>Your form:input tag doesn't and
shouldn't know anything about the fact
that it is used inside another tag.
That is why you need to include the
index.</p>
</blockquote>
<p>So the solution is:</p>
<pre><code><html:text property="allSrv[${srvSta.index}].nbDays"/>
</code></pre>
|
Webpart Connections asp.net VB <p>Im having the following problem with vb.net asp.net webparts. Im trying to create a static connection between webparts but im running into a problem, namely: </p>
<blockquote>
<p>Could not find the connection provider Web Part with ID 'Ucl_Diary_Summary1'</p>
</blockquote>
<p>I have the following defined as my iterface:</p>
<pre><code>Public Interface IDiaryPartsProvider
function Test as String
End Interface
</code></pre>
<p>I have the following as my Consumer (UserControl):</p>
<pre><code>Partial Class UsrCtrls_Diary_ucl_DiaryAwaitingReview
Inherits System.Web.UI.UserControl
<ConnectionConsumer("Test", "myID")> _
Public Sub GetTextTransferInterface(ByVal provider As IDiaryPartsProvider)
Dim a As String = provider.Test()
UserMsgBox(a.ToString, Me.Page)
End Sub
End Class
</code></pre>
<p>I have the following defined as my Provider (UserControl):</p>
<pre><code>Partial Class UsrCtrls_Diary_Diary_Summary
Inherits System.Web.UI.UserControl
Implements IWebPart, IDiaryPartsProvider
<ConnectionProvider("myID")> _
Public Function Test() As String Implements IDiaryPartsProvider.Test
Return "this is a test"
End Function
End Class
</code></pre>
<p>I have my default.aspx as follows:</p>
<pre><code><%@ Register Src="UsrCtrls/Diary/ucl_Diary_Summary.ascx" TagName="ucl_Diary_Summary"
TagPrefix="uc4" %>
<%@ Register Src="UsrCtrls/Diary/ucl_DiaryAwaitingReview.ascx" TagName="ucl_DiaryAwaitingReview"
TagPrefix="uc5" %>
<asp:WebPartManager ID="WebPartManager1" runat="server">
<StaticConnections>
<asp:WebPartConnection ID="cnn"
ConsumerID="Ucl_DiaryAwaitingReview1"
ProviderID="Ucl_Diary_Summary1"
/>
</StaticConnections>
</asp:WebPartManager>
<asp:WebPartZone ID="zoneDiaryTopLeft" runat="server" EmptyZoneText="Add WebPart Here" DragHighlightColor="#454777" HeaderText=" ">
<ZoneTemplate>
<asp:Panel ID="pnl1" runat="server" title="Claims Awaiting Review">
<asp:UpdatePanel ID="udp_TopLeft" runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional">
<ContentTemplate>
<uc5:ucl_DiaryAwaitingReview ID="Ucl_DiaryAwaitingReview1" runat="server" title="Claims Awaiting Review" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ZoneTemplate>
</asp:WebPartZone>
<asp:WebPartZone ID="zoneDiaryTopRight" runat="server" EmptyZoneText="Add WebPart Here" DragHighlightColor="#454777" HeaderText=" ">
<ZoneTemplate>
<asp:Panel ID="PNL2" runat="server" title="Diary Summary">
<asp:UpdatePanel ID="udp_TopRight" runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional">
<ContentTemplate>
<uc4:ucl_Diary_Summary ID="Ucl_Diary_Summary1" runat="server" Title="Diary Summary" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ZoneTemplate>
</asp:WebPartZone>
</code></pre>
<p>I can only assume its because I have my webparts - usercontrol wrapped in a panel (used for scrolling) and also an updatepanel which I use to refresh, so how do I get it to see the usercontrol?</p>
<p>Thanks in advance.</p>
<p>James.</p>
| <p>I didn't have a chance to look at your message in detail but the issue appears to be with your provider. It should be returning an object that implements the interface used for communication to the consumer (usually a reference to itself).</p>
<p>Check out the following resource for more info:</p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc188696.aspx" rel="nofollow">Introducing ASP.NET Web Part Connections</a></p>
|
How to troubleshoot Oracle database server errors? <p>My team inherited an Oracle-based web application and they are fairly inexperienced with Oracle database servers.</p>
<p>The Oracle 10g server is running on a Windows 2003 Server with plenty of disk space and from time to time, all connectivity is lost, the application stops working, not even SQL Plus is able to connect to the database server.</p>
<p>But when we check the Windows Service manager, it says that the service is up and running. A restart usually fixes the problem, but we need to properly troubleshoot it so we know what's causing it and so we can avoid it to happen anymore.</p>
<p>Where should we start looking for clues? What are the criticial log files we should be investigating?</p>
| <p>On the server you should have an environment variable called ORACLE_HOME which indicate the root of the Oracle install. Most likely the Oracle trace/dump folders will be under there. Search for a folder called "bdump" (background dump). That's where the main log file, knows as the alert log, will be, as well as trace files generated by background processes. There will be an adjacent file called "udump" which will contain any trace files generated by user processes.</p>
<p>However, my real advice is that you should either hire someone who knows Oracle or get Oracle Support involved.</p>
|
flash interaction with javascript internet explorer <p>I have a flash object interacting with a javascript function. The interaction works fine in every browser except in IE (all versions)
I have tried with swfobject and with classic embeding. AllowScriptAccess is set to "always". Is there any cause for this flaw ?
Thanks</p>
| <p>If you're using ExternalInterface, the problem may be related to the way you're attempting to reference the object in JavaScript. <a href="http://stackoverflow.com/questions/472026/problem-with-flash-externalinterface-on-google-app-engine#472184">Take a look at my answer to this question</a> -- it might not be exactly the same issue, but my answer provides an end-to-end example of ExternalInterface that's been tested on IE, too, so you might want to compare it to your own to see whether anything's missing or out of place.</p>
<p>If that doesn't help, though, try posting some code, so we can have a look at what's going on and maybe diagnose the problem more specifically.</p>
|
Create GUI from Windows Service with a Network Log on <p>I have been reading a lot about executing a GUI application from a Windows Service. The "Allow service to interact with desktop" check box worked for me when the Service runs as the SYSTEM user (I am using Windows XP).
Now I need the Service to run as a User defined in a domain (from the network). Everything works fine (even if no user is logged into the machine) but the GUIs are not shown (even if the same network user is logged in!).
I know that the GUIs are running, it's just that they are hidden. Why is that? Is there a way to show them if a user is logged on (like when created by the SYSTEM user and allowed interaction with desktop!) ?
if so, would it work if the user logged in is not the same as the one the service is running on? </p>
<p><hr /></p>
<h3>Edit:</h3>
<p>@casperOne: I see your solution, and it is the same that people (even you) have been posting around. In my case though, I am sure I am running on a secure environment and ONLY one user will be logged into a machine at a time. Isn't there anything one can do to simply unhide the GUIs? Why would this work with the user SYSTEM allowing interaction with desktop and not with another user?</p>
| <p>Your approach is completely wrong, and will not work when deployed on Vista.</p>
<p>Services should NEVER assume a login session with a desktop to interact with.</p>
<p>Rather, you should have a second application which is run when the user logs in (or some other point in time) which communicates with the service and then displays UI elements when it receives notifications/responses from the service.</p>
<p>See this other question (and answers) for further information:</p>
<p><a href="http://stackoverflow.com/questions/466199/how-to-detect-if-a-window-can-be-shown">http://stackoverflow.com/questions/466199/how-to-detect-if-a-window-can-be-shown</a></p>
|
ASP.NET: Pass value from User Control to page? <p>I am creating a user control in ASP.NET (using VB) that uses the autocomplete ajax control on a textbox to get a value. Then I want the page to post back and run some code according to whatever value is passed to it from this control. Problem is, I'm not exactly sure how to do this. I'm sure it's easy and I should know, but I don't.</p>
<p>Thanks in advance!</p>
| <p>In your user control expose a property for the value</p>
<pre><code>Public Property SomeValue() As String
Get
Return textbox1.Text
End Get
End Property
</code></pre>
<p>Then in your aspx page load, just reference the user control's value. </p>
<pre><code>userControl1.SomeValue
</code></pre>
<p>Edit, I just tried changing my syntax to vb.net, I don't actually know vb, so that syntax may or may not be right.</p>
|
Need advice on attribution/copyright of heavily modified OSS code (BSD, Apache, etc) in source headers <p>I've got a question about use of permissive-licensed (BSD, Apache, MIT, etc) source where the line may be heavily blurred between original code and borrowed code. </p>
<p>We are more than happy to disclose a copyrights for original source as required by the licenses.</p>
<p>The specific case I'm wondering about is how to correctly update source headers in files I've modified. </p>
<p>Assume you have some source from another project you'd like to make use of. It contains a header like the following.</p>
<pre><code>/*
* Copyright (C) 2006, 2007 John Doe.
* Copyright (C) 2008, 2009 Project comitters.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 07. March 2004 by John Doe
*/
</code></pre>
<p>For a trivial bug fix, I would just make my small change, send it upstream and hope the fix gets incorporated. When it does, I would drop my patched version and go back to mainline.</p>
<p>Some times I want to use the source as a jumping off point. It gets transformed over time and reworked and improved. It may resemble the original code but it certainly would be our own work by that point.</p>
<p>Is it ok then to replace that header with my own? Should I just write something like "Based on original XYZ by John Doe"? </p>
| <p>The BSD family of licenses expressly forbid you from modifying or removing their headers.</p>
<p>Edit: I suppose I should go more into depth on this.</p>
<p>Essentially, you used their code as a basis for your own. Due to that influence, you are still bound by the original license, and thus have to keep the original attribution intact.</p>
|
How do I create a parameterized SQL query? Why Should I? <p>I've heard that "everyone" is using parameterized SQL queries to protect against SQL injection attacks without having to vailidate every piece of user input.</p>
<p>How do you do this? Do you get this automatically when using stored procedures?</p>
<p>So my understanding this is non-parameterized:</p>
<pre><code>cmdText = String.Format("SELECT foo FROM bar WHERE baz = '{0}'", fuz)
</code></pre>
<p>Would this be parameterized?</p>
<pre><code>cmdText = String.Format("EXEC foo_from_baz '{0}'", fuz)
</code></pre>
<p>Or do I need to do somethng more extensive like this in order to protect myself from SQL injection?</p>
<pre><code>With command
.Parameters.Count = 1
.Parameters.Item(0).ParameterName = "@baz"
.Parameters.Item(0).Value = fuz
End With
</code></pre>
<p>Are there other advantages to using parameterized queries besides the security considerations?</p>
<p>Update: This great article was linked in one of the questions references by Grotok.
<a href="http://www.sommarskog.se/dynamic_sql.html">http://www.sommarskog.se/dynamic_sql.html</a></p>
| <p>Your EXEC example would NOT be parameterized. You need parameterized queries (prepared statements in some circles) to prevent input like this from causing damage:</p>
<blockquote>
<p>';DROP TABLE bar;--</p>
</blockquote>
<p>Try putting that in your fuz variable (or don't, if you value your bar table). More subtle and damaging queries are possible as well.</p>
<p>Here's an example of how you do parameters with Sql Server:</p>
<pre><code>Public Function GetBarFooByBaz(ByVal Baz As String) As String
Dim sql As String = "SELECT foo FROM bar WHERE baz= @Baz"
Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("@Baz", SqlDbType.VarChar, 50).Value = Baz
Return cmd.ExecuteScalar().ToString()
End Using
End Function
</code></pre>
<p>Stored procedures are sometimes credited with preventing SQL injection. However, most of the time you still have to call them using query parameters or they don't help. If you use stored procedures <em>exclusively</em>, then you can turn off permissions for SELECT, UPDATE, ALTER, CREATE, DELETE, etc (just about everything but EXEC) for the application user account and get some protection that way.</p>
|
How to reset or kill JVM context? <p>I am running a simple java client through <code>java <class file></code> command. The java command is actually invoked by a system process. This is on Unix.</p>
<p>We were facing problem with X11 Display. So we added <code>export DISPLAY=:0.0</code> in the startup file and the Display problem was resolved. Now when the <code>export DISPLAY=:0.0</code> line is removed from the startup file and the java client is run again, we are not able to revert to old state, i.e., we no longer get the X11 Display error. So there is something that is persisting on the system. Is there any way to make sure the JVM context was killed before running the client?</p>
<p>We have killed the process that triggers the java client, then restarted the process to run the java client again. But not succeeded to go back to the old state.</p>
<p>[Edit] I forgot to mention that I have already tried "unset DISPLAY" in the stop file. The startup fie is run when the environment is brought up and the stop file is run when the environment is brought down. I have also tried headless mode but that doesn't work for our program. </p>
| <p>If you have previously executed the export command in the current shell (from the startup file, even), then the value is in your environment. Unsetting it (or getting a new shell with a clean environment) is the only way to get rid of the environment setting.</p>
<p>I would suggested adding a line to your startup script to echo $DISPLAY, so that it will be obvious what is currently set while you're troubleshooting the problem.</p>
<p>If your process doesn't actually need the xwindows display, you should start the JVM in headless mode. Details are <a href="http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/" rel="nofollow">here</a>.</p>
|
Where should I set compiler options like {$STRINGCHECKS OFF}? <p>If I place it in the .dpr or any other unit will it be considered globally?</p>
| <p>I dont think so. IIRC the rule is that anything in the dpr or unit is local to that file. If you put it into the project options (under conditionals) then it is global. Many writers put such stuff into a text file and then do a {$I MyConditionals.txt} at the top of each unit.</p>
|
Is this bad oop design? <p>Imagine I have an interface called IVehicle.</p>
<p>From this interface, I derive several concrete types such as bus and car (all can move, slow down, switch off engine, etc). My interface has no fields.</p>
<p>Would it be bad design to have one class which has fields (e.g. top speed of vehicle) and use this by each of the concrete types? Would this be bad design? Also, if I store state in this class (e.g. use the fields), then would it have to be static?</p>
<p>Thanks</p>
| <p>You're talking about an abstract class, and no, it's not bad design. That's what they're for (basically, interfaces, but with some basic implementation).</p>
<p>State wouldn't have to be stored statically. There will be a full implementation of this class (in the form of one of the derived classes) each time you create a Car, Bus, etc.</p>
|
Need a custom currency format to use with String.Format <p>I'm trying to use String.Format("{0:c}", somevalue) in C# but am having a hard time figuring out how to configure the output to meet my needs. Here are my needs:</p>
<ol>
<li>0 outputs to blank</li>
<li>1.00 outputs to $1.00</li>
<li>10.00 outputs to $10.00</li>
<li>100.00 outputs to $100.00</li>
<li>1000.00 outputs to $1,000.00</li>
</ol>
<p>I've tried String.Format("{0:c}", somevalue) but for zero values it outputs $0.00 which is not what I want. I've also tried String.Format("{0:$0,0.00;$(0,0.00);#}", somevalue), but for 1.0 it outputs $01.00. String.Format("{0:$0.00;$(0.00);#}", somevalue) works for most cases, but when somevalue is 1000.00 the output is $1000.00. </p>
<p>Is there some format that will fit all 5 cases above? All of the documentation I've read only details the basics and doesn't touch on this type of scenario.</p>
| <p>If you use </p>
<pre><code>string.Format("{0:$#,##0.00;($#,##0.00);''}", value)
</code></pre>
<p>You will get "" for the zero value and the other values should be formatted properly too.</p>
|
Who calls this function? <p>At my last job (legacy FORTRAN 77 code), we had files of cross references that list what subroutines called other subroutines, in what files subroutines were defined, what common blocks held what variables, what subroutines included what common blocks, etc. These were then used by shell scripts that grepped the cross reference files and would tell you things about the design of the program.</p>
<p>I'm now at a new company (C++ code), and I've found ctags to replace some of that functionality. The one thing I miss the most is a command we called "who.calls" that lists what subroutines (I mean functions or methods, gotta get used to the OO-speak) call a given subroutine. For example, if the subroutine <code>foo</code> calls the subroutine <code>bar</code>:</p>
<pre><code>>who.calls bar
foo
</code></pre>
<p>Any suggestions for how to do this without re-engineering the programming environment from my old company? I'm looking for a super regex or some other method that I can use at the command line, but I'm open to other methods that take some totally different approach to give me the same information. I basically want to discover a debug function stack without running the debugger.</p>
| <p>You might want to consider using <a href="http://www.stack.nl/~dimitri/doxygen/" rel="nofollow">Doxygen</a>. It can produce web pages that show you the entire call tree and class structure, as well as pulling out properly formatted comments to document the classes and methods just like Javadocs do for java.</p>
<p>Another possibility is to start using an IDE. After 25 years of using vi (and then gvim) and ctags, I've recently joined the 21st century and started using Eclipse (I'm doing Java, but I've seen C++ plugins for Eclipse). As well as being able to do everything that tags can do, it can also take you to all the callers of the current method. And on top of that, it has a damn good interactive debugger built in.</p>
|
What is wrong with my WINAPI call to handle long file paths? <p>I've been trying to figure out the best way to copy files in Windows with deep paths (files, not folders so robocopy is out of the question). The best solution I've been able to come up with is writing my own solution. I've been able to write the code to handle listing directories with 10,000 character deeps paths but using the same approach doesn't seem to be working for actually copying files. I tired using the System.IO libraries with \?\ prefixed to paths and that didn't seem to work.</p>
<pre><code>[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFile(string lpExistingFileName, string lpNewFileName,
bool bFailIfExists);
public static bool CopyFile(string source, string dest)
{
source = fixPathForLong(source);
dest = fixPathForLong(dest);
return CopyFile(source, dest, false);
}
private static string fixPathForLong(String path)
{
if (!path.StartsWith(@"\\?\"))
path = @"\\?\" + path;
return path;
}
</code></pre>
| <p>Should you call the function CopyFileW instead? Note the W at the end. Also, i don't know if you are using UNC paths. If so you need to prefix with "\\?\UNC\" instead.</p>
<p>This is a good article for long path handling </p>
<p><a href="http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx" rel="nofollow">http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx</a></p>
|
I have StartDate and EndDate for each record. Should I give NULL a special meaning when used in these 2 fields? <p>So, I have a table where StartDate and EndDate's are used to determine the activeness of a record. I thought of using NULLs to relieve the maintainers from having to manufacture some crazy dates for some of the records. For example, if NULL had defined as positive infinite when used in EndDate, the data maintainers wouldn't need to come up with something like 1-1-2100 for long-lived records. </p>
<p>I can speculate some of the trade offs on my own: defining NULL as infinities means cleaner data and elimination of periodic maintenance work, but it also means longer queries and stored procedures. So I was wondering how you guys in the real world weigh in on this. </p>
<p>EDIT: the opinions are about half-half. If I had clarified that the StartDate and EndDate are used solely for the purpose of determining the activeness of a record in the where clause, and never appears in the select list, would that tilt the scale? One subject I need to read on is probably indexing. Thanks'all. </p>
| <p>If either <code>StartDate</code> or <code>EndDate</code> of your record will be <code>NULL</code>, then the following condition:</p>
<pre><code>BETWEEN StartDate AND EndDate
</code></pre>
<p>will never match this record.</p>
<p>You'll need to do following:</p>
<pre><code>BETWEEN IFNULL(StartDate, '01.01.1000') AND IFNULL(EndDate, '01.01.3000')
</code></pre>
<p>, which, of course, is not good for indices.</p>
<p>Of course, you may create a function based index, but you'll need to provide a constant for it anyway.</p>
<p><em>Summary: if you want performance, use constants, do not use NULLs</em></p>
|
Text replacement efficiency <p>An extension to my previous question:<br />
<a href="http://stackoverflow.com/questions/542226/text-cleaning-and-replacement-delete-n-from-a-text-in-java">Text cleaning and replacement: delete \n from a text in Java</a></p>
<p>I am cleaning this incoming text, which comes from a database with irregular text. That means, there' s no standard or rules. Some contain HTML characters like &reg, &trade, &lt, and others come in this form: &#8221, &#8211, etc. Other times I just get the HTML tags with < and >.</p>
<p>I am using String.replace to replace the characters by their meaning (this should be fine since I'm using UTF-8 right?), and replaceAll() to remove the HTML tags with a regular expression. </p>
<p>Other than one call to the replace() function for each replacement, and compiling the <strong>HTML</strong> tags regular expression, is there any recommendation to make this replacement efficient?</p>
| <p>My first suggestion is to measure the performance of the simplest way of doing it (which is probably multiple replace/replaceAll calls). Yes, it's potentially inefficient. Quite often the simplest way of doing this is inefficient. You need to ask yourself: <strong>how much do you care?</strong></p>
<p>Do you have sample data and a threshold at which point the performance is acceptable? If you don't, that's the first port of call. Then test the naive implementation, and see whether it really <em>is</em> a problem. (Bear in mind that string replacement is almost certainly only <em>part</em> of what you're doing. As you're fetching the text from a database to start with, that <em>may</em> well end up being the bottleneck.)</p>
<p>Once you've determined that the replacement really is the bottleneck, it's worth performing some tests to see which <em>bits</em> of the replacement are causing the biggest problem - it sounds like you're doing several different kinds of replacement. The more you can narrow it down, the better: you may find that the real bottleneck in the simplest code is caused by something which is easy to make efficient in a <em>reasonably</em> simple way, whereas trying to optimise <em>everything</em> would be a lot harder.</p>
|
Get just the Date from grouping in select from DateTime column in SQL Server <p>I need to group some records based on a date but it is a date and time field and I need to ignore the time part of is and just group by the date part - here is my SQL as it stands:</p>
<pre><code>SELECT
AutoShipItems.CustomerID,AutoShipItems.NextOrderDate,
Customer.FirstName,Customer.LastName, Customer.EmailAddress
FROM
AutoShipItems
INNER JOIN Customer ON
AutoShipItems.CustomerID =Customer.CustomerID
WHERE
(AutoShipItems.NextOrderDate <= GETDATE())
GROUP BY
AutoShipItems.CustomerID, AutoShipItems.NextOrderDate,
Customer.FirstName, Customer.LastName,
Customer.EmailAddress
ORDER BY
AutoShipItems.NextOrderDate
</code></pre>
| <p>You can group by this:</p>
<pre><code>cast(floor(cast(AutoShipItems.NextOrderDate as float)) as datetime)
</code></pre>
<p>I put this into a scalar user-defined function to make it easier:</p>
<pre><code>create function [dbo].[xfn_TrimTimeFromDateTime]
(
@date as datetime
)
returns datetime with schemabinding as
begin
--- Convert to a float, and get the integer that represents it.
--- And then convert back to datetime.
return cast(floor(cast(@date as float)) as datetime)
end
</code></pre>
<p>Which you would then call like this:</p>
<pre><code>GROUP BY
AutoShipItems.CustomerID,
dbo.xfn_TrimTimeFromDateTime(AutoShipItems.NextOrderDate),
Customer.FirstName, Customer.LastName, Customer.EmailAddress
</code></pre>
<p>Note that you might have to change the values in the SELECT clause, since you are grouping by something different now.</p>
|
How can I insert an image into a RichTextBox? <p>Most of the examples I see say to put it on the clipboard and use paste, but that doesn't seem to be very good because it overwrites the clipboard.</p>
<p>I did see <a href="http://www.codeproject.com/KB/edit/csexrichtextbox.aspx">one method</a> that manually put the image into the RTF using a pinvoke to convert the image to a wmf. Is this the best way? Is there any more straightforward thing I can do?</p>
| <p>The most straightforward way would be to modify the RTF code to insert the picture yourself. </p>
<p>In RTF, a picture is defined like this:</p>
<p>'{' \pict (brdr? & shading? & picttype & pictsize & metafileinfo?) data '}'
A question mark indicates the control word is optional.
"data" is simply the content of the file in hex format. If you want to use binary, use the \bin control word. </p>
<p>For instance:</p>
<pre><code>{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860 hex data}
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860\bin binary data}
</code></pre>
<p>\pict = starts a picture group,
\pngblip = png picture
\picwX = width of the picture (X is the pixel value)
\pichX = height of the picture
\picwgoalX = desired width of the picture in twips</p>
<p>So, to insert a picture, you just need to open your picture, convert the data to hex, load these data into a string and add the RTF codes around it to define a RTF picture. Now, you have a self contained string with picture data which you can insert in the RTF code of a document. Don't forget the closing "}"</p>
<p>Next, you get the RTF code from your RichTextBox (rtbBox.Rtf), insert the picture at the proper location, and set the code of rtbBox.Rtf</p>
<p>One issue you may run into is that .NET RTB does not have a very good support of the RTF standard. </p>
<p>I have just made a small application* which allows you to quickly test some RTF code inside a RTB and see how it handles it. You can download it here:
<a href="http://your-translations.com/toys/">RTB tester</a> (<a href="http://your-translations.com/toys">http://your-translations.com/toys</a>). </p>
<p>You can paste some RTF content (from Word, for instance) into the left RTF box and click on the "Show RTF codes" to display the RTF codes in the right RTF box, or you can paste RTF code in the right RTB and click on "Apply RTF codes" to see the results on the left hand side. </p>
<p>You can of course edit the codes as you like, which makes it quite convenient for testing whether or not the RichTextBox supports the commands you need, or learn how to use the RTF control words. </p>
<p>You can download a full specification for RTF online.</p>
<p><hr /></p>
<p>NB It's just a little thing I slapped together in 5 minutes, so I didn't implement file open or save, drag and drop, or other civilized stuff. </p>
|
IE hosted windows control with dependent assemblies <p>I am working with a windows forms user control that needs to be hosted in Internet Explorer. Info about the technique I am trying to duplicate can be found <a href="http://www.15seconds.com/issue/030610.htm" rel="nofollow">here</a> and <a href="http://www.c-sharpcorner.com/UploadFile/jdivine/UserControlInInternetExplorer11172005231420PM/UserControlInInternetExplorer.aspx" rel="nofollow">here</a>.</p>
<p>However, the control fails to load in the browser because it relies on multiple other dependant dllâs. Is there a way to get the dependent assemblies to be downloaded with the control?</p>
| <p>I also use this method to host WinForms-Controls on a html page. I found out that the internetexplorer tries to find the dependant dll in the root of the webserver. Cave: the internetexplorer does not look for the dlls in the root of the webapplication.</p>
<p>Let me tell you a example.
I built a audio-recorder control Recorder.dll. This control uses RecLib.dll.
I have a WebApp named Recorder on my local IIS and use the dll within http//localhost/Recorder/default.aspx
The classid points to "localhost/Recorder/Recorder.dll#..."
I have put my Recorder.dll to c:\inetpub\wwwroot\Recorder\Recorder.dll.
Then I have to put the RecLib.dll to c:\inetpub\wwwroot\RecLib.dll.
This is because the IE tries to find the Librariy at http//localhost/Reclib.dll</p>
<p>Hope I could make things clearer to you.</p>
|
Flex app embedding and communicating with older Flash 8 app <p>I currently maintain an application that's written in Flash 8 (AS2) which is used to embed and control some auto-generated SWFs. The auto-generated SWFs are also Flash 8 (actually, they work at least in 7, possibly even older), so my current app is able to directly reference variables and functions within the embedded SWF.</p>
<p>We're now working on a new version of this application, written in Flex. We need to duplicate the current app's functionality of embedding and controlling the auto-generated AS2 SWFs. However, AS3-based SWFs can't reference variables or functions within an embedded AS2-based SWF. Unfortunately we don't have control over the auto-generation tool, so we can't change that to output AS3-based SWFs.</p>
<p>The only real solution to getting the AS3 and AS2 SWFs to communicate is to use LocalConnection. I'd need to create a wrapper AS2 SWF that would load the auto-generated SWF and act as a proxy, communicating with my Flex app via LocalConnection and doing whatever needs to be done to the auto-generated SWF. However, there's a problem with this. The proxy SWF needs to know what LocalConnection ID to use, but I can't find a way to communicate the ID to it (I can't just hard-code some random ID as I need to be able to support multiple instances of this app simultaneously).</p>
<p>Has anyone solved this? Is there any way to get some kind of unique identifier to the embedded SWF?</p>
| <p>Not sure I get exactly how the application works so excuse me if I'm wrong.
If the flex instance must load the AVM1 proxy wouldn't it be possible to inject a flash-var via the URL containing a generated ID for the LocalConnection to use ?</p>
<p>In addition to your comment, just added how to send variables to the AVM1 movie.
This works fine locally at least (not tested on network):</p>
<p><strong>AS3 - FP10</strong>:</p>
<pre><code>loader = new Loader();
var request:URLRequest = new URLRequest("as2proxy.swf");
var variables:URLVariables = new URLVariables();
variables.id = "local_connection_id";
request.data = variables;
loader.load(request);
</code></pre>
<p><strong>AS2 - FP7</strong> (first frame on the timeline of <em>"as2proxy.swf"</em>) :</p>
<pre><code>trace(id); // (_root.id)
</code></pre>
<p>BTW, stumbled on the following class from Libspark :
<a href="http://www.libspark.org/svn/as3/ForcibleLoader/src/org/libspark/utils/ForcibleLoader.as" rel="nofollow">http://www.libspark.org/svn/as3/ForcibleLoader/src/org/libspark/utils/ForcibleLoader.as</a></p>
|
Delphi : How to create MP3 file with certain number of seconds of silence? <p>I need to create a mp3 file with certain number of seconds of silence? </p>
<p>What would be way to do it programatically?</p>
<p>Edit:
It doesn't need to be re inserted in mp3, just a single mp3 file that contain silence x seconds long.</p>
| <p>Do you just want an MP3 of X seconds long that is just silence, or do you want to inject silence into an existing MP3?</p>
<p>This is a bit more complicated. Windows XP by default has a low quality MPEG encoding codec installed. You can find some informant about <a href="http://www.efg2.com/Lab/Library/Delphi/Graphics/Multimedia.htm" rel="nofollow">encoding to an MP3 with Delphi</a> on that same page if you scroll to the bottom there is information on Wave files. Some of the links are broken though.</p>
<p>It is a two step process, you need to generate a waveform and then encode that waveform to an MP3 file. MP3 files have a header and blocks, so you can't just loop a 40ms mp3 a few times.</p>
|
I would like a separate process to when django starts - is there an accepted way of doing this? <p>I was thinking of making settings.py start the process but this seemed slightly ugly.</p>
<p>I don't really want to make make custom start up scripts, nor can I really make the starting of this process lazy.</p>
| <p>You might be able to register a listener to the "class-prepared" signal on one of your model classes and fire your process from there. However, I think the need to do this is most likely a design smell, or a case of the tail wagging the dog. </p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/signals/#class-prepared" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/signals/#class-prepared</a></p>
<p>I'd be curious to know why your design calls for this, but that may get us off-topic here.</p>
|
My SQL triggers <p>Is it possible to set up a mysql trigger that fires back the id number of that record when ever there is an insert into the database AND how do i capture that using php?</p>
| <p>Unless I don't fully understand your question, you don't need a trigger for this - just use the "last inserted ID" functionality of your database driver.</p>
<p>Here's an example using the basic mysql driver in PHP.</p>
<pre><code><?php
$db = mysql_connect( 'localhost', 'user', 'pass' );
$result = mysql_query( "insert into table (col1, col2) values ('foo', 'bar')", $db );
$lastId = mysql_insert_id();
</code></pre>
<p>This is a connection-safe way to obtain the ID.</p>
|
Silverlight sockets or db requests? <p>I am currently coding an online turn based rpg for an assignment. In the game players can chat with each other and send their actions once they complete a turn. What is the best way to take care of the data exchange between the players. Sockets or storing all information in a database and the program periodically does requests to check for any updates? Unless there is a better approach.</p>
<p>Please note that the game is meant to be wide scale, i.e alot of players will be having a number of games simultaniously on the same sever, so I must try to be as efficient as possible.</p>
| <p>In Silverlight, you can only connect back to the host that served the Silverlight app, so that rules out client-client sockets. Everything in your game (including chat) will have to go via a server.</p>
<p>Windows Communication Foundation (WCF) is quite nice to work with in Silverlight2. Having your game turn-based makes things a little bit easier because it means you dont have to maintain the exact same game-state between players in realtime (ie: not aiming for max 100ms latency).</p>
|
Java 2D and resize <p>I have some old Java 2D code I want to reuse, but was wondering, is this the best way to get the highest quality images?</p>
<pre><code> public static BufferedImage getScaled(BufferedImage imgSrc, Dimension dim) {
// This code ensures that all the pixels in the image are loaded.
Image scaled = imgSrc.getScaledInstance(
dim.width, dim.height, Image.SCALE_SMOOTH);
// This code ensures that all the pixels in the image are loaded.
Image temp = new ImageIcon(scaled).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null),temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
// j2d's image scaling quality is rather poor, especially when
// scaling down an image to a much smaller size. We'll post filter
// our images using a trick found at
// http://blogs.cocoondev.org/mpo/archives/003584.html
// to increase the perceived quality....
float origArea = imgSrc.getWidth() * imgSrc.getHeight();
float newArea = dim.width * dim.height;
if (newArea <= (origArea / 2.)) {
bufferedImage = blurImg(bufferedImage);
}
return bufferedImage;
}
public static BufferedImage blurImg(BufferedImage src) {
// soften factor - increase to increase blur strength
float softenFactor = 0.010f;
// convolution kernel (blur)
float[] softenArray = {
0, softenFactor, 0,
softenFactor, 1-(softenFactor*4), softenFactor,
0, softenFactor, 0};
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
return cOp.filter(src, null);
}
</code></pre>
| <p>Chris Campbell has an excellent and detailed write-up on scaling images - see <b><a href="http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html" rel="nofollow">this article</a></b>.</p>
<p>Chet Haase and Romain Guy also have a detailed and very informative write-up of image scaling in their book, <b><a href="http://filthyrichclients.org/" rel="nofollow">Filthy Rich Clients</a></b>.</p>
|
Granularity of Paradigm Mixing <p>When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?</p>
| <p>Different paradigms mix in different ways. For example, Using OOP doesn't eliminate the use of subroutines and procedural code from an outside library. It merely moves the procedures around into a different place.</p>
<p>It is impossible to purely program with one paradigm. You may think you have a single one in mind when you program, but that's your illusion. Your resultant code will land along the borders and within the bounds of many paradigms.</p>
|
Visual Studio Setup Project-- adding prebuild step <p>I want to make my build process for producing a setup project to be a single click. However, I also want to add {smartassembly} to the build step to obfuscate the build, but only on our build machine. How can I add a pre-build step to a visual studio 2008 vdproj?</p>
<p>Basically, I want to move the command line argument to obfuscate the build from the end of building the application to part of the setup program, so only the build machine needs to have a license.</p>
<p>Alternatively, should we just get {smartassembly} for all of our developers? It's a very large cost change (going from one build license to 5 is not a trivial amount of money), so the reasoning here has to be pretty airtight. I was going to add it to just the machine responsible for the build, rather than having all developers have it, and then force developers to try to reproduce bugs in the release build that customers actually have.</p>
| <p>yeah, it turns out I'm a moron. The UI is different, but the pre- and post- build items are in the properties as if it were a UI property, not a project property.</p>
|
Which is more usable, outputting dates relative to now or relative to the main action's point in time? <p>I was just reading the <a href="http://blog.objectmentor.com/articles/2009/02/06/on-open-letter-to-joel-spolsky-and-jeff-atwood" rel="nofollow">"Open Letter to Joel and Jeff"</a> and I noticed the dates on the comments are relative to when the blog entry was posted. So that means the first entry will always stay as "12 minutes later" and the next will always be "14 minutes later".</p>
<p>From a usability standpoint, does it make more sense to list out times relative to now, or to when the main action occurred?</p>
<p>Upon first seeing this I thought it was a little confusing (I think because I wasn't expecting this), but it very quickly grew on me. </p>
| <p>As Steve Krug recommends in <a href="http://rads.stackoverflow.com/amzn/click/0321344758" rel="nofollow">Don't Make Me Think</a>, get rid of the question marks that pop in the user's head when they come to your site. If it is confusing it isn't likely to be helpful.</p>
<p>Although an interesting concept, in this context I think it is more confusing than useful. If I see "answered 18 mins ago" and "answered 17 mins ago" I have a perfect frame of reference. Also this is something I see on many other sites so it does not require me to learn anything new.</p>
<p>On the other hand if I see two comments that contain "5 mins later" and "6 mins later" I don't have a clear frame of reference. The first might be after the original question, but the other? Is it 6 minutes after that previous comment? Or 6 minutes after the original question, thus one minute after the other comment? Finally, this isn't what you typically see on a site so there will be a moment of "huh?" follow by either "wtf?" or "cool!". Not a reaction that should be left to chance.</p>
|
is flex actionscript? <p>I've been using flash for a long time, mostly as an animation tool with a little dabbling in actionscript. Over the years I've moved from mostly making animations to mostly making small flash games or proof of concepts in my spare time. I've been very reluctant to learn as3 as I am not much of a programmer, but a friend of mine convinced me.</p>
<p>I was looking things up and I keep coming across Flex, I am not entirely sure what flex is and I was hoping someone could explain it to me. From what I've looked up, it sounds like flex is just actionscript outside of flash if that makes sense. Is this someone thing I should look into? </p>
| <p>Both Flash and Flex use the ActionScript language â Flash CS3 and Flex 2 both support ActionScript 3 (which is compliant with the ECMAScript Edition 4), whereas the older version of Flash supports only ActionScript 2.</p>
<p>The differences between the two are:</p>
<p>1) Flash has been designed to facilitate the creation of interactive content, whereas Flex is geared toward application development.</p>
<p>2) Flash stores your application structure in a binary FLA file, whereas Flex uses a text file based on the markup language of Flex, MXML.</p>
<p>3) Different deployment models.</p>
<p>Flex originally was designed to bring enterprise programmers to the Flash Platform. As a result, Flex features tools designed to accommodate the special needs of hardcore programmers. </p>
<p>Take a look at <a href="http://paragmetha.blog.com/1831276/">this blog post</a> which illustrates the strength and weaknesses of Flash and Felx quite nicely.</p>
|
getopt() in VC++ <p>I'm quite fond of using GNU <a href="http://www.gnu.org/software/libtool/manual/libc/Getopt.html"><b>getopt</b></a>, when programming under <strong>Linux</strong>. I understand, that getopt(), is not available under MS VC++.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Win32 environment</li>
<li>using Visual Studio</li>
<li>No <a href="http://www.boost.org/">Boost</a></li>
<li>No MFC</li>
<li>Not concerned with portability</li>
</ul>
<p><strong>Question:</strong></p>
<ul>
<li>How can I then port getopt() accordingly?
<ul>
<li>What guidelines should I be aware of while porting?</li>
</ul></li>
<li>Known port with <strong>same</strong> features?</li>
</ul>
| <p>This may help, it's also very easy to integrate</p>
<p><a href="http://www.codeproject.com/KB/cpp/xgetopt.aspx">http://www.codeproject.com/KB/cpp/xgetopt.aspx</a></p>
|
Equals(=) vs. LIKE <p>When using SQL, are there any benefits of using <code>=</code> in a <code>WHERE</code> clause instead of <code>LIKE</code>?</p>
<p>Without any special operators, <code>LIKE</code> and <code>=</code> are the same, right?</p>
| <p>The equals (=) operator is a "comparison operator compares two values for equality." In other words, in an SQL statement, it won't return true unless both sides of the equation are equal. For example:</p>
<pre><code>SELECT * FROM Store WHERE Quantity = 200;
</code></pre>
<p>The LIKE operator "implements a pattern match comparison" that attempts to match "a string value against a pattern string containing wild-card characters." For example:</p>
<pre><code>SELECT * FROM Employees WHERE Name LIKE 'Chris%';
</code></pre>
<p>LIKE is generally used only with strings and equals (I believe) is faster. The equals operator treats wild-card characters as literal characters. The difference in results returned are as follows:</p>
<pre><code>SELECT * FROM Employees WHERE Name = 'Chris';
</code></pre>
<p>And</p>
<pre><code>SELECT * FROM Employees WHERE Name LIKE 'Chris';
</code></pre>
<p>Would return the same result, though using LIKE would generally take longer as its a pattern match. However,</p>
<pre><code>SELECT * FROM Employees WHERE Name = 'Chris%';
</code></pre>
<p>And</p>
<pre><code>SELECT * FROM Employees WHERE Name LIKE 'Chris%';
</code></pre>
<p>Would return different results, where using "=" results in only results with "Chris%" being returned and the LIKE operator will return anything starting with "Chris".</p>
<p>Hope that helps. Some good info can be found <a href="http://www.firstsql.com/tutor2.htm">here</a>.</p>
|
How to map 2+ entities to same table in .NET Entity Framework? <p>I'm trying to create 2 entities that operate as different views on the same underlying db table. When I create these in Visual Studio's entity model and place an association between them, I get a "Association is not mapped" error. I read an article (<a href="http://blogs.msdn.com/adonet/archive/2008/12/05/table-splitting-mapping-multiple-entity-types-to-the-same-table.aspx" rel="nofollow">http://blogs.msdn.com/adonet/archive/2008/12/05/table-splitting-mapping-multiple-entity-types-to-the-same-table.aspx</a>) that describes how to hand-code the XML in the edmx to add a ReferentialConstraint but that didn't help me any.</p>
<p>Any thoughts? Does the designer not support this?</p>
| <p>From the error, I'd guess that there wasn't an Association created for the storage schema in the edmx (the SSDL of the edmx XML). A conceptual association has been created if you can see it in the designer, but there's no storage definition behind the scenes. I'm guessin'. =)</p>
|
When to upgrade libraries <p>I work with a lot of open source libraries in my daily tasks (java FYI). By the time a project comes close to maturing, many of the libraries have released newer versions. Do people generally upgrade just to upgrade, or wait until you see a specific bug? Often the release notes say things like "improved performance and memory management", so I'm not sure if it's worth it to potentially break something. But on the other hand most libraries strive and claim to not break anything when releasing new versions.</p>
<p>What is your stance on this? I'll admit, I am kind of addicted to upgrading the libraries. Often times it really does help with performance and making things easier.</p>
| <p>The rule for us is to stay up to date before integration testing but to permit no changes to any library once we're past this point. Of course, if integration testing reveals flaws that are due to an issue with a library that has been fixed, then we'd go back and update. Fortunately, I cannot remember a situation where that has happened.</p>
<p>Update: I understand Philuminati's point about not upgrading until you have a reason. However, I think of it this way: I continuously pursue improvements in my own code and I use libraries built by people that I believe think the same way. Would I fail to use my own improved code? Well, no. So why would I fail to use the code that others have improved? </p>
|
How to display 1 instead of 01 in ToString(); <p>I am using the format ToString("0,0") to display a number like <pre>5000 as 5,000</pre> but if the number is 0 - 9, it displays 01, 02, 03, etc. Does anyone know the correct syntax so it does not display the leading 0?</p>
<p>Thanks,
XaiSoft</p>
| <pre><code>ToString("#,0")
</code></pre>
<p>Also, <a href="http://acodingfool.typepad.com/blog/dotnet-string-formatting-cheat-sheet.html">this</a> may help you further</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.