input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
What to do when you need to store a (very) large number? <p>I am trying to do a <a href="https://projecteuler.net/problems" rel="nofollow">Project Euler</a> problem but it involves adding the digits of a very large number. (100!)</p>
<p>Using Java int and long are too small. </p>
<p>Thanks for any suggestions</p>
| <p>Class <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html" rel="nofollow">BigInteger</a>
looks like it might be what you are looking for.</p>
|
iPhone app using openAL works in simulator, but not on device <p>I added the openAL framework to my app and I am using the sound engine that is in the demo CrashLanding. It works just fine on the simulator, but when I build it for my device, I get errors. It looks like the framework isn't added. I've tried: restarting xcode; delete the framework and add it in again; cleaning the target; restart the computer. It still works on the simulator, but the device setting won't even compile. Does anyone have any other ideas or am I doing something wrong? </p>
<p>Here's a more specific error, there are 17 right now:</p>
<p>"_alSourcePlay", referenced from:</p>
<p>SoundEngineEffect::PlaybackProc(void*) in SoundEngine.o</p>
<p>SoundEngineEffect::Start() in SoundEngine.o</p>
<p>Also, CrashLanding runs fine on my device.</p>
| <p>Remove the OpenAL framework you added.</p>
<p>Go to one of the other frameworks in your project, say UIKit, right-click and "reveal in finder".</p>
<p>Drag the OpenAL you find there from the Finder window into XCode under Frameworks.</p>
<p>Now it will probably work... sometimes when you say "Add Existing Frameworks" it seems to choose a wrong directory, and you are probably adding the OS X OpenAL framework (which is fine for the simulator).</p>
|
Windows Named-Pipe ACL under IIS <p>I am trying to connect a CGI process to my windows service with a named pipe.
My code runs fine using another server on my development machine, but on IIS there are security issues when I call CreateFile() in the CGI process.</p>
<p>The Windows service is the Named Pipe Server and so the CGI process is trying to connect to that named pipe as a client.</p>
<p>I have dug up some code that creates a Global security descriptor with the flag SECURITY_WORLD_SID_AUTHORITY by calling:</p>
<pre><code> InitializeAcl()
AddAccessAllowedAce()
SetSecurityDescriptorDacl()
</code></pre>
<p>But I dont really understand the concept.
I am assuming that the Pipe Server CreateNamedPipe() must be called with this ACL in the SECURITY_ATTRIBUTES structure but what about the Named Pipe client?</p>
<p>Do I create another Global security descriptor and call CreateFile() with that?</p>
<p>Do I inherit it with </p>
<pre><code> SecurityAttributes.bInheritHandle = TRUE;
</code></pre>
<p>Do I just pass Null in the CreateFile() call?</p>
| <p>Since the pipe is created by the server, only the server needs to specify the ACL, the client uses NULL for the ACL. </p>
<p>Inheritance only applies if the named pipe is created in one process and that processes creates a new process in which you want that spawned process to have direct access to the handle (it doesn't reopen the handle, rather it gets the value some other way, like a command line).</p>
<p>You can use the Process Explorer on <a href="http://technet.microsoft.com/en-us/sysinternals/default.aspx" rel="nofollow">sysinternals</a> to view named pipes open in a process and then look at the ACL. </p>
|
Saving/Loading RichTextBox Content with other data using C# <p>I am currently trying to figure out how to save the content from a RichTextbox into a stream(currently using FileStream) and do this alongside a bunch of other data. Then of course I want to be able to load from this file.
I was currently trying to use something along the following lines.</p>
<pre><code>FileStream stream = new FileStream(); //this is actually correctly defined.
ASCIIEncoding encoding = new ASCIIEncoding();
//write Title
byte[] array = encoding.GetBytes(Title);
stream.WriteByte(Convert.ToByte(array.Length));
stream.Write(array, 0, array.Length);
//save textRange
textRange.Save(stream, System.Windows.DataFormats.Rtf);
//write Subtitle
byte[] array = encoding.GetBytes(Subtitle);
stream.WriteByte(Convert.ToByte(array.Length));
stream.Write(array, 0, array.Length);
//ect...and something very similar for Loading a file.
</code></pre>
<p>This is basically what I am trying to do. I am actually saving 2 TextRanges and a bunch more Properties. So my problem is that TextRange.Load() reads to the end of the file...making it impossible for me to use that considering I have 2 TextRanges I need to save/load.
So here I am trying to come up with another way to be able to save/load the content of a RichTextBox with other data. I dont have to use a Stream. I am pretty much open to any feasible solutions. Thanks in advance!</p>
<p>~Jasson</p>
| <p>You could load/save to a MemoryStream to solve your issue with reading to the end of the file. It could look like this:</p>
<ul>
<li>Load your file into memory</li>
<li>Load the section of that file that is the contents of the richtextbox into a MemoryStream</li>
<li>Load the richtextbox contents from that MemoryStream</li>
</ul>
<p>Or are you wanting to know how you'd create and parse a file to contain different sections for the title, and the contents, and any other fields ?</p>
|
Most efficient way to convert a ISO Date into Unix timestamp? <p>In my application, I have some records which I need to filter based on some time parameters. To do the date comparisons, I need to convert the dates in my records (a string in the format YYYY-MM-DD), to a unix timestamp (seconds since 1970). Since I have many thousands of records, I really want to find the most efficient way to do it.</p>
<p>Answers to <a href="http://stackoverflow.com/questions/455554/datetime-to-unix-timestamp">another question</a> suggested doing it in the database (not an option here, sadly), using <code>strtotime()</code> or <code>strptime()</code>, but these don't <em>feel</em> like the most memory- and time-efficient methods, you know?</p>
<p>Given that I know the exact format of my input, would perhaps using some form of string manipulation (<code>substr</code>, or <code>explode</code>) combined with <code>mktime</code> be better?</p>
<p><em>If you believe I'm being premature in my optimisation, then just humour me ok?</em></p>
| <p>Why do you think strtotime() is not an efficient function? Have you done any benchmarks. Keep in mind that strtotime() is a builtin library function which will is written directly in C, whereas anything you come up will run through the php interpreter. </p>
<p>Also keep in mind that date calculations are inherently tricky, do to issues like leap years and timezones.</p>
<p>As for an alternate faster method, I think using substr() to parse will be faster than a regex. Feed the results in to mktime() and you're set.</p>
|
How to Make sure the code is still working after refactoring ( Dynamic language) <p>How to make sure that code is still working after refactoring ( i.e, after variable name change)?</p>
<p>In static language, if a class is renamed but other referring class is not, then I will get a compilation error. </p>
<p>But in dynamic language there is no such safety net, and your code can break during refactoring <strong>if you are not careful enough</strong>. You can use unit test, but when you are using mocks it's pretty hard to know the name changes and as a consequence, it may not help.</p>
<p>How to solve this problem?</p>
| <p>Before you start refactoring you should create tests that will be able to test what you're going to change - if you say unit tests will not be enought, or they will be hard to create, then by all means create higher level tests possibly even excersising the whole of your product. </p>
<p>If you have code coverage tools for your language use them to measure the quality of the tests that you've created - after it's reached a reasonably high value and if the tests are kept up to date and extended you'll be able to do anything with your code very efficiently and be rather sure things are not going in the wrong direction.</p>
|
How to create a UTF-8 string literal in Visual C++ 2008 <p>In VC++ 2003, I could just save the source file as UTF-8 and all strings were used as is. In other words, the following code would print the strings as is to the console. If the source file was saved as UTF-8 then the output would be UTF-8.</p>
<pre><code>printf("Chinese (Traditional)");
printf("ä¸å½èª (ç¹ä½)");
printf("ì¤êµì´ (ë²ì²´)");
printf("Chinês (Tradicional)");
</code></pre>
<p>I have saved the file in UTF-8 format with the UTF-8 BOM. However compiling with VC2008 results in:</p>
<pre><code>warning C4566: character represented by universal-character-name '\uC911'
cannot be represented in the current code page (932)
warning C4566: character represented by universal-character-name '\uAD6D'
cannot be represented in the current code page (932)
etc.
</code></pre>
<p>The characters causing these warnings are corrupted. The ones that do fit the locale (in this case 932 = Japanese) are converted to the locale encoding, i.e. Shift-JIS.</p>
<p>I cannot find a way to get VC++ 2008 to compile this for me. Note that it doesn't matter what locale I use in the source file. There doesn't appear to be a locale that says "I know what I'm doing, so don't f$%##ng change my string literals". In particular, the useless UTF-8 pseudo-locale doesn't work.</p>
<pre><code>#pragma setlocale(".65001")
=> error C2175: '.65001' : invalid locale
</code></pre>
<p>Neither does "C":</p>
<pre><code>#pragma setlocale("C")
=> see warnings above (in particular locale is still 932)
</code></pre>
<p>It appears that VC2008 forces all characters into the specified (or default) locale, and that locale cannot be UTF-8. I do not want to change the file to use escape strings like "\xbf\x11..." because the same source is compiled using gcc which can quite happily deal with UTF-8 files.</p>
<p>Is there any way to specify that compilation of the source file should leave string literals untouched?</p>
<p>To ask it differently, what compile flags can I use to specify backward compatibility with VC2003 when compiling the source file. i.e. do not change the string literals, use them byte for byte as they are.</p>
<p><b>Update</b></p>
<p>Thanks for the suggestions, but I want to avoid wchar. Since this app deals with strings in UTF-8 exclusively, using wchar would then require me to convert all strings back into UTF-8 which should be unnecessary. All input, output and internal processing is in UTF-8. It is a simple app that works fine as is on Linux and when compiled with VC2003. I want to be able to compile the same app with VC2008 and have it work. </p>
<p>For this to happen, I need VC2008 to not try to convert it to my local machine's locale (Japanese, 932). I want VC2008 to be backward compatible with VC2003. I want a locale or compiler setting that says strings are used as is, essentially as opaque arrays of char, or as UTF-8. It looks like I might be stuck with VC2003 and gcc though, VC2008 is trying to be too smart in this instance.</p>
| <p>Update:</p>
<p>I've decided that there is no guaranteed way to do this. The solution that I present below works for English version VC2003, but fails when compiling with Japanese version VC2003 (or perhaps it is Japanese OS). In any case, it cannot be depended on to work. Note that even declaring everything as L"" strings didn't work (and is painful in gcc as described below). </p>
<p>Instead I believe that you just need to bite the bullet and move all text into a data file and load it from there. I am now storing and accessing the text in INI files via <a href="http://code.jellycan.com/simpleini/">SimpleIni</a> (cross-platform INI-file library). At least there is a guarantee that it works as all text is out of the program.</p>
<p>Original:</p>
<p>I'm answering this myself since only Evan appeared to understand the problem. The answers regarding what Unicode is and how to use wchar_t are not relevant for this problem as this is not about internationalization, nor a misunderstanding of Unicode, character encodings. I appreciate your attempt to help though, apologies if I wasn't clear enough.</p>
<p>The problem is that I have source files that need to be cross-compiled under a variety of platforms and compilers. The program does UTF-8 processing. It doesn't care about any other encodings. I want to have string literals in UTF-8 like currently works with gcc and vc2003. How do I do it with VC2008? (i.e. backward compatible solution). </p>
<p>This is what I have found:</p>
<p>gcc (v4.3.2 20081105):</p>
<ul>
<li>string literals are used as is (raw strings)</li>
<li>supports UTF-8 encoded source files</li>
<li>source files must not have a UTF-8 BOM</li>
</ul>
<p>vc2003:</p>
<ul>
<li>string literals are used as is (raw strings)</li>
<li>supports UTF-8 encoded source files</li>
<li>source files may or may not have a UTF-8 BOM (it doesn't matter)</li>
</ul>
<p>vc2005+:</p>
<ul>
<li>string literals are massaged by the compiler (no raw strings)</li>
<li>char string literals are re-encoded to a specified locale</li>
<li>UTF-8 is not supported as a target locale</li>
<li>source files must have a UTF-8 BOM</li>
</ul>
<p>So, the simple answer is that for this particular purpose, VC2005+ is broken and does not supply a backward compatible compile path. The only way to get Unicode strings into the compiled program is via UTF-8 + BOM + wchar which means that I need to convert all strings back to UTF-8 at time of use.</p>
<p>There isn't any simple cross-platform method of converting wchar to UTF-8, for instance, what size and encoding is the wchar in? On Windows, UTF-16. On other platforms? It varies. See the <a href="http://icu-project.org/docs/papers/unicode%5Fwchar%5Ft.html">ICU project</a> for some details.</p>
<p>In the end I decided that I will avoid the conversion cost on all compilers other than vc2005+ with source like the following. </p>
<pre><code>#if defined(_MSC_VER) && _MSC_VER > 1310
// Visual C++ 2005 and later require the source files in UTF-8, and all strings
// to be encoded as wchar_t otherwise the strings will be converted into the
// local multibyte encoding and cause errors. To use a wchar_t as UTF-8, these
// strings then need to be convert back to UTF-8. This function is just a rough
// example of how to do this.
# define utf8(str) ConvertToUTF8(L##str)
const char * ConvertToUTF8(const wchar_t * pStr) {
static char szBuf[1024];
WideCharToMultiByte(CP_UTF8, 0, pStr, -1, szBuf, sizeof(szBuf), NULL, NULL);
return szBuf;
}
#else
// Visual C++ 2003 and gcc will use the string literals as is, so the files
// should be saved as UTF-8. gcc requires the files to not have a UTF-8 BOM.
# define utf8(str) str
#endif
</code></pre>
<p>Note that this code is just a simplified example. Production use would need to clean it up in a variety of ways (thread-safety, error checking, buffer size checks, etc).</p>
<p>This is used like the following code. It compiles cleanly and works correctly in my tests on gcc, vc2003, and vc2008:</p>
<pre><code>std::string mText;
mText = utf8("Chinese (Traditional)");
mText = utf8("ä¸å½èª (ç¹ä½)");
mText = utf8("ì¤êµì´ (ë²ì²´)");
mText = utf8("Chinês (Tradicional)");
</code></pre>
|
Changing a string <p>I am using Linux GCC c99.</p>
<p>I am wondering what would be the best technique. To change a string. I am using strstr();</p>
<p>I have a filename called "file.vce" and I want to change the extension to "file.wav".</p>
<p>Is this the best method:</p>
<pre><code>char file_name[80] = "filename.vce";
char *new_file_name = NULL;
new_file_name = strstr(file_name, "vce");
strncpy(new_file_name, "wav", 3);
printf("new file name: %s\n", new_file_name);
printf("file name: %s\n", file_name);
</code></pre>
<p>Many thanks for any advice,</p>
<hr>
<p>I have edited my answer using using your suggestions. Can you see anything else wrong?</p>
<pre><code>/** Replace the file extension .vce with .wav */
void replace_file_extension(char *file_name)
{
char *p_extension;
/** Find the extension .vce */
p_extension = strrchr(file_name, '.');
if(p_extension)
{
strcpy(++p_extension, "wav");
}
else
{
/** Filename did not have the .vce extension */
/** Display debug information */
}
}
int main(void)
{
char filename[80] = "filename.vce";
replace_file_extension(filename);
printf("filename: %s\n", filename);
return 0;
}
</code></pre>
| <p>There are a few problems with:</p>
<pre><code>char file_name[80] = "filename.vce";
char *new_file_name = NULL;
new_file_name = strstr(file_name, "vce");
strncpy(new_file_name, "wav", 3);
printf("new file name: %s\n", new_file_name);
printf("file name: %s\n", file_name);
</code></pre>
<p>There is only storage for one string, but at the end you attempt to print two different strings.</p>
<p>The variable named <code>new_file_name</code> actually points to part of the same filename.</p>
<p>The string vce might occur anywhere within a filename, not just an the extension. What if the filename was <code>srvce.vce</code>?</p>
<p>You probably want to find the last . character in the string, then check whether it is followed by the expected extension, and then replace that extension. And remember that if you do this by modifying the original buffer, you will not be able to print the old string afterwards.</p>
|
Reading metadata from images in WPF <p>I'm aware that WPF allows you to use images that require WIC codecs to view (for the sake of argument, say a digital camera RAW file); however I can only see that it lets you show the image natively, but I can't see anyway of getting at the meta-data (for example, the exposure time).</p>
<p>It obviously can be done, as Windows Explorer shows it, but is this exposed through the .net API or do you reckon that it is just down to calling the native COM interfaces</p>
| <p>Check out my <a href="http://intuipic.codeplex.com/SourceControl/changeset/view/7348#114514">Intuipic</a> project. In particular, the <a href="http://intuipic.codeplex.com/SourceControl/changeset/view/7348#114514">BitmapOrientationConverter</a> class, which reads metadata to determine the image's orientation:</p>
<pre><code>using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
BitmapFrame bitmapFrame = BitmapFrame.Create(fileStream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
BitmapMetadata bitmapMetadata = bitmapFrame.Metadata as BitmapMetadata;
if ((bitmapMetadata != null) && (bitmapMetadata.ContainsQuery(_orientationQuery)))
{
object o = bitmapMetadata.GetQuery(_orientationQuery);
if (o != null)
{
//refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values
switch ((ushort) o)
{
case 6:
return 90D;
case 3:
return 180D;
case 8:
return 270D;
}
}
}
}
</code></pre>
|
How to organize views and controllers hierarchically when having model with many children <p>Lets say I've a website that lists Persons, and each Person has multiple properties, some one-to-one (name, address), some one-to-many (favorite colors, bank-accounts etc).</p>
<p>In my business layer it's nicely hierarchically organized. </p>
<p>How do I organize this is my controllers and views?
Should I have a PersonsController, FavoriteColorsController etc? all residing in the same namespace and folder? Or should I have ony a PersonsController with many actions, such as IndexFavouriteColors, UpdateFavoriteColor etc. Both of the options are not quite it. The first one doesn't show that FavoriteColors is a child of Person and can only be used in the context of a person. The second one will create a huge PersonController.</p>
<p>The same thing with the views of course. The nicest would be to have</p>
<ul>
<li>Views/Persons/index.aspx</li>
<li>Views/Persons/details.aspx </li>
<li>Views/Persons/ etc.</li>
<li>Views/Persons/FavoriteColors/index.aspx </li>
<li>Views/Persons/FavoriteColors/details.aspx</li>
</ul>
<p>In this example I gave only a few one-to-many properties to the Person, but actually there are many (10+), so that increases the need for clarity.</p>
<p>Thanks.</p>
| <p>Actually I found the answer in "Areas", which is supposedly supported by Rails, but not by MVC, though there are private implementations:</p>
<p><a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" rel="nofollow">Grouping Controllers with ASP.NET MVC</a><br />
<a href="http://devlicio.us/blogs/billy%5Fmccafferty/archive/2009/01/22/mvc-quot-areas-quot-as-hierarchical-subfolders-under-views.aspx" rel="nofollow">Creating MVC "Areas" as Subfolders under Views </a></p>
|
Hosting multiple endpoints under WAS <p>Is it possible to host a service with multiple binding endpoints under WAS. For example a service with tow TCP endpoints and tow message queue endpoints?</p>
<p>Is that possible?</p>
| <p>Sure, no problem. The only rule is: you cannot have two endpoints with the same address and protocol, e.g. you cannot have two HTTP endpoint on localhost:8000.</p>
<p>Marc</p>
|
how to Play .flv files in WPF? <p>How to Play .flv files in WPF? please anyone help me out.</p>
| <pre><code>// Create the interop host control.
var host = new WindowsFormsHost();
// Create the ActiveX control.
var axShockwaveFlash = new AxShockwaveFlash();
// Assign the ActiveX control as the host control's child.
host.Child = axShockwaveFlash;
// Add the interop host control to the Grid
// control's collection of child controls.
this.MainGrid.Children.Add(host);
axShockwaveFlash.Location = new System.Drawing.Point(0, 0);
axShockwaveFlash.LoadMovie(0, @"C:\player.swf");
axShockwaveFlash.SetVariable("quality", "Low");
axShockwaveFlash.ScaleMode = 0;
axShockwaveFlash.AllowScriptAccess = "always";
//axShockwaveFlash.FlashVars = @"file=C:\barsandtone.flv" +
//&autostart=true&fullscreen=true&controlbar=none&repeat=" +
//"always&stretching=fill";
axShockwaveFlash.CallFunction("<invoke name=\"loadFLV\" " +
"returntype=\"xml\"><arguments><string>barsandtone.flv</string>" +
"</arguments></invoke>");
axShockwaveFlash.Play();
</code></pre>
<p><strong>Reference</strong>:</p>
<ul>
<li><a href="http://www.infosysblogs.com/microsoft/2008/07/hosting%5Fflash%5Fmovie%5Fin%5Fa%5Fwpf%5Fp.html" rel="nofollow">Hosting Flash movie in a WPF project</a></li>
<li><a href="http://www.infosysblogs.com/microsoft/2008/08/hosting%5Fflash%5Fmovie%5Fin%5Fwpf%5Fpar.html" rel="nofollow">Hosting Flash Movie in WPF (Part 2)</a>: Some âStrictly Microsoft Technology Pleaseâ options</li>
</ul>
|
How to do silverlight 3 blur effect in code behind? <p>The blur effect in silverlight 3 is nice:</p>
<pre><code><StackPanel HorizontalAlignment="Left">
<Button x:Name="Button1"
Content="Click This"
Click="Button1_Click">
<Button.Effect>
<BlurEffect Radius="2"/>
</Button.Effect>
</Button>
</StackPanel>
</code></pre>
<p>But how would I do it in code behind:</p>
<pre><code>private void Button1_Click(object sender, RoutedEventArgs e)
{
Button1.Content = "was clicked";
//Button1.Effect.bl...
}
</code></pre>
| <p>Silverlight 3 only</p>
<pre><code>private void Button1_Click(object sender, RoutedEventArgs e)
{
((Button)sender).Content = "was clicked";
((Button)sender).Effect = new BlurEffect { Radius = 8 };
}
</code></pre>
|
CAPICOM - Verify SignedCode is from a Trusted Publisher without UI <p>I'm using CAPICOM in a .NET 3.0 C# app to check an Authenticode signature on an exe file. I need to make sure that the certificate is listed as a Trusted Publisher. Using <code>signedCode.Verify(true)</code> will show a dialog if the certificate is not already trusted, so the user can choose whether or not to do so. However, <code>signedCode.Verify(false)</code> is verifying the signature even if it is not from a trusted publisher - presumably this is only checking that the certificate is valid.</p>
<p>How can I check that the signature on a file is from a valid and trusted certificate without the UI?</p>
| <p>First, <strong>StrongNameSignatureVerificationEx</strong> is for assembly signature verification and not Authenticode signature verification. So, this is not relevant to the context of original poster's question.</p>
<p>Concerning the initial question, you can manually check that the signer certificate is correctly chained to a trusted root without any GUI by using the following code : </p>
<pre><code>ICertificateStatus certStatus = signedCode.Signer.Certificate.IsValid();
</code></pre>
<p>The idea is to retrieve the signer's certificate and to tell CAPICom to check if it has a correct trust chain.</p>
<p>I hope this will help.
Cheers,</p>
<p>Mounir IDRASSI, IDRIX, <a href="http://www.idrix.fr" rel="nofollow">http://www.idrix.fr</a></p>
|
Find the foreground thread from the background thread <p>When you are in the context of the background thread.</p>
<pre><code>Thread.IsBackground == true
</code></pre>
<p>There is a way to find the foreground thread calling this background thread ?</p>
<p>Thanks for your help</p>
<p>Update: The thread created are background and handled by a threadpool (Inside the Workflow Foundation Runtime). I have no way to add the reference from the main thread inside each background thread. There is no way to find that foreground thread from the threadpool ?</p>
| <p>There's no such relationship. <em>Any</em> thread can create a new thread, including another background thread. After the new thread has been created, there's no relationship between the creating thread and the new thread. If you need to know which thread created the new thread, you'll need to pass that information in the <code>ThreadStart</code>.</p>
<p>EDIT: For thread-pool threads, by the time any of your code is running I assume it's been specified by you as a task somewhere, in some way. If you need some information to be available (whether that's a thread ID or anything else) you need to put it in the context for that task.</p>
|
Best way to programmatically configure network adapters in .NET <p>I have an application written in C# that needs to be able to configure the network adapters in Windows. I have this basically working through WMI, but there are a couple of things I don't like about that solution: sometimes the settings don't seem to stick, and when the network cable is not plugged in, errors are returned from the WMI methods, so I can't tell if they really succeeded or not.</p>
<p>I need to be able to configure all of the settings available through the network connections - Properties - TCP/IP screens.</p>
<p>What's the best way to do this?</p>
| <p>You could use <code>Process</code> to fire off <a href="http://support.microsoft.com/kb/242468">netsh</a> commands to set all the properties in the network dialogs.</p>
<p>eg:
To set a static ipaddress on an adapter </p>
<pre><code>netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.1 1
</code></pre>
<p>To set it to dhcp you'd use</p>
<pre><code>netsh interface ip set address "Local Area Connection" dhcp
</code></pre>
<p>To do it from C# would be</p>
<pre><code>Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1");
p.StartInfo = psi;
p.Start();
</code></pre>
<p>Setting to static can take a good couple of seconds to complete so if you need to, make sure you wait for the process to exit.</p>
|
How is the upcoming 'dynamic' keyword in .net 4.0 going to make my life better? <p>I don't quite get what it's going to let me do (or get away with :)</p>
| <p>From Charlie Calvert's blog:</p>
<blockquote>
<p>Useful Scenarios</p>
<p>There are three primary scenarios that will be enabled by the new support for dynamic lookup:</p>
<ol>
<li>Office automation and other COM Interop scenarios</li>
<li>Consuming types written in dynamic languages</li>
<li>Enhanced support for reflection</li>
</ol>
</blockquote>
<p>Read more here: <a href="http://blogs.msdn.com/charlie/archive/2008/01/25/future-focus.aspx" rel="nofollow">http://blogs.msdn.com/charlie/archive/2008/01/25/future-focus.aspx</a></p>
|
Problem with IE7 JQuery, Ajax and CSS <p>In a simple web page I load some new HTML into a <strong>div</strong> using <em>load(url)</em>
Works fine in most browsers but, surprise, surprise, IE7 behaves differently.
All the other browsers apply the pages CSS styles to the newly loaded HTML but IE7 doesn't.</p>
<p>Any ideas?</p>
<p>Ken</p>
<p><hr /></p>
<p><strong>Update</strong>
The new HTML is just a code fragment, e.g.</p>
<pre><code><div class="classname">
blah blah blah
</div>
</code></pre>
<p><hr /></p>
<p><strong>Update</strong> I think I'm calling it OK.
This isn't what I'm actually doing but a simplified version which reproduces the problem ...</p>
<pre><code>.
.
.
google.load("jquery", "1.3.2");
google.setOnLoadCallback(function() {
$(document).ready(function() {
$("#nav-home").click(function() {
$("#girc-content").load("home.html");
});
.
.
.
</code></pre>
<p><strong>Update</strong> On further investigation the problem appears to be slightly more odd than I thought. </p>
<p>I tried Steerpike's suggestion because I originally thought the problem was that the CSS styles were not being applied.</p>
<p>However, it now appears that only some of the styles are being applied.
For example, the text color attribute for the <code><h2></code> tag is applied, but the width attribute for the <code><div></code> tag is not.</p>
| <p>In light of extra information, take 2...</p>
<p>Are the styles not being applied in the master HTML page or the page you're loading? If they're in the page you're loading it seems that IE strips out script and style tags from XMLHttpRequest objects.</p>
<p>Given that it's not that and I'm intrigued I constructed a sample:</p>
<pre><code><html>
<head>
<title>test</title>
<style type="text/css">
#girc-content { border: 1px solid black; width: 100px }
h3 { color: red; }
</style>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.setOnLoadCallback(function() {
$(document).ready(function() {
$("#nav-home").click(function() {
$("#girc-content").load("test2.html");
});
});
});
</script>
</head>
<body>
<div id="girc-content">
blah blah blah
</div>
<input type="button" value="click me" id="nav-home">
</body>
</html>
</code></pre>
<p>and test2.html:</p>
<pre><code><html>
<head>
</head>
<body>
<h3>This is a test</h3>
</body>
</html>
</code></pre>
<p>This works perfectly for me in IE8 standards and compatibility mode (sorry no IE7 any more).</p>
<p>I did notice when I copied your google onload snippet that you were missing some closing braces/parentheses. Was this just a cut and paste error or a problem with your Javascript? It might explain the inconsistent behaviour.</p>
|
.Net Hosting (Flexible Medium Trust) <p>Any recommendations for cheap .Net hosting that has flexible medium trust rules allowing the use of reflection?</p>
| <ul>
<li><strong><a href="http://www.godaddy.com" rel="nofollow">GoDaddy Hosting</a></strong> (<a href="http://www.bizshark.com/company/godaddy.com" rel="nofollow">info</a>) - Really cheap, $5/month. And the most popular.</li>
<li><strong><a href="http://www.discountasp.net" rel="nofollow">DiscountASP.NET</a></strong> (<a href="http://www.bizshark.com/company/discountasp.net" rel="nofollow">info</a>) - More expansive, starting from $10/month+. The good thing is that they are specializing on .NET</li>
<li><strong><a href="http://www.softsyshosting.com/" rel="nofollow">SoftSys Hosting</a></strong> - Small company. But they are more flexible. They are also specializing in Windows Hosting solutions.</li>
</ul>
|
Money Denominations <p>I have payroll database, on my payroll payslip i would like to make money denominations for the salary of each employee, I.e if an employe has got 759 Dollar then the cashier wil withdraw 7 one hundreds ,1 Fifty Dolar, 9 ten dollars from a banck
please give me a code in vb.net</p>
<p>Salary hundred Fifty ten</p>
<p>759 7 1 9</p>
<p>Please help me thans a lot</p>
| <p><strong>Duplicate</strong>:</p>
<p><a href="http://stackoverflow.com/questions/554314/how-can-i-convert-an-integer-into-its-verbal-representation">How can I convert an integer into its verbal representation</a>?</p>
<p><a href="http://stackoverflow.com/questions/666432/how-can-i-display-money-amounts-in-word-form-closed">How can I display money amounts in word form?</a></p>
<p><a href="http://stackoverflow.com/questions/621062/python-function-find-change-from-purchase-amount/621118">Python function: Find Change from purchase amount</a></p>
|
Java Collections copy list - I don't understand <p>I have an <code>ArrayList</code> and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the <code>Collections</code> class which contains a copy method.</p>
<p>Suppose I have the following:</p>
<pre><code>List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
List<String> b = new ArrayList<String>(a.size());
Collections.copy(b,a);
</code></pre>
<p>This fails because basically it thinks <code>b</code> isn't big enough to hold <code>a</code>. Yes I know <code>b</code> has size 0, but it should be big enough now shouldn't it? If I have to fill <code>b</code> first, then <code>Collections.copy()</code> becomes a completely useless function in my mind. So, except for programming a copy function (which I'm going to do now) is there a proper way to do this?</p>
| <p><code>b</code> has a <em>capacity</em> of 3, but a <em>size</em> of 0. The fact that <code>ArrayList</code> has some sort of buffer capacity is an implementation detail - it's not part of the <code>List</code> interface, so <code>Collections.copy(List, List)</code> doesn't use it. It would be ugly for it to special-case <code>ArrayList</code>.</p>
<p>As MrWiggles has indicated, using the ArrayList constructor which takes a collection is the way to in the example provided.</p>
<p>For more complicated scenarios (which may well include your real code), you may find the <a href="http://code.google.com/p/google-collections/">Google Java Collections library</a> useful.</p>
|
Is there Cache with Linq query support <p>Is there Cache preferably a distributed cache with Linq query support?</p>
| <p>I am not aware of any yet but Velocity will support Linq. I'm not sure if they are going to support it at ctp3 that launches any day now or at v1.</p>
<p><a href="http://weblogs.asp.net/rchartier/archive/2009/03/13/microsoft-velocity-q-amp-a.aspx" rel="nofollow">http://weblogs.asp.net/rchartier/archive/2009/03/13/microsoft-velocity-q-amp-a.aspx</a></p>
|
Java ConcurentMap keySet() question when map is modified and iterating over keyset <p>Quick background I have a concurrent map I used to cache some values that change quite often (still worth caching them from testing). I want to evict items from my cache at regular intervals by examining an expire time in the value. I am using the keySet() method to get a reference to all my keys and then check the values and if expired i remove them. In other threads the cache is being queried and updated(removed) constantly. </p>
<p>From the javadocs for keySet() it mentioned if the map changes while I am iterating over the keyset Set the results are undefined. Obviously I would like a defined way of dealing with this so the results are valid. Would it be enough to pass the Set to a HashSet and then iterate over this set as it is my understanding this set will not be backed by the map, is this a wasteful of memory way of doing it? Any ideas appreciated.</p>
<p>Unfortunately my evictor is not the only way for items to be removed from the concurrent map so am I correct in saying that I need to copy the keySet to another Set before iterating through it.</p>
<p>Thanks in advance</p>
<p>EDIT: It turns out I was reading the javadocs for the Map keySet() method instead of the ConcurrentMap keySet(). Thanks my bad :)</p>
<blockquote>
<p>Returns a set view of the keys
contained in this map. The set is
backed by the map, so changes to the
map are reflected in the set, and
vice-versa. If the map is modified
while an iteration over the set is in
progress (except through the
iterator's own remove operation), the
results of the iteration are
undefined. The set supports element
removal, which removes the
corresponding mapping from the map,
via the Iterator.remove, Set.remove,
removeAll retainAll, and clear
operations. It does not support the
add or addAll operations.</p>
</blockquote>
| <p>Are you using <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html">the Java Concurrent HashMap</a> ? From the keySet() documentation it appears to behave in a fashion which you'd find useful.</p>
<blockquote>
<p>Returns a set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. The set supports element removal, which removes the corresponding mapping from this map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. The view's returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction. </p>
</blockquote>
<p>i.e. you can remove stuff and you should be fine.</p>
<p>If you're not using this implementation, then which are you using (and why ? Not being funny, but it would be interesting to know why you've made that choice)</p>
|
Delphi silently cropping string literals <p>Delphi 2009 Win32.</p>
<p>The code below tries to add a 257 length string to a memo.
It compiles and runs fine, but nothing is added to the memo.</p>
<pre><code>Memo1.Lines.Add('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
</code></pre>
<p>Looks like a compiler bug. Is it? Because if the string was 256 long, I'd get a compiler error and couldn't compile the app.</p>
<p>Any way to make the app break when the developer tries to do something like this?</p>
<p>I know I could split the string and make this code work, but my point is to prevent developers for using this invalid code without noticing.</p>
<p>Thanks</p>
| <p>This is a Delphi 2009 bug with string literals, it should raise the same error as D2007.</p>
<p>Try latest version of Andreas IDE Fix pack, its supose to fix this bug.
<a href="http://andy.jgknet.de/blog/?page_id=246" rel="nofollow">http://andy.jgknet.de/blog/?page_id=246</a></p>
|
Programatically insert ActiveX Control into Word Document using VBA? <p>is it possible? I couldn't find any code that does that. </p>
| <p>When I want to write a macro (=VBA) in Office, I just start by recording a macro, and then do what you want to do manually.</p>
<p>The recorded macro will help you on your way.</p>
<p>This is what I ended up with:</p>
<pre><code>Sub Macro1()
'
' Macro1 Macro
'
'
Selection.InlineShapes.AddOLEObject ClassType:="WordPad.Document.1", _
FileName:="", LinkToFile:=False, DisplayAsIcon:=False
End Sub
</code></pre>
<p>Answer is: use the <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.shapes.addoleobject%28VS.80%29.aspx" rel="nofollow">AddOLEObject</a> method</p>
|
Building Python PIL for JPEG looks okay, but fails the selftest <p>I'm on Fedora Core 6 (64 bit)</p>
<p>after "yum install libjpeg-devel" I have downloaded and built PIL. It gives the message:</p>
<p>--- JPEG support ok</p>
<p>Looks like JPEG built okay, but when running selftest.py:</p>
<p>IOError: decoder jpeg not available</p>
<p>Why would it appear to have built correctly, but fail the selftest?</p>
| <p>You probably need more packages. Install <code>libjpeg</code> which includes <code>/usr/lib/libjpeg.so*</code> and try again.</p>
<p>On my Fedora (another version), PIL is installed with the <code>python-imaging</code> rpm :</p>
<pre><code>ldd _imaging.so
linux-gate.so.1 => (0x004c6000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x00a07000)
libz.so.1 => /lib/libz.so.1 (0x00b91000)
libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0x00110000)
libpthread.so.0 => /lib/libpthread.so.0 (0x00ee8000)
libc.so.6 => /lib/libc.so.6 (0x00260000)
libdl.so.2 => /lib/libdl.so.2 (0x003c9000)
libutil.so.1 => /lib/libutil.so.1 (0x00fcd000)
libm.so.6 => /lib/libm.so.6 (0x00ad1000)
/lib/ld-linux.so.2 (0x007a1000)
</code></pre>
<p>Which means PIL needs <code>libjpeg.so</code>.</p>
|
How to execute an Installshield Custom action while Rollback? <p>I have an InstallShield installer which does some stuff. In case the installation breaks the rollback sequence gets started. I do know that I can create conditions for my custom actions in order to make it run only during install or uninstall, but which condition do I set to make it run on rollback? </p>
<p>To be precisely I need rollback and remove. At the moment I have already set REMOVE which works perfectly on uninstall.</p>
| <p>Rollback is not detected through conditions. Instead set the in-script execution of the custom action to one of the rollback options. This action will then run only during a rollback that occurs after the sequence at which it was scheduled, and only if its condition was true at that point in the sequence.</p>
|
Handling desktop position, font and other win32 console parameters <p>Is it possible to programmatically set such windows console parameters as its left-top desktop position, console font, fast insert and selection by mouse options, etc.?</p>
<p>Unfortunately we can set some console parameters by invoking undocumented Windows API. For example: <code>SetConsoleFont</code>, <code>GetConsoleFontInfo</code>, <code>GetNumberOfConsoleFonts</code> from <code>KERNEL32.DLL</code>.</p>
| <p>In order to reposition the console you need to update the underlying HWND. You can use the GetConsoleWindow() function to get a handle to the HWND. From there you can call GetWindowInfo, SetWindowINfo and the like to update it's postition and size</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms683175%28VS.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms683175(VS.85).aspx</a></p>
<p><strong>EDIT</strong> The below is actually for updating the buffer.</p>
<p>I believe you are looking for the SetConsoleWindowInfo function. This will allow you to control positioning of the Console Window. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms686125%28VS.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms686125(VS.85).aspx</a></p>
|
Hashtable with MultiDimensional Key in C# <p>I'm basically looking for a way to access a hashtable value using a two-dimensional typed key in c#.</p>
<p>Eventually I would be able to do something like this </p>
<pre><code>HashTable[1][false] = 5;
int a = HashTable[1][false];
//a = 5
</code></pre>
<p>This is what I've been trying...hasn't worked</p>
<pre><code>Hashtable test = new Hashtable();
test.Add(new Dictionary<int, bool>() { { 1, true } }, 555);
Dictionary<int, bool> temp = new Dictionary<int, bool>() {{1, true}};
string testz = test[temp].ToString();
</code></pre>
| <p>I think a better approach is to encapsulate the many fields of your multi-dimensional key into a class / struct. For example</p>
<pre><code>struct Key {
public readonly int Dimension1;
public readonly bool Dimension2;
public Key(int p1, bool p2) {
Dimension1 = p1;
Dimension2 = p2;
}
// Equals and GetHashCode ommitted
}
</code></pre>
<p>Now you can create and use a normal HashTable and use this wrapper as a Key.</p>
|
Post code API Lookup <p>Has anyone had experience with the post code anywhere lookup API. The service appears to be a bargain - through experience - when something is too good to be true it often is. </p>
<p>I have reservations about the countries that are being offered, there seem to be some missing. </p>
<p>Has anyone had any good experiences with post code lookup API providers that could assist me in choosing a reliable and good source?</p>
<p>I should specify</p>
<p>The data I am after is for the whole of europe.</p>
<p>The issue with google seems to be the accuracy of the postcode and being able to return a matching address. Although its free...</p>
| <p>If you're going to make less than 5,000 requests per day, the <a href="http://developer.yahoo.com/maps/rest/V1/geocode.html">YAHOO Geocoding API</a> might be suitable for you.</p>
<p>Though not made clear in that page, you can get accurate UK data by requesting URLs like </p>
<p><a href="http://local.yahooapis.com/MapsService/V1/geocode?appid=YD-9G7bey8%5FJXxQP6rxl.fBFGgCdNjoDMACQA--&zip=N1%203DJ">http://local.yahooapis.com/MapsService/V1/geocode?appid=YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--&zip=N1%203DJ</a></p>
|
Specific rights to GRANT, REVOKE or DENY on stored procedures <p>On a SQL Server 2008 database I want to give a user the rights to GRANT, REVOKE and DENY on objects only of type stored procedure (not using the db_securityadmin database role). How can i do this? Thanks!</p>
<p>Sandor</p>
| <p>Wrap the GRANT/REVOKE/DENY via another stored proc that:</p>
<ul>
<li>Has EXECUTE AS OWNER (or user if different schema) to avoid direct rights for the user</li>
<li>Checks the target object in a stored proc</li>
<li>Checks the user is allowed or a member of a certain role etc</li>
</ul>
<p>Otherwise, there is no way to separate permissions per object type</p>
|
Delete an image bound to a control <p>I am writing an Image Manager WPF application. I have a ListBox with the following ItemsTemplate:</p>
<pre><code> <Grid x:Name="grid" Width="150" Height="150" Background="{x:Null}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="27.45"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Border Margin="5,5,5,5.745" Grid.RowSpan="2" Background="#FF828282" BorderBrush="{DynamicResource ListBorder}" CornerRadius="5,5,5,5" BorderThickness="1,1,2,2" x:Name="border">
<Grid>
<Viewbox Margin="0,0,0,21.705">
<Image Width="Auto" Height="Auto" x:Name="picture" Source="{Binding Path=FullName}" />
</Viewbox>
<TextBlock Height="Auto" Text="{Binding Path=Name}" TextWrapping="Wrap" x:Name="PictureText" HorizontalAlignment="Left" Margin="70,0,0,0" VerticalAlignment="Bottom" />
</Grid>
</Border>
</Grid>
</code></pre>
<p>Note that the "Image" control is bound to the "FullName" property, which is a string representing the absolute path to a JPG.</p>
<p>Several application features require that I alter the JPG file (move, rename, or delete). When I try to do so (currently trying to Move the file) I receive an IOException: "The process cannot access the file because it is being used by another process." The process locking the file is my WPF application.</p>
<p>I did some searching online and found several postings indicating that Images in particular have trouble letting go of their resources. I have tried the following:</p>
<ol>
<li>Setting the ListBox.Source to null</li>
<li>Adding a 10 second wait time before
attempting the move.</li>
<li>Issuing GC.Collect().</li>
<li>Moving the operation to a different
thread.</li>
</ol>
<p>What else can I try? I thought about finding a reference to the Image object in the ItemsTemplate and trying to dispose of the Image, but I can't figure out how to get the reference.</p>
<p>One possible solution I read about was to create copies of the Images rather than the actual images, but since the Binding is to the filename and not the actual Image I don't know if I could make this work.</p>
<p>Any help or suggestions would be most appreciated.</p>
| <p>My <a href="http://intuipic.codeplex.com" rel="nofollow">Intuipic</a> application allows users to delete images, too. I had to write <a href="http://intuipic.codeplex.com/SourceControl/changeset/view/7348#114513" rel="nofollow">this converter</a> to achieve it. Relevant code:</p>
<pre><code>//create new stream and create bitmap frame
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read);
bitmapImage.DecodePixelWidth = (int) _decodePixelWidth;
bitmapImage.DecodePixelHeight = (int) _decodePixelHeight;
//load the image now so we can immediately dispose of the stream
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
//clean up the stream to avoid file access exceptions when attempting to delete images
bitmapImage.StreamSource.Dispose();
</code></pre>
|
Using C# to automate functions and movement between two different browser applications? <p>I'm a newb. So forgive me if I'm vague or not specific enough to be helpful, please let me know so I can clarify. </p>
<p>I use 2 different applications for work and would be interested in a little tool to automate some of the functions.
1. IP Based phone system we use.
We have to copy and paste numbers from one web browser (always located in same field, text area)
And select several buttons
2. Mortgage Application terminal run through web browser. </p>
<p>I would like to click a button, have it copy text (ie the number) from the field in the mortgage servicing application, then paste that info to the textbox on the other browser that is our phone system and select from several different radio buttons, hit the next button and then it will dial. </p>
<p>We have SUCH a slow system, with too many clicks to i'm hoping this would be feasible without super advanced programming knowledge. Tips?</p>
<p>One script that I've reviewed from VBScript shows excerpts... (i've done mild VBA, but not a Vbscript master! ) </p>
<p>Is this possible, or am I stuck to clicking everything individually?</p>
<pre><code>Dim at99999Tool, atlDirectorObject
Dim strErrMsg
Dim strScreenName
Dim strLoanNumber
Const S_OK=0
Const DELAY=60
Const QUOTES = """"
subGetSession
strScreenName=Wscript.Arguments(0)
strLoanNumber=Wscript.Arguments(1)
subGoToScreen strScreenName, "********", strLoanNumber
subTerminateScript 3, ""
more functions etc...
Sub subGetSession()
Set atlDirectorObject = CreateObject("atlDirectorObject.atlDirector")
If atlDirectorObject.CreateTool("9999", 1, True, True, 0, atl3299Tool, strErrMsg) <> S_OK Then
subTerminateScript 2, strErrMsg
End If
End Sub
</code></pre>
| <p>Check out this article about using PowerShell for Web interface automation.</p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc337896.aspx?pr=blog" rel="nofollow">MSDN Magazine: Web UI Automation with Windows PowerShell</a></p>
|
Limit an html form input to a certain float range <p>Is there a way to limit a form input field to be between certain number range, say (0,100)</p>
<p>I'm filtering the input in the onkeydown event, to accept only numbers, the problem
is I want to reject a number if that number would make the input to go out of range</p>
<p>So I need a way to see if the current value of the input plus the key the user is pressing
will sum up between the range.</p>
<p>I tried using:</p>
<pre><code>if((parseFloat(this.value) + parseFloat(String.fromCharCode(e.keyCode)) > 100){
return false;
}
</code></pre>
<p>the thing is e.keyCode can return different codes for the same number, right now is returning 57 for the
number 9, but 105 if i press the number on the numpad.</p>
<p>Is there a way to accomplish this?</p>
| <p>Personally, I would just check it when the field loses focus (or when the form is submitted). Popping up errors as the user is typing (or preventing their keystrokes from registering in the field) is usually just going to annoy them.</p>
<p>And of course you probably knew this already, but make sure you check the value on the server side after the form is submitted as well. Never rely on javascript validation!</p>
|
Virtual PC LAMP Server <p>I have a mirror of a RedHat6 LAMP server setup locally on my development machine (XP pro) for testing.</p>
<p>I am trying to configure it so I can connect to it. However I am having problems.</p>
<p>I've given the image a static IP address of 192.168.1.5. The httpd service is running, and when in RH6 I can view the apache test page by visiting <a href="http://192.168.1.5/" rel="nofollow">http://192.168.1.5/</a>.</p>
<p>I can also successfully ping the virtualpc from the windows cmd line. However when I try to visit the test page from Windows it eventually times out.</p>
<p>I have tried Shared Network, local only and the physical adapter in the VirtualPC settings. Only the physical adaptor will allow me to ping the virtual pc.</p>
<p>What do I need to do to be able to use it successfully as a test server?</p>
<p><strong>NOTE</strong>: I can't replace RH6 with <<em>insert-your-favourite-distro-here</em>>, though if you can demonstrate a benefit switching from VirtualPC then I might do so.</p>
| <p>Maybe you need to open up port 80 through the firewall in RH6. I don't have RH6 running infront of me but I think it's in the menus in System Settings -> Security or something.</p>
|
does this switch statement smell bad? <pre><code>Switch(some case) {
case 1:
// compute something ...
return something;
break;
case 2:
// compute something ...
return something;
break;
/* some more cases ... */
case X:
// compute something ...
return something;
break;
default:
// do something
return something;
break;
}
</code></pre>
<p>In my opinion:</p>
<blockquote>
<p>Assuming this switch statement is justifiable, the return and break just doesnt look right or feel right. </p>
</blockquote>
<p>The break is obviously redundant, but is omission poor style (or is this poor style to begin with?) ?</p>
<p><hr /></p>
<p>I personally dont do this, but there is some of this in the codebase at work. And no, im not going to be self-righteous and correct the codebase.</p>
| <p>No, omission is not poor style - <em>inclusion</em> is poor style. Those are unreachable statements. Get rid of them.</p>
<p>I like the fact that the cases return directly instead of setting a local variable and then returning just at the bottom - it means that it's incredibly clear when you're reading the code that it <em>does</em> just need to return, and that's all.</p>
<p>Side-note in terms of switching in the first place:</p>
<p>As for whether using a switch statement is the right thing to do here, it really depends on other things. Would it make sense to use a polymorphic type instead? If you're in Java, could you use a smart enum? (You can mimic these in C#, but there isn't as much support.)</p>
<p>I'd say this should at least prompt <em>considering</em> different designs - but it may well be the simplest way to do what you want.</p>
|
How to return specific date format as JSON in Grails? <p>In Grails, you can use the JSON converters to do this in the controller:</p>
<pre><code>render Book.list() as JSON
</code></pre>
<p>The render result is</p>
<pre><code>[
{"id":1,
"class":"Book",
"author":"Stephen King",
"releaseDate":'2007-04-06T00:00:00',
"title":"The Shining"}
]
</code></pre>
<p>You can control the output date by make a setting in Config.groovy</p>
<pre><code>grails.converters.json.date = 'javascript' // default or Javascript
</code></pre>
<p>Then the result will be a native javascript date</p>
<pre><code>[
{"id":1,
"class":"Book",
"author":"Stephen King",
"releaseDate":new Date(1194127343161),
"title":"The Shining"}
]
</code></pre>
<p>If I want to get a specific date format like this:</p>
<pre><code>"releaseDate":"06-04-2007"
</code></pre>
<p>I have to use 'collect', which requires a lot of typing:</p>
<pre><code>return Book.list().collect(){
[
id:it.id,
class:it.class,
author:it.author,
releaseDate:new java.text.SimpleDateFormat("dd-MM-yyyy").format(it.releaseDate),
title:it.title
]
} as JSON
</code></pre>
<p>Is there a simpler way to do this?</p>
| <p>There is a simple solution: Since Grails 1.1 the Converters have been rewritten to be more modular. Unfortunately I didn't finish the documentation for that. It allows now to register so called ObjectMarshallers (simple Pogo/Pojo's that implement the <code>org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller</code> interface). </p>
<p>To achieve your desired output, you could register such an ObjectMarshaller in BootStrap.groovy that way:</p>
<pre><code>import grails.converters.JSON;
class BootStrap {
def init = { servletContext ->
JSON.registerObjectMarshaller(Date) {
return it?.format("dd-MM-yyyy")
}
}
def destroy = {
}
}
</code></pre>
<p>There are several other ways to customize the output of the Converters and I'll do my best do catch up with the documentation asap.</p>
|
Add hover image (CSS) to ASP.NET link button in a DataPager <p>I add hover images to .Net LinkButtons using the following method:</p>
<pre><code>.rollover a
{
background-image:url(/images/shoppingcart/butpill_continue.gif);
}
.rollover a:hover
{
background-image:url(/images/shoppingcart/butpill_continue_over.gif);
}
<div class="rollover">
<asp:LinkButton ID="btnContinue" runat="server"></asp:LinkButton>
</div>
</code></pre>
<p>This works fine with regular link buttons. </p>
<p>I need to add this to my next/previous buttons in a DataPager. I tried setting the ButtonType to "Link" and applying the ButtonCssClass="rollover" but this doesn't work. Is there a way to accomplish this?</p>
| <p>Try changing your css to</p>
<pre><code>a.rollover { background-image:url(/images/shoppingcart/butpill_continue.gif); }
a.rollover:hover { background-image:url(/images/shoppingcart/butpill_continue_over.gif); }
</code></pre>
<p>Or just</p>
<pre><code>.rollover { background-image:url(/images/shoppingcart/butpill_continue.gif); }
.rollover:hover { background-image:url(/images/shoppingcart/butpill_continue_over.gif); }
</code></pre>
<p>You'll also have to change your other images to something like this</p>
<pre><code><asp:LinkButton ID="btnContinue" runat="server" CssClass="rollover" />
</code></pre>
|
ATTnnnnn.txt attachments when e-mail is received in Outlook <p>I've written an SMTP client that sends e-mails with attachments. Everything's fine except that when an e-mail sent by my program is received by Outlook it displays two attachments - the file actually sent and a file with two characters CR and LF inside and this file has name ATT?????.txt.</p>
<p>I've done search - found a lot of matches like <a href="http://stackoverflow.com/questions/92196/why-does-my-d2009-exe-produce-emails-with-attachments-named-attnnnnn-dat">this</a> for similar problems and checked everything I could. Even more - I compared two emails - sent by my program and sent by Opera and I can't deduce the difference. However what Opera sends is interpreted correctly, but what my program sends is not. What my program sends is interpreted by a set of other mail clients correctly, but not by Outlook.</p>
<p>I've telnet'et to the SMTP server, retrieved the two emails into a text file - one from my program, another from Opera, and compared them side-by-side. I didn't see any difference that could affect interpretation by an email client.</p>
<p>Here's a sample message (addresses substituted, file contents cropped, blank lines exactly as they appear in real messages, lines never exceed 80 characters):</p>
<pre>
To: user1@host.com, user2@host.com
Subject: subject
Content-Type: multipart/mixed; boundary="------------boundary"
MIME-Version: 1.0
--------------boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64
here goes the Base64 encoded text part - it may be localized, so
it's better to UTF8 it and do Base64
--------------boundary
Content-Disposition: attachment; filename="file.jpg"
Content-Type: application/octet-stream; name="file.jpg"
Content-Transfer-Encoding: base64
here goes the Base64 encoded file data
--------------boundary
</pre>
<p>I tried to play with linebreaks after the last boundary - tried none, one, two, three, but this doesn't improve the situation.</p>
<p>Is there a set of some weird limitations that a mail client must follow to produce messages that are interpreted by Outlook correctly?</p>
| <p>The last boundary of a MIME part must be indicated by appending two dashes:</p>
<pre>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="------------boundary"
--------------boundary
...
--------------boundary
...
--------------boundary--
</pre>
<p>More reading here: <a href="http://www.w3.org/Protocols/rfc1341/7%5F2%5FMultipart.html">RFC1341 / 7.2 The Multipart Content-Type</a></p>
|
C# script in XSLT: "msxsl:script cannot be empty" error <p>I have an XSLT with a C# script in it:</p>
<pre><code><msxsl:script language="C#" implements-prefix="user">
<msxsl:using namespace="System.Xml"/>
<msxsl:using namespace="System.Xml.XPath"/>
<![CDATA[
public string GetMenuPath(XPathNodeIterator node)
{
XPathNavigator dataSourceNode = node.Current;
return dataSourceNode.Name;
}
]]>
</msxsl:script>
</code></pre>
<p>And somewhere in the XSLT this function is called:</p>
<pre><code><xsl:value-of select="user:GetMenuPath(current())"/>
</code></pre>
<p>But as I try to run the XSLT transformation on the XML input (the input does not matter), it stop immediately with the error "msxsl:script cannot be empty".</p>
<p>I have absolutely no idea why... I use nxslt with .NET Framework.</p>
<p>Thank you for help !</p>
| <p>Thank you for your answers, I found out the origin of the problem now. It was because I was using the "style" tag instead of "nxslt" for calling the XSLT transformation. "style" works as long as there is no extension script.</p>
<pre><code><nxslt style="transformation.xsl" in="input.xml" out="output.xls" verbose="true">
</code></pre>
|
How do I Execute SQL Stored Procedures from within another Stored Procedure? <p>Everytime I refresh my DB with a backup file. I have to run about 10 stored procs separately because the backup file does not contain them. </p>
<p>Is there a way to have one single sql script that refrences all these 10 stored procs and just run that ONE file compared to TEN?</p>
| <p>this doesn't check for any errors..</p>
<pre><code>CREATE PROCEDURE RUN_ALL
AS
SET NOCOUNT ON
EXEC YourProcedureA
EXEC YourProcedureB
EXEC YourProcedureC
RETURN 0
GO
</code></pre>
|
calling a Flash ExternalInterface with JavaScript <p>I'm trying to call a function declared with ExternalInterface in a Flash swf, using JavaScript. It worked once, but all of a sudden, it stopped working. </p>
<p>I have a debug version of the Flash Player, but no errors occur in Flash. Not even a "Security Sandbox Error" or something. The only error I get is the following error in JavaScript <code>Error: Error in Actionscript. Use a try/catch block to find error.</code></p>
<p>I'm using AS3, exporting for Flash Player 10 and testing on Firefox 3/Safari 4, on a Mac.</p>
<p>Any assistance would be greatly appreciated.</p>
| <p>Check out <a href="http://livedocs.adobe.com/flex/3/langref/flash/external/ExternalInterface.html#marshallExceptions">ExternalInterface.marshallExceptions</a>. It should allow you to see more details about the error.</p>
|
How to create directory with all rights granted to everyone <p>I need to programatically create a directory that grants "Full Control" to the group "Everyone". If I use</p>
<pre><code>CreateDirectory(path, NULL)
</code></pre>
<p>This will, according to the Win32 SDK <a href="http://msdn.microsoft.com/library/aa363855.aspx">documentation</a> this will create a directory that inherits from its parent directory. I do not want to inherit the access rights of the parent directory I need to ensure that "Everyone" has full control over the directory.</p>
<p>Obviously, this will required setting up the SECURITY_ATTRIBUTES structure with the appropriate security descriptor. How do I do that?</p>
| <p>Here's one technique that seems to work:</p>
<pre><code>SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
PSID everyone_sid = NULL;
AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0, &everyone_sid);
EXPLICIT_ACCESS ea;
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
ea.grfAccessPermissions = SPECIFIC_RIGHTS_ALL | STANDARD_RIGHTS_ALL;
ea.grfAccessMode = SET_ACCESS;
ea.grfInheritance = NO_INHERITANCE;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ea.Trustee.ptstrName = (LPWSTR)everyone_sid;
PACL acl = NULL;
SetEntriesInAcl(1, &ea, NULL, &acl);
PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR,
SECURITY_DESCRIPTOR_MIN_LENGTH);
InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
CreateDirectory(path, &sa);
FreeSid(everyone_sid);
LocalFree(sd);
LocalFree(acl);
</code></pre>
<p>Note that this sample code has absolutely no error checking -- you'll have to supply that yourself.</p>
|
OpenNetCF SDF vs .Net CF 3.5 <p>Going through the documentation of the SDF, i found many classes like the BitmapEx class or the TextBox2 class. I could see their members, but i could not find any text that explained to me why i needed to use them instead of whats given in the .Net CF 3.5</p>
<p>So, what i am requesting is something [a document] or someone to explain how or <strong>why the SDF classes are better than their CF equivalents.</strong> Now, the bitmap and textbox where just examples. It would be preferable if i could know more about the framework itself and how to use it. </p>
<p>Just for background: </p>
<p>I am developing an OCR solution for mobile phones. It does the entire processing and detecting using the cell phone capabilities. The app is able to segment [into characters] a 800x600 area of image with some 7 lines of text in around 80 seconds on a HTC Diamond. I believe i should be able to improve the performance. Right now i have done absolutely no performance optimizations. Am reading lots of articles on optimizations etc... will post some separate questions on those topics as and when i come across something i cant solve... </p>
| <p>The SDF classes aren't designed to be "better" than the CF classes - they are largely an extension of the CF-supplied classes. In many cases they provides methods, properties, etc. that the full framework may have but that the CF omitted. </p>
<p>Obviously that's an over-simplification - for example the entire OpenNETCF.WindowsCE namespace is purely features that don't exist in the FFx or the CF, but as a general answer, that's how it works. </p>
<p>The SDF is not a replacement for the CF, it's an extension of it.</p>
|
Javascript conflict on my html page <p>I have an accordion menu and a lightwindow script on my web page. The lightwindow script does not work because of the accordion script because if I delete the latter the lightwindow script works. There must be a conflict but what?</p>
<p>Here is the head section of my page:</p>
<pre><code><!-- lightwindow files -->
<script type="text/javascript" src="lightwindow/javascript/prototype.js"></script>
<script type="text/javascript" src="lightwindow/javascript/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="lightwindow/javascript/lightwindow.js"></script>
<link rel="stylesheet" href="lightwindow/css/lightwindow.css" type="text/css" media="screen" />
<!-- accordion scripts -->
<script src="js/jquery-1.2.1.min.js" type="text/javascript"></script>
<script src="js/menu.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="css/accordion.css" />
</code></pre>
<p>Thank you for your time.</p>
<p>Cheers</p>
<p>tochiro</p>
| <p>You would need to use the jQuery.noConflict method described at <a href="http://docs.jquery.com/Core/jQuery.noConflict" rel="nofollow">http://docs.jquery.com/Core/jQuery.noConflict</a>.</p>
<p>Not for certain if version 1.2.1 will have it though.</p>
<p>Just read the instructions on that page for how to wire it up.
First thing is that you'll need to put jQuery before the other libraries.</p>
<p>Update: added the code below to help you apply the fix.
If the line jQuery.noConflict() causes an error then you may need to try a newer version of jQuery.</p>
<pre><code><script src="js/jquery-1.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript"> jQuery.noConflict() </script>
<!-- lightwindow files -->
<script type="text/javascript" src="lightwindow/javascript/prototype.js"></script>
<script type="text/javascript" src="lightwindow/javascript/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="lightwindow/javascript/lightwindow.js"></script>
<link rel="stylesheet" href="lightwindow/css/lightwindow.css" type="text/css" media="screen" />
<!-- accordion scripts -->
<script src="js/menu.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="css/accordion.css" />
</code></pre>
<p>Also, NOTE you may need to swap some of your code from $(...) to jQuery(...)</p>
<p>From the jQuery doc page:</p>
<p><em>where you used to do $("div p"), you now must do jQuery("div p").</em></p>
|
Converting webpages from UTF-8 to ISO-8859-1 in linux <p>Anyone have a neat trick on how to convert a number of php and html files from UTF-8 to ISO-8859-1 in linux (Ubuntu)?</p>
| <p>Ubuntu has <a href="http://packages.ubuntu.com/intrepid/recode">recode</a></p>
<pre><code>$ sudo apt-get install recode
$ recode UTF-8..latin1 *.php
</code></pre>
<p>Recursively, thanks to <a href="http://stackoverflow.com/users/104/ted-dziuba">Ted Dziuba</a>:</p>
<pre><code>$ find . -name "*.php" -exec recode UTF-8..latin1 {} \;
</code></pre>
|
Monotone - only pull the latest revision of a repository <p>I have a remote monotone repos I want to pull from, but I really only need the latest revision (Nope, don't need the history. Yes I'm sure. And I really don't want to wait the hour-and-a-half required to get the full history). </p>
<p>Is there a quick and easy way I can do that?</p>
| <p>monotone is a versioning system, its main reason to be is to be used by developers to actually manage the history and not by users to get the nightly tarball... so, even tough it could certainly be an useful feature, what you want was not yet implemented. Of course many websites do provide nightly tarballs, but that has nothing much to do with the specific versionig system they're using anyways and more with some <code>cron</code> script they have laying around (and those could be easily be done for monotone-hosted projects as well, even in realtime, using server-side hooks such as the one that updates <a href="http://monotone.ca/" rel="nofollow">monotone website itself</a> as soon as a new revision is uploaded).</p>
<p>OTOH if you want a "real checkout" of an incomplete set of revisions (intended for a developer, not as a static tarball) what you want is a future feature which in monotone lingo is called <a href="http://www.monotone.ca/wiki/PartialPull/" rel="nofollow">partial pull</a>.</p>
<p>If what you really meant is that, yes, you would like to have the history too, but was only trying to avoid that for performance reasons, that's a still different issue... and the main reason for that is that "mtn pull" (or the pull-part of "mtn sync") doesn't mean "I want to download stuff" but really means "I want to download stuff and cryptographically check every single bit of it so that I'm sure no untrusted data ever shows up in my local database" and, of course, cryptographically check every single bit needs some time... yes, a "pull without checking, I will do 'mtn check' later" could help here.</p>
<p>I do agree that, for a user that really only wants to download "an instant tarball" of current revision could be useful and, for a developer which is not much interested in past history, partial pull or "fast unchecked pull" could be an interesting features. Unfortunately, the monotone contributors didn't so far mange to write those features; any help is appreciated. ;-)</p>
|
Set Identity Seed to 0 Using NHibernate SchemaExport <p>I'm using the SchemaExport class in NHibernate to generate my database from my .hbm.xml files. Is there a way to set the Identity Seed on my tables to 0 rather than 1? For ref tables, I prefer to have all my initial status ids set to 0, and I don't want to have to reset this value every time I regenerate my DB while in dev. I'm using SQL Server 2005, NHibernate version 1.2.1.</p>
| <p>It's best NOT to use Identity columns with NHibernate if possible; They cause NHibernate to make more trips to the database, make batching impossible, and essentially break the Unit of Work pattern. This is discussed on <a href="http://nhibernate.info" rel="nofollow">nhibernate.info</a> and in a few <a href="http://devlicio.us/blogs/tuna_toksoz/archive/2009/03/20/nhibernate-poid-generators-revealed.aspx" rel="nofollow">blog posts</a> like this one. Guid.comb or Hi-Lo is usually a better option.</p>
<p>If you really want to continue using Identity, and have it seed from 0, then here's some possibilities (not tested). </p>
<p>Just a guess, but you'd probably need to first set your <code>unsaved-value="-1"</code> like this:</p>
<p>
</p>
<p>This allows NHibernate to know that an identity of -1 means the object is not saved (transient). </p>
<p>You would also need to ensure that all Entities id's have a default value of -1 also (numbers obviously default to 0):</p>
<pre><code>public class Order {
public virtual long Id{get; private set;}
public Order(){
Id = -1;
}
}
</code></pre>
<p>It's pretty yukky! Then it's a matter of figuring out how to get SchemaExport to seed from 0. It may do this already (by using unsaved-value +1 as the seed)? Check to see if it work. If not, then you might need to look at patching it or overriding the hbm.xml. One way would be to use XSLT to transform the generated HBM files. Again, pretty yukky. </p>
|
rails technoweenie / restful-authentication magi-code: Can't find `User#register!` <p>I recently installed the technoweenie / restful-authentication plugin (which works as promised), but while going through <code>users_controller#created</code>, I found a reference to a method call on the <code>user</code> model</p>
<pre><code> @user.register!
</code></pre>
<p><em>Does anyone know where the method is defined?</em> I've pretty much search all of the generated code, and still don't see a register method.</p>
| <p>It's defined in restful-authentication/lib/authorization/stateful_roles.rb</p>
<pre><code> event :register do
transitions :from => :passive, :to => :pending, :guard => Proc.new {|u| !(u.crypted_password.blank? && u.password.blank?) }
end
</code></pre>
<p>The actual method <code>register!</code> is created dynamically from this event by the acts_as_state_machine plugin that should be in your project as well. This method was inserted into your controller because when you generated your controller you specified either <code>--stateful</code> or '--aasm'. </p>
<p>There is a very good write up on acts_as_state_machine <a href="http://rails.aizatto.com/2007/05/24/ruby-on-rails-finite-state-machine-plugin-acts%5Fas%5Fstate%5Fmachine/">here</a> if you would like to learn more.</p>
|
How to decompress a file in fortran77? <p>I have a compressed file.
Let's ignore the tar command because I'm not sure it is compressed with that.
All I know is that it is compressed in fortran77 and that is what I should use to decompress it.
How can I do it?
Is decompression a one way road or do I need a certain header file that will lead (direct) the decompression?</p>
<p>It's not a .Z file. It ends at something else.
What do I need to decompress it? I know the format of the final decompressed archive.</p>
<p>Is it possible that the file is compressed thru a simple way but it appears with a different extension?</p>
| <p>First, let's get the "fortran" part out of the equation. There is no standard (and by that, I mean the fortran standard) way to either compress or decompress files, since fortran doesn't have a compression utility as part of the language. Maybe someone written some of their own, but that's entirely up to him.</p>
<p>So, you're stuck with publicly available compression utilities, and such. On systems which have those available, and on compilers which support it (it varies), you can use the SYSTEM function, which executes the system command by passing a command string to the operating system's command interpreter (I know it exists in cvf, probably ivf ... you should probably look it up in help of your compiler).</p>
<p>Since you asked a similar question <a href="http://stackoverflow.com/questions/680478/is-there-a-command-in-fortran77-or-later-that-decompresses-a-file">already</a> I assume you're still having problem with this. You mentioned that "it was compressed with fortran77". What do you mean by that ? That someone builded a compression utility in f77 and used it ? So that would make it a custom solution ?</p>
<p>If it's some kind of a custom solution, then it can practically be anything, since a lot of algorithms can serve as "compression algorithms" (writing file as binary compared to plain text will save a few bytes; voila, "compression")</p>
<p>Or have I misunderstood something ? Please, elaborate this a little.</p>
|
Change Access link from SQL Server to another Access file? <p>I've seen lots of questions regarding moving data from Access to SQL Server, but I'd like to go the other route. Here's why:</p>
<p>I've been working on a sizable project with a SQL Server 2008 back-end and Access 2007 front-end. I'd like to be able to do some work on the front-end from home over the weekend, but I don't have access (VPN or otherwise) to SQL Server from there. I'd like to change my linked tables from SQL Server to another Access database file where I imported a snapshot of the SQL Server data. Then, come Monday morning, switch links back to SQL Server.</p>
<p>My problem is when I go to the Linked Table Manager and attempt to change the link, all I get is the ODBC Select Data Source dialog. If I try to link to an Access database, it tells me ODBC can't be used to link, import or export to another Access file.</p>
<p>One thought has occurred to me but I haven't tried yet; maybe someone could tell me if it's a good or bad idea: would I be able to delete the links, re-create them to the other Access file, and not lose any functionality in my queries/forms/reports?</p>
| <p>My proposal would be to have SQLExpress (free) installed on your computer. You can then have all the data available on the machine. Create a publication on your main server, and have your local machine suscribe to this replication (if you don't need to save/synchronize the data changes done on your machine, you can stick to a basic 'snapshot' replication.)</p>
<p>You then just have to change your connection string from your network MSSQLSERVER to your localhost SQLEXPRESS server instance to have your app work.</p>
<p>If, for any reasons, you have to make changes to the database model while being off-line, you will then have to unsubscribe from the main server before making the changes on the local server. When you're back to the office, make sure that the same changes are done on the main server. My advice is to write your changes in T-SQL, save them in a file, and launch the file against the main server once you're back to work. </p>
<p><strong>My opinion</strong>: don't work too much on weekends, or make sure your client is being billed for that.</p>
|
Communicating with an HTTP Proxy via a .NET TcpClient <p>How can I communicate through an HTTP proxy with <code>TcpClient</code> in C#, kind of like <code>WebProxy</code> when using <code>HttpWebResponse</code>?</p>
| <p>Well, TCP doesn't have anything directly equivalent to HTTP proxying. In HTTP, the client (generally) knows about the proxying - it talks to the proxy, and <em>asks</em> the proxy to connect to the real web server on its behalf.</p>
<p>TCP doesn't define that sort of thing, so any proxying would have to either be transparent (i.e. something that a router or the operating system does without the client knowing, e.g. with <a href="http://en.wikipedia.org/wiki/Iptables">iptables</a>) or as part of the protocol on top of TCP (HTTP proxying is a good example of this, as is <a href="http://en.wikipedia.org/wiki/SOCKS">SOCKS</a> mentioned in a different answer).</p>
|
How is the lifetime of a static class affected in a stateless asp.net application? <p>I've defined a helper class to keep track of a small dictionary of items. it stores this information as a static property, which is initialized in the static constructor. the list is very small and will never change so I chose this method over xml or a db lookup table...</p>
<p>however what I would like to know is, will this static property retain its values between pages, or even within pages if asp.net is supposed to be stateless?</p>
<p>for example, I'm binding this list to two different dropdownlists on my page</p>
<pre><code>DropDownList1.DataSource = Helper.MyList;
DropDownList2.DataSource = Helper.MyList;
</code></pre>
<p>Since the static class Helper is called two separate times, is its constructor also called twice, or does it stay in scope throughout the full page lifecycle?</p>
<p>What about if I navigate to the next page and need to bind again, will it still be initialized or will it start all over again?</p>
| <p>No, that won't initialize the type twice. The <code>Helper</code> class will only need to be reinitialized next time you get a new <code>AppDomain</code> - either because the application is refreshed/restarted or due to <a href="http://weblogs.asp.net/owscott/archive/2006/02/21/ASP.NET-v2.0-%5F2D00%5F-AppDomain-recycles%5F2C00%5F-more-common-than-before.aspx#440333" rel="nofollow"><code>AppDomain</code> recycling</a>.</p>
|
Query will not run with variables, will work when variable's definitions are pasted in <p>This is a Query in VBA (Access 2007)
I have 3 strings defined:</p>
<pre><code>str_a = "db.col1 = 5"
str_b = " and db.col2 = 123"
str_c = " and db.col3 = 42"
</code></pre>
<p>Then I use these in the WHERE part of my Query:</p>
<pre><code>"WHERE '" & str_a & "' '" & str_b & "' '" & str_c & "' ;"
</code></pre>
<p>This fails, but If I paste in the strings like this:</p>
<pre><code>"WHERE db.col1 = 5 and db.col2 = 123 and db.col3 = 42;"
</code></pre>
<p>It works perfectly. I'm guessing the syntax is wrong when using multiple variables in a string.<br />
Anyone have any hints?</p>
| <p>You've got some extra single quotes in there.</p>
<p>Try this:</p>
<pre><code>"WHERE " & str_a & str_b & str_c
</code></pre>
<p>Note: In general, you shouldn't build query strings by concatenating strings, because this leaves you vulnerable to SQL injection, and mishandles special characters. A better solution is to use prepared statements. But assuming you're operating in a very controlled environment the solution I gave should work.</p>
|
Non-Unicode CSV Export from SQL Server Report Server <p>I am using the SQL Server Report Server from Microsoft SQL Server 2005.</p>
<p>In the report server report viewer control, there is a CSV download option. The CSV download option is currently downloading a Unicode CSV file, which does not load into Microsoft Excel with the correct column formatting.</p>
<p>If I save the Unicode CSV file and convert it to a ASCII file it works fine in Excel.</p>
<p>How can I can I set a report or the SSRS Report Viewer to export CSV as ASCII instead of Unicode?</p>
<p>Thanks in advance for any help with this.</p>
| <p>Go to the <strong>RSReportserver.config</strong> file (should be in the root of your reportserver virtual directory e.g. "<strong>C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\ReportServer</strong>")</p>
<p>Find the CSV Extension - should look something like below. Change the Encoding node to read <strong>ASCII</strong> instead of <strong>Unicode</strong> or whatevr you have in there.</p>
<pre><code> <Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering">
<Configuration>
<DeviceInfo>
<Encoding>Unicode</Encoding>
</DeviceInfo>
</Configuration>
</Extension>
</code></pre>
|
Best way to get Ruby documentation translated into Japanese? <p>We just finished a project that we need to share with a team of Ruby developers in Japan who, as it turns out, know absolutely no English. Has anyone used a service for translating code documentation into Japanese? I don't know if such a thing even exists. Maybe I just need to use a regular business translation service and hope that the translators don't think our documentation is geek nonsense. If so, could anyone recommend a good online or offline service specifically for translations?</p>
| <p>On what basis did you determine that you must translate your documentation into Japanese? Did you show the documentation to these Japanese developers and then they said that they didn't understand it? I'm asking because all Japanese take at least 6 years of English, all through middle school and high school, and they're even starting earlier now. Despite this, it is true that most Japanese do not <em>speak</em> English very well. But, most Japanese developers can <em>read</em> technical documentation in English. You probably cannot have a conversation with them, and they might not even be able to ask you questions very well in English (even through email), but most Japanese developers that I've worked with (and I've worked with a lot) can <em>read</em> English documentation (if it's technical).</p>
<p>If you do find that you need to translate your documentation, be sure that you use a service that specializes in technical documentation. It requires a very different skill set from normal translation. You should have the vendor translate a small piece first, send that to your developers in Japan, and have them review the translation first before you get the whole thing translated.</p>
<p>There are lots of firms that can handle this work (LionBridge, WeLocalize), but depending on volume and cost, you might search for an independent contractor first using a search engine. I know a lot of good translators that prefer to work solo rather than work for one of the big localization firms.</p>
<p>One possible way to find an independent contractor is to use Guru.com or elance.com, and do a search for "japanese technical translation" (or whatever you want to search on). For a search on "japanese technical translation", many potential candidates showed up, with their skillsets listed, rank, scores, feedback etc all listed.</p>
|
Finding a $cid based on $nid in drupal <p>I have a node in drupal. I want to be able to input a node id and then then have it output a single comment id which was made on that node. How would I go about doing this? Thank you.</p>
| <pre><code>$mycid = db_fetch_object(db_query('SELECT * FROM {comments} WHERE nid = %d ORDER BY RAND() LIMIT 1', $mynid));
return theme_comment_view($mycid,$mynid);
</code></pre>
<p>$mynid is your node id to load. This code will take your node id and render a random comment from that node's comments.</p>
<p>Check <a href="http://api.drupal.org/api/function/theme%5Fcomment%5Fview/6" rel="nofollow">here</a>.</p>
|
Is there a method in python that's like os.path.split for other delimiters? <p>I want to use something like this:</p>
<pre><code>os.path.split("C:\\a\\b\\c")
</code></pre>
<p>With this kind of output:</p>
<p>('C:\a\b', 'c')</p>
<p><hr /></p>
<p>However I want it to work on other delimiters like this:</p>
<pre><code>method ('a_b_c_d')
</code></pre>
<p>With this kind of output:</p>
<p>('a_b_c', 'd')</p>
| <pre><code>>>> 'a_b_c_d'.rsplit('_', 1)
['a_b_c', 'd']
</code></pre>
<blockquote>
<p>Help on built-in function rsplit:</p>
<p>rsplit(...)
<code>S.rsplit([sep [,maxsplit]])</code> -> list of strings</p>
<p>Return a list of the words in the string S, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.</p>
</blockquote>
|
Spring validation, how to have PropertyEditor generate specific error message <p>I'm using Spring for form input and validation. The form controller's command contains the model that's being edited. Some of the model's attributes are a custom type. For example, Person's social security number is a custom SSN type.</p>
<pre><code>public class Person {
public String getName() {...}
public void setName(String name) {...}
public SSN getSocialSecurtyNumber() {...}
public void setSocialSecurtyNumber(SSN ssn) {...}
}
</code></pre>
<p>and wrapping Person in a Spring form edit command:</p>
<pre><code>public class EditPersonCommand {
public Person getPerson() {...}
public void setPerson(Person person) {...}
}
</code></pre>
<p>Since Spring doesn't know how to convert text to a SSN, I register a customer editor with the form controller's binder:</p>
<pre><code>public class EditPersonController extends SimpleFormController {
protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) {
super.initBinder(req, binder);
binder.registerCustomEditor(SSN.class, "person.ssn", new SsnEditor());
}
}
</code></pre>
<p>and SsnEditor is just a custom <code>java.beans.PropertyEditor</code> that can convert text to a SSN object:</p>
<pre><code>public class SsnEditor extends PropertyEditorSupport {
public String getAsText() {...} // converts SSN to text
public void setAsText(String str) {
// converts text to SSN
// throws IllegalArgumentException for invalid text
}
}
</code></pre>
<p>If <code>setAsText</code> encounters text that is invalid and can't be converted to a SSN, then it throws <code>IllegalArgumentException</code> (per <code>PropertyEditor</code> <code>setAsText</code>'s specification). The issue I'm having is that the text to object conversion (via <code>PropertyEditor.setAsText()</code>) takes place <strong>before</strong> my Spring validator is called. When <code>setAsText</code> throws <code>IllegalArgumentException</code>, Spring simply displays the generic error message defined in <code>errors.properties</code>. What I want is a specific error message that depends on the exact reason why the entered SSN is invalid. <code>PropertyEditor.setAsText()</code> would determine the reason. I've tried embedded the error reason text in <code>IllegalArgumentException</code>'s text, but Spring just treats it as a generic error.</p>
<p>Is there a solution to this? To repeat, what I want is the specific error message generated by the <code>PropertyEditor</code> to surface to the error message on the Spring form. The only alternative I can think of is to store the SSN as text in the command and perform validation in the validator. The text to SSN object conversion would take place in the form's <code>onSubmit</code>. This is less desirable as my form (and model) has many properties and I don't want to have to create and maintain a command that has each and every model attribute as a text field.</p>
<p>The above is just an example, my actual code isn't Person/SSN, so there's no need to reply with "why not store SSN as text..."</p>
| <p>You're trying to do validation in a binder. That's not the binder's purpose. A binder is supposed to bind request parameters to your backing object, nothing more. A property editor converts Strings to objects and vice versa - it is not designed to do anything else.</p>
<p>In other words, you need to consider separation of concerns - you're trying to shoehorn functionality into an object that was never meant to do anything more than convert a string into an object and vice versa.</p>
<p>You might consider breaking up your SSN object into multiple, validateable fields that are easily bound (String objects, basic objects like Dates, etc). This way you can use a validator after binding to verify that the SSN is correct, or you can set an error directly. With a property editor, you throw an IllegalArgumentException, Spring converts it to a type mismatch error because that's what it is - the string doesn't match the type that is expected. That's all that it is. A validator, on the other hand, can do this. You can use the spring bind tag to bind to nested fields, as long as the SSN instance is populated - it must be initialized with new() first. For instance:</p>
<pre><code><spring:bind path="ssn.firstNestedField">...</spring:bind>
</code></pre>
<p>If you truly want to persist on this path, however, have your property editor keep a list of errors - if it is to throw an IllegalArgumentException, add it to the list and then throw the IllegalArgumentException (catch and rethrow if needed). Because you can construct your property editor in the same thread as the binding, it will be threadsafe if you simply override the property editor default behavior - you need to find the hook it uses to do binding, and override it - do the same property editor registration you're doing now (except in the same method, so that you can keep the reference to your editor) and then at the end of the binding, you can register errors by retrieving the list from your editor if you provide a public accessor. Once the list is retrieved you can process it and add your errors accordingly.</p>
|
Reusing a JPanel in NetBeans GUI Designer <p>This is in NetBeans 6.5, Java 6.</p>
<p>I have the following hierarchy in the NetBeans GUI Designer:</p>
<pre><code>JFrame
JTabbedPane
JPanel X
<...>
JPanel
JButton
JPanel Y
<...>
JButton
</code></pre>
<h2>Question:</h2>
<p>JPanel Y is identical to JPanel X, so I'd like to simply reuse JPanel X in both places, but how do I do this inside the GUI Builder?</p>
<h2>Attempts:</h2>
<p>I tried copy-pasting JPanel X, but it creates a full "deep" copy (JPanel X1, etc), duplicating everything in JPanel X.</p>
<p>Some googling indicated it might be possible to add it to the Palette, but I haven't found a way to add a simple JPanel to the palette (as opposed to a complete JFrame).</p>
| <p>Create a separate JPanel class. Customize JPanel as needed. You can then drag-and-drop the JPanel class onto the Form Designer. This is exactly what I do.</p>
<p>Alternatively, you can click on Use Bean and then type in the name of the class.</p>
<p>Alternatively, you can do an Add from the pallete and it will scan your JAR for any "beans". It should pick up your custom JPanel as well.</p>
|
Rails Restful-Authentication Plugin fails to login <p>My clean install of the <strong><em>Restful-Authentication</em></strong> plugin fails with the following message.</p>
<pre><code>undefined method `acts_as_state_machine' for #Class:0x46edaf8
</code></pre>
<p>Any ideas on how I can resolve this? </p>
<p>Note: The <strong>*act_as_state_machine*</strong> plugin is installed </p>
<p>Note: The restful-authentication plugin was installed with the following command</p>
<pre><code>script/generate authenticated user sessions --include-activation --stateful
</code></pre>
<p>Thanks</p>
<p>H</p>
| <p>There was nothing wrong with the code. I just needed to restart the server. Additionally, I found a great blog post provided information that can be used to extend the vanilla restful-authentication plugin.
<a href="http://railsonedge.blogspot.com/2008/03/rails-forum-restful-authenticationpart.html" rel="nofollow">Restful Authentication(Part 3 of 3)</a></p>
|
How do you activate the MVC templates in VS2008 from a WebForms App <p>I'm in the process of adding ASP.NET MVC to a WebForms app. One of the neat features of an ASP.NET MVC solution that you create from scratch is that a right click on the solution explorer and Add > New Item... will give a list of templates which include the MVC templates. However, in a WebForms app these templates don't appear.</p>
<p>I thought that there might be a setting in the .sln solution file that indicated that one was an ASP.NET MVC app but I couldn't find anything that that stuck out.</p>
<p>EDIT: To expand the question, how does Visual Studio know to add a "Controller..." menu item on to the "Add" menu when you right click on the Controllers folder in the Solution Explorer of an MVC app? Likewise it adds a "View..." menu item to the "Add" menu when you right click on the Views folder. Where does Visual Studio get this info from and how can I add those 2 folders to another web app and get the same functionality?</p>
<p>Ideas?</p>
| <p>I believe that the logic for that is contained in the dll </p>
<blockquote>
<p>Microsoft.VisualStudio.Web.ExtensionsUI</p>
</blockquote>
<p>Which is registered in the Project template used when you create a new ASP.NET MVC project:</p>
<pre><code><WizardExtension>
<Assembly>
Microsoft.VisualStudio.Web.Extensions,
Version=9.0.0.0,
Culture=neutral,
PublicKeyToken=31bf3856ad364e35
</Assembly>
<FullClassName>
Microsoft.VisualStudio.Web.Mvc.TemplateWizard
</FullClassName>
</WizardExtension>
</code></pre>
<blockquote>
<p>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\CSharp\Web\1033\MvcWebApplicationProjectTemplatev1.cs.zip</p>
</blockquote>
<p>You could probably also mess around with the Project Type Guids in your .xxproj file:</p>
<pre><code><ProjectTypeGuids>
{603c0e0b-db56-11dc-be95-000d561079b0};
{349c5851-65df-11da-9384-00065b846f21};
{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
</ProjectTypeGuids>
</code></pre>
<p>Seem to be the default ones for an ASP.NET MVC project, compare those with the ones in your web application, and go from there.</p>
<p>However, in a lot of these circumstances I'd agree with gisresearch: it's often easier to create the more complex project (the MVC one) first, and then move the origininal into it.</p>
<p>Also, there's nothing to stop you having multiple projects hosted in the same web application - pull the common logic from the web application into a shared class library, and then reference that from a clean MVC app, with a slightly different namespace, and then merge the two sites within IIS, drop the dlls into a shared bin folder (or strongly name them and put them in the global assembly cache), share the images/scripts, and away you go - you just need to take care with the Global.asax, which would be common to both.</p>
|
How do I save an entity for the first time that requires another pre-existing entity to be attached to it <p>I need to save a Company entity to the database as a new entity. In order to do this I need to associate a CompanyType entity to the Company entity. I can't save the Company without do this. Do I attach the newly created company to the context and then attach the company type entity to the company and then save my results? This code works...but just doesn't feel right.</p>
<pre><code>public RepositoryStatus SaveCompany(Company company, CompanyType companyType)
{
RepositoryStatus rs = new RepositoryStatus();
try
{
using (RanchBuddyEntities dc = new Connection().GetContext())
{
if (company.CompanyID > 0)
{
company.UpdateDate = DateTime.Now;
Company original = dc.CompanySet.Where(c => c.CompanyID == company.CompanyID).FirstOrDefault();
dc.ApplyPropertyChanges("CompanySet", company);
dc.Attach(companyType);
company.CompanyTypesReference.Attach(companyType);
}
else
{
company.CreateDate = DateTime.Now;
company.UpdateDate = DateTime.Now;
dc.AddToCompanySet(company);
dc.Attach(companyType);
company.CompanyTypesReference.Value = companyType;
}
dc.SaveChanges();
}
rs.SetObject(company);
rs.StatusType = Status.StatusTypes.Success;
}
catch (Exception e)
{
rs.SetObject(company);
rs.StatusType = Status.StatusTypes.Failure;
rs.AddMessage(e.Message + Environment.NewLine + e.StackTrace);
}
return rs;
}
</code></pre>
<p>The CompanyType was attached to another context and detached which is why it is passed in here. Would I be better off passing in the CompanyTypeID and query for the associated object inside of the same using statement? </p>
<p>I can't stand that I have to take so many steps to get EF goign where LINQ to SQL was so easy! Still - EF seems easier than NHibernate!</p>
| <p>I do it like this:</p>
<pre><code>Company company = new Company();
company.CreateDate = DateTime.Now;
company.UpdateDate = DateTime.Now;
company.CompanyType = companyType;
RanchBuddyEntities.AddToCompanies(company);
RanchBuddyEntities.SaveChanges();
</code></pre>
|
How do I write stderr to a file while using "tee" with a pipe? <p>I have below a command which will print the output of <code>aaa.sh</code> to the screen while also writing <em>stdout</em> to <code>bbb.out</code>; however I would also like to write <em>stderr</em> to a file named <code>ccc.out</code>. Any suggestions on how to modify the piece below?</p>
<pre><code>./aaa.sh | tee ./bbb.out
</code></pre>
<p><strong>Update:</strong> <em>stdout</em> and <em>stderr</em> should still both be printed to the screen, regardless.</p>
| <p>I'm assuming you want to still see STDERR and STDOUT on the terminal. You could go for Josh Kelley's answer, but I find keeping a <code>tail</code> around in the background which outputs your log file very hackish and cludgy. Notice how you need to keep an exra FD and do cleanup afterward by killing it and technically should be doing that in a <code>trap '...' EXIT</code>.</p>
<p>There is a better way to do this, and you've already discovered it: <code>tee</code>.</p>
<p>Only, instead of just using it for your stdout, have a tee for stdout and one for stderr. How will you accomplish this? Process substitution and file redirection:</p>
<pre><code>command > >(tee stdout.log) 2> >(tee stderr.log >&2)
</code></pre>
<p>Let's split it up and explain:</p>
<pre><code>> >(..)
</code></pre>
<p><code>>(...)</code> (process substitution) creates a FIFO and lets <code>tee</code> listen on it. Then, it uses <code>></code> (file redirection) to redirect the STDOUT of <code>command</code> to the FIFO that your first <code>tee</code> is listening on.</p>
<p>Same thing for the second:</p>
<pre><code>2> >(tee stderr.log >&2)
</code></pre>
<p>We use process substitution again to make a <code>tee</code> process that reads from STDIN and dumps it into <code>stderr.log</code>. <code>tee</code> outputs its input back on STDOUT, but since its input is our STDERR, we want to redirect <code>tee</code>'s STDOUT to our STDERR again. Then we use file redirection to redirect <code>command</code>'s STDERR to the FIFO's input (<code>tee</code>'s STDIN).</p>
<p>See <a href="http://mywiki.wooledge.org/BashGuide/InputAndOutput"><a href="http://mywiki.wooledge.org/BashGuide/InputAndOutput">http://mywiki.wooledge.org/BashGuide/InputAndOutput</a></a></p>
<p>Process substitution is one of those really lovely things you get as a bonus of choosing <code>bash</code> as your shell as opposed to <code>sh</code> (POSIX or Bourne).</p>
<hr>
<p>In <code>sh</code>, you'd have to do things manually:</p>
<pre><code>out="${TMPDIR:-/tmp}/out.$$" err="${TMPDIR:-/tmp}/err.$$"
mkfifo "$out" "$err"
trap 'rm "$out" "$err"' EXIT
tee stdout.log < "$out" &
tee stderr.log < "$err" >&2 &
command >"$out" 2>"$err"
</code></pre>
|
How to get facebook data from app? <p>I'm writing a sort of visualization desktop (non-web) application, just for fun.<br />
However, ideally I'd want it to be able to pull information from the user's facebook account. (after getting its credentials, of course)<br />
What's the best way to do this? Should I register a new 'facebook app' even though I'm not really making it web-based? I've never written a facebook app before. </p>
<p>I'm using Java as my prog language, btw.</p>
<p>Thanks!</p>
| <p>Yes. Facebook supports desktop applications, but they must go through a special authentication mechanism. Essentially, the user will need to be directed to facebook through a web browser window as part of the authentication process.</p>
<p>Here is the documentation on the authentication process: <a href="http://wiki.developers.facebook.com/index.php/Login%5FDesktop%5FApp" rel="nofollow">http://wiki.developers.facebook.com/index.php/Login_Desktop_App</a></p>
<p>There is a relatively polished Java library for facebook here: <a href="http://code.google.com/p/facebook-java-api/" rel="nofollow">http://code.google.com/p/facebook-java-api/</a></p>
<p>If the Java library above does not meets your needs, you can build an implementation on your own. Essentially, you will need to interact with the Facebook REST server, as described at the top of the page here: <a href="http://wiki.developers.facebook.com/index.php/API" rel="nofollow">http://wiki.developers.facebook.com/index.php/API</a></p>
<p>Edit: After doing some more research I have a few more resources to provide:
Here is a list of some applications written using Java for facebook:</p>
<p><a href="http://wiki.developers.facebook.com/index.php/Facebook%5Fapps%5Fwritten%5Fin%5FJava" rel="nofollow">http://wiki.developers.facebook.com/index.php/Facebook_apps_written_in_Java</a></p>
<p>And there's even a neat desktop application that is open source here:</p>
<p><a href="http://code.google.com/p/fb-photo-uploader/" rel="nofollow">http://code.google.com/p/fb-photo-uploader/</a></p>
<p>Good luck!</p>
|
Adding values from a tab delimited string to a plist <p>How would I go about adding values from a tab delimited string to a plist?</p>
<pre>
(dolist (x *lines*)
(cl-ppcre:split "\t" x))
</pre>
<p><code>*lines*</code> is a list of tab delimited strings loaded from a file, and I want to make a plist of the form</p>
<pre>
(:a value1 :b value2 :c value 3)
</pre>
<p>Thanks!</p>
| <pre><code>(let ((line '("foo" "bar" "baz")))
(loop for item in line and key in '(:a :b :c) collect key collect item))
=> (:A "foo" :B "bar" :C "baz")
(mapcan 'list '(:a :b :c) '("foo" "bar" "baz"))
=> (:A "foo" :B "bar" :C "baz")
</code></pre>
|
Is it bad form to call a classmethod as a method from an instance? <p>Ex.</p>
<p>If I have something like this:</p>
<pre><code>class C(object):
@classmethod
def f(cls, x):
return x + x
</code></pre>
<p>This will work:</p>
<pre><code>c = C()
c.f(2)
4
</code></pre>
<p>But is that bad form?
Should I only call</p>
<pre><code>C.f()
</code></pre>
<p>or </p>
<pre><code>c.__class__.f()
</code></pre>
<p>Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.</p>
<p>?</p>
| <p>If you are tempted to call a class method from an instance you probably don't need a class method.</p>
<p>In the example you gave a static method would be more appropriate precisely because of your last remark (no self/cls interaction).</p>
<pre><code>class C(object):
@staticmethod
def f(x):
return x + x
</code></pre>
<p>this way it's "good form" to do both</p>
<pre><code>c = C()
c.f(2)
</code></pre>
<p>and</p>
<pre><code>C.f(2)
</code></pre>
|
How to generate table of contents using dompdf? <p>I am using the dompdf library of php to generate PDF report from an HTML template. In that html template there is a section table of contents. When genrating PDF i need to update the page number of table of contents. Does anyone know how I can achieve this in dompdf library of php?</p>
<p>Thanks in advance.</p>
| <p>Generating a Table of Contents from HTML (with h1,h2,h3), I did the following:</p>
<ul>
<li>First give every header an unique ID (because we are using PrinceXML) and is a good pratice.</li>
<li>Then create an OL/LI structure of it, although that piece of code can contain bugs.</li>
</ul>
<p>See: <a href="http://pastie.org/655728" rel="nofollow">http://pastie.org/655728</a></p>
|
How to pass in runtime a index of row for ListView? <p>I have an question, On my page i have a ListView control, I also have a button that has CommandArgument. I know i can read and find a control in the ListView as :</p>
<pre><code>ListView.Items[i].FindControl("controlname");
</code></pre>
<p>and my button in ListView is like that</p>
<pre><code> asp:Button ID="WisdomButton" runat="server" CommandName="UpdateWisdom" CommandArgument='<%# need my index for Item[i] to post here %>'
OnCommand="UpdateWisdom" Text="Update" />
</code></pre>
<p>I want to add index value in runtime to the CommantParameter, so when i go to the Function onCommand i will know exactly from what row[i] i Need to get my controls from ListView.</p>
<p>So my question is, how do i dinamicly add index of ListView.Rows[i] into CommmandArgument for the Button in runtime ?</p>
<p>Thanks in advance.</p>
| <p>Check out the API</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewcommandeventargs.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewcommandeventargs.aspx</a></p>
<p>The ListViewCommandEventArgs item has an index, IE it is already available in the argument</p>
<pre><code>ListViewDataItem dataItem = (ListViewDataItem)e.Item;
int i = dataItem.DisplayIndex;
</code></pre>
<p>But from here you will have access to those controls</p>
<pre><code>e.Item.FindConrol("controlName");
</code></pre>
<p>If you are calling the method a different way you could aways assign the index through an ItemDataBound Event</p>
<pre><code>void MyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
((Button)e.Item.FindControl("WisdomButton")).CommandArgument = ((ListViewDataItem)e.Item).DisplayIndex;
}
</code></pre>
<p>OR try something like this for giggles</p>
<pre><code><asp:Button runat="server" CommandArgument='<%# DisplayIndex %>'/>
// OR
<asp:Button runat="server" CommandArgument='<%# NextIndex() %>'/>
</code></pre>
|
Rails Application Admin Section <p>I am working on my first Rails application and want to create an admin section. </p>
<p>Do I want to keep my views and controllers completely separate (that is, in separate directories) for the admin section and the rest of the site? </p>
<p>How can I organize my views/controllers in custom directories (how do I configure the routing)?</p>
| <p>To create your admin controllers:</p>
<pre><code>script/generate controller admin/articles
</code></pre>
<p>Then in your routes.rb file</p>
<pre><code>map.resource :admin do |admin|
admin.resources :articles, :path_prefix => "admin", :name_prefix => "admin_", :controller => "admin/articles"
end
</code></pre>
<p>You could then access the index url for this:</p>
<pre><code><%= link_to "Articles Admin", admin_articles_path %>
</code></pre>
|
.NET Framework 3.0 Service Pack 1 <p>I am so confused that there is no 64-bit .NET Framework 3.0 Service Pack 1 download? If there is, could anyone send me a link please? My OS is Windows Server 2003 x64. Thanks.</p>
<p>thanks in advance,
George</p>
| <p>Just get the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=AB99342F-5D1A-413D-8319-81DA479AB0D7&displaylang=en" rel="nofollow">3.5 SP1 download</a> instead. It includes 2.0 SP2 and 3.0 SP2.</p>
|
Hello OS with C# & mono? <p>Is there a way to identify in which OS we are running mono, with C# code? </p>
<p>Some sort of Hello World, but instead of using a fixed string as an output use the current OS?</p>
| <p>Try <code>System.Environment.OSVersion</code></p>
<p>You can also detect if your code is run under Mono or MS.NET:</p>
<pre><code>if (Type.GetType("Mono.Runtime") != null)
{
// we're on Mono
IsMono = true;
}
else
IsMono = false;
</code></pre>
|
Compile .dbml file into separate assembly <p>I have a website project, and using Linq to SQL in it. Currently, I have my .dbml file in the App_Code directory, but I want to separate it out into a different project in order to compile it into a separate dll; is it possible?</p>
<p>I tried adding a DB project to my solution, but didn't have much luck with it.</p>
| <p>Yes, it is possible.</p>
<p>Just create a new project of type <strong>class library</strong>, and copy and paste your .dbml into the new project. Add a reference to the new project (class library) on your website project in the end.</p>
<p>I believe that a DB project is just a way to store SQL Scripts to be executed against a DB.</p>
|
Windows Integrated Authentication Conflict With MS-SQL 2000 DB Connection With Integrated Security <p>We are developing an intranet web application on .NET 2.0 platform.
The application is using Integrated Windows Authentication for Single Sign On. The users are authorized to use diffent modules according to the Active Directory Groups they are in. </p>
<p>Up to the point where authentication and authorization is accomplished everything works fine. But the problem starts when application tries to connect to the database on MSSQL Server.</p>
<p>According to the security policies of our customer, no database user or password data should be kept in connection strings or in registry even if encrypted. So we are forced to use Integrated Security=SSPI in the connection string. </p>
<p>The Application Pool on IIS is configured by them with the Identity User who has access to the database.</p>
<p>When we deactivate Windows Integrated Authentication, we connect to the db with the Application Pool's Identity User. But when Integrated Authentication is on, the application is trying to connect to the database with logon user credentials.</p>
<p>We tried every combination of Integrated Authentication, with or without impersonation, to solve the problem.</p>
<p>Is there any way to solve this conflict? </p>
| <p>Normally the way you are doing it should work. Do you have Kerberos with delegation enabled?</p>
<p>Maybe this helps:</p>
<ul>
<li><p><a href="http://msdn.microsoft.com/en-us/library/bsz5788z.aspx" rel="nofollow">How to: Access SQL Server Using Windows Integrated Security</a></p></li>
<li><p><a href="http://blogs.msdn.com/sql%5Fprotocols/archive/2006/12/02/understanding-kerberos-and-ntlm-authentication-in-sql-server-connections.aspx" rel="nofollow">http://blogs.msdn.com/sql_protocols/archive/2006/12/02/understanding-kerberos-and-ntlm-authentication-in-sql-server-connections.aspx</a></p></li>
</ul>
<p>Edit: if both SQL and IIS are on the same machine you need to turn off impersonate:</p>
<ul>
<li><authentication mode="Windows" /></li>
<li><identity impersonate="false" /></li>
</ul>
|
Examples of usage of Generics in .Net (C#/VB.NET) <p>What are some examples of where you would use generics in C#/VB.NET and why would you want to use generics?</p>
| <p>Simply, you declare a type or method with extra tags to indicate the generic bits:</p>
<pre><code>class Foo<T> {
public Foo(T value) {
Value = value;
}
public T Value {get;private set;}
}
</code></pre>
<p>The above defines a generic type <code>Foo</code> "of <code>T</code>", where the <code>T</code> is provided by the caller. By convention, generic type arguments start with T. If there is only one, <code>T</code> is fine - otherwise name them all usefully: <code>TSource</code>, <code>TValue</code>, <code>TListType</code> etc</p>
<p>Unlike C++ templates, .NET generics are provided by the runtime (not compiler tricks). For example:</p>
<pre><code>Foo<int> foo = new Foo<int>(27);
</code></pre>
<p>All <code>T</code>s have been replaced with <code>int</code> in the above. If necessary, you can restrict generic arguments with constraints:</p>
<pre><code>class Foo<T> where T : struct {}
</code></pre>
<p>Now <code>Foo<string></code> will refuse to compile - as <code>string</code> is not a struct (value-type). Valid constraints are:</p>
<pre><code>T : class // reference-type (class/interface/delegate)
T : struct // value-type except Nullable<T>
T : new() // has a public parameterless constructor
T : SomeClass // is SomeClass or inherited from SomeClass
T : ISomeInterface // implements ISomeInterface
</code></pre>
<p>Constraints can also involve other generic type arguments, for example:</p>
<pre><code>T : IComparable<T> // or another type argument
</code></pre>
<p>You can have as many generic arguments as you need:</p>
<pre><code>public struct KeyValuePair<TKey,TValue> {...}
</code></pre>
<p>Other things to note:</p>
<ul>
<li>static members etc are defined <strong>per generic type combination</strong> - so a static field on <code>Foo<int></code> is separate to that on <code>Foo<float></code>.</li>
<li>methods can be generic too - try to avoid using the same names as the class uses, as you won't be able to disambiguate</li>
<li>nested types inherit the generic types from their parents</li>
</ul>
<p>for example:</p>
<pre><code>class Foo<T> {
class Bar<TInner> {} // is effectively Bar<T,TInner>, for the outer T
}
</code></pre>
|
how to use the key board as command to zoom in opengl? <p>can anyone tell me how?</p>
<p>i've never done this before so i'm not sure as what library to use and how to call the command that a key pressed as a instruction rather than input..</p>
<p>i'm writing a OpenGL program in Visio C++</p>
| <p>Zooming in OpenGL and getting keyboar inputs are two different things. You can use whatever GUI (MFC, wxWidgets, Qt, .Net) to capture keyboard events as input. Then, you can call OpenGL functions (glTranslate) to change the zoom and then redraw everything in your scene.</p>
|
Webbrowser Control stealing shortcuts <p>Webbrowser Control in my .NET Windows Form application is stealing shortcuts when on focused. To able to use <code>Alt + F4</code> I had to click a control first.</p>
<p>Currently "<code>WebbrowserShortcuts = false</code>" but it's still same.</p>
<p>Is there a way to stop this irritating behaviour?</p>
| <p>I had this problem when loading Silverlight inside a winforms WebBrowser and I solved it by adding the following to the <code><body></code> element:</p>
<pre><code>onload="document.getElementById('silverlightControl').focus()"
</code></pre>
<p>...which, of course, meant I have to give an id of <code>silverlightControl</code> to my <code><object></code> element:</p>
<pre><code><object id="silverlightControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
</code></pre>
<p>If you only have HTML, maybe you can call <code>focus()</code> on the <code>document</code> or perhaps the first hyperlink?</p>
|
How do I return errors from my asp.net mvc controller when doing a jquery ajax post? <p>I'm creating a website in ASP.NET MVC and have stumbled across something I really can't figure out.</p>
<p>I've got a user profile page that allows a user to change his password. On the serverside, I want to validate that the user has entered a correct "current" password before allowing the change. </p>
<p>What's the best way to return to my View when the password isn't correct? I've tried using ModelState.AddModelError and then return Json(View()) but I can't see the error message anywhere in the JSON object returned to the browser. </p>
<p>What's the best way to do this using jquery on the client?</p>
<p>/Jesper</p>
| <p>I would create to classes</p>
<pre><code>JsonOK : JsonResult { ... }
JsonError : JsonResult { ... }
</code></pre>
<p>And use those 2 for OK and Error responses.</p>
<pre><code>try
{
...
}
catch (Exception ex)
{
return JsonError(ex.Message);
// or output your own message
// or pass into it ModelState with your errors
}
</code></pre>
|
iphone: problem with events <h1>MainViewController.h</h1>
<pre><code>@class EventViewController;
@class MainViewController;
@interface MainViewController : UIViewController {
EventViewController *eventViewController;
MainViewController *mainViewController;
//extern int i;
@public
NSString *titlegame;
}
@property (retain,nonatomic) EventViewController *eventViewController;
@property (retain,nonatomic) MainViewController *mainViewController;
@property (retain,nonatomic)IBOutlet NSString *titlegame;
@end
</code></pre>
<h1>MainViewController.m</h1>
<pre><code>-(IBAction)buttonClick:(id)sender{
titlegame = [sender titleForState: UIControlStateNormal];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"You selecet!!!!"
message:titlegame
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
//[titlegame release];
[alert release];
////////
if([titlegame isEqualToString: @"FootBall"]==YES)
NSLog( @"Equal");
else
NSLog( @"NotEqual");
EventViewController *eventController = [[EventViewController alloc]
initWithNibName: @"EventView"
bundle:nil];
self.eventViewController = eventController;
[eventController release];
[[self mainViewController] dismissModalViewControllerAnimated:YES];
[eventViewController.view removeFromSuperview];
[self.view addSubview: eventController.view];
// eventController.labelgame.text = titlegame;
eventViewController.labelgame.text =titlegame;
NSLog(@"title==>%@",eventController.labelgame.text);
NSLog(@"title1==>%@",eventViewController.labelgame.text);
[eventViewController.labelgame retain];
}
</code></pre>
<p>it works properly</p>
<p>but in EventViewController's ViewDidLoad method i cant that label's value..</p>
<h1>EventViewController.m:</h1>
<pre><code>- (void)viewDidLoad {
NSLog(@"titlegame==>%@",labelgame.text);
}
</code></pre>
<h1>EventWiseViewController.m:</h1>
<pre><code>-(IBAction)BackPressed :(id) sender
{
EventViewController *eventController = [[EventViewController alloc]
initWithNibName: @"EventView"
bundle:nil];
self.eventWiseViewController = eventController;
[eventController release];
[[self eventWiseViewController] dismissModalViewControllerAnimated:YES];
[eventViewController.view removeFromSuperview];
[self.view addSubview: eventController.view];
NSLog(@"final=---->%@",eventController.game1);
eventController.labelgame.text = mainViewController.titlegame;
NSLog(@"gmename1 ==>%@", [mainViewController titlegame]);
NSLog(@"gamename2 ==>%@", mainViewController.titlegame);
//NSLog(@"gmename1 ==>%@",eventController.labelgame.text);
//NSLog(@"gmename2 ==>%@",eventController.game1);
}
</code></pre>
<p>but here when i go back to EventViewController the label get blank ,why??
plz tell me..</p>
| <p>I believe you need to use something like this to access the titlegame field from a different controller</p>
<pre><code>[AppDelegate sharedDelegate].mainViewController.titlegame;
</code></pre>
<p>This may not be exactly correct. But I think the problem you are having is related to this concept.</p>
|
COM Interop IDictionary - How to retrieve a value in C#? <p>using: VS2008, C#</p>
<p>I have a COM dll I need to use in a .NET project. In there I have a class with a method that returns an IDictionary object. IDictionary is defined in the COM dll so I'm not sure if it's the same as IDictionary in .NET.</p>
<p>My problem: I know the dictionary keys and I want to retrieve the values. The documentation
for this COM dll gives code in Classic ASP like </p>
<pre><code>someValue = oMyDictionary.someDictionaryKey
</code></pre>
<p>My Question: How do I retrieve the values for the specific keys in C#?</p>
<p>When I create the IDictionary object in C# like this:</p>
<pre><code>IDictionary oDictConfig = oAppConfig.GetOptionsDictionary("");
</code></pre>
<p>VS2008 reckons this dictionary object (interface) has the following methods and properties:</p>
<pre><code>Cast<>
Count
Equals
GetEnumerator
GetHashCode
GetMultiple
GetType
let_Value
OfType<>
Prefix
PutMultiple
ToString
</code></pre>
<p>Sorry if this is a silly question, but I can't see how to retrieve a value passing a key.</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/system.collections.idictionary.aspx" rel="nofollow">IDictionary</a> has an Item property among its <a href="http://msdn.microsoft.com/en-us/library/system.collections.idictionary%5Fmembers.aspx" rel="nofollow">members</a> that you access via [ ].</p>
<pre><code>var obj = oDictConfig[key];
</code></pre>
|
C# Problem using blowfish NET: How to convert from Uint32[] to byte[] <p>In C#,I'm using Blowfish.NET 2.1.3's BlowfishECB.cs file(<a href="http://www.hotpixel.net/software.html" rel="nofollow">can be found here</a>)</p>
<p>In C++,It's unknown,but it is similiar.</p>
<p>In C++,the Initialize(blowfish) procedure is the following:</p>
<pre><code>void cBlowFish::Initialize(BYTE key[], int keybytes)
</code></pre>
<p>In C#,the Initialize(blowfish) procedure is the same</p>
<pre><code>public void Initialize(byte[] key, int ofs, int len)
</code></pre>
<p>This is the problem:</p>
<p>This is how the key is initialized in C++</p>
<pre><code>DWORD keyArray[2] = {0}; //declaration
...some code
blowfish.Initialize((LPBYTE)keyArray, 8);
</code></pre>
<p>As you see,the key is an array of two DWORDS,which is 8 bytes total.</p>
<p>In C# I declare it like that,but I get an error</p>
<pre><code>BlowfishECB blowfish = new BlowfishECB();
UInt32[] keyarray = new UInt32[2];
..some code
blowfish.Initialize(keyarray, 0, 8);
</code></pre>
<p>The error is:</p>
<p>Argument '1': cannot convert from 'uint[]' to 'byte[]'</p>
<p>What am I doing wrong?</p>
<p>Thanks in advance!</p>
| <p>You can use <a href="http://msdn.microsoft.com/en-us/library/1184xdy4.aspx">BitConverter</a> to get the bytes from a UInt32.</p>
<p><hr /></p>
<p>To do this, you'll need to convert each element in a loop. I would do something like:</p>
<p><code><pre>
private byte[] ConvertFromUInt32Array(UInt32[] array)
{
List<byte> results = new List<byte>();
foreach(UInt32 value in array)
{
byte[] converted = BitConverter.GetBytes(value);
results.AddRange(converted);
}
return results.ToArray();
}
</pre></code></p>
<p>To go back:</p>
<p><code><pre>
private UInt32[] ConvertFromByteArray(byte[] array)
{
List<UInt32> results = new List<UInt32>();
for(int i=0;i<array.Length;i += 4)
{
byte[] temp = new byte[4];
for (int j=0;j<4;++j)
temp[j] = array[i+j];
results.Add(BitConverter.ToUInt32(temp);
}
return results.ToArray();
}
</pre></code></p>
|
TCP: How are the seq / ack numbers generated? <p>I am currently working on a program which sniffs TCP packets being sent and received to and from a particular address. What I am trying to accomplish is replying with custom tailored packets to certain received packets. I've already got the parsing done. I can already generated valid Ethernet, IP, and--for the most part--TCP packets.</p>
<p>The only thing that I cannot figure out is how the seq / ack numbers are determined.</p>
<p>While this may be irrelevant to the problem, the program is written in C++ using WinPCap. I am asking for any tips, articles, or other resources that may help me.</p>
| <p>When a TCP connection is established, each side generates a random number as its initial sequence number. It is a strongly random number: there are security problems if anybody on the internet can guess the sequence number, as they can easily forge packets to inject into the TCP stream.</p>
<p>Thereafter, for every byte transmitted the sequence number will increment by 1. The ACK field is the sequence number from the other side, sent back to acknowledge reception.</p>
<p>RFC 793 (the original TCP protocol specification) would be of great help.</p>
|
HTTP Transfer-Encoding and requests <p>the HTTP specification states that the Transfer-Encoding header is allowed for requests - but what error code should a server respond if it doesn't understand that given Transfer-Encoding.</p>
<p>As far as I know the HTTP standard doesn't cover this possibility, but maybe I have just overlooked it.</p>
| <p>An unknown transfer-encoding should raise a HTTP error 501 "NOT IMPLEMENTED".
That's what Apache does, at least.</p>
<p>Also see <a href="http://argray.com/unixfaq/httpd_error_codes.shtml" rel="nofollow">http://argray.com/unixfaq/httpd_error_codes.shtml</a></p>
<p><strong>Edit:</strong> pointer to the corresponding RFC section: <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.2" rel="nofollow">http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.2</a></p>
|
Access to the ANT Wireless and GPS receiver modules in iPhone/iPod Touch <p>I'm an iPhone/iPod-touch newbie, and would like to write an iPhone application utilizing the built-in <a href="http://www.thisisant.com" rel="nofollow">ANT wireless</a> radio. As I found out both the iPhone and iPod Touch have an ANT wireless module, that is used in the <a href="http://www.apple.com/de/ipod/nike" rel="nofollow">Nike+iPod Sport Kit</a> to connect the Nike sensor with the iPhone/iPod.</p>
<p>After some googleing, I didn't find much (one <a href="http://www.cs.washington.edu/research/systems/nikeipod/tracker-paper.pdf" rel="nofollow">article</a> was interesting, but not what I'm looking for).</p>
<p>So my questions: </p>
<ul>
<li>Is it possible to access the built-in ANT Wireless device in iPhone/iPod Touch?</li>
<li>Is it possible to access the built-in GPS module in iPhone?</li>
<li>Are there some APIs or SDKs that provide access to the ANT or the GPS module?</li>
</ul>
<p>I can imagine that Apple is not eager opening the access to all of the iPhone features. But at least the GPS module should be accessible.</p>
| <p>The GPS radio is only accessible through the Core Location API, which will give you a latitude and longitude fix to your desired level of accuracy, but does not provide any low-level access to the radio. The ANT radio is not available using public APIs, although it may be possible to talk to it on a jailbroken phone. Any such application could not be distributed through the App Store, however.</p>
|
Application_Start not being hit in ASP.NET web app <p>I'm trying to debug something in the global.asax.cs file in an ASP.NET web app and have set a breakpoint in the Application_Start() event however that event is not getting fired when I start the web app inside VS2008. I'm targeting the 3.5 framework.</p>
<p>What could prevent this event from being fired? Or how could I have messed up the project such that this event is no longer wired up?</p>
| <p>One easy trick to debug newly written code in the global.asax file is to save the web.config file. Each time the config.file is saved, the application is stopped and started.</p>
<p>You could find useful information in this blog entry</p>
<p><a href="http://blogs.msdn.com/webdevtools/archive/2007/12/13/workaround-debugging-global-aspx-cs-application-start-with-asp-net-web-server-within-visual-studio.aspx">Workaround: Debugging Global.aspx.cs Application_Start() with ASP.Net Web Server within Visual Studio</a> </p>
<blockquote>
<p>The reason behind this is that we do
not kill the ASP.Net Web Server
process after your every debug run and
hence Application_Start() is not fired
every time. There is a good reason
why we do so... Starting ASP.Net Web
Server process is an expensive task
and in most of the scenarios recycling
this process after every debug would
adversely impact your performance...
If you do not want to debug your
Application_Start() method then
probably you do not need to have the
process restart and save performance
most of the time...</p>
</blockquote>
<p>One of the proposed workarounds:</p>
<blockquote>
<p>You can go to your property pages of
your web application and enable Edit &
Continue like shown below:</p>
</blockquote>
<p><img src="http://blogs.msdn.com/blogfiles/webdevtools/WindowsLiveWriter/Workaroun.NetWebServerwithinVisualStudio%5F11E09/image%5Fthumb%5F3.png" alt="alt text" /></p>
<p>(from the Visual Web Developer Team Blog)</p>
|
Implementing observer pattern using WCF <p>When I first posted this question I had strong coupling between my web service and application controller where the controller needed to open multiple threads to the service and as it received back data it had to do a lot of processing on the returned data and merge it into one dataset. I did not like the fact that the client had to so much processing and merge the returned data before it was ready to be used and wanted to move that layer to the service and let the service open the asynchronous threads to the suppliers and merge the results before returning them to the client.</p>
<p>One challenge I had was that I could not wait till all threads were complete and results were merged, I had to start receiving data as it was available. That called me to implement an observer pattern on the service so that it would notify my application when new set of results are merged and ready to be used and send them to the application. </p>
<p>I was looking for how to do this using either on ASMX webservices or WCF and so far I have found implementing it using WCF but this thread is always open for suggestions and improvements.</p>
| <p>OK the solution to my problem came from <a href="http://msdn.microsoft.com/en-us/netframework/aa663324.aspx" rel="nofollow">WCF</a></p>
<p>In addition to classic request-reply operation of ASMX web services, WCF supports additional operation types like; one-way calls, duplex callbacks and streaming. </p>
<p>Not too hard to guess, duplex callback was what I was looking for.</p>
<p>Duplex callbacks simply allow the service to do call backs to the client. A callback contract is defined on the server and client is required to provide the callback endpoint on every call. Then it is up to the service to decide when and how many times to use the callback reference.</p>
<p>Only bidirectiona-capable bindings support callback operations. WCF offers the WSDualHttpBinding to support callbacks over HTTP (Callback support also exists by NetNamedPipeBinding and NetTcpBinding as TCP and IPC protocols support duplex communication)</p>
<p>One very important thing to note here is that duplex callbacks are nonstandard and pure Microsoft feature. This is not creating a problem on my current task at hand as both my web service and application are running on Microsoft ASP.NET</p>
<p><a href="http://rads.stackoverflow.com/amzn/click/0596521308" rel="nofollow">Programming WCF Services</a> gave me a good jump start on WCF. Being over 700 pages it delves deep into all WCF consepts and has a dedicated chapter on the Callback and other type of operations. </p>
<p>Some other good resources I found on the net are;</p>
<p><a href="http://social.msdn.microsoft.com/content/en-us/msft/netframework/wcf/screencasts" rel="nofollow">Windows Communication Foundation (WCF) Screencasts</a></p>
<p><a href="http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?culture=en-US&EventID=1032344313&CountryCode=US" rel="nofollow">MSDN Webcast: Windows Communication Foundation Top to Bottom</a></p>
<p><a href="http://www.codeplex.com/servicefactory" rel="nofollow">Web Service Software Factory</a></p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc163481.aspx" rel="nofollow">The Service Factory for WCF</a></p>
|
How can you find unused functions in Python code? <p>So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?</p>
<p>I've seen these two references: <a href="http://stackoverflow.com/questions/245963">Find unused code</a> and <a href="http://stackoverflow.com/questions/11532">Tool to find unused functions in php project</a>, but they seem specific to C# and PHP, respectively.</p>
<p>Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?</p>
| <p>In python you can find unused code by using dynamic or static code analyzers. Two examples for dynamic analyzers are <strong>coverage</strong> and <strong>figleaf</strong>. They have the drawback that you have to run all possible branches of your code in order to find unused parts, but they also have the advantage that you get very reliable results.</p>
<p>Alternatively, you can use static code analyzers, that just look at your code, but don't actually run it. This has the advantage that they run much faster, but due to python's dynamic nature the results are not 100% percent accurate and you might want to double-check them.
Two tools that come to mind here are <strong>pyflakes</strong> and <strong>vulture</strong>. They are complementary: Pyflakes finds unused imports and unused local variables while vulture finds unused functions, methods, classes, variables and attributes.</p>
<p>The tools are all available at the Python Package Index <a href="http://pypi.python.org/pypi">http://pypi.python.org/pypi</a>.</p>
|
Linux linker flag -lXi not finding lib when compiling Lazarus code <p>After I solved my <a href="http://stackoverflow.com/questions/673086/faulty-fonts-on-lazarus">first problem</a> I got into another one.
Looks like I'm missing some kind of library, making the linker complain that the -lXi is not working.</p>
<p>I've included most of the Xorg devel packages, what more do I need?</p>
| <p>When linking to "-lXi" the compiler looks for a file with name starting with "libXi.so" (followed by some version number). The command </p>
<pre><code>locate libXi.so | xargs rpm -qf | sort -u
</code></pre>
<p>gives</p>
<pre><code>libXi-1.1.3-4.fc9.i386
libXi-1.1.3-4.fc9.x86_64
libXi-debuginfo-1.1.3-4.fc9.x86_64
libXi-devel-1.1.3-4.fc9.x86_64
</code></pre>
<p>on my Fedora 10 system, so you are probably missing the <em>libXi-devel</em> package.</p>
|
Reading and writing XML using JUST Java 1.5 (or earlier) <p>For reading XML, there is SAX and DOM built into Java 1.5. You can use JAXP and not need to know details about what parser is available... So, what are some prescribed APIs for one to <strong>write</strong> XML documents in Java 1.5 and earlier?</p>
<ul>
<li>I don't want to use a third party binary</li>
<li>I don't want to assume a Sun VM or IBM VM etc and use some specialized class</li>
<li>Whatever means there is of writing the document, I would like to read in a complementary way.</li>
<li>Performance and suitability for large XML files is not particularly important</li>
</ul>
<p>Ideally, a read-and-write with no changes is just a few lines of code.</p>
| <p>Java 1.4 comes with <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/transform/package-summary.html">javax.xml.transform</a>, which can take a <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/transform/dom/DOMSource.html">DOMSource</a>, <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/transform/sax/SAXSource.html">SAXSource</a>, etc:</p>
<pre><code>// print document
InputSource inputSource = new InputSource(stream);
Source saxSource = new SAXSource(inputSource);
Result result = new StreamResult(System.out);
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory
.newTransformer();
transformer.transform(saxSource, result);
</code></pre>
<p>If you want to go back to the J2SE 1.3 API, you're pretty much on your own (though if you're on the J2EE API of that era, there might be something - I don't recall).</p>
|
How do I pass a Linq query to a method? <p>I'd like to pass a Linq query to a method, how do I specify the argument type?</p>
<p>My link query look something like:</p>
<pre><code>var query =
from p in pointList
where p.X < 100
select new {X = p.X, Y = p.Y}
</code></pre>
<p>clearly I'm new to Linq, and will probably get rid of the receiving method eventually when I convert the rest of my code, but it seems like something I should know...</p>
<p>thanks</p>
| <p>You'll need to either use a normal type for the projection, or make the method you're passing it to generic as well (which will mean you can't do as much with it). What exactly are you trying to do? If you need to use the X and Y values from the method, you'll definitely need to create a normal type. (There are horribly hacky ways of avoiding it, but they're not a good idea.)</p>
<p>Note: some other answers are currently talking about <code>IQueryable<T></code>, but there's no indication that you're using anything more than LINQ to Objects, in which case it'll be an <code>IEnumerable<T></code> instead - but the <code>T</code> is currently an anonymous type. That's the bit you'll need to work on if you want to use the individual values within each item. If you're <em>not</em> using LINQ to Objects, please clarify the question and I'll edit this answer.</p>
<p>For example, taking your current query (which is slightly broken, as you can't use two projection initializers twice with the same name X). You'd create a new type, e.g. <code>MyPoint</code> </p>
<pre><code>public sealed class MyPoint
{
private readonly int x;
private readonly int y;
public int X { get { return x; } }
public int Y { get { return y; } }
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
}
</code></pre>
<p>Your query would then be:</p>
<pre><code>var query =
from p in pointList
where p.X < 100
select new MyPoint(p.X, p.Y);
</code></pre>
<p>You'd then write your method as:</p>
<pre><code>public void SomeMethod(IEnumerable<MyPoint> points)
{
...
}
</code></pre>
<p>And call it as <code>SomeMethod(query);</code></p>
|
Zend Framework Forms - How to I make a control an array <p>Using Zend form how would I make a control (element) an array?</p>
<p>An example use case:</p>
<p>I have a list of items and I want each item to have it's own checkbox on a form, but those checkboxes should post as an array. This means that each checkbox name is 'item[]'. How can I achive this using Zend Form? I have tried setting the isArray property on the checkboxes to true but giving them the same name, but this doesnt seem to work.</p>
| <p><a href="http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.multiCheckbox" rel="nofollow">http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.multiCheckbox</a></p>
|
VS 2008 - Link against older C runtime <p>How can I compile using Visual C++ 2008 and link against an older version of the C runtime (I want version 7 instead of 9)?</p>
| <p>I think what you have to do is find the Linker -> Input property page for your project and tell it to specifically ignore msvcrtd.dll / msvcrt.dll and then explicitly link to the version you want (full path). Not sure what will happen if they have the same name... </p>
|
How Do You Create Multiple Instances of a Library Class in CodeIgniter? <p>I'd like to create several instances of a class in CodeIgniter. I have created my class as a library, but cannot figure out the syntax to use to create more than one instance.</p>
| <p>From the CodeIgniter users guide:</p>
<p><a href="http://codeigniter.com/user%5Fguide/libraries/loader.html">CI Users Guide: Loader Class</a></p>
<blockquote>
<p><strong>Assigning a Library to a different object name</strong></p>
<p>If the third (optional) parameter is
blank, the library will usually be
assigned to an object with the same
name as the library. For example, if
the library is named Session, it will
be assigned to a variable named
$this->session.</p>
<p>If you prefer to set your own class
names you can pass its value to the
third parameter:
$this->load->library('session', '',
'my_session');</p>
<p>// Session class is now accessed
using:</p>
<p>$this->my_session</p>
</blockquote>
<p>I think that's what you're looking for.</p>
|
Php on zend, how to escape a variable for a query? <p>im doing some queries in Zend Framework and i need to make sure no SQL injection is possible in the next kind of formats. I can use mysql_escape(deprecated) and wont do all the work. If i try to use real_mysql_escape it wont be able to grab the conection with the database and i cant find how zend_filter would solve the problem. </p>
<p>The query im doing (simplied) have the next sintaxes:</p>
<pre><code> $db = Zend_Registry::get('db');
$select = "SELECT COUNT(*) AS num
FROM message m
WHERE m.message LIKE '".$username." %'";
$row = $db->fetchRow($select);
</code></pre>
<p>What is the best way to prevent SQL INJECTION with this framework?</p>
| <p>Easy: </p>
<pre><code>$db->quote($username);
</code></pre>
<p>So:</p>
<pre><code> $username = $db->quote($username . '%');
$select = 'SELECT COUNT(*) AS num
FROM message m
WHERE m.message LIKE ' . $username;
$row = $db->fetchRow($select);
</code></pre>
|
How would you develop a workflow application in Java? <p>I want to develop an application that allows its users to define workflows and then executes them.</p>
<p>My environment is JBoss so naturally I'm considering jBPM.</p>
<p>I can NOT use the jBPM graphic workflow design tools since my workflows are very specific and I don't want to expose my users to all jBPM features.</p>
<p>Questions:</p>
<ol>
<li>Is jBPM robust and scalable?</li>
<li>Is jBPM standard (i.e., used by enough people)?</li>
<li>How do I tie my own workflow GUI to the jBPM engine?</li>
<li>Is jBPM suitable for the job, should I consider a different platform or maybe do it (the workflow logic) myself?</li>
</ol>
| <ol>
<li><p>Is jBPM robust and scalable? </p>
<p>Ans: Yes, Jbpm is robust and scalable. Need to configure/develop properly..</p></li>
<li><p>Is jBPM standard (i.e., used by enough people)? </p>
<p>Ans : You need to ask with jbpm forum. </p></li>
<li><p>How do I tie my own workflow GUI to the jBPM engine? </p>
<p>Ans : You need to develop processConfiguration file for each workflow, and deploy<br />
these config file(xml file), this updates jbpm related tables and your
workflow related tables. </p></li>
<li><p>Is jBPM suitable for the job, should I consider a different platform or maybe do it
(the workflow logic) myself? </p>
<p>Ans : Its suitable for big workflows( where the stages/Nodes and logic are more).
And easy to Integrate with rule engine. </p></li>
</ol>
|
how do i get started using boost <p>I hear a lot about boost here and I am beginning to think it could help a lot with my software development. More so in concurrency and memory management in my particular case as we have had a lot of bugs in this area. </p>
<p>What are the key language features I need to polish up on to effectively benefit from using boost and to shorten the learning curve? I have seen that <strong><em>function objects</em></strong> are commonly used so I would probably need to polish up on that.</p>
<p>Additionally, are there any tutorials and 101 resources I can quickly look at to just get a feel and understanding on using boost. </p>
<p>I realise there is a lot boost offers and I have to pick the right tools for the right job but any leads will help.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/379290/how-to-learn-boost">How to learn boost</a> (no longer valid; HTTP return status 404)</li>
</ul>
| <p>Boost has an unimaginable number of libraries.
Easy ones to get started on are </p>
<ul>
<li>noncopyable</li>
<li>array</li>
<li>circular_buffer</li>
<li>foreach</li>
<li>operators (one of my personal favorites)</li>
<li>smart_ptr</li>
<li>date_time</li>
</ul>
<p>More advanced ones include </p>
<ul>
<li>lambda</li>
<li>bind</li>
<li>iostreams</li>
<li>serialization</li>
<li>threads</li>
</ul>
<p>Getting used to boost takes time, but I assure you it will make your life much better. Plus, looking at how the boost libraries are coded will help you get better at c++ coding, especially templates.</p>
<p>You mentioned what should you look up before trying boost. I agree that function objects are a great thing to research. Also, make sure to look up about template programming. A common problem to make sure you know is when to use the <code>typename</code> qualifier for dependent types. For the most part, however, the libraries are very well documented, with examples and reference materials.</p>
|
Query the AppStore? <p>How do sites like Apptism and Appbeacon build their list of apps from the AppStore? Is there some way to query the store and get information such as title, author, ratings, etc.?</p>
| <p>They screen-scrape the html. <a href="http://benchatelain.com/2009/03/05/scraping-app-store-rankings-around-the-world/" rel="nofollow">This article</a> may be helpful for you.</p>
<p>Several websites (such as Pinch) use this data to provide RSS feeds of different application categories and their associated information. Depending on your needs this may be an easier option.</p>
|
Database for an embedded system <p>I'm looking for a very high performance and cheap (hopefully free) database engine to be used on an x86 embedded platform in <strong>Windows CE</strong>. Can anyone give some suggestions?
The important things I'm looking for are:</p>
<ol>
<li>High Performance (for a real-time system)</li>
<li>Low cost</li>
<li>Usable with Compact .NET framework</li>
</ol>
<p>Thanks</p>
| <p>Given your needs the easiest is likely <a href="http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx" rel="nofollow">SQL Server Compact Edition</a></p>
<ol>
<li>Performance is pretty good.</li>
<li>Free</li>
<li>Provides good .NET interoperability</li>
</ol>
<p><a href="http://www.sqlite.org/" rel="nofollow">SQLite</a> is another option that also meets all of the above. There are numerous tests around that compare the performance of these two under different conditions.</p>
|
How can I capture the text between specific delimiters into a shell variable? <p>I have little problem with specifying my variable. I have a file with normal text and somewhere in it there are brackets <code>[ ]</code> (only 1 pair of brackets in whole file), and some text between them. I need to capture the text within these brackets in a shell (bash) variable. How can I do that, please?</p>
| <p>Bash/sed:</p>
<pre><code>VARIABLE=$(tr -d '\n' filename | sed -n -e '/\[[^]]/s/^[^[]*\[\([^]]*\)].*$/\1/p')
</code></pre>
<p>If that is unreadable, here's a bit of an explanation:</p>
<pre><code>VARIABLE=`subexpression` Assigns the variable VARIABLE to the output of the subexpression.
tr -d '\n' filename Reads filename, deletes newline characters, and prints the result to sed's input
sed -n -e 'command' Executes the sed command without printing any lines
/\[[^]]/ Execute the command only on lines which contain [some text]
s/ Substitute
^[^[]* Match any non-[ text
\[ Match [
\([^]]*\) Match any non-] text into group 1
] Match ]
.*$ Match any text
/\1/ Replaces the line with group 1
p Prints the line
</code></pre>
|
Linking two Abstract Factory Patterns in Java <p>I am writing a quote-matching program in which two Abstract Factory Patterns are required, these are two interfaces; <strong>QuoteFactory</strong> and <strong><em>ModeFactory</em></strong>. ModeFactory switches between <strong><em>EasyMode</em></strong> and <strong><em>HardMode</em></strong> and QuoteFactory picks out Quotes between several different subjects (i.e. <strong>PoliticalQuotes</strong>, <strong>SportsQuotes</strong>). In short, the user will pick a mode, if the EasyMode is picked then the user has to guess the quote whereas if the user chooses the HardMode the user is told who said the quote and then has to guess, so the implementation of the Quotes will change depending on the Mode as well as the Quotes chosen.</p>
<p>So far I have created ModeFactory as an interface and implemented it into EasyMode and HardMode, but now I need to somehow integrate another Abstract Factory Pattern (or more) into these modes so that the Quotes can be chosen. If it is helpful I have also created a Quote class in which my Quotes are defined.</p>
<p>Can anyone help me come up with a basic implementation of these Abstract Factories? This is the outline of what I have so far, although I cannot help but feel that I have overcomplicated it somehow... </p>
<p>EDIT: To reclarify what I mean: If the user picks the Easy Mode then they are provided with the start of a quote AND the author of that quote, whereas if they pick the Hard Mode they are only provided with the start of the quote. For example</p>
<p><strong>Easy Mode:</strong>
"I felt the power of..."
Jose Mourinho</p>
<p><strong>Hard Mode:</strong>
"I felt the power of..."</p>
<p>The hard mode does not give the author to make it harder for the user to guess the rest of the quote. Also, this is not a school assignment. I've been reading Head First Design Patterns and now I'm trying to apply what I've learned into different situations (instead of their Pizza example I'm working on a Quote Guessing Game, after reading through the QI (British TV Show) book.</p>
<pre><code>public interface ModeFactory {
public Mode retrieveMode(String s);
}
public interface QuoteFactory {
public Quote retrieveQuote(String s);
}
</code></pre>
| <p>Can you take one step back and restate what it is you are trying to do? I sometimes find that by going through the effort of explaining the challenge to someone not familiar with it, the solution emerges to me sort of organically. </p>
<p>From your descrpition, it seems like you have started with a partial solution ("I want to use an Abstract Factory pattern"), rather than starting with what you really want to do (eg, "I want to provide a quote class that delivers different quotes depending on Flavor (political, sports) and mode (easy, hard)") .</p>
<p>It feels to me like an enum, not a factory. There's an enum for {political, sports} and a separate one for mode. </p>
<p><strong>EDIT</strong>: after thinking about this again, maybe it's a school assignment ("Use an abstract factory pattern to ....blah blah blah") and that is the reason you have sort of started with a half-solution. </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.