Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Final question for today :) thanks for your input on the previous ones. BTW: Already searched the forum on this and nothing quite answers this one. We use some 3rd party libraries which pop work onto the Threadpool and we don't want to shutdown while there are outstanding activities. When shutting down an application, the application will shutdown even if there is work outstanding in the System.Threading.ThreadPool because these threads are back ground threads. Other than doing some form of reference counting (and enforcing every item Queued into the pool to use this mechanism, which we don't have control over) is there some way to stop the application shutting down while there is outstanding work to be done. I've looked at using the GetAvailableThreads() vs GetMaxThreads(), but these can be the same because we may have caught the Threadpool as a thread was freed up but not allocated a queued workitem. All help appreciated? Kind Regards Noel
Thanks for your replies. I've found a work-around outside of the thread pool using AOP and [Castle Windsors](http://www.castleproject.org/container/index.html) dynamic proxy to inject referencing counting around the class. Luckily for me the class exposed a clean interface that I could wrap and it works a treat.
Since I'm real programmer (that's C, boys ;-) I've not used ThreadPool. However, a suggestion comes to mind - have a semaphore increment on each task you issue into threadpool, and that that semaphore be released on completion. When your app comes to exit, wait on the semaphore. Any use?
Is there any way to stop an application shutting down with work still in the system Threadpool
[ "", "c#", "multithreading", "" ]
If I want to read or write a file I *could* use stream.BeginRead and stream.EndRead, but that requires callbacks and a LOT of ugly, complicated code using the asynchronous programming model. Why would I want to use these asynchronous IO methods (that use the .NET threadpool behind the scenes) than write the same code in a synchronous style, and pass *that* to the thread pool. (Rather than chopping up my method with the callbacks.) Update: Some (good) responses indicate that using the APM saves me from creating a thread - which I agree with since new threads each have their own 2MB stack. But where does the 'BeginRead' and 'Endread' execute? The threadpool? Is reusing a thread which has already been allocated the only benefit?
First of all, you should also look into the [Event-based APM](http://msdn.microsoft.com/en-us/library/wewwczdw.aspx). To answer your question, you're probably thinking about using a separate thread, and making synchronous calls. The other thread would block waiting for the calls to complete. With the APM, there are no threads blocking at all. There is no draw from the Thread Pool. This is especially important for server applications like ASP.NET, since it means that a blocking thread won't be preventing requests from being processed.
Jeff Richter has a very clever and clean [way](http://channel9.msdn.com/posts/Charles/Jeffrey-Richter-and-his-AsyncEnumerator/) to use APM.
Why use the APM instead of using a separate thread?
[ "", "c#", ".net", "multithreading", "asynchronous", "" ]
My ASP.NET application loads an assembly and creates a class instance from an object within it. The assembly itself has a reference to a dll called "Aspose.Cells.dll" which it can access without any problems and is located on the same path as the assembly file itself. However, when I make a method call to one of its methods I get this error: > Could not load file or assembly 'Aspose.Cells, Version=4.1.2.0, Culture=neutral, PublicKeyToken=9a40d5a4b59e5256' or one of its dependencies. I figure that I need to make my ASP.NET application reference this DLL as well but everything I've tried so far has failed. The assembly DLL which is loaded is not located within the root of the web application and I'm hoping that it doesn't have to be. I can load the assembly like this: ``` Assembly asm = Assembly.LoadFile(@"D:\Dev\EasyFlow\Plugins\ImportExportLibrary\bin\Debug\Aspose.Cells.dll"); ``` But I can not use it like this: ``` AppDomain newDomain = AppDomain.CreateDomain("testAspose"); Assembly asm = newDomain.Load(System.IO.File.ReadAllBytes(@"D:\Dev\EasyFlow\Plugins\ImportExportLibrary\bin\Debug\Aspose.Cells.dll")); ``` Is there a better way to do it? ### Update: Thanks for your replies. I forgot to mention that I cannot copy the assemblies to the bin folder or the GAC because I want it to work as a plugin system where assemblies can be replaced easily by changing the path to assemblies in a configuration file and not having to manually copy files into the main project. However, the `AssemblyResolve` event seems interesting and I will give it a try later.
There are a few ways to do this. One way is described in the Microsoft Knowledge Base article "[How to load an assembly at runtime that is located in a folder that is not the bin folder of the application](http://support.microsoft.com/kb/837908)". It provides a pretty good step-by-step method of how to do this.
You can copy the dependent assembly into the Bin folder or install it in the GAC.
ASP.NET application reference to assembly in programmatically loaded assembly
[ "", "c#", "assemblies", "" ]
I'm trying to open a JMX connection to java application running on a remote machine. The application JVM is configured with the following options: * com.sun.management.jmxremote * com.sun.management.jmxremote.port=1088 * com.sun.management.jmxremote.authenticate=false * com.sun.management.jmxremote.ssl=false I'm able to connect using `localhost:1088` using jconsole or jvisualvm. But I'm not able to connect using `xxx.xxx.xxx.xxx:1088` from a remote machine. There is no firewall between the servers, or on the OS. But to eliminate this possibility I `telnet xxx.xxx.xxx.xxx 1088` and I think it connects, as the console screen turns blank. Both servers are Windows Server 2008 x64. Tried with 64-bit JVM and 32-bit, neither work.
Had it been on Linux the problem would be that *localhost is the loopback interface*, you need to application to bind to your *network interface*. You can use the netstat to confirm that it is not bound to the expected network interface. You can make this work by invoking the program with the system parameter `java.rmi.server.hostname="YOUR_IP"`, either as an environment variable or using ``` java -Djava.rmi.server.hostname=YOUR_IP YOUR_APP ```
I've spend more than a day trying to make JMX to work from outside localhost. It seems that SUN/Oracle failed to provide a good documentation on this. Be sure that the following command returns you a real IP or HOSTNAME. If it does return something like 127.0.0.1, 127.0.1.1 or localhost it will not work and you will have to update `/etc/hosts` file. ``` hostname -i ``` Here is the command needed to enable JMX even from outside ``` -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=1100 -Djava.rmi.server.hostname=myserver.example.com ``` Where as you assumed, myserver.example.com must match what `hostname -i` returns. Obviously, you need to be sure that the firewall does not block you, but I'm almost sure that this is not your problem, the problem being the last parameter that is not documented.
Remote JMX connection
[ "", "java", "jmx", "jconsole", "" ]
I'm trying to figure out texture mapping in OpenGL and I can't get a simple example to work. The polygon is being drawn, though it's not textured but just a solid color. Also the bitmap is being loaded correctly into sprite1[] as I was successfully using glDrawPixels up til now. I use glGenTextures to get my tex name, but I notice it doesn't change texName1; this GLuint is whatever I initialize it to, even after the call to glGenTextures... I have enabled GL\_TEXTURE\_2D. Heres the code: ``` GLuint texName1 = 0; glGenTextures(1, &texName1); glBindTexture(GL_TEXTURE_2D, texName1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT, sprite1[18], sprite1[22], 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, &sprite1[54]); glColor3f(1, 1, 0); glBindTexture(GL_TEXTURE_2D, texName1); glBegin(GL_QUADS); glTexCoord2f (0.0, 0.0); glVertex3f (0.0, 0.0, -5.0f); glTexCoord2f (1.0, 0.0); glVertex3f (.5, 0.0, -5.0f); glTexCoord2f (1.0, 1.0); glVertex3f (.5, .5, -5.0f); glTexCoord2f (0.0, 1.0); glVertex3f (0.0, .5, -5.0f); glEnd(); ``` UPDATE: I'm at a loss. Here's everything I've tried: 1. Turns out I was initializing my texture before OGL was initialized. The texture is initialized (glGenTextures->glTexImage2D) in a class constructor and drawn (glBegin->glEnd) in a member function that is called every frame. genTextures appears to be working correctly now and I'm getting a name of 1. 2. Every possible combination of GL\_RGBA8, GL\_BGRA\_EXT (GL\_BGRA doesn't work on my system; I need the \_EXT), and I even removed the alpha channel from the bitmap and tried all combinations of GL\_RGB, GL\_BGR\_EXT, etc etc. No luck. 3. Tried procedurally creating a bitmap and using that 4. Made sure GL\_COLOR\_MATERIAL isn't enabled. 5. Changed bitmap size to 32x32. 6. Tried glTexEnvi instead of glTexEnvf.
I found the problem. My call to `glEnable` was `glEnable(GL_BLEND | GL_TEXTURE_2D)`. Using glGetError I saw I was getting a GL\_INVALID\_ENUM for this call, so I moved GL\_TEXTURE\_2D to its own enable function and bingo. I guess logical OR isn't allowed for glEnable?
In addition to [mentat's note](https://stackoverflow.com/questions/742342/simple-opengl-texture-map-not-working/759322#759322) that you might have a problem with non-power-of-two texture dimensions, you mention the texture name generation not changing the name. That sounds as if you're calling `glGenTextures()` too early, i.e. before initializing OpenGL. If you're not, then I suggest adding code just after the call to `glGenTextures()` that check the OpenGL error state, by calling `glGetError()`.
Simple OpenGL texture map not working?
[ "", "c++", "opengl", "textures", "" ]
Does anyone know how (or process) to remove comments from Java class file at build time? i would like to do this for specific packages in the project when the project is build using Ant. Any ANT scripts or some custom code most welcome.
There are no comments in the compiled `.class` file.
I believe the Java compiler does this for you already.
Script to remove comments in Java
[ "", "java", "ant", "build-automation", "" ]
I'm using jQuery with the BlockUI plugin to block a page after a link is clicked. I'm also using a DOM element to display a message when the page is blocked. Here's a simple example of the code used: ``` <a id="testme" href="#">Click Me</a> <script type="text/javascript"> $(document).ready(function() { $('#testme').click(function() { // Set our message in the message panel.... $('#progressMessage').text('Please wait!'); $.blockUI({ message: $('#progressWidget') }); }); } </script> <div id="progressWidget" style="display:none" align="center"> <div class="modalUpdateProgressMessage"> <div id="progressMessage" /> <img src="spinbar.gif" /> </div> </div> ``` The problem I'm encountering is that when I set the `.text()` of the `<div id="progressMessage" />` element, the `<img src="spinbar.gif" />` element seems to get removed. I've verified that this is actually happening using Firebug. I've also tried using a `<span>` instead of a `<div>` for `progressMessage` but the result is the same. Can anyone explain why this is happening?
Don't do a self-closing DIV, it's not valid.
The self closing is the problem ``` $("#selector").append("<div>"); //fail $("#selector").append("<div/>"); //fail $("#selector").append("<div></div>"); //SUCCESS! ```
Why is jQuery deleting my <img> element?
[ "", "javascript", "jquery", "jquery-plugins", "" ]
Assume you have two web applications running in two different tabs/windows in your browser. Is there a predefined interface in IE, Firefox or Google Chrome to pass data between the two windows? If so it should be possible to implement drag'n drop, right? Because I don't think this is possible I wonder if the same could be achieved with Flash. This sums up to the following question: Is it possible to implement cross-application drag'n drop behaviour with Javascript/DOM or Flash?
I think you'll find an answer in the Chrome Experiment's [Browser Ball.](http://www.chromeexperiments.com/detail/browser-ball/) In short, there is no good way to do this - but you'll see it's definitely possible. Edit: I suppose I should make clear: you're very limited in what you can actually pass stuff between, and the browsers which are supported. What it seems like you're actually trying to accomplish may be impossible, but the general concept of passing between multiple windows is **"possible".**
No Javascript can not interact with another window. This is a restriction of the browser and Javascript's restriction to interact outside of its domain. And as far as I know, this is not possible with Flash either.
Drag'n drop between two unrelated web applications
[ "", "javascript", "flash", "web-applications", "drag-and-drop", "" ]
Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)
[Dive into Python](https://web.archive.org/web/20180905200140/http://diveintopython.net/object_oriented_framework/index.html) uses MP3 ID3 tags as an example.
Mutagen <https://bitbucket.org/lazka/mutagen> *Edited 14/09/23 with current code host location* eyeD3 <http://eyed3.nicfit.net/>
How to read ID3 Tag in an MP3 using Python?
[ "", "python", "tags", "mp3", "id3", "" ]
How would you, in C#, determine the name of the variable that was used in calling a method? Example: ``` public void MyTestMethod1() { string myVar = "Hello World"; MyTestMethod2(myVar); } public void MyMethod2(string parm) { // do some reflection magic here that detects that this method was called using a variable called 'myVar' } ``` I understand that the parameter might not always be a variable, but the place I am using it is in some validation code where I am hoping that the dev can either explicitly state the friendly name of the value they are validating, and if they don't then it just infers it from the name of the var that they called the method with...
Unfortunately, that's going to be very hard, if not impossible. Why exactly do you need the name of the variable originally sent in? Remember that there might not be an actual variable used: ``` MyMethod2(myVar + "! 123"); ``` In this case, myVar holds just parts of the value, the rest is calculated in the expression at runtime.
There is a way, but it's pretty ugly. ``` public void MyTestMethod1() { string myVar = "Hello World"; MyTestMethod2(() => myVar); } public void MyMethod2(Expression<Func<string>> func) { var localVariable = (func.Body as MemberExpression).Member.Name; // localVariable == "myVar" } ``` As you can see, all your calls would have to be wrapped into lambdas and this method breaks down if you start to do anything else in the lambda besides return a single variable.
Determine the name of the variable used as a parameter to a method
[ "", "c#", "reflection", "parameters", "" ]
I would like to use the following code in C# but I just can't seem to get out of it. I would like to terminate the application if the user presses a key or moves the rodent (aka mouse). Here is my code (no laughing!). ``` private void frmDots_KeyDown(object sender, KeyEventArgs e) { bgNotClicked = false; Close(); } private void frmDots_Click(object sender, EventArgs e) { bgNotClicked = false; Close(); } while (bgNotClicked) { // Clear the first element in our XY position. This is the reverse of the way I normally create the dots application System.Drawing.Rectangle clearDots = new System.Drawing.Rectangle(Dots.PositionX[iCounter], Dots.PositionY[iCounter], 8, 8); // Create the black color and brush to clear dots Color clearDotsColor = Color.Black; SolidBrush clearDotsBrush = new SolidBrush(clearDotsColor); // Finally clear the dot e.Graphics.FillEllipse(clearDotsBrush, clearDots); GetRandomPosition(iCounter); // Fill the elements to display colors on the displays canvas System.Drawing.Rectangle colorDots = new System.Drawing.Rectangle(Dots.PositionX[iCounter], Dots.PositionY[iCounter], 8, 8); // Create the color and brush to show dots Color colorRandom = GetRandomColor(); SolidBrush colorBrush = new SolidBrush(colorRandom); // Finally show the dot e.Graphics.FillEllipse(colorBrush, colorDots); Thread.Sleep(5); iCounter++; if (iCounter == 399) { iCounter = 0; } } } ```
Edit: After seeing your edit, this is definitely your problem. The issue is that your while loop blocks the main UI thread, so it never handles the Windows Messages which trigger your key press/mouse/etc handlers. You have a couple of options - you can either move some of this onto a separate thread, do what I suggested below, or add a call to [Application.DoEvents](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents.aspx) in your while loop. This would allow your event handlers to run, which would in turn set `bgNotClicked = false;`. Right now, that's never occurring because your UI is blocked entirely. --- Original Post: If you're doing this loop in your UI thread, you're going to need to rethink the design a bit. Setting `bgNotClicked = false;` somewhere in an event handler will work, but only if your event handler is able to run. If you're doing the above code in the UI thread, it will block your UI thread indefinitely, preventing the event handler from firing. I would recommend reworking this to be based off a timer (so it runs repeatedly on regular intervals), instead of locked into a while loop. This would allow your other UI events to fire between runs, and instead of setting `bgNotClicked = false;`, your event handler could just set the timer to be not enabled.
Your "busy waiting" strategy is poor design. Instead, you should use event handlers that are fired: * On keypress. * When the mouse is moved. In either case, you can respond by terminating the application.
How can I stop my while loop?
[ "", "c#", "" ]
I keep a Session variable when the user is logged in. So that when the user click on btnLogout it must clear all my sessions and Log the User out for GOOD!!! It does clear my sessions but if i click the BACK button in IE right after i logged out then i am still logged in! Meaning it goes back to screen where the user was still logged into. My code on log out ``` protected void btnLogout_Click { Session.Clear(); Session.Abandon(); Session.RemoveAll(); Response.Redirect("Home.aspx"); } ``` Why is this and how can i prevent this? **EDIT:** Is there maybe an option in code i can do that will disable the user from pressing the BACK button in the Web Browzer?
You could put this in the Page\_Init of your Master: ``` Response.Cache.SetNoServerCaching(); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); Response.Cache.SetExpires(new DateTime(1900, 01, 01, 00, 00, 00, 00)); ``` This is, e.g., what most bank websites do so you can't effectively use the back button.
Is this really an issue though? Yes they could see their previous page as it has been cached, but as soon as they attempt to make any other legitimate requests within this context these will fail as your session variables are gone. Unless you have some very specific reason for coding around this you would be solving a problem that doesn't really exist.
Problem with my Session variables in asp.net 2.0
[ "", "c#", "asp.net", "vb.net", "session", "back-button", "" ]
Say you have a function that returns an enum: ``` public enum ServerStatus { Down, Up } private ServerStatus GetServerStatus(int time) { if (time >= 0 && time < 12) { return ServerStatus.Down; } else if (time >= 12 && time <= 23) { return ServerStatus.Up; } else { return ?? // Server status is neither Up nor Down } } ``` Should I: 1. Add "Neither" to ServerStatus 2. Makes GetServerStatus return ServerStatus? and return null 3. Return a another bool that indicate if the value is meaningful
If that case should never happen in practice, and you don't expect to have to produce something other than 'Up' and 'Down', then you should throw an exception.
If you don't want to throw an exception then you could always have an Unknown enum value. For example server status could be Up, Down or Unknown. The unknown status could be valid in some cases (e.g. if you cant get a connection to the server). This unknown value could be tested like a boolean value to decide if the answer is meaningful if appropriate. I'm not saying that this is better than an ArgumentOutOfRangeException, just that it is another way of dealing with the problem. Your calling code could always throw the exception depending on other criteria.
Value to return to denote invalid value
[ "", "c#", "" ]
Properties `document.body.clientHeight` and `document.body.clientWidth` return different values on IE7, IE8 and Firefox: IE 8: ``` document.body.clientHeight : 704 document.body.clientWidth : 1148 ``` IE 7: ``` document.body.clientHeight : 704 document.body.clientWidth : 1132 ``` FireFox: ``` document.body.clientHeight : 620 document.body.clientWidth : 1152 ``` Why does this discrepancy exist? Are there any equivalent properties that are consistent across different browsers (IE8, IE7, Firefox) without using jQuery?
This has to do with the browser's box model. Use something like jQuery or another JavaScript abstraction library to normalize the DOM model.
Paul A is right about why the discrepancy exists but the solution offered by Ngm is wrong (in the sense of JQuery). The equivalent of clientHeight and clientWidth in jquery (1.3) is ``` $(window).width(), $(window).height() ```
clientHeight/clientWidth returning different values on different browsers
[ "", "javascript", "css", "firefox", "internet-explorer-8", "internet-explorer-7", "" ]
Wondering if there is any way to get the lambda expressions that result from a LINQ "query" syntax expression. Given: ``` var query = from c in dc.Colors where c.ID == 213 orderby c.Name, c.Description select new {c.ID, c.Name, c.Description }; ``` Is there any way to get the generated "lambda" code / expression? ``` var query = dc.Colors .Where(c => c.ID == 213) .OrderBy(c => c.Name) .ThenBy(c => c.Description) .Select(c => new {c.ID, c.Name, c.Description, }); ``` I know these are very simple examples and that the C# compiler generates a lambda expression from the query expression when compiling the code. Is there any way to get a copy of that expression? I am hoping to use this as a training tool for some of my team members that aren't very comfortable with lambda expressions. Also, I have used Linq Pad, but ideally this can be accomplised without a 3rd party tool.
Simply go: ``` string lambdaSyntax = query.Expression.ToString(); ``` The disadvantage compared to LINQPad is that the result is formatted all one line.
You could try compiling the assembly and then having a look at it using Reflector. This might be a bit more complicated than you want though, because the compiler will compile things right down to the direct method calls (everything will be static method calls, not extension methods, and the lambdas will get compiled into their own functions which are usually called something like `<ClassName>b_88f`) You'll certainly figure out what's going on though :-)
LINQ Query Syntax to Lambda
[ "", "c#", "linq", "" ]
This has probably been answered else where but how do you get the character value of an int value? Specifically I'm reading a from a tcp stream and the readers .read() method returns an int. How do I get a char from this?
If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the [`String`](http://java.sun.com/javase/6/docs/api/java/lang/String.html) constructor and provide a [`Charset`](http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html), or use [`InputStreamReader`](http://java.sun.com/javase/6/docs/api/java/io/InputStreamReader.html) with the appropriate `Charset` instead. Simply casting from `int` to `char` only works if you want ISO-8859-1, if you're reading bytes from a stream directly. EDIT: If you *are* already using a `Reader`, then casting the return value of `read()` to `char` is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call `read(char[], int, int)` to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.
Maybe you are asking for: ``` Character.toChars(65) // returns ['A'] ``` More info: [`Character.toChars(int codePoint)`](http://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#toChars-int-) > Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
Converting stream of int's to char's in java
[ "", "java", "types", "" ]
I have found an [example](http://blogs.msdn.com/markhsch/archive/2007/11/19/c-webcam-user-control-source.aspx) for accessing a webcam in C#. The example uses the [DirectShow.NET](http://directshownet.sourceforge.net/) library. I have tried to understand the code, but so far the only thing I could figure out is that somehow the usercontrol calls directshow to draw directly to the surface of the user control. I want to access each frame and put it into a Bitmap object. How can I tell when a new frame arrived? How can I capture this new frame into a Bitmap Object? This might be simple to answer if you know your way around DirectShow.NET.
You will need to use the [ISampleGrabber](http://msdn.microsoft.com/en-us/library/dd376984(VS.85).aspx) interface there are many c++ examples on the net on how to use it, it will give you data the in RGB raw format which you can feed into the Bitmap class. There is also an open source library called [Touchless](http://www.codeplex.com/touchless) it has a project in code which takes a web cam and give you a callback every time a new frame arrived.
Be sure to take a look at this article - <http://www.codeproject.com/Articles/125478/Versatile-WebCam-C-library> ; it is based on Touchless WebCam capturing component (but without other parts from Touchless SDK).
C# + DirectShow.NET = Simple WebCam access?
[ "", "c#", "directshow", "webcam", "directshow.net", "" ]
In large apps I find myself really wishing I had built-in AOP facilities. As it stands in C# the best you can do is factories and RealProxys, PostSharp, ICorDebug, ICorProfiler or injection frameworks. There is no clean built-in way of doing AOP. Is there any indication anywhere (blog post / internal discussion) that indicates that AOP is on the way?
Romain's answer covers (almost :) perfectly the current solutions. As for the future support, [Anders Hejlsberg](http://www.microsoft.com/presspass/exec/techfellow/hejlsberg/default.mspx) has [previously stated](http://almaer.com/blog/anders-hejlsberg-and-aop) that they'were in wait & see mode about AOP. We can only hope that with the managed rewrite of csc, and a «Compiler as a Service», one could plug into the compiler, and inject aspects there.
I haven't heard of a "clean built-in way of doing AOP". But as you stated, there are already plenty "clean ways of doing AOP", using mature and powerful frameworks like [PostSharp](http://www.postsharp.org) or [Castle DynamicProxy](http://www.castleproject.org/dynamicproxy/index.html). Using the BCL, one obvious way to do AOP, with pretty strong limitations thought, is to use transparent and real proxys, from .NET Remoting stack. Another way is to rely on System.Reflection.Emit to dynamically generate proxies, like, hum, DynamicProxy from Castle. Finally, there is also another official Microsoft flagged solution, that came with the [Enterprise Library](http://msdn.microsoft.com/en-us/library/cc467894.aspx). I'm talking about the [Policy Injection Application Block](http://msdn.microsoft.com/en-us/library/dd139982.aspx). [Unity](http://msdn.microsoft.com/en-us/library/dd139982.aspx) also offers some interception capabilities that leverage PIAB.
Built-in AOP in C# - is it on the way?
[ "", "c#", ".net", "aop", "" ]
How can I read from a stream when I don't know in advance how much data will come in? Right now I just picked a number on a high side (as in code below), but there's no guarantee I won't get more than that. So I read a byte at a time in a loop, resizing array each time? Sounds like too much resizing to be done :-/ ``` TcpClient tcpclnt = new TcpClient(); tcpclnt.Connect(ip, port); Stream stm = tcpclnt.GetStream(); stm.Write(cmdBuffer, 0, cmdBuffer.Length); byte[] response = new Byte[2048]; int read = stm.Read(response, 0, 2048); tcpclnt.Close(); ```
Putting it all together, assuming you're not getting a HUGE (more than can fit into memory)amount of data: ``` TcpClient tcpclnt = new TcpClient(); tcpclnt.Connect(ip, port); Stream stm = tcpclnt.GetStream(); stm.Write(cmdBuffer, 0, cmdBuffer.Length); MemoryStream ms = new MemoryStream(); byte[] buffer = new Byte[2048]; int length; while ((length = stm.Read(buffer, 0, buffer.Length)) > 0) ms.Write(buffer, 0, length); tcpclnt.Close(); byte[] response = ms.ToArray(); ``` As mentioned the `MemoryStream` will handle the dynamic byte array allocation for you. And `Stream.Read(byte[], int, int)` will return the length of the bytes found in this 'read' or `0` if it's reached the end.
MemoryStream is your friend ``` http://msdn.microsoft.com/en-us/library/system.io.memorystream ``` Construct with no default size and it will autoresize. Then just loop as you suggest reading a reasonable amount of data each time. I usually pick at minimum the MTU as the default buffer size. To get the underlying byte[] array that it creates call ``` memoryStreamInstance.GetBuffer() ```
Reading from a stream not knowing how much to expect [c#]
[ "", "c#", "arrays", "stream", "" ]
I'm having to modify some client side code because the comms protocol wasn't defined properly. I'd assummed that a tcp message from the server would terminate in a new line so I used reader.readLine() to read my Data. Now I've been told that this is not the case and that instead the first 4 chars of the message are the message length and then I have to read the rest of the message. What is the most efficient sensible way to do this? my general Idea was as follows: 1. Create a 4 char array 2. Read in first 4 characters 3. Determine what the message length is 4. Create a new array of message length 5. read into the new array. Here is an example of the code (reader is a BufferedReader created elsewhere): ``` char[] chars = new char[4]; int charCount = reader.read(chars); String messageLengthString = new String(chars); int messageLength = Integer.parseInt(messageLengthString); chars = new char[messageLength]; charCount = reader.read(chars); if (charCount != messageLength) { // Something went wrong... } ``` I know how to do this, but Do I have to worry about the character buffers not being filled? if so how should I deal with this happening?
Chars in Java are for *text* data. Are you sure the protocol *really* defines the length of the message this way? More likely it's the first four *bytes* to represent a 32-bit length. If you're talking to C or C++ developers they may be using "char" as a synonym for "byte". EDIT: Okay, based on the comment: I would create a method which took a `Reader` and a count and repeatedly called `read()` until it had read the right amount of data, or threw an exception. Something like this: ``` public static String readFully(Reader reader, int length) throws IOException { char[] buffer = new char[length]; int totalRead = 0; while (totalRead < length) { int read = reader.read(buffer, totalRead, length-totalRead); if (read == -1) { throw new IOException("Insufficient data"); } totalRead += read; } return new String(buffer); } ``` Then your code can be: ``` String lengthText = readFully(reader, 4); int length = Integer.parseInt(lengthText); String data = readFully(reader, length); // Use data now ``` You should check what happens when they want to send fewer than 1000 (or more than 9999) characters though...
Relating to the part of the question where you need to read a certain number of characters once you've established what this is, the following idiom is common with java.io.Readers: ``` int lengthToRead = getRequiredReadLength(); // Left as exercise to reader :-) char[] content = new char[lengthToRead] int from = 0; while (lengthToRead > 0) { try { int nRead = reader.read(context, from, lengthToRead); if (nRead == -1) { // End of stream reached before expected number of characters // read so handle this appropriately - probably throw an exception } lengthToRead -= nRead; from += nRead; } catch (IOException e) { // Handle exception } } ``` Since the `read` call is guaranteed to return a non-zero result (the call blocks until *some* data is available, the end of the stream is reached (returns -1) or an exception is thrown) this while loop ensures you'll read as many characters as you need so long as the stream can supply them. In general, whenever more than one character is asked for at once from a Reader one should be aware there's no guarantees that that many characters were actually supplied, and the return value should always be inspected to see what happened. Otherwise you'll inevitably end up with bugs at some point, where parts of your stream "disappear".
Most efficient way to read in a tcp stream in Java
[ "", "java", "tcp", "" ]
I am working on a program that requires the date of an event to get returned. I am looking for a `Date`, not a `DateTime`. Is there a datatype that returns just the date?
No there isn't. `DateTime` represents some point in time that is composed of a date and a time. However, you can retrieve the date part via the [`Date`](http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx) property (which is another `DateTime` with the time set to `00:00:00`). And you can retrieve individual date properties via [`Day`](http://msdn.microsoft.com/en-us/library/system.datetime.day.aspx), [`Month`](http://msdn.microsoft.com/en-us/library/system.datetime.month.aspx) and [`Year`](http://msdn.microsoft.com/en-us/library/system.datetime.year.aspx). **UPDATE**: In .NET 6 the types `DateOnly` and `TimeOnly` [are introduced](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/#introducing-the-dateonly-and-timeonly-types) that represent just a date or just a time.
I created a simple [Date struct](https://github.com/claycephus/csharp-date) for times when you need a simple date without worrying about time portion, timezones, local vs. utc, etc. ``` Date today = Date.Today; Date yesterday = Date.Today.AddDays(-1); Date independenceDay = Date.Parse("2013-07-04"); independenceDay.ToLongString(); // "Thursday, July 4, 2013" independenceDay.ToShortString(); // "7/4/2013" independenceDay.ToString(); // "7/4/2013" independenceDay.ToString("s"); // "2013-07-04" int july = independenceDay.Month; // 7 ``` <https://github.com/claycephus/csharp-date>
Date vs DateTime
[ "", "c#", ".net", "asp.net", "" ]
I have needed in several occasions some classes to represent and manipulate conditions (typically in a UI so the user builds a query by combining different condition types and then the code can transform that depending on the underlying system to be queried, for example lucene and a db). I searched all over for a reusable set of classes, I am sure this has to be used in many existing places (all the expression languages for starters) but could not find anything easily usable. I ended up coding both times myself, but felt bad about not reusing something I am sure exists. Typical needs are: - several operators: and or etc - variable number of operands - combining conditions to build expressions - serializing of expressions - parsing/formatting of expressions from/to strings has somebody found something like that?
Take a look at [Apache Commons Functor](http://commons.apache.org/sandbox/functor/). E.g. [UnaryPredicate](http://commons.apache.org/sandbox/functor/apidocs/org/apache/commons/functor/UnaryPredicate.html), [UnaryAnd](http://commons.apache.org/sandbox/functor/apidocs/org/apache/commons/functor/core/composite/UnaryAnd.html), [UnaryOr](http://commons.apache.org/sandbox/functor/apidocs/org/apache/commons/functor/core/composite/UnaryOr.html), etc. The built-in implementations are Serializable, but I don't know about parsing from strings. Still, I think it's a very good start towards what you want. Also, take a look at [this IBM tutorial](http://www.ibm.com/developerworks/java/library/j-fp.html) based on the library.
It does sound like you might be looking for [Functors](http://en.wikipedia.org/wiki/Function_object) (aka function objects). If so, this [SO question](https://stackoverflow.com/questions/651541/best-java-functor-lib-jga-commons-functor-mango-or) would be relevant, wrt. choices: Commons functor (mentioned already) is one alternative but there are others too. All functor libs come with the framework (which is quite simple; unary, binary predicates, mapping functionality for those, combining by chaining) and basic set of functions most commonly needed.
reusable condition/expression classes
[ "", "java", "expression", "functor", "" ]
I have noticed this piece of code: ``` FileInfo[] files =new DirectoryInfo(@"C:\").GetFiles(); ``` What is the purpose of `@`? Are there other uses?
# Strings literals C# supports two forms of string literals: **regular string literals** and **verbatim string literals**. A **regular string literal** consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences. A **verbatim string literal** consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines. **Example 1:** ``` @"C:\Path\File.zip" == "C:\\Path\\File.zip" // where "C:\\Path\\File.zip" // regular string literal @"C:\Path\File.zip" // verbatim string literal ``` **Note**: In verbatim string literals you should escape double quotes. **Example 2:** ``` @"He said: ""Hello""" == "He said: \"Hello\"" ``` **More info here**: * [string (C# Reference)](http://msdn.microsoft.com/en-us/library/362314fe.aspx) at MSDN * [String literals](http://msdn.microsoft.com/en-us/library/aa691090.aspx) at MSDN * [String Basics (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms228362.aspx) at MSDN * [Working with Strings in C#](http://www.techotopia.com/index.php/Working_with_Strings_in_C_Sharp) * [Strings in .NET and C#](http://www.yoda.arachsys.com/csharp/strings.html) # Identifiers The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier. Use of the @ prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style. **Example:** ``` class @class { public static void @static(bool @bool) { if (@bool) System.Console.WriteLine("true"); else System.Console.WriteLine("false"); } } class Class1 { static void M() { cl\u0061ss.st\u0061tic(true); } } ```
The `@` symbol has a couple of meanings in C#: * **When used at the beginning of the string,** it means "take this string literally; do not interpret characters that would otherwise be used as escape characters." This is called the **[verbatim string literal](http://msdn.microsoft.com/en-us/library/aa691090.aspx)**. For example, `@"\n\t"` is equal to `"\\n\\t"`. * **When used at the beginning of an identifier,** it means "interpret this as an identifier, not as a keyword". For example, `int @this` would allow you to name an integer variable "this", which would normally be illegal since `this` is a keyword.
What are all the usages of '@' in C#?
[ "", "c#", ".net", "" ]
I'm designing a new site for a local government department in Scotland and I want to make sure I meet the minimum accessibility level for the site. I had planned to use some jQuery effects, and also to AJAXify the content. But I realised all this JavaScript probably won't be accessible. We will be using VS2008 ASP.NET 3.5 framework. (C# server side and SQL Server 2005 db) Does anyone know what the min standard would be for a government run site? It will be public facing and its target user will be kids between 11 and 17. Also, is there any tools out there for checking our web site? Built in/Add on tools for Visual Studio would be great. We normally design in house site for our administration teams, so this is the first time we've had to worry about accessibility so answer in a "For Dummies" style if you want! :) Thanks!
You also have to comply with the Disability Discrimination act - especially as this is a Government resource. Info on the act <http://www.direct.gov.uk/en/DisabledPeople/RightsAndObligations/DisabilityRights/DG_4001068> and <http://www.coi.gov.uk/guidance.php?page=169> And some information regarding websites and the act at <http://www.webcredible.co.uk/user-friendly-resources/web-accessibility/uk-website-legal-requirements.shtml> and <http://www.alistapart.com/articles/accessuk> We deal with quite a few local councils and all of their sites must be accessible via screen readers so that those with visual impairments can use them, as such they need to be able to be navigated if the user has JavaScript and CSS disabled. You need to ensure that if you use any CSS on the site that the navigation and structure degrade gracefully so that they make sense (e.g. don't make the navigation the last item on the page and then use CSS to move it to the top). Don't make any navigation dependant on Javascript either (or at least have an alternative method of navigating if the user has JavaScript turned off). HTML and CSS should be validated to ensure there are no errors. All images need ALT attributes All links need title attributes Any tables should have a summary There are many more items like these but testing should flag these up. In terms of testing the site, there are a few free screen readers available - although we had limited success with these as they were pretty hit and miss as to how they worked. "Jaws" seems to be the industry "standard" at the moment but this is ridiculously expensive so you may want to outsource any testing to another company; although some councils will organise this themselves. You should also test the site on a text-only browser such as Lynx. A few more resources can be found below: Jaws <http://www.freedomscientific.com/products/fs/jaws-product-page.asp> Free <http://www.screenreader.net>, <http://www.webaim.org/simulations/screenreader.php>, <http://www.xpscreenreader.com/> <http://firevox.clcworld.net/> - Firefox plugin <http://sourceforge.net/projects/fangs/> - Firefox plugin Accessibility Checkers Functional Accessibility Evaluator - <http://fae.cita.uiuc.edu/> WAVE - <http://wave.webaim.org/> Cynthia Says - <http://www.cynthiasays.com/> TAW Web Accessibility Test - <http://www.tawdis.net/taw3/cms/en/> Or download the Firefox accessibility checker which contains checks for all the above as wells as HTML and CSS validators <https://addons.mozilla.org/en-US/firefox/addon/5809>
You should firstly get the client to clarify these requirements, and make sure they actually research the subject as they may not currently have any idea about it and will just add the requirements further down the line when someone points it out (trust me, I've worked within a Scottish government organisation!) Back when I worked in government (2004 - 2006), it was the e-Gov guidelines that were important and there was one on accessibility. I can't remember if these were publicly accessible or only available on an intranet, but I did find this page with what looks like the same documents: [Web Guidelines](http://www.cabinetoffice.gov.uk/government_it/web_guidelines.aspx). Again, you should clarify with the client what is the correct document to adhere to. They may also have their own accessibility standards, depending on what organisation they are (not that you can say of course, but I doubt one of the smaller councils is likely to have this). The documents can be quite bland and hard to read, and often result in ugly websites because people believe simplicity is the only way to achieve accessibility. Of course this isn't true, so it's up to you to interpret the guidelines and provide justification for breaking them were necessary. On the subject of tools, I assume you mean some kind of automated testing? If so, the answer is yes they exist, but please don't rely on them as your sole testing method! No amount of automated testing can ever tell you how truly accessible a website is, only real-world testing can do that. One place where a tool can come in handy however is checking colour contrast, there are several that will render your page using algorithms that emulate various forms of colour blindness.
What is the basic level of Accessibility for UK local government web site?
[ "", ".net", "asp.net", "javascript", "accessibility", "" ]
everyone said the "underscore, no underscore" debate is purely philosophical and user preference driven but with intelli-sense having the underscore allows you to differentiate your member variables from your local variable very easily and thus giving you a concrete benefit is there any counter argument to this benefit of having underscores to all member variables?
Yes - for some people it reduces readability. I believe different people read in different ways (some internally vocalise and others don't, for instance). For some people (myself included) underscores interrupt the "flow" of code when I'm reading it. I'd argue that if you're having difficulties telling local and instance variables apart, then quite possibly either your methods are too big or your class is doing too much. That's not always going to be the case of course, but I don't tend to find it a problem at all with short classes/methods.
If it's just the intellisense you want you can always get it by typing "`this.`". OK, it's 4 more chars than "\_", but the intellisense will then bring up your members for you. If you use underscores and your team uses underscores then keep using them. Others will use "`m`\_", others might have other ideas. I use StyleCop and on my team the debate is over, we use "`this`." and Hungarian style or underscore prefixes are not used. And we just don't worry about it anymore. [Edit] This is not a criticism of your question - it's a valid question and it's worth asking - but this debate wastes way too much time on dev projects. Even though I don't like everying about StyleCop I willingly use it as it cuts out this type of debate. Seriously, I've been in hour long meetings where this kind of discussion occupies a whole dev team. Crazy. Like I say, your question is valid but please don't waste your own time agonising over this, it's not worth it:-)
Underscore prefix on member variables. intellisense
[ "", "c#", "coding-style", "naming-conventions", "" ]
I'm using itextsharp to generate the PDFs, but I need to change some text dynamically. I know that it's possible to change if there's any AcroField, but my PDF doen's have any of it. It just has some pure texts and I need to change some of them. Does anyone know how to do it?
Actually, I have a blog post on how to do it! But like IanGilham said, it depends on whether you have control over the original PDF. The basic idea is you setup a form on the page and replace the form fields with the text you want. (You can style the form so it doesn't look like a form) If you don't have control over the PDF, let me know how to do it! Here is a link to the full post: [Using a template to programmatically create PDFs with C# and iTextSharp](http://johnnycode.com/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/)
I haven't used itextsharp, but I have been using [PDFNet SDK](http://www.pdftron.com/) to explore the content of a large pile of PDFs for localisation over the last few weeks. I would say that what you require is absolutely achievable, but how difficult it is will depend entirely on how much control you have over the quality of the files. In my case, the files can be constructed from any combination of images, text in any random order, tables, forms, paths, single pixel graphics and scanned pages, some of which are composed from hundreds of smaller images. Let's just say we're having fun with it. In the PDFTron way of doing things, you would have to implement a viewer (sample available), and add some code over a text selection. Given the complexities of the format, it may be necessary to implement a simple editor in a secondary dialog with the ability to expand the selection to the next line (or whatever other fundamental object is used to make up text). The string could then be edited and applied by copying the entire page of the document into a new page, replacing the selected elements with your new string. You would probably have to do some mathematics to get this to work well though, as just about everything in PDF is located on the page by means of an [affine transform](http://en.wikipedia.org/wiki/Affine_transform). Good luck. I'm sure there are people on here with some experience of itextsharp and PDF in general.
Is there a way to replace a text in a PDF file with itextsharp?
[ "", "c#", "itext", "" ]
Most of our development is done in vb.net (not my choice) and one frequently used code pattern uses an 'On Error GoTo' followed by a 'Resume Next' so that all database fields can be read with a DirectCast() and any DBNull values are just ignored. The current code would be ``` On Error GoTo error_code oObject.Name = DirectCast(oReader.Item("Name"), String) oObject.Value = DirectCast(oReader.Item("Value"), Integer) error_code: Resume Next ``` C# code to replace this an enable the removal of the On Error code would be ``` oObject.Name = oReader["Name"] as string ?? string.Empty; oObject.Value = oReader["Value"] as int? ?? -1; ``` The problem is that the vb.net eqivelent of this C# code uses a TryCast() which can only be used for reference types (nullable types are value types) whilst the C# as keyword can be used for reference and nullable types. So in summary does anyone have an example of vb.net code that does the same thing as the C# code in a single line per database field? -EDIT- I've decided what I think is the best solution in our case. Helper methods would not be suitable (due to management) and we can't have extension methods as we're only using .NET 2.0 (though with VS 2008 so we get the If()) ``` oObject.Name = If(oReader.IsDBNull(oReader.GetOrdinal("Name")), String.Empty, oReader.GetString(oReader.GetOrdinal("Name"))) oObject.Value = If(oReader.IsDBNull(oReader.GetOrdinal("Value")), 0, oReader.GetInt32(oReader.GetOrdinal("Value"))) ```
In VB 9.0, "IF" is a true coalescing operation equivalent to C#'s "??". Source [MSDN](http://msdn.microsoft.com/en-us/library/2hxce09y.aspx "Operators"): So you could use: ``` oObject.Name = IF(oReader.Item("Name").Equals(DBNull.Value),string.Empty,DirectCast(oReader.Item("Name"), String)) ```
## Edit Sorry for sprouting such nonsense. I relied on a [posting by Paul Vick](http://www.panopticoncentral.net/archive/2004/03/03/281.aspx) (then head of the VB team) rather than the [MSDN](http://msdn.microsoft.com/en-us/library/zyy863x8(VS.80).aspx) and don't have Windows installed to test the code. I'll still leave my posting – heavily modified (refer to the edit history to read the wrong original text) – because I find the points still have some merit. So, once again, three things to recap: 1. For **reference types**, C#'s `as` is directly modelled by `TryCast` in VB. However, C# adds a little extra for the handling of value types via unboxing (namely the possibilities to unbox value types to their `Nullable` counterpart via `as`). 2. VB 9 provides the **`If` operator** to implement two distinct C# operators: `null` coalescing (`??`) and conditional (`?:`), as follows: ``` ' Null coalescing: ' Dim result = If(value_or_null, default_value) ' Conditional operator: ' Dim result = If(condition, true_value, false_value) ``` Unlike the previous `IIf` function these are real short-circuited operators, i.e. only the necessary part will be executed. In particular, the following code will compile and run just fine (it wouldn't, with the `IIf` function, since we could divide by zero): ``` Dim divisor = Integer.Parse(Console.ReadLine()) Dim result = If(divisor = 0, -1, 1 \ divisor) ``` 1. Don't use VB6 style error handling (`On Error GoTo …` or `On Error Resume [Next]`). That's backwards compatibility stuff for easy VB6 conversion. Instead, use .NET's exception handling mechanisms like you would in C#.
How to achieve the C# 'as' keyword for value types in vb.net?
[ "", "c#", ".net", "vb.net", "" ]
I have Java desktop application that works with CSV files. And i want add some functionality. At this moment i need to open selected file with default system text editor. When i run my program on Windows i have no problems, just by calling notepad.exe, but what to do with \*nix systems? One way of solution is to customly set the way to preffered text editor in program options, but it is not a best solution... But maybe it would be better add to program own text editor, even with less functionality ?
I believe [`java.awt.Desktop.edit()`](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#edit(java.io.File)) may be what you're looking for, although it will launch whatever the OS thinks the file should be edited with, which in the case of CSV is usually a spreadsheet app rather than a text editor - maybe you can rename the files to TXT temporarily or permanently.
For such functionality, I believe that is much better to use [JTextArea](http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html) and provide your own basic text editor. Anyway, have a look at the [BareBonesBrowserLauncher](http://www.centerkey.com/java/browser/). It is a Java class that allows you to launch the default browser in any platform. You can adapt it for your needs. Copied from there: ``` String[] editors = { "vim", "emacs", "vi",}; String editor = null; for (int count = 0; count < editors.length && editors == null; count++) if (Runtime.getRuntime().exec( new String[] {"which", editors[count]}).waitFor() == 0) editor = editors[count]; if (editor == null) throw new Exception("Could not find editor"); else Runtime.getRuntime().exec(new String[] {editor, filename}); ```
call system text editor
[ "", "java", "text", "editor", "" ]
Just been asked this question as a true / false in a telephone job interview and was a little stumped. Any ideas?
You can get hold of the Response object from the HttpContext static object: ``` System.Web.HttpContext.Current.Response.Write("Some Text") ``` If current returns null then the code is not being run as part of a page request. If you get asked the question again then that's the answer but a follow up question should be "why would you need to?"
The short answer is yes. In an interview id mention UserControl for an example.
In .Net, is it possible to use Response.Write in a class that does not inherit from System.Web.UI.Page
[ "", "c#", ".net", "" ]
I am wondering if it is possible to have multiple Update statements in a store procedure Something like this: ``` Update Table1 set field1 = @new_value where id = @table1_id Update Table2 set field2 = @new_value where id = @table2_id Update Table3 set field3 = @new_value where id = @table3_id ``` Right now I am executing them seperately but as they are only used together I wonder if they could be located in just one SP.
Yes, it's possible: ``` CREATE PROCEDURE prc_update (@table1_id INT, @table2_id INT, @table3_id INT, @new_value INT) AS BEGIN UPDATE Table1 SET field1 = @new_value WHERE id = @table1_id UPDATE Table2 SET field2 = @new_value WHERE id = @table2_id UPDATE Table3 SET field3 = @new_value WHERE id = @table3_id END ```
Yes, that works fine. Also put this in the stored procedure before the updates: ``` set nocount on ``` This keeps the stored procedures from creating result sets for queries without a result. Otherwise each update will produce an empty result set that is sent back to the client.
Multiple update statements in one StoredProcedure
[ "", "sql", "stored-procedures", "" ]
I'm trying to export classes from a DLL that contain objects such as `std::vectors` and `std::strings` - the whole class is declared as DLL export through: ``` class DLL_EXPORT FontManager { ``` The problem is that for members of the complex types I get this warning: > ``` > warning C4251: 'FontManager::m__fonts' : class 'std::map<_Kty,_Ty>' needs to have dll-interface to be used by clients of class 'FontManager' > with > [ > _Kty=std::string, > _Ty=tFontInfoRef > ] > ``` I'm able to remove some of the warnings by putting the following forward class declaration before them even though I'm not changing the type of the member variables themselves: ``` template class DLL_EXPORT std::allocator<tCharGlyphProviderRef>; template class DLL_EXPORT std::vector<tCharGlyphProviderRef,std::allocator<tCharGlyphProviderRef> >; std::vector<tCharGlyphProviderRef> m_glyphProviders; ``` Looks like the forward declaration "injects" the `DLL_EXPORT` for when the member is compiled but is it safe? Does it really change anything when the client compiles this header and uses the `std::` container on his side? Will it make all future uses of such a container `DLL_EXPORT` (and possibly not inline)? And does it really solve the problem that the warning tries to warn about? Is this warning anything I should be worried about or would it be best to disable it in the scope of these constructs? The clients and the DLL will always be built using the same set of libraries and compilers and those are header only classes... I'm using Visual Studio 2003 with the standard STD library. --- ### Update I'd like to target you more though as I see the answers are general and here we're talking about std containers and types (such as `std::string`) - maybe the question really is: Can we disable the warning for standard containers and types available to both the client and the DLL through the same library headers and treat them just as we'd treat an `int` or any other built-in type? (It does seem to work correctly on my side) If so would should be the conditions under which we can do this? Or should maybe using such containers be prohibited or at least ultra care taken to make sure no assignment operators, copy constructors etc will get inlined into the DLL client? In general I'd like to know if you feel designing a DLL interface having such objects (and for example using them to return stuff to the client as return value types) is a good idea or not and why, I'd like to have a "high level" interface to this functionality... Maybe the best solution is what Neil Butterworth suggested - creating a static library?
When you touch a member in your class from the client, you need to provide a DLL-interface. A DLL-interface means, that the compiler creates the function in the DLL itself and makes it importable. Because the compiler doesn't know which methods are used by the clients of a DLL\_EXPORTED class it must enforce that all methods are dll-exported. It must enforce that all members which can be accessed by clients must dll-export their functions too. This happens when the compiler is warning you of methods not exported and the linker of the client sending errors. Not every member must be marked with with dll-export, e.g. private members not touchable by clients. Here you can ignore/disable the warnings (beware of compiler generated dtor/ctors). Otherwise the members must export their methods. Forward declaring them with DLL\_EXPORT does not export the methods of these classes. You have to mark the according classes in their compilation-unit as DLL\_EXPORT. What it boils down to ... (for not dll-exportable members) 1. If you have members which aren't/can't be used by clients, switch off the warning. 2. If you have members which must be used by clients, create a dll-export wrapper or create indirection methods. 3. To cut down the count of externally visible members, use approaches such as the [PIMPL idiom](http://c2.com/cgi/wiki?PimplIdiom). --- ``` template class DLL_EXPORT std::allocator<tCharGlyphProviderRef>; ``` This does create an instantiation of the template specialization in the current compilation unit. So this creates the methods of std::allocator in the dll and exports the corresponding methods. This does not work for concrete classes as this is only an instantiation of template classes.
That warning is telling you that users of your DLL will not have access to your container member variables across the DLL boundary. Explicitly exporting them makes them available, but is it a good idea? In general, I'd avoid exporting std containers from your DLL. If you can absolutely guarantee your DLL will be used with the same runtime and compiler version you'd be safe. You must ensure memory allocated in your DLL is deallocated using the same memory manager. To do otherwise will, at best, assert at runtime. So, don't expose containers directly across DLL boundaries. If you need to expose container elements, do so via accessor methods. In the case you provided, separate the interface from the implementation and expose the inteface at the DLL level. Your use of std containers is an implementation detail that the client of your DLL shouldn't need to access. Alternatively, do what Neil suggest and create a static library instead of a DLL. You lose the ability to load the library at runtime, and consumers of your library must relink anytime you change your library. If these are compromises you can live with, a static library would at least get you past this problem. I'll still argue you're exposing implementation details unnecessarily but it might make sense for your particular library.
Exporting classes containing `std::` objects (vector, map etc.) from a DLL
[ "", "c++", "visual-studio", "dll", "" ]
I have the following ant `build.xml`: ``` <path id="antclasspath"> <fileset dir="lib"> <include name="*.jar"/> </fileset> </path> <property name="pathvar" refid="antclasspath" /> <echo message="Classpath is ${pathvar}"/> <sql driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@myserver.hu:1521:dbid" userid="myuserid" password="mypassword" print="yes" classpathref="antclasspath"> select * from table </sql> ``` There is an Oracle JDBC driver in the lib directory. Echo prints it out correctly: ``` Classpath is E:\MyDir\lib\ojdbc14-10_2_0_3.jar ``` Somehow sql ant task is still not able to load the Oracle driver: ``` E:\MyDir\build.xml:100: Class Not Found: JDBC driver oracle.jdbc.driver.OracleDriver could not be loaded ``` What is the problem with this build.xml? It is quite strange that it was working few times yesterday, but never again. Using `classpath="E:\MyDir\lib\ojdbc14-10_2_0_3.jar"` in the task gives the same error message. I'm using ant 1.7.1 (built in Netbeans 6.5)
The syntax looks correct to me. Try passing the `-v` switch to your ant command, that will direct the `sql` task to print out the classpath it's using. You should see something like: ``` [sql] connecting to jdbc:oracle:thin:@myserver.hu:1521:dbid [sql] Loading oracle.jdbc.driver.OracleDriver using AntClassLoader with classpath E:\MyDir\lib\ojdbc14-10_2_0_3.jar [sql] Executing commands [sql] SQL: select * from dual [sql] Processing new result set. [sql] DUMMY [sql] X [sql] 0 rows affected [sql] 0 rows affected [sql] Committing transaction [sql] 1 of 1 SQL statements executed successfully ``` If that doesn't help, you can try passing the `-debug` switch, which will print out reams of information including classloader debugging. Finally, have you verified that your ojdbc jar is not corrupt and does, in fact, contain the OracleDriver class?
Try changing the class name to oracle.jdbc.OracleDriver. The oracle.jdbc.driver package is being deprecated in favour of oracle.jdbc. See the section "The Old oracle.jdbc.driver Package Will Go Away" in the readme [here](http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/readme_10201.html).
ant sql task classpath problem
[ "", "sql", "ant", "classpath", "" ]
I'm having a weird issue when where the date format of from the date fields changes from 4/16/2009 12:00:00 AM to 16/04/2009 00:00:00. I set the application to write out each stored proc that fired with the same corresponding date field if it exists. Here's what came out. You'll notice that the format switch inexplicable half way through. ``` EXECUTE uspContent_SelectOne '132' 4/16/2009 12:00:00 AM EXECUTE uspContent_SelectOne '127' 4/16/2009 12:00:00 AM EXECUTE uspContent_SelectOne '133' 4/16/2009 12:00:00 AM EXECUTE uspContent_SelectOne '131' 4/16/2009 12:00:00 AM EXECUTE uspAttachment_SelectAll EXECUTE uspArticleAuthors_SelectAll_ArticleId '3' EXECUTE uspArticles_SelectOne '3' EXECUTE uspAuthors_Letters EXECUTE uspAuthors_Letters EXECUTE uspAuthors_Letters EXECUTE uspAuthors_SelectAll_Letter_LastName 'A' EXECUTE uspFiles_SelectAll_NoFileData EXECUTE uspArticles_SelectOne '3' EXECUTE uspArticleTypes_SelectAll EXECUTE uspFiles_SelectAll_NoFileData EXECUTE uspAuthors_SelectOne '0' EXECUTE uspArticleAttachments_SelectAll_ArticleId '3' EXECUTE uspArticleAttachments_SelectOne_ArticleId_AttachmentId '3','4' EXECUTE uspAttachment_SelectOne '4' EXECUTE uspContent_SelectOne '132' 16/04/2009 00:00:00 EXECUTE uspContent_SelectOne '127' 16/04/2009 00:00:00 EXECUTE uspFiles_SelectOne_NoFileData '60' EXECUTE uspArticleAttachments_SelectOne_ArticleId_AttachmentId '3','3' EXECUTE uspAttachment_SelectOne '3' EXECUTE uspContent_SelectOne '133' 16/04/2009 00:00:00 EXECUTE uspContent_SelectOne '131' 16/04/2009 00:00:00 EXECUTE uspAttachment_SelectAll EXECUTE uspArticleAuthors_SelectAll_ArticleId '3' EXECUTE uspAuthors_SelectAll_Letter_LastName 'A' EXECUTE uspContent_SelectOne '129' 18/09/2008 00:00:00 EXECUTE uspContent_SelectOne '7' 18/09/2008 00:00:00 EXECUTE uspContent_SelectOne '8' 18/09/2008 00:00:00 EXECUTE uspContent_SelectOne '9' 18/09/2008 00:00:00 EXECUTE uspContent_SelectOne '10' 18/09/2008 00:00:00 EXECUTE uspContent_SelectOne '11' 18/09/2008 00:00:00 EXECUTE uspFiles_SelectAll_NoFileData ``` I can't figure out why. I'm using the ASP.NET/C#, SQL Server 2005, and the MS Enterprise Library 4.1. **UPDATE 1** I checked the culture settings of the app and got this. For every date field query I checked the culture. In the screen shot below you can see how the culture changes from US to UK: [image of cuture changing http://www.craigmoliver.com/cultureissue.jpg](http://www.craigmoliver.com/cultureissue.jpg) The setting in the web.config it's set as follows: ``` <globalization culture="en-US" uiCulture="en-US" requestEncoding="utf-8" responseEncoding="utf-8" enableClientBasedCulture="false" /> ```
Are the requests coming from different browsers? Are you picking up the Culture/UICulture from the Accept-Language header in the HTTP Request? If so, it is possible that you have one browser that has it's preferred language set to en-US and another set to en-GB?
The suggestions to check the current culture are promising. One additional possibility to consider: Is your application running in a load-balanced server farm and are the web servers properly configured identically?
Culture changing inexplicably during ASP.NET web application request
[ "", "c#", "asp.net", "sql-server-2005", "" ]
Are there any good ways to work with blocks of text (Strings) within Java source code? Many other languages have [heredoc](http://en.wikipedia.org/wiki/Heredoc) syntax available to them, but Java does not. This makes it pretty inconvenient to work with things like tag libraries which output a lot of static markup, and unit tests where you need to assert comparisons against blocks of XML. How do other people work around this? Is it even possible? Or do I just have to put up with it?
While you could use certain formatters to convert and embed any text file or long literal as a Java string (e.g., with newline breaks, the necessary escapes, etc.), I can't really think of frequent situations where you would need these capabilities. The trend in software is generally to separate code from the data it operates on. Large text sections, even if meant just for display or comparison, are data, and are thus typically stored externally. The cost of reading a file (or even caching the result in memory) is fairly low. Internationalization is easier. Changing is easier. Version control is easier. Other tools (e.g., spell checkers) can easily be used. I agree that in the case of unit tests where you want to compare things against a mock you would need large scale text comparisons. However, when you deal with such large files you will typically have tests that can work on several different large inputs to produce several large outputs, so why not just have your test load the appropriate files rather than inline it ? Same goes with XML. In fact, for XML I would argue that in many cases you would want to read the XML and build a DOM tree which you would then compare rather than do a text compare that can be affected by whitespaces. And manually creating an XML tree in your unit test is ugly.
If the text is static, or can be parameterized, a possible solution would be to store it in an external file and then import it. However, this creates file I/O which may be unnecessary or have a performance impact. Using this solution would need to involve caching the file contents to reduce the number of file reads.
Working with large text snippets in Java source
[ "", "java", "text", "heredoc", "" ]
I have the following SQL query: ``` select      ID, COLUMN1, COLUMN2 from      (select ID, COLUMN1, COLUMN2, row_number() over (order by 2 DESC) NO from A_TABLE) where      NO between 0 and 100 ``` What I am trying to do is to select the first 100 records of the query ``` select ID, COLUMN1, COLUMN2 from ATABLE order by 2 DESC ``` And here are the problems: 1. Apparently, the `order by` clause is not working. I've noticed that I have to add another `order by 2 DESC` clause, just after `(...) from ATABLE`, for my query to work. Is there something I do wrong? Or is it expected behaviour? 2. How can I add a `where` clause? Let's say I need to select only the first 100 records of the table `where COLUMN1 like '%value%'`. I've tried adding the where clause after `(...) from ATABLE` but it produced an error... Help? Thanks. PS: I'm using Oracle 10g R2.
rownum is a pseudo column that counts rows in the result set *after* the where clause has been applied. Is this what you're trying to get? ``` SELECT * FROM ( SELECT id, column1, column2 FROM atable ORDER BY 2 DESC ) WHERE ROWNUM < 100; ``` Because it's a pseudo column that is strictly a counter of rows resulting from the where clause it will not allow you to do pagination (i.e. between 200 & 300). This is probably what you're looking for: ``` SELECT * FROM (SELECT a.*, rownum rnum FROM (SELECT id, column1, column2 FROM atable ORDER BY 2 DESC) a WHERE rownum <= 300) WHERE rnum >= 200; ```
[Check out this Oracle FAQ](http://www.orafaq.com/faq/can_one_retrieve_only_rows_x_to_y_from_a_table). In particular this part: ``` SELECT * FROM (SELECT a.*, rownum RN FROM (SELECT * FROM t1 ORDER BY key_column) a WHERE rownum <=7) WHERE rn >=5 ```
SQL Query With Row_Number, order by and where clause
[ "", "sql", "oracle", "select", "oracle10g", "row-number", "" ]
I have tried finding a simialr example and using that to answer my problem, but I can't seem to get it to work, so apologies if this sounds similar to other problems. Basically, I am using Terminal Four's Site Manager CMS system to build my websites. This tool allows you to generate navigation elements to use through out your site. I need to add a custom bit of JS to append to these links an anchor. The links generated are similar to this: ``` <ul id="tab-menu"> <li><a href="/section/page">test link, can i rewrite and add an anchor!!!</a></li> </ul> ``` I can edit the css properties of the link, but I can't figure out how to add an anchor. The JQuery I am using is as follows: ``` <script type="text/javascript" src="http://jquery.com/src/jquery-latest.pack.js"></script> <script type="text/javascript"> $(document).ready(function(){ // everything goes here $("#tab-menu").children("li").each(function() { $(this).children("a").css({color:"red"}); }); }); </script> ``` Thanks in advance for any help. Paddy
A nice jQuery-based method is to use the .get(index) method to access the raw DOM element within your each() function. This then gives you access to the JavaScript link object, which has a property called 'hash' that represents the anchor part of a url. So amending your code slightly: ``` <script type="text/javascript"> $(document).ready(function(){ // everything goes here $("#tab-menu").children("li").children("a").each(function() { $(this).css({color:"red"}).get(0).hash = "boom"; }); }); ``` Would change all the links in "#tab\_menu li" to red, and attach "#boom" to the end. Hope this helps!
sort of duplicate of this: [How to change the href for a hyperlink using jQuery](https://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery) just copy the old href and add anchor to it and paste that back ``` var link = $(this).children("a").attr("href"); $(this).children("a").attr("href", link+ "your own stuff"); ```
Adding an anchor to generated URLs
[ "", "javascript", "jquery", "append", "anchor", "" ]
I am using [Jetty](http://www.mortbay.org) and [Selenium](http://seleniumhq.org/) to automate some unit tests from my [Maven 2](http://maven.apache.org). We only really want to run these tests as part of the CI build and would like to control it via the `-Dmaven.test.skip` property. I cannot find a way to apply this to the executions for the Jetty plugin. Am I missing something obvious?
The maven.test.skip property is a property that the surefire plugin looks at to decide if it should just skip. The jetty plugin doesn't care at all about this property. The only way to do this would move your jetty plugin execution to a profile and try [activating](http://maven.apache.org/pom.html#Activation) it if the maven.test.skip property is false.
Feature request about this capability already fixed and now you can skip jetty plugin execution by setting `jetty.skip` property: ``` $ mvn -Djetty.skip=true ``` See also: * <http://wiki.eclipse.org/Jetty/Feature/Jetty_Maven_Plugin#Skipping_execution_of_jetty> * <http://jira.codehaus.org/browse/JETTY-1051>
How do I control execution of Maven Jetty Plugin with -Dmaven.test.skip
[ "", "java", "maven-2", "jetty", "" ]
I wanted to bring this challenge to the attention of the stackoverflow community. The original problem and answers are [here](http://blogs.msdn.com/ericlippert/archive/2009/04/15/comma-quibbling.aspx). BTW, if you did not follow it before, you should try to read Eric's blog, it is pure wisdom. **Summary:** Write a function that takes a non-null IEnumerable and returns a string with the following characteristics: 1. If the sequence is empty the resulting string is "{}". 2. If the sequence is a single item "ABC" then the resulting string is "{ABC}". 3. If the sequence is the two item sequence "ABC", "DEF" then the resulting string is "{ABC and DEF}". 4. If the sequence has more than two items, say, "ABC", "DEF", "G", "H" then the resulting string is "{ABC, DEF, G and H}". (Note: no Oxford comma!) As you can see even our very own Jon Skeet (yes, it is well known that [he can be in two places at the same time](https://stackoverflow.com/questions/305223/jon-skeet-facts)) has posted a solution but his (IMHO) is not the most elegant although probably you can not beat its performance. What do you think? There are pretty good options there. I really like one of the solutions that involves the select and aggregate methods (from Fernando Nicolet). Linq is very powerful and dedicating some time to challenges like this make you learn a lot. I twisted it a bit so it is a bit more performant and clear (by using Count and avoiding Reverse): ``` public static string CommaQuibbling(IEnumerable<string> items) { int last = items.Count() - 1; Func<int, string> getSeparator = (i) => i == 0 ? string.Empty : (i == last ? " and " : ", "); string answer = string.Empty; return "{" + items.Select((s, i) => new { Index = i, Value = s }) .Aggregate(answer, (s, a) => s + getSeparator(a.Index) + a.Value) + "}"; } ```
How about this approach? Purely cumulative - no back-tracking, and only iterates once. For raw performance, I'm not sure you'll do better with LINQ etc, regardless of how "pretty" a LINQ answer might be. ``` using System; using System.Collections.Generic; using System.Text; static class Program { public static string CommaQuibbling(IEnumerable<string> items) { StringBuilder sb = new StringBuilder('{'); using (var iter = items.GetEnumerator()) { if (iter.MoveNext()) { // first item can be appended directly sb.Append(iter.Current); if (iter.MoveNext()) { // more than one; only add each // term when we know there is another string lastItem = iter.Current; while (iter.MoveNext()) { // middle term; use ", " sb.Append(", ").Append(lastItem); lastItem = iter.Current; } // add the final term; since we are on at least the // second term, always use " and " sb.Append(" and ").Append(lastItem); } } } return sb.Append('}').ToString(); } static void Main() { Console.WriteLine(CommaQuibbling(new string[] { })); Console.WriteLine(CommaQuibbling(new string[] { "ABC" })); Console.WriteLine(CommaQuibbling(new string[] { "ABC", "DEF" })); Console.WriteLine(CommaQuibbling(new string[] { "ABC", "DEF", "G", "H" })); } } ```
Inefficient, but I think clear. ``` public static string CommaQuibbling(IEnumerable<string> items) { List<String> list = new List<String>(items); if (list.Count == 0) { return "{}"; } if (list.Count == 1) { return "{" + list[0] + "}"; } String[] initial = list.GetRange(0, list.Count - 1).ToArray(); return "{" + String.Join(", ", initial) + " and " + list[list.Count - 1] + "}"; } ``` If I was maintaining the code, I'd prefer this to more clever versions.
Eric Lippert's challenge "comma-quibbling", best answer?
[ "", "c#", "programming-languages", "puzzle", "" ]
I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example: ``` x = [1,2,2,2,2] for i in x: x.remove(i) print x ``` Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list. What am I doing wrong? Thanks for all the help in advance. Edit: I don't want to empty a list, this is just an example...
This is a well-documented behaviour in Python, that you aren't supposed to modify the list being iterated through. Try this instead: ``` for i in x[:]: x.remove(i) ``` The `[:]` returns a "slice" of `x`, which happens to contain all its elements, and is thus effectively a copy of `x`.
When you delete an element, and the for-loop incs to the next index, you then skip an element. Do it backwards. Or please state your real problem.
Why does Python skip elements when I modify a list while iterating over it?
[ "", "python", "list", "foreach", "" ]
It's well-known that the order of evaluation of a function's arguments in unspecified and can differ between different compilers. What doesn't seem so clear is whether function calls can be interleaved, in the following sense: ``` f(g(h()), i(j())) ``` Let's assume the compiler chooses to evaluate f's first parameter first. Is the compiler free to call `j` between calling `h` and `g`? I believe so, but I don't know where to find confirmation in the Standard.
The evaluation order is unspecified - see section 5.2.2/8 of the Standard: > The order of evaluation of arguments > is unspecified. All side effects of > argument expression evaluations take > effect before the function is entered.
I don't know what the standard says, but I think that if it matters to you, then you should probably re-arrange the code so that you know what's going to happen in which order (temp variables are your friends). Even if you figure out what the standard says, AND if we assume that your compiler implements that correctly, you're still leaving a maintenance time bomb, because your successors WON'T know everything you do.
Nested function calls order of evaluation
[ "", "c++", "" ]
Its been one of those days can someone help me out with this. I have 2 Stock Objects which I want to compare properties of at runtime. One instance is the cached instance, the other is a new stock instance which has just been delivered to my system, which may or may not equal the cached instance. See below where m is a method from the class Stock and stock is an instance of Stock ``` try { // I want to compare these two objects, return type of m may vary Object result = m.invoke(stock); Object cacheResult = m.invoke(stockCache.get(ticker)); // The return type of m may vary but is known at runtime Class returnType = m.getReturnType(); // I assume I need to cast before .equals() will work correctly if(result.equals(cacheResult)) { // Will this work or do I need to cast } }catch (Exception ex) { } ``` EDIT: For those who have asked about why I am using reflection, I am using the reverse ajax framework DWR and I am trying to map a html id property to my object properties, allowing me to annotate my properties with their associated HTML id value. When pushing the object to the UI this method will allow me to only push properties that have changed and not the whole object.
You shouldn't need to cast. Java will automatically choose the correct `equals` method. I recommend you debug that line to see what `Class` each object is.
No, you dont need to cast. Normally, equals method looks like ``` @Override public boolean equals(Object o){ if (! o instance of ThisClass){ return false; } //other equality tests based on members } ``` If your cache holds only one class-objects (i.e not caching derived classes), it should work. Looks like that you are storing Objects in your StockCache. Maybe that's a little too generic, and narrowing down to some base class (maybe StockClass) would be a better option. Then, your getter would be, defined in your cache class would be: ``` StockObject getStockObject(KeyType key); ``` In addition to this, reflection seems like an overkill (if you alredy have the objects you want to compare, why use reflection?)
Java Reflection Equals Question
[ "", "java", "reflection", "equals", "" ]
My main process calls an external library method. This method sometimes hangs. I can not fix the external library because another company is responsible for it. I want to use a Thread for the library calls with a defined execution timer. When the method call takes to long, the Thread with the Runnable in which the method call is placed should stop and the main process should go forward. 1. Main Thread wait 2. Execute Thread * start Start timer Thread * When timer thread is finished kill Execute Thread 3. Execute Thread stop Main 4. thread resume Does anybody have some code this logic is for, a design pattern i can use or a internet page i can read some informations? Thanks
Take a look at the `java.lang.concurrent` package in Java 5 and later, in particular the `CompletionService` interface and the classes that implement it. This interface includes calls that allow you to submit a task and either wait for it to complete, or else continue after a timeout.
This will wait up to 30 seconds for the thread to finish. ``` Thread t = new Thread() { public void run() { badExternalMethod(); synchronized (this) { notifyAll(); } } }; synchronized (t) { t.start(); try { t.wait(30000); // 30 secs } catch (InterruptedException e) { e.printStackTrace(); } } ``` // t has completed or timed out
Start Thread with a given execution time
[ "", "java", "multithreading", "timer", "kill", "execution", "" ]
I've seen this on [nerd dinner](http://nerddinner.codeplex.com) and other sites. On page load (in JavaScript, via the browser), an AJAX request will go out to get some data from the same server that rendered the initial page. The data will be small and there are no technical limitations that would have otherwise prevented them from just pulling down that data in the first place. Isn't this a bad thing? It seems like a waste of an AJAX call, since they could just render this data as JavaScript with the rest of the page. My bank uses AJAX to pull the information to build form elements for a "Transfer Funds" form. That information is a few kilobytes, an AJAX request there seems overkill. In nerd dinner, at least in the [MIX09 video](http://videos.visitmix.com/MIX09/T49F) that I saw, they are querying (via AJAX) a set of dinners to render on the map control on page load. I could understand if we're talking large amounts of data that would otherwise take too long to pull down, but if its under 10-15kb, wouldn't it just be better to pull the data down with the markup? Are they doing this to avoid caching of the data? Edit: What I'm proposing is that instead of opening up an AJAX call to the server to pull down json data on the clients onload, simply have asp.net (or whatever) render the json in the pages content when it renders everything else. I just felt the need to point that out because the actual client side code would be exactly the same, except for where the json variable originates.
Generally speaking, in my experience, you want to avoid any Javascript on your page that you can. By this I mean, if you can do it on serverside instead of with Javascript then you should. Your page will load faster and you'll just have a better user experience. That can sometimes be more work, particularly if that same on-load AJAX call is used during the page at later points. You might be duplicating code by doing it serverside. So there's a tradeoff between performance and how much code you want to write. The other aspect to this is that Javascript is sometimes used defensively against bots, scrapers, malware (like keysniffers and so on), etc for both your security and that of the site. This can mean, for example, loading page elements with Javascript simply because it makes it harder to hack or scrape. Not impossible midn you, just harder.
## Back Button If the user clicks back / forward, the server will not get called again since its pulling the content out of cache. However, with an ajax call on client side pageload, the server will always get called.
Isn't AJAX on pageload a bad thing?
[ "", "javascript", "ajax", "" ]
So I have this query working (where `signal_data` is a column) in Sybase but it doesn't work in Microsoft SQL Server: ``` HEXTOINT(SUBSTRING((INTTOHEX(signal_data)),5,2)) as Signal ``` I also have it in Excel (where `A1` contains the value): ``` =HEX2DEC(LEFT(DEC2HEX(A1),LEN(DEC2HEX(A1))-2)) ``` Does anyone know how I would do this in SQL Server?
Convert INT to hex: ``` SELECT CONVERT(VARBINARY(8), 16777215) ``` Convert hex to INT: ``` SELECT CONVERT(INT, 0xFFFFFF) ``` ### Update 2015-03-16 The above example has the limitation that it only works when the HEX value is given as an integer literal. For completeness, if the value to convert is a hexadecimal string (such as found in a varchar column) use: ``` -- If the '0x' marker is present: SELECT CONVERT(INT, CONVERT(VARBINARY, '0x1FFFFF', 1)) -- If the '0x' marker is NOT present: SELECT CONVERT(INT, CONVERT(VARBINARY, '1FFFFF', 2)) ``` **Note:** The string must contain an even number of hex digits. An odd number of digits will yield an error. More details can be found in the "Binary Styles" section of [CAST and CONVERT (Transact-SQL)](https://msdn.microsoft.com/en-us/library/ms187928.aspx). I believe SQL Server 2008 or later is required.
Actually, the built-in function is named master.dbo.fn\_varbintohexstr. So, for example: ``` SELECT 100, master.dbo.fn_varbintohexstr(100) ``` Gives you 100 0x00000064
Convert integer to hex and hex to integer
[ "", "sql", "sql-server", "integer", "hex", "" ]
I have a SQL 2005 Reporting Services report that has several report parameters. One of them is called IsActive and is of type Boolean. The parameter is hidden and set to allow null values. For its default values settings, I have it set to null. In my application that has the reportviewer control, I have logic that decided whether or not to set this parameter to a value (true or false). There are conditions that require it to be not set at all. For some reason, if I do not pass a value, the parameter defaults to TRUE. It operates fine when a value is passed. Is my problem stemming from the simple reason that it is a Boolean parameter? Would changing it to a string be better? Thanks!
Changing it to a string is only necessary if there's no way to get it to take the NULL value because of a bug or "feature".
Don't know if this is related... I had a problem where I could not get the default value to be selected when viewing the report from outside of the BIDS after making changes to the report. It turned out that the parameter settings was not updated when deploying the report. Changing the settings manually via the Report Manager or removing and re-deploying the report solved the problem.
Problem with default values for Reporting Services parameters
[ "", "sql", "sql-server-2005", "reporting-services", "parameters", "default-value", "" ]
For example, ``` int myResult= (new UnmanagedResourceUsingMemorySuckingPig()).GetThingsDone(id); ``` There is no using block, no obvious way to use a using block, no obvious way to call Dispose(). And of course UnmanagedResourceUsingMemorySuckingPig does implement IDisposable.
If the finalizer of that class calls `Dispose()`, yes. If not, no. **(edit)** Just some [additional info](http://msdn.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx): > Do not assume that Dispose will be > called. Unmanaged resources owned by a > type should also be released in a > Finalize method in the event that > Dispose is not called. **Edit** To clarify the above edit, I have seen many people (in this thread, on SO, and elsewhere) claim that "The GC will call `Dispose()` when the object is removed." This is not the case at all. Yes, a good, defensive coder writing a component will assume that `Dispose()` won't be called explicitly and does so in the finalizer. However, a good, defensive coder USING a component must assume that the finalizer does NOT call `Dispose()`. **There is no automatic calling of `Dispose()` in the garbage collector**. This functionality is ONLY in place if the finalizer calls `Dispose()`.
I don't believe so. You'll have to write: ``` using (UnmanagedResourceUsingMemorySuckingPig urumsp = new UnmanagedResourceUsingMemorySuckingPig()) { myResult= urumsp.GetThingsDone(id); } ```
Will dispose be called for anonymous variables?
[ "", "c#", "idisposable", "anonymous-class", "" ]
Is there an easy way to export and then import users/permissions from one Sql Server 2005 instance to another?
Use the management console to generate a script for your users and thier associated permissions. Same can be done for the server logins in the security folder. Select your user: Select DB and expand security\users folder Right Click --> Script User As --> Create To --> New Query For Logins Select your Login: Expand security\logins folder Right Click --> Script Login As --> Create To --> New Query Now just run the query on your new instance. Just choose the db to run the script in.
Might need to do a "sp\_change\_users\_login AUTO\_FIX, 'my\_user'" afterwards to re-link security logins to their respective data as well.
Easy way to import/export Sql Server 2005 users/permissions across instances?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
We have a report generator. Daily, it writes its data into a excel file. For reasons of version controlling and file data safety, we need to alter this file, and commit the changes into a repository. Do you recommend any .net SVN API you've used?
You should take a look at the [SharpSvn](http://sharpsvn.net/) .NET library. You will probably need checkout and commit commands: Checking out: ``` string wcPath = "c:\\my working copy"; using (SvnClient client = new SvnClient()) { client.CheckOut(new Uri("http://server/path/to/repos"), wcPath); } ``` Committing: ``` string wcPath = "c:\\my working copy"; SvnCommitArgs a = new SvnCommitArgs(); a.LogMessage = "My log message"; using (SvnClient client = new SvnClient()) { client.Commit(wcPath, a); } ```
We are using tool that actually searching for installed TortoiseSVN in predefined locations and using it command-line api. If that is for Windows and it's for not redistribution - it might be easier to do. Helpful code for cmd: ``` @echo off if exist "%ProgramW6432%\TortoiseSVN\bin\TortoiseProc.exe" set patht=%ProgramW6432% if exist "%ProgramFiles%\TortoiseSVN\bin\TortoiseProc.exe" set patht=%ProgramFiles% if exist "%ProgramFiles(x86)%\TortoiseSVN\bin\TortoiseProc.exe" set patht=%ProgramFiles(x86)% echo Placing SVN Commit "%patht%\TortoiseSVN\bin\TortoiseProc.exe" /command:commit /path:"%CD%" /notempfile ``` If you still want to do that task from code - SharpSVN <http://sharpsvn.open.collab.net> is better choiсe
How to programatically do file versioning with SVN and .NET?
[ "", "c#", ".net", "svn", "api", "c#-3.0", "" ]
I am working in PHP. Please what's the proper way of inserting new records into the DB, which has unique field. I am inserting lot of records in a batch and I just want the new ones to be inserted and I don't want any error for the duplicate entry. Is there only way to first make a SELECT and to see if the entry is already there before the INSERT - and to INSERT only when SELECT returns no records? I hope not. I would like to somehow tell MySQL to ignore these inserts without any error. Thank you
You can use [INSERT... IGNORE](http://dev.mysql.com/doc/refman/5.1/en/insert.html) syntax if you want to take no action when there's a duplicate record. You can use [REPLACE INTO](http://dev.mysql.com/doc/refman/5.0/en/replace.html) syntax if you want to overwrite an old record with a new one with the same key. Or, you can use [INSERT... ON DUPLICATE KEY UPDATE](http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html) syntax if you want to perform an update to the record instead when you encounter a duplicate. Edit: Thought I'd add some examples. ## Examples Say you have a table named `tbl` with two columns, `id` and `value`. There is one entry, id=1 and value=1. If you run the following statements: ``` REPLACE INTO tbl VALUES(1,50); ``` You still have one record, with id=1 value=50. Note that the whole record was DELETED first however, and then re-inserted. Then: ``` INSERT IGNORE INTO tbl VALUES (1,10); ``` The operation executes successfully, but nothing is inserted. You still have id=1 and value=50. Finally: ``` INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200; ``` You now have a single record with id=1 and value=200.
You can make sure that you do not insert duplicate information by using the EXISTS condition. For example, if you had a table named clients with a primary key of client\_id, you could use the following statement: ``` INSERT INTO clients (client_id, client_name, client_type) SELECT supplier_id, supplier_name, 'advertising' FROM suppliers WHERE not exists (select * from clients where clients.client_id = suppliers.supplier_id); ``` This statement inserts multiple records with a subselect. If you wanted to insert a single record, you could use the following statement: ``` INSERT INTO clients (client_id, client_name, client_type) SELECT 10345, 'IBM', 'advertising' FROM dual WHERE not exists (select * from clients where clients.client_id = 10345); ``` The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table. from <http://www.techonthenet.com/sql/insert.php>
MySQL - ignore insert error: duplicate entry
[ "", "php", "mysql", "insert", "" ]
If I use a configuration file to store for example the sitename, database host, etc.. what is the best practice to handle this? 1. `$sitename="stackoverflow.com";` and then setting global $sitename in functions 2. `DEFINE(_SITENAME,"stackoverflow.com")` 3. `function vars(){return array(sitename=>"stackoverflow");}` 4. ? I would love a technical explanation on why should I pick one instead of the other. Thank you!
I tend to use define() for "environmental" configuration, since referencing a constant *should* be faster than calling a new function. It's also conceptually in line with what I'm doing: ``` /** * Set the application mode. Valid options are "development" and "production" */ define('APP_MODE', 'development'); // Database Host define('DB_HOST', 'localhost'); ``` Another option is to use ini files (make sure they are **not** in the web root) and the `parse_ini_file()` function, although you should only run this once and use a singleton to access the variables after that. (Really, you should lazy-load it, only parsing the file when the first request is made.)
It's generally considered 'better' practice to keep **application-level** configuration directives in a separate configuration text or XML file. You can create a class that's loaded as a singleton instance that parses the file and gives you what you want, e.g: ``` $config->get('DB_HOSTNAME'); ``` Have a look at [Zend\_Config](http://framework.zend.com/manual/en/zend.config.html).
What is considered the best practice to handle variables stored in a configuration file?
[ "", "php", "" ]
Simple example: 2 `JTextFields`, one for a spanish word another one for it's translation. Is there a way to preserve keyboard layout per `JTextField` so that the user wouldn't have to switch back and forth? TIA.
Yes, this demo code uses the keyboard layout for the selected locales in each text field: ``` public class InputMethodTest { public static void main(String[] args) { final InputContext en = InputContext.getInstance(); en.selectInputMethod(Locale.UK); final InputContext es = InputContext.getInstance(); es.selectInputMethod(new Locale("es", "ES")); JTextArea english = new JTextArea() { @Override public InputContext getInputContext() { return en; } }; JTextArea spanish = new JTextArea() { @Override public InputContext getInputContext() { return es; } }; JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new GridLayout()); frame.getContentPane().add(new JScrollPane(english)); frame.getContentPane().add(new JScrollPane(spanish)); frame.setSize(600, 400); frame.setVisible(true); } } ``` Tested on Windows XP Home with EN and ES keyboard layouts installed (via Control Panel > Regional and Language Options > Languages > Details...). See the [Java Input Method Framework](http://java.sun.com/javase/6/docs/technotes/guides/imf/index.html) for more details.
No, keyboard layouts are managed by the OS or desktop environment.
Preserving keyboard layout in a JTextfield?
[ "", "java", "swing", "keyboard-layout", "" ]
I have a strange problem with lxml when using the deployed version of my Django application. I use lxml to parse another HTML page which I fetch from my server. This works perfectly well on my development server on my own computer, but for some reason it gives me `UnicodeDecodeError` on the server. ``` ('utf8', "\x85why hello there!", 0, 1, 'unexpected code byte') ``` I have made sure that Apache (with mod\_python) runs with `LANG='en_US.UTF-8'`. I've tried googling for this problem and tried different approaches to decoding the string correctly, but I can't figure it out. In your answer, you may assume that my string is called `hello` or something.
"\x85why hello there!" is not a utf-8 encoded string. You should try decoding the webpage before passing it to lxml. Check what encoding it uses by looking at the http headers when you fetch the page maybe you find the problem there.
Doesn't syntax such as `u"\x85why hello there!"` help? You may find the following resources from the official Python documentation helpful: * [Python introduction, Unicode Strings](http://docs.python.org/tutorial/introduction.html#unicode-strings) * [Sequence Types — str, unicode, list, tuple, buffer, xrange](http://docs.python.org/library/stdtypes.html#typesseq)
Decoding problems in Django and lxml
[ "", "python", "django", "utf-8", "lxml", "decoding", "" ]
How can I put some text into a `TextBox` which will be removed automatically when the user types something in it?
This is a sample which demonstrates how to create a watermark textbox in WPF: ``` <Window x:Class="WaterMarkTextBoxDemo.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WaterMarkTextBoxDemo" Height="200" Width="400"> <Window.Resources> <SolidColorBrush x:Key="brushWatermarkBackground" Color="White" /> <SolidColorBrush x:Key="brushWatermarkForeground" Color="LightSteelBlue" /> <SolidColorBrush x:Key="brushWatermarkBorder" Color="Indigo" /> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> <local:TextInputToVisibilityConverter x:Key="TextInputToVisibilityConverter" /> <Style x:Key="EntryFieldStyle" TargetType="Grid" > <Setter Property="HorizontalAlignment" Value="Stretch" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="Margin" Value="20,0" /> </Style> </Window.Resources> <Grid Background="LightBlue"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid Grid.Row="0" Background="{StaticResource brushWatermarkBackground}" Style="{StaticResource EntryFieldStyle}" > <TextBlock Margin="5,2" Text="This prompt dissappears as you type..." Foreground="{StaticResource brushWatermarkForeground}" Visibility="{Binding ElementName=txtUserEntry, Path=Text.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}}" /> <TextBox Name="txtUserEntry" Background="Transparent" BorderBrush="{StaticResource brushWatermarkBorder}" /> </Grid> <Grid Grid.Row="1" Background="{StaticResource brushWatermarkBackground}" Style="{StaticResource EntryFieldStyle}" > <TextBlock Margin="5,2" Text="This dissappears as the control gets focus..." Foreground="{StaticResource brushWatermarkForeground}" > <TextBlock.Visibility> <MultiBinding Converter="{StaticResource TextInputToVisibilityConverter}"> <Binding ElementName="txtUserEntry2" Path="Text.IsEmpty" /> <Binding ElementName="txtUserEntry2" Path="IsFocused" /> </MultiBinding> </TextBlock.Visibility> </TextBlock> <TextBox Name="txtUserEntry2" Background="Transparent" BorderBrush="{StaticResource brushWatermarkBorder}" /> </Grid> </Grid> </Window> ``` TextInputToVisibilityConverter is defined as: ``` using System; using System.Windows.Data; using System.Windows; namespace WaterMarkTextBoxDemo { public class TextInputToVisibilityConverter : IMultiValueConverter { public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture ) { // Always test MultiValueConverter inputs for non-null // (to avoid crash bugs for views in the designer) if (values[0] is bool && values[1] is bool) { bool hasText = !(bool)values[0]; bool hasFocus = (bool)values[1]; if (hasFocus || hasText) return Visibility.Collapsed; } return Visibility.Visible; } public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture ) { throw new NotImplementedException(); } } } ``` **Note:** This is not my code. I found it [here](http://www.codeproject.com/Articles/26977/A-WatermarkTextBox-in-lines-of-XAML), but I think this is the best approach.
You can create a watermark that can be added to any `TextBox` with an Attached Property. Here is the source for the Attached Property: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; /// <summary> /// Class that provides the Watermark attached property /// </summary> public static class WatermarkService { /// <summary> /// Watermark Attached Dependency Property /// </summary> public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached( "Watermark", typeof(object), typeof(WatermarkService), new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged))); #region Private Fields /// <summary> /// Dictionary of ItemsControls /// </summary> private static readonly Dictionary<object, ItemsControl> itemsControls = new Dictionary<object, ItemsControl>(); #endregion /// <summary> /// Gets the Watermark property. This dependency property indicates the watermark for the control. /// </summary> /// <param name="d"><see cref="DependencyObject"/> to get the property from</param> /// <returns>The value of the Watermark property</returns> public static object GetWatermark(DependencyObject d) { return (object)d.GetValue(WatermarkProperty); } /// <summary> /// Sets the Watermark property. This dependency property indicates the watermark for the control. /// </summary> /// <param name="d"><see cref="DependencyObject"/> to set the property on</param> /// <param name="value">value of the property</param> public static void SetWatermark(DependencyObject d, object value) { d.SetValue(WatermarkProperty, value); } /// <summary> /// Handles changes to the Watermark property. /// </summary> /// <param name="d"><see cref="DependencyObject"/> that fired the event</param> /// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param> private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Control control = (Control)d; control.Loaded += Control_Loaded; if (d is ComboBox) { control.GotKeyboardFocus += Control_GotKeyboardFocus; control.LostKeyboardFocus += Control_Loaded; } else if (d is TextBox) { control.GotKeyboardFocus += Control_GotKeyboardFocus; control.LostKeyboardFocus += Control_Loaded; ((TextBox)control).TextChanged += Control_GotKeyboardFocus; } if (d is ItemsControl && !(d is ComboBox)) { ItemsControl i = (ItemsControl)d; // for Items property i.ItemContainerGenerator.ItemsChanged += ItemsChanged; itemsControls.Add(i.ItemContainerGenerator, i); // for ItemsSource property DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType()); prop.AddValueChanged(i, ItemsSourceChanged); } } #region Event Handlers /// <summary> /// Handle the GotFocus event on the control /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param> private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e) { Control c = (Control)sender; if (ShouldShowWatermark(c)) { ShowWatermark(c); } else { RemoveWatermark(c); } } /// <summary> /// Handle the Loaded and LostFocus event on the control /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param> private static void Control_Loaded(object sender, RoutedEventArgs e) { Control control = (Control)sender; if (ShouldShowWatermark(control)) { ShowWatermark(control); } } /// <summary> /// Event handler for the items source changed event /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param> private static void ItemsSourceChanged(object sender, EventArgs e) { ItemsControl c = (ItemsControl)sender; if (c.ItemsSource != null) { if (ShouldShowWatermark(c)) { ShowWatermark(c); } else { RemoveWatermark(c); } } else { ShowWatermark(c); } } /// <summary> /// Event handler for the items changed event /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A <see cref="ItemsChangedEventArgs"/> that contains the event data.</param> private static void ItemsChanged(object sender, ItemsChangedEventArgs e) { ItemsControl control; if (itemsControls.TryGetValue(sender, out control)) { if (ShouldShowWatermark(control)) { ShowWatermark(control); } else { RemoveWatermark(control); } } } #endregion #region Helper Methods /// <summary> /// Remove the watermark from the specified element /// </summary> /// <param name="control">Element to remove the watermark from</param> private static void RemoveWatermark(UIElement control) { AdornerLayer layer = AdornerLayer.GetAdornerLayer(control); // layer could be null if control is no longer in the visual tree if (layer != null) { Adorner[] adorners = layer.GetAdorners(control); if (adorners == null) { return; } foreach (Adorner adorner in adorners) { if (adorner is WatermarkAdorner) { adorner.Visibility = Visibility.Hidden; layer.Remove(adorner); } } } } /// <summary> /// Show the watermark on the specified control /// </summary> /// <param name="control">Control to show the watermark on</param> private static void ShowWatermark(Control control) { AdornerLayer layer = AdornerLayer.GetAdornerLayer(control); // layer could be null if control is no longer in the visual tree if (layer != null) { layer.Add(new WatermarkAdorner(control, GetWatermark(control))); } } /// <summary> /// Indicates whether or not the watermark should be shown on the specified control /// </summary> /// <param name="c"><see cref="Control"/> to test</param> /// <returns>true if the watermark should be shown; false otherwise</returns> private static bool ShouldShowWatermark(Control c) { if (c is ComboBox) { return (c as ComboBox).Text == string.Empty; } else if (c is TextBoxBase) { return (c as TextBox).Text == string.Empty; } else if (c is ItemsControl) { return (c as ItemsControl).Items.Count == 0; } else { return false; } } #endregion } ``` The Attached Property uses a class called `WatermarkAdorner`, here is that source: ``` using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; /// <summary> /// Adorner for the watermark /// </summary> internal class WatermarkAdorner : Adorner { #region Private Fields /// <summary> /// <see cref="ContentPresenter"/> that holds the watermark /// </summary> private readonly ContentPresenter contentPresenter; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="WatermarkAdorner"/> class /// </summary> /// <param name="adornedElement"><see cref="UIElement"/> to be adorned</param> /// <param name="watermark">The watermark</param> public WatermarkAdorner(UIElement adornedElement, object watermark) : base(adornedElement) { this.IsHitTestVisible = false; this.contentPresenter = new ContentPresenter(); this.contentPresenter.Content = watermark; this.contentPresenter.Opacity = 0.5; this.contentPresenter.Margin = new Thickness(Control.Margin.Left + Control.Padding.Left, Control.Margin.Top + Control.Padding.Top, 0, 0); if (this.Control is ItemsControl && !(this.Control is ComboBox)) { this.contentPresenter.VerticalAlignment = VerticalAlignment.Center; this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center; } // Hide the control adorner when the adorned element is hidden Binding binding = new Binding("IsVisible"); binding.Source = adornedElement; binding.Converter = new BooleanToVisibilityConverter(); this.SetBinding(VisibilityProperty, binding); } #endregion #region Protected Properties /// <summary> /// Gets the number of children for the <see cref="ContainerVisual"/>. /// </summary> protected override int VisualChildrenCount { get { return 1; } } #endregion #region Private Properties /// <summary> /// Gets the control that is being adorned /// </summary> private Control Control { get { return (Control)this.AdornedElement; } } #endregion #region Protected Overrides /// <summary> /// Returns a specified child <see cref="Visual"/> for the parent <see cref="ContainerVisual"/>. /// </summary> /// <param name="index">A 32-bit signed integer that represents the index value of the child <see cref="Visual"/>. The value of index must be between 0 and <see cref="VisualChildrenCount"/> - 1.</param> /// <returns>The child <see cref="Visual"/>.</returns> protected override Visual GetVisualChild(int index) { return this.contentPresenter; } /// <summary> /// Implements any custom measuring behavior for the adorner. /// </summary> /// <param name="constraint">A size to constrain the adorner to.</param> /// <returns>A <see cref="Size"/> object representing the amount of layout space needed by the adorner.</returns> protected override Size MeasureOverride(Size constraint) { // Here's the secret to getting the adorner to cover the whole control this.contentPresenter.Measure(Control.RenderSize); return Control.RenderSize; } /// <summary> /// When overridden in a derived class, positions child elements and determines a size for a <see cref="FrameworkElement"/> derived class. /// </summary> /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param> /// <returns>The actual size used.</returns> protected override Size ArrangeOverride(Size finalSize) { this.contentPresenter.Arrange(new Rect(finalSize)); return finalSize; } #endregion } ``` Now you can put a watermark on any TextBox like this: ``` <AdornerDecorator> <TextBox x:Name="SearchTextBox"> <controls:WatermarkService.Watermark> <TextBlock>Type here to search text</TextBlock> </controls:WatermarkService.Watermark> </TextBox> </AdornerDecorator> ``` The watermark can be anything you want (text, images ...). In addition to working for TextBoxes, this watermark also works for ComboBoxes and ItemControls. This code was adapted from [this blog post](http://www.ageektrapped.com/blog/the-missing-net-4-cue-banner-in-wpf-i-mean-watermark-in-wpf/).
Watermark / hint / placeholder text in TextBox?
[ "", "c#", "wpf", "textbox", "watermark", "hint", "" ]
Another interview question which was expecting a true / false answer and I wasn't too sure. ### Duplicate * [In .NET, what if something fails in the catch block, will finally always get called?](https://stackoverflow.com/questions/582095/in-net-what-if-something-fails-in-the-catch-block-will-finally-always-get-call) * [Does a finally block always run?](https://stackoverflow.com/questions/464098/does-a-finally-block-always-run) * [Conditions when finally does not execute in a .net try..finally block](https://stackoverflow.com/questions/111597/conditions-when-finally-does-not-execute-in-a-net-try-finally-block) * [Will code in a Finally statement fire if I return a value in a Try block?](https://stackoverflow.com/questions/345091/will-code-in-a-finally-statement-fire-if-i-return-a-value-in-a-try-block)
`finally` is executed **most of the time**. It's almost all cases. For instance, if an async exception (like `StackOverflowException`, `OutOfMemoryException`, `ThreadAbortException`) is thrown on the thread, `finally` execution is not guaranteed. This is why [constrained execution regions](http://msdn.microsoft.com/en-us/library/ms228973.aspx) exist for writing highly reliable code. For interview purposes, I expect the answer to this question to be **false** (I won't guarantee anything! The interviewer might not know this herself!).
Straight from MSDN: > The finally block is useful for > cleaning up any resources allocated in > the try block. Control is always > passed to the finally block regardless > of how the try block exits. > > Whereas catch is used to handle > exceptions that occur in a statement > block, finally is used to guarantee a > statement block of code executes > regardless of how the preceding try > block is exited. <http://msdn.microsoft.com/en-us/library/zwc8s4fz(VS.71,loband).aspx>
In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown?
[ "", "c#", ".net", "finally", "" ]
Is it any possible to get my listbox to be shown outside of the form's bounds? One of the solutions is to make the form itself transparent, and add the panel instead of the form for the background. But is there any other, more delightful way to do that? UPD: i need to make a custom autocomplete for textbox, to support wildcards. so i want a listbox to be shown below the textbox. my form's size should be about the size of the textbox. so, stretching the form vertically doesn't work in this case. thx
Actually, its possible. Here's the way: ``` public class PopupWindow : System.Windows.Forms.ToolStripDropDown { private System.Windows.Forms.Control _content; private System.Windows.Forms.ToolStripControlHost _host; public PopupWindow(System.Windows.Forms.Control content) { //Basic setup... this.AutoSize = false; this.DoubleBuffered = true; this.ResizeRedraw = true; this._content = content; this._host = new System.Windows.Forms.ToolStripControlHost(content); //Positioning and Sizing this.MinimumSize = content.MinimumSize; this.MaximumSize = content.Size; this.Size = content.Size; content.Location = Point.Empty; //Add the host to the list this.Items.Add(this._host); } } popup = new PopupWindow(listbox1); PopupWindow.show(); ```
Could you use a second form that *only* contains the listbox? You'd need a little code to move it relative to the main form, but it should work...
Show listbox outside of form (winforms)
[ "", "c#", "winforms", "" ]
I'm writing web application where I need to push data from server to the connected clients. This data can be send from any other script from web application. For example one user make some changes on the server and other users should be notified about that. So my idea is to use unix socket (path to socket based on user #ID) to send data for corresponding user (web app scripts will connect to this socket and write data). The second part is ThreadingTCPServer which will accept user connections and push data from unix socket to user over TCP socket connection. Here is the workflow: 1. Used connect to the TCP Server 2. Django script open unixsocket and write data to it. 3. TCP Server read data from unix socket and send it to open connection with user. I hope you understand my idea :) So, I have 2 questions: 1.What do you think about my idea in general? Is it good or bad solution? Any recommendations are welcome. 2.Here is my code. ``` import SocketServer import socket import netstring import sys, os, os.path import string import time class MyRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: print "Connected:", self.client_address user = self.request.recv(1024).strip().split(":")[1] user = int(user) self.request.send('Welcome #%s' % user) self.usocket_path = '/tmp/u%s.sock' % user if os.path.exists(self.usocket_path): os.remove(self.usocket_path) self.usocket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) self.usocket.bind(self.usocket_path) self.usocket.listen(1) while 1: usocket_conn, addr = self.usocket.accept() while 1: data = usocket_conn.recv(1024) if not data: break self.request.send(data) break usocket_conn.close() time.sleep(0.1) except KeyboardInterrupt: self.request.send('close') self.request.close() myServer = SocketServer.ThreadingTCPServer(('', 8081), MyRequestHandler) myServer.serve_forever() ``` and I got an exception ``` File "server1.py", line 23, in handle self.usocket.listen(1) File "<string>", line 1, in listen error: (102, 'Operation not supported on socket') ```
I think You should not use unix sockets. If Your app will (someday) become popular or mission-critical, You won't be able to just add another server to add scalability or to make it redundant and fail-safe. If, on the other hand, You will put the data into f.e. memcached (and user's "dataset number" as the separate key) You'll be able to put data into memcached from multiple servers and read it from multiple servers. If user will disconnect and connect back from some other server, You'll still be able to get the data for him. You could also use a database (to make it more fail-safe), or a mix of database and memcached if You like, but I have seen an app using unix sockets in the way You are trying to, and the programmer regreted it later. The table could have userid, data and timestamp columns and You could remember the last timestamp for the given user.
This is too complex. Use the [socketserver](http://docs.python.org/library/socketserver.html#module-SocketServer) module, please.
Threading TCP Server as proxy between connected user and unix socket
[ "", "python", "multithreading", "sockets", "tcp", "" ]
I have two tables in my database: * Company table (ID, CompanyName, CompanyUsername, CompanyPassword) * Employee table (ID, CompanyID, Name, Username, Password) Right now I am designing an internal mail system for which employees can write to each other, but also write directly to the company account. My internal mail table has these fields: * ID * FromID * ToID * Message * ... Now my problem occurs, when I fill the message table with ID's (From/To) I have no clue if the message is from the company or the employee as the ID might exists in both tables. What could my solution be? **Update** The example above was to simplify my question. The employee and company tables does not contain username or password, but an reference to ASP.NET's membership `uniqueidentifier` for managing logins. As suggested below with using UI's to control the from and the reciever, I go with UI from the ASP.NET Membership controller. Thanks. :-)
Use a uniqueidentifier for id in the Company and Employee tables and use newid() as the default value. Alternatively, Merge the tables and add a field to show whether the record is a Company or Employee.
You could use two foreign keys, on to company and one to employee and ensure that only one is ever set.
Structuring internal mail system
[ "", "sql", "email", "system", "internal", "" ]
My organization has made an upper level decision to move to maven as the standard build tool for Java projects. I have been tasked with helping our local teams migrate projects over to maven. One of the core tools that is in play is the MyEclipse IDE. MyEclipse seems to have had a "fun" history with the maven team as [evidenced](http://www.sonatype.com/people/2008/09/how-did-myeclipse-get-their-maven-integration-so-wrong/) in [various](http://www.myeclipseide.com/PNphpBB2-viewtopic-t-23178.html) places, especially when dealing with war projects. I haven't encountered problems with simple jar projects...yet. After fighting with MyEclipse and failing to make it recognize a war project easily, the question becomes, is MyEclipse worth it for developing maven war apps? If so, is there a way to get MyEclipse to play nicely with a war project that I've not found? Or, am I simply better off suggesting its time to use Eclipse Java EE edition with m2eclipse?
I am working as a tech lead, and we recently started moving to maven. I had a couple of issues getting maven to work with myeclipse. First, even when I "Enabled all m2eclipse features" checkbox, I still couldn't check out a project as a maven project, from subversion. That option (that you get from m2eclipse) just wasn't available. Also, some of the preferences you get with m2eclipse are not available with maven4myeclipse. Finally, I couldn't just uninstall the maven4eclipse plugin and install m2eclipse. That would have been an acceptable workaround. I think Genutec tried to make Maven more accesible to newbies, but there are some problems in the impementation, and I don't see them being fixed soon. For us, that will likely delegate MyEclipse to being just a fancy jsp editor.
No. MyEclipse does not support projects that were created outside of it. It is by design only working with projects created using its wizards. From the [Using Maven in MyEclipse Overview](http://www.myeclipseide.com/documentation/quickstarts/maven_overview/) > NOTE: Maven is only supported for new projects. Migration of existing > projects to Maven-enabled projects is not supported at this time, but > may be considered for a later release. Right now the MyEclipse team is > focused on providing as fluid a new-Maven-project experience as > possible
Is Developing Maven war apps in MyEclipse worth it?
[ "", "java", "maven-2", "war", "myeclipse", "" ]
I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX. Since Python scripts can run for an unlimited period, I thought Python would be a great solution. On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine. The App Engine allows 160,000 external URL accesses (right?) so you should have 160000/31/24/60 = 3,6 accesses per minute. So my script would be: ``` import time import urllib while time.clock() < 86400: # execute pseudo-cronjob file and then wait 60 seconds content = urllib.urlopen('http://www.example.org/cronjob_file.php').read() time.sleep(60) ``` Unfortunately, I have no possibility to test the script, so my questions are: 1) Do you think this would work? 2) Is it allowed (Google TOS) to use the service for such an activity? 3) Is my calculation for the URL accesses per minute right? Thanks in advance!
Maybe I'm misunderstanding you, but the cron config files will let you do this (without Python). You can add something like this to you cron.yaml file: ``` cron: - description: job that runs every minute url: /cronjobs/job1 schedule: every minute ``` See [Google's documentation](http://code.google.com/appengine/docs/python/config/cron.html#About_cron_yaml) for more info on scheduling.
Google has some limits on how long a task can run. URLFetch calls made in the SDK now have a 5 second timeout, [here](http://googleappengine.blogspot.com/2008/11/sdk-116-released.html) They allow you to schedule up to 20 cron tasks in any given day. [Here](http://code.google.com/appengine/docs/python/config/cron.html)
Google App Engine for pseudo-cronjobs?
[ "", "python", "google-app-engine", "cron", "" ]
I have created some simple app in Java, and 'deployed' it using Java Web Start (and jnlp) on my local machine. Now I would like to put it on the web, to have some feedback from various people. I was thinking about embedding my app in Google infrastructure (pages.google.com/sites.google.com/blogger.com - whatever). Question: How do I do that? What do I change in my .jnlp file (now i have there local path hardcoded - 'jnlp codebase="file:/D:/Projects/SomeApp/dist"...')? How to embed file structure (/../dist/somefiles and /../dist/lib/somefiles) into (mentioned) Google infrastructure?
I was looking for an answer but I couldn't find it anywhere. Maybe everyone are hosting on sourceforge.net or Java Web Start is not popular at all. First I have found post on newsgroup saying that on code.google.com you can call .jnlp file directly form SVN. This encouraged me to play with sites.google.com and it occurs to be very simple. 1) Create page and embed all files there – for this purpose 'file cabinet' page type will be the best. So you will have page <http://sites.google.com/site/MyPage> with bunch of jars attached to it. 2) In your launch.jnlp file put following edits: for codebase ``` <jnlp codebase="http://sites.google.com/site/MyPage" href="launch.jnlp" spec="1.0+"> ``` for any jars referenced: ``` <jar href="http://sites.google.com/site/MyPage/SomeLibrary.jar"/> ``` 3) Attach launch.jnlp to MyPage and that is all. 4) Clicking on launch file will start application. Organizing everything in more structured way doesn't break anything as long as you remember to update links in launch.jnlp.
If you need to deploy everything in a WAR file, the JnlpDownloadServlet system may be just what you need as it allows you to do exactly this. <http://java.sun.com/javase/6/docs/technotes/guides/javaws/developersguide/downloadservletguide.html>
How to embed Java Web Start (with jnlp) application on google?
[ "", "java", "jnlp", "java-web-start", "" ]
Let's say I have a `DataGridView` Control that displays about 100 records of a specified table. Every time a user scrolls down to the lowest point, I want to add another 100 records to the `DataSet` that stands behind my `DataGridView`. I knwo that a DataGridView Control has a Scroll Event like `private void DataGridView_Scroll(object sender, ScrollEventArgs e)`, and that the `ScrollEventArg`s give me the `ScrollOrientation` and the `ScrollEventType`. But how exactly do I figure out exactly when the scroll has reached the end of the scroll bar? Tnks.
Every DataGridViewRow has a "Displayed" property that indicates whether or not the row is currently being shown on screen. Therefore, you can do something like this: ``` if(this.dataGridView1.Rows[this.dataGridView1.Rows.Count - 1].Displayed) { //last rows is displayed, do what you gotta do } ```
It sounds like you might want to look at ["virtual mode"](http://msdn.microsoft.com/en-us/library/ms171622.aspx). The data binding works differently, but it is well suited to lazy data fetching.
Scroll Event in C#
[ "", "c#", ".net", "winforms", "" ]
What is the difference between GTK# and windows forms? Are they totally different? Thanks
[Gtk#](http://mono-project.com/GtkSharp): GTK# is a .NET binding for the Gtk+ toolkit. The toolkit is written in C for speed and compatibility, while the GTK# binding provides an easy to use, object oriented API for managed use. It is in active development by the Mono project, and there are various real-world applications available that use it ([Banshee](http://banshee-project.org/Main_Page) , [F-Spot](http://f-spot.org/Main_Page), [Beagle](http://beagle-project.org/Main_Page), [MonoDevelop](http://www.monodevelop.com/Main_Page)). In general, GTK# applications are written using [MonoDevelop](http://www.monodevelop.com/Main_Page), which provides a visual designer for creating GTK# GUIs. Platforms: Unix, Windows, OSX Pros: * Good support for accessibility through its Gtk+ heritage. * Layout engine ideal for handling internationalized environments, and adapts to font-size without breaking applications. * Applications integrate with the Gnome Desktop. * API is familiar to Gtk+ developers. * Large Gtk+ community. * A Win32 port is available, with native look on Windows XP. * The API is fairly stable at this point, and syntactic sugar is being added to improve it. * Unicode support is exceptional. Cons: * Gtk+ apps run like foreign applications on MacOS X. * Incomplete documentation. --- [Windows.Forms](http://mono-project.com/WinForms): Windows.Forms is a binding developed by Microsoft to the Win32 toolkit. As a popular toolkit used by millions of Windows developers (especially for internal enterprise applications), the Mono project decided to produce a compatible implementation (Winforms) to allow these developers to easily port their applications to run on Linux and other Mono platforms. Whereas the .Net implementation is a binding to the Win32 toolkit, the Mono implementation is written in C# to allow it to work on multiple platforms. Most of the Windows.Forms API will work on Mono, however some applications (and especially third party controls) occasionally bypass the API and P/Invoke straight to the Win32 API. These calls will likely have to changed to work on Mono. In general, Winforms applications are written using Microsoft's Visual Studio or [SharpDevelop](http://www.icsharpcode.net/opensource/sd/), which both provide a visual designer for creating Winforms GUIs. Platforms: Windows, Unix, OSX Pros: * Extensive documentation exists for it (books, tutorials, online documents). * Large community of active developers. * Easiest route to port an existing Windows.Forms application. Cons: * Internationalization can be tricky with fixed layouts. * Looks alien on non-Windows platforms. * Code that calls the Win32 API is not portable. --- Source: [Picking the Right Toolkit](http://www.icsharpcode.net/opensource/sd/)
They are both GUI toolkits, each having their strength and weaknesses. From my experience: * Winforms does not require installation on windows, Gtk# does require installation on Windows. * Winforms has a designer in Visual Studio, Gtk# has standalone designer and integrated designed in MonoDevelop. * Winforms is bound to Windows, Gtk# is cross-platform. * Winforms is slow and flickers. Gtk is faster. * Most Winforms controls are wrappers around standard windows controls and offer very limited functionality. Gtk widgets are more feature-rich. * Gtk allows creating forms and widgets with complex layout. Winforms offers only trivial variants of layout, and FlowLayout & TableLayout & AutoSize are too weak to be able to have complex forms that resize and automatically accomodate to different font sizes, different resolutions. * Cairo is faster and has more features than Gdi+ (Cairo supports output and input from more types of files, e.g., svg, pdf) * Gtk# is open-source, winforms is not * Winforms and Gtk# have 3rd-party controls/widgets (however, with Gtk# there is less need for them because basic controls work really good). In short, I would not recommend using Winforms (except when there is a strong reason not to have more dependencies than .NET FW), but using Gtk# or WPF.
What is the difference between GTK# and Windows Forms?
[ "", "c#", "winforms", "mono", "gtk", "monodevelop", "" ]
I just did a fresh install of lamp stack on ubuntu and enabled the mod\_rewrite module for my default website. What I want is something similar to the drupal's queries, when the whole query string is kept in one variable. For this purposes the following mod\_rewrite code may be used: ``` RewriteRule ^(.*)$ home.php?q=$1 [L,QSA] ``` The problem begins when some a string starts with the name of the file already existing in the directory; For example if I open a page: `http://localhost/home/blablabla` - the contents of $\_GET are as follows: ``` Array ( [q] => home.php ) ``` What I want to see is: ``` Array ( [q] => home/blablabla ) ``` I think it's something with default website or mod\_rewrite configuration, but I just couldn't figure it out...
You have to exclude the `home.php`: ``` RewriteCond %{REQUEST_URI} !^/home\.php$ RewriteRule ^(.*)$ home.php?q=$1 [L,QSA] ``` Or you exclude every existing file: ``` RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ home.php?q=$1 [L,QSA] ``` The reason: The [`L` flag causes an internal redirect](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriterule) with the new rewritten URL. And the new URL `home.php` is also matched by the expression `^(.*)$`.
Not *exactly* an answer to your question, but isn't that what \_SERVER["REQUEST\_URI"] and \_SERVER["REDIRECT\_URL"] are for?
Unwanted mod_rewrite behaviour
[ "", "php", "apache", "mod-rewrite", "url-rewriting", "" ]
I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell. Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.
FTPLib is implemented in Python whereas your "DOS Script" is actually a script which calls a compiled command. Executing this command is probably faster than interpreting Python code. If it is too slow for you, I suggest to call the DOS command from Python using the [subprocess module](http://docs.python.org/library/subprocess.html).
The speed problem is probably in your code. FTPlib is not 10 times slower.
Python's FTPLib too slow?
[ "", "python", "ftp", "performance", "dos", "" ]
I have two options - I can either use JNI or use Runtime.exec to execute a C++ library. The C++ program is CPU intensive and long running i.e. some calls may take up to a couple of hours to return. What are the pros and cons of each? Which approach should I go for?
If you need to interact with the C++ library, go for JNI. If it's a standalone program that you just want to invoke (and perhaps grab the output), `Runtime.exec()` is much, much simpler.
Have you looked into [JNA](https://github.com/twall/jna) as a third option? From the JNA site: > JNA provides Java programs easy access > to native shared libraries (DLLs on > Windows) without writing anything but > Java code—no JNI or native code is > required. This functionality is > comparable to Windows' Platform/Invoke > and Python's ctypes. Access is dynamic > at runtime without code generation. See their [getting started](https://github.com/twall/jna/blob/master/www/GettingStarted.md) guide for an introduction.
JNI vs Runtime.exec()
[ "", "java", "java-native-interface", "" ]
in **Access DB**... I need to extract the itemcode / desc combination for each itemcode in the following table where the desc has been used most frequently. **most frequently could possibly mean that there was only one version (see added record for pear)** in the case of **itemcode 777**, I'll have to decide later which description version to use. if there are multiple records, each containing a single version of a description, that will definately create an additional problem. the original question should probably also include returning the first row for itemcodes like 777 where all the existing records for an itemcode contain a single, unique description (so that the count would always be 1). the first row may not always be the correct version - but I won't be able to automate that phase anyway. ``` --------------------- itemcode | desc --------------------- 123 | apple 123 | apple 123 | apple 123 | apple 2 123 | apple-2 001 | orange 001 | orange 001 | ORANGE 1 001 | orange-1 666 | pear 777 | bananananana 777 | banana ``` so - I'm looking to end up with the following: ``` --------------------- itemcode | desc --------------------- 123 | apple 001 | orange 666 | pear 777 | bananananana ``` I think I'm close, but the following only gets the description in the database which appears most frequently and only returns one row. ``` SELECT itemcode, desc, count(desc) from table group by itemcode, desc having count(desc) = ( select max(ct) from ( select itemcode, desc, count(desc) as ct from table group by itemcode, desc ) ); ``` returns: ``` --------------------- itemcode | desc --------------------- 123 | apple ```
This would work through a correlated sub-query: ``` SELECT t.itemcode, t.desc, Count(t.desc) AS CountOfdesc FROM [table] AS t GROUP BY t.itemcode, t.desc HAVING Count(t.desc) IN ( SELECT TOP 1 Count(i.desc) FROM [table] AS i WHERE i.itemcode = t.itemcode GROUP BY i.itemcode, i.desc ORDER BY Count(i.desc) DESC ) AND t.desc = ( SELECT TOP 1 i.desc FROM [table] AS i WHERE i.itemcode = t.itemcode GROUP BY i.itemcode, i.desc ORDER BY i.desc ) ; ``` Returns (tested with Access 2003): ``` itemcode desc CountOfdesc 001 orange 2 123 apple 3 666 pear 1 777 banana 1 ``` BTW you should really not be calling a table "table" and a column "desc". Those are reserved SQL keywords, just avoid them to make your life easier.
Your query returns the MAX. Find a way to create a rule that would satisfy your requirements. That "which appears most frequently" means what? appears>2? appears>3? appear>4?...
access db, select group by having max problem
[ "", "sql", "database", "ms-access", "" ]
I have an issue cropping up in a form I'm trying to post. In the scenario where the form doesn't validate, I'm taking the standard route of calling `ModelState.AddModelError()` then returning a View result. The thing is, the HTML.\* helpers are supposed to pick up the posted value when rendering and I'm noticing that my text fields ONLY do so if I include them in the parameter list of the postback action, which shouldn't be required seeing as some forms have way too many fields to want to list them all as parameters. My action code is roughly: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditDataDefinition(long? id, string name) { var dataDefinition = ... // do some validation stuff if (!ModelState.IsValid) { // manually set checkbox fields via ViewData seeing as this STILL doesn't work in MC 1.0 :P // ... return View(dataDefinition); } } ``` Now, dataDefinition (which is a LINQ to SQL entity) has a field *MinVolume*, is handled in the view by this line: ``` Minimum: <%= Html.TextBox("MinVolume", null, new { size = 5 })%> ``` Yet when the view is rendered after a failed ModelState validation, the value typed into it on the original page we posted is not preserved UNLESS I include it as a parameter in the postback method. Literally, I can "solve the problem" by doing this: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditDataDefinition(long? id, string name, string minVolume) ``` For some reason that will force the field value to be preserved. This seems stupid to me because my form has way more values than just that and I shouldn't have to add a parameter for just that field. Any ideas?
Could it be that your code: ``` <%= Html.TextBox("MinVolume", null, new { size = 5 })%> ``` ..has the `null` for the default value param? Maybe if you change the `null` to `Model.MinVolume` it will persist the value. Like this: ``` <%= Html.TextBox("MinVolume", Model.MinVolume, new { size = 5 })%> ``` I'm not sure if your action returns the value `MinVolume` in the model tho. If it does, the above should work. Else, you may need to refactor the action slightly.
Oh man I've just improved my application design. The problem occurs because you have custom validation (I have too). You have to add after ``` ModelState.AddModelError() ``` this ``` ModelState.SetModelValue("MinVolume", ValueProvider["MinVolume"]); ``` In view it has to be ``` Mimum:<%=Html.Textbox("MinVolume")%> ``` Still not sure why it works but it worked for me.
ASP.Net MVC ModelState / Html.TextBox postback issue
[ "", "c#", "asp.net-mvc", "html-helper", "" ]
I have a MDB (Message driven bean) that receives messages with String which represent a word. Also I have a table in the database. The MDB should store in the table, the words and the number of times each word was received (counter). The problem is that to get better performance the MDB started in many instances and when the same new word is received by different instances they both create the same row with count of 1. To solve this I should make the word field unique and then the second instance will fail on commit, retransmitting the message, which will work, but may be problematic. Is it a good practice ? Another solution is to merge these lines afterwards summing the counter. But what if another instance will increase the counter in the middle of the update. What if two instances try to increase the counter ? `@Version` should be enough? I'm not sure what is the proper solution here. How would you handle such cases ? Also can you suggest some books about concurrency practices (not about the use of `synchronized` as I need to support Java EE and may run a cluster of application servers)? --- **Update:** After reading more about EJB and JPA I suppose I want something like an locking entity. For example I can create a new table with only id and key columns and data like this: ``` ID | KEY 1 | WORDS_CREATE_LOCK ``` So that when I need to handle a new word I will do something like this (not exact code, not sure it will even compile): ``` // MAIN FUNCTION public void handleWord(String wordStr) { Word w = getWord(wordStr); if (w == null) w = getNewOrSychronizedWord(wordStr); em.lock(w); w.setCounter(w.getCounter() + 1); em.unlock(w); } // Returns Word instance or null if not found private Word getWord(String wordStr) { Word w = null; Query query = em.createQuery("select w from words as w where w.string = :wordStr order by w.id asc"); query.setParameter("wordStr", wordStr); List<Word> words = query.getResultList(); if (words.getSize() > 0) w = words.get(0); return w; } // Handles locking to prevent duplicate word creation private Word getNewOrSynchronizedWord(String wordStr) { Word w = null; Locks l = em.find(WORDS_CREATE_LOCK_ID, Locks.class); em.lock(l); Word w = getWord(wordStr); if (w == null) { w = new Word(wordStr); em.persist(w); } em.unlock(l); return w; } ``` **So the question is will it work that way? And can I do the same without maintaining a DB Table with locking rows? May be some Java EE container locking mechanism ?** If it helps I'm using JBoss 4.2. --- I have a new idea for this. I can create two MDBs: 1st MDB with many instances allowed, that will handle all the messages and if the word is not found will send the word to the second MDB 2nd MDB with only one instance allowed, will handle the messages serially and will allow creation of new word The best part: no entire table/method/process locking, only row locking on counter update How good is that ? Thanks.
If you are looking for performance, no locking, etc. I would suggest to have another table: (word, timestamp). Your MDBs will just insert the word and the timestamp. Another process will count and update the table with the totals.
This sounds like it needs to be solved within the database by choosing the correct [transaction isolation](http://en.wikipedia.org/wiki/Isolation_(database_systems)) level - repeatable read should be sufficient. What you need is a book about databases, focusing on transactions.
Java EE concurrency & locking
[ "", "java", "jakarta-ee", "concurrency", "locking", "" ]
Apparently `libigraph` and `python-igraph` are the only packages on earth that can't be installed via `apt-get` or `easy_install` under Ubuntu 8.04 LTS 64-bit. Installing both from source from source on seems to go smoothly...until I try to use them. When I run python I get: ``` >>> import igraph Traceback (most recent call last): File "<stdin>", line 1, in <module> File "igraph/__init__.py", line 30, in <module> from igraph.core import * ImportError: No module named core ``` or (if I use the easy\_install version of python-igraph) ``` >>> import igraph Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 30, in <module> File "build/bdist.linux-x86_64/egg/igraph/core.py", line 7, in <module> File "build/bdist.linux-x86_64/egg/igraph/core.py", line 6, in __bootstrap__ ImportError: libigraph.so.0: cannot open shared object file: No such file or directory ``` I grabbed the source from here igraph 0.5.2 = <http://igraph.sourceforge.net/download.html> python-igraph 0.5.2 = <http://pypi.python.org/pypi/python-igraph/0.5.2> Can anybody point me in the right direction?
How did you compile? Did you do a make install (if there was any). As for the 'library not found' error in the easy\_install version, i'd try the following: 1. '`sudo updatedb`' (to update the locate database) 2. '`locate libigraph.so.0`' (to find where this file is on your system. If you did a make install it could have went to /usr/local/lib ... or is it in the python lib dir?) 3. Find out if the directory where this file is in is missing from your current LD\_LIBRARY\_PATH ('`echo $LD_LIBRARY_PATH`'). 4. If this directory is not in here, add it try '`export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/yourdirhere`' (make it permanent by adding it to /etc/ld.so.conf) / '`ldconfig -n /yourdirhere`'
Note that there are official Ubuntu packages for igraph available from Launchpad as of 8 Nov 2009. See the corresponding [page](https://launchpad.net/~igraph/+archive/ppa) on Launchpad for instructions. Unlike the earlier Debian package repository, this should work on both 32-bit and 64-bit architectures.
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
[ "", "python", "64-bit", "ubuntu-8.04", "igraph", "" ]
I have this code: ``` #define _WIN32_WINNT 0x0500 #include <cstdlib> #include <iostream> #include <windows.h> using namespace std; int main(int argc, char *argv[]) { Sleep(500); HDESK hOriginalThread; HDESK hOriginalInput; hOriginalThread = GetThreadDesktop(GetCurrentThreadId()); hOriginalInput = OpenInputDesktop(0, FALSE, DESKTOP_SWITCHDESKTOP); HDESK hNewDesktop=CreateDesktop("Test",NULL,NULL,0,DELETE|READ_CONTROL|WRITE_DAC|WRITE_OWNER|GENERIC_ALL,NULL); cout<<SetThreadDesktop(hNewDesktop); Sleep(575); SwitchDesktop(hNewDesktop); system("cmd"); Sleep(1000); SwitchDesktop(hOriginalInput); SetThreadDesktop(hOriginalThread); CloseDesktop(hNewDesktop); CloseDesktop(hOriginalInput); Sleep(1000); return 0; } ``` When I run this, it creates new desktop, switch to it, but command prompt not appeared. I must manualy terminate process "cmd" and my program then continue. Is there a way to show window of any application on other desktop? And how I can change background of desktop I created? Please help.
You can pick which desktop to start an application in when the application starts. ``` STARTUPINFO si = {0}; si.cb = sizeof(STARTUPINFO); si.lpDesktop = L"winsta0\\Default"; ``` Then pass this struct into [CreateProcess](http://msdn.microsoft.com/en-us/library/ms682425.aspx) or [CreateProcessAsUser](http://msdn.microsoft.com/en-us/library/ms682425.aspx). --- You can also pick which session to start the application in (Enable the session ID column in task manager to see which one you want) You can create a process in another session by using: [SetTokenInformation](http://SetTokenInformation) on the token that you use in CreateProcessAsUser passing in a TokenSessionId You can't change the session of an already running process.
Are you just trying to run "cmd" in non-blocking mode? I believe you can do that in Windows with: ``` system(1, "cmd"); ```
Problem with desktops
[ "", "c++", "windows-vista", "desktop", "" ]
I'm trying to regex-out a hash given in a string from a web-service response. The response given is in the format: ``` Write this code down, this is your id for the following tasks: P+3zLI8x1AokfbZ1jXat9g== You will need to enter the code in each of the following steps. The next task is somewhat simpler, and demonstrates the process of validating data input to a service. The next method that has been exposed for you is a method called 'girls'. This method takes five parameters, the first four of which are the first names of the members of Girls Aloud, in alphabetical order (a quick search on wikipedia will help out here), and the fifth parameter is your unique id code. Create a windows application to send the correct data and the response will be a string with your next set of instructions.` ``` The hash I'm interested in is the "id", id est, `"P+3zLI8x1AokfbZ1jXat9g=="`. I tried using a regex such as `"^:\\w*=$"` but it didn't match it... Can anyone give me a hand here? (And, for those intrerested, it is from a simple web-services example from a non-cs course; I'm trying to extract the hash via regex instead of just writing it down.)
\S\*== This matches all whole words at the end of a line, ending with '=='. [RegexStudio](http://www.regexstudio.com/) is your friend ;)
> [A-Za-z+0-9]{22}== Should work because hashes are always a specific length and use a limited character set (no punctuation). The biggest problem with the regex you posted is that you tried to anchor it to the front and end of the line, such that the expression would match if the hash is the *only* thing on that line. You don't really need to do that. If you really want to, you can anchor this expression to just the *end* of the line, but it's not necessary to get your match.
Simple C# Regex
[ "", "c#", "regex", "" ]
I've run into a problem which seems troubling to me. It seems I've found a situation that's easy enough to work-around, but that could lead to problems if a) I have a lapse in concentration while programming or b) somebody else starts implementing my interfaces and doesn't know how to handle this situation. Here's my basic setup: I've got an abstract class that I'm using as a generic interface to several data types. I've adopted the non-virtual public interface paradigm (Sutter, 2001) along with scoped locking to provide some thread safety. An example interface class would look something like this (I've left out details about scoped locking and the mutex implementation, as I don't think they're relevant): ``` class Foo { public: A( ) { ScopedLock lock( mutex ); aImp( ); } B( ) { ScopedLock lock( mutex ); bImp( ); } protected: aImp( ) = 0; bImp( ) = 0; } ``` It is then up to the user to implement aImp and bImp, which is where the problem comes in. If aImp performs some operation which uses bImp, it's extremely easy (and almost logical, in some sense) to do this: ``` class Bar { protected: aImp( ) { ... B( ); ... } bImp( ) { ... } } ``` Deadlock. Of course, the easy solution to this is to always call the protected virtual functions rather than their public variants (replace B( ) with bImp( ) in the above snippet). But it still seems far to easy to hang myself if I make a mistake, or worse yet allow others to hang themselves. Does anybody have some way to attempt to either stop an implementer of the abstract class from calling those public functions at compile-time, or otherwise help to avoid the deadlock solution? Just for kicks, some mutexes allow for operation which will avoid deadlock problems. As an example, if I implement this using the windows functions EnterCriticalSection and LeaveCriticalSection, there's no issue. But I'd rather avoid platform specific functionality. I'm currently using boost::mutex and boost::shared\_mutex in my scoped lock implementation, and as far as I've seen it doesn't attempt to avoid deadlock (which I think I almost prefer).
Using private inheritance will potentially solve your problem: ``` class Foo { public: void A( ) { ScopedLock lock( mutex ); aImp( ); } void B( ) { ScopedLock lock( mutex ); bImp( ); } protected: virtual void aImp( ) = 0; virtual void bImp( ) = 0; }; class FooMiddle : private Foo { public: using Foo::aImp; using Foo::bImp; }; class Bar : public FooMiddle { virtual void aImpl () { bImp (); B (); // Compile error - B is private } }; ``` Deriving from Foo privately, and then using FooMiddle ensures that Bar doesn't have access to A or B. However, bar is still able to override aImp and bImp, and the using declarations in FooMiddle mean that these can still be called from Bar. Alternatively, an option that will *help* but not solve the problem is to use the Pimpl pattern. You'd end up with something as follows: ``` class FooImpl { public: virtual void aImp( ) = 0; virtual void bImp( ) = 0; }; class Foo { public: void A( ) { ScopedLock lock( mutex ); m_impl->aImp( ); } void B( ) { ScopedLock lock( mutex ); m_impl->bImp( ); } private: FooImpl * m_impl; } ``` The benefit is that in the classes deriving from FooImpl, they no longer have a "Foo" object and so cannot easily call "A" or "B".
Your mutex must not be a recursive mutex. If its not a recursive mutex, a second attempt to lock the mutex in the same thread will result in that thread blocking. Since that thread locked the mutex, but is blocked on that mutex, you have a deadlock. You probably want to look at: ``` boost::recursive_mutex ``` <http://www.boost.org/doc/libs/1_32_0/doc/html/recursive_mutex.html> It's supposed to implement recursive mutex behavior cross platform.Note Win32 CRITICAL\_SECTION's (used via Enter/LeaveCriticalSection) are recursive, which would create the behavior you describe.
Avoid Deadlock using Non-virtual Public Interface and Scoped Locks in C++
[ "", "c++", "multithreading", "synchronization", "abstract-class", "" ]
I need to recursively cast a PHP SimpleXMLObject to an array. The problem is that each sub element is also a PHP SimpleXMLElement. Is this possible?
``` json_decode(json_encode((array) simplexml_load_string($obj)), 1); ```
Didn't test this one, but this seems to get it done: ``` function convertXmlObjToArr($obj, &$arr) { $children = $obj->children(); foreach ($children as $elementName => $node) { $nextIdx = count($arr); $arr[$nextIdx] = array(); $arr[$nextIdx]['@name'] = strtolower((string)$elementName); $arr[$nextIdx]['@attributes'] = array(); $attributes = $node->attributes(); foreach ($attributes as $attributeName => $attributeValue) { $attribName = strtolower(trim((string)$attributeName)); $attribVal = trim((string)$attributeValue); $arr[$nextIdx]['@attributes'][$attribName] = $attribVal; } $text = (string)$node; $text = trim($text); if (strlen($text) > 0) { $arr[$nextIdx]['@text'] = $text; } $arr[$nextIdx]['@children'] = array(); convertXmlObjToArr($node, $arr[$nextIdx]['@children']); } return; } ``` Taken from <http://www.codingforums.com/showthread.php?t=87283>
Recursive cast from SimpleXMLObject to Array
[ "", "php", "casting", "simplexml", "" ]
How can I convert a single jpg image into 3 different image formats, gif, png and bmp, using PHP?
You first create an image object out of your file with [imagecreatefromjpeg()](http://www.php.net/manual/en/function.imagecreatefromjpeg.php). You then dump that object into different formats (using [imagegif()](http://www.php.net/manual/en/function.imagegif.php) for example): ``` $imageObject = imagecreatefromjpeg($imageFile); imagegif($imageObject, $imageFile . '.gif'); imagepng($imageObject, $imageFile . '.png'); imagewbmp($imageObject, $imageFile . '.bmp'); ```
Use libGD — <http://www.php.net/manual/en/book.image.php>
Convert jpg image to gif, png & bmp format using PHP
[ "", "php", "image-processing", "" ]
What is the use of .map files VC++ linker produces when /MAP parameter or "Generate map file" project setting is used? When do I need them and how do I benefit from them?
A nice article on how to use map files for finding crashes. <http://www.codeproject.com/KB/debug/mapfile.aspx> Manually doing all this is very uninteresting. I am not aware of any tools which can read map file and help in finding the crash location. If anybody knows please update us.
For embedded systems, map files are a lot more useful. (Although you wouldn't be using Visual C++ for that ;) Things like knowing how close you are to running out of program/data memory, and what location a particular variable resides in, are important.
What's the use of .map files the linker produces?
[ "", "c++", "visual-c++", "linker", "" ]
Everyone knows and love String.IsNullOrEmpty(yourString) method. I was wondering if it's going to confuse developers or make code better if we extend String class to have method like this: ``` yourString.IsNullOrEmpty(); ``` **Pro:** 1. More readable. 2. Less typing. **Cons:** 1. Can be confusing because `yourString` variable can be `null` and it looks like you're executing method on a `null` variable. What do you think? The same question we can ask about `myObject.IsNull()` method. That how I would write it: ``` public static class StringExt { public static bool IsNullOrEmpty(this string text) { return string.IsNullOrEmpty(text); } public static bool IsNull(this object obj) { return obj == null; } } ```
I'm personally not a fan of doing this. The biggest problem with extension methods right now is discoverability. Unleses you flat out know all of the methods which exist on a particular type, it's not possible to look at a method call and know that it's an extension method. As such I find it problematic to do anything with an extension method that would not be possible with a normal method call. Otherwise you will end up confusing developers. A corollary to this problem exist in C++. In several C++ implementations it's possible to call instance methods on NULL pointers as long as you don't touch any fields or virtual methods on the type. I've worked with several pieces of code that do this intentionally and give methods differentt behavior when "`this==NULL`". It's quite maddening to work with. This is not to say that I don't like extension methods. Quite the contrary, I enjoy them and use them frequently. But I think there are 2 important rules you should follow when writing them. * Treat the actual method implementation as if it's just another static method because it in fact is. For example throw ArgumentException instead of NullReference exception for a null this * Don't let an extension method perform tricks that a normal instance method couldn't do **EDIT** Responding to Mehrdad's comment The problem with taking advantage of it is that I don't see str.IsNullOrEmpty as having a significant functional advantage over String.IsNullOrEmpty(str). The only advantage I see is that one requires less typing than the other. The same could be said about extension methods in general. But in this case you're additionally altering the way people think about program flow. If shorter typing is what people really want wouldn't IsNullOrEmpty(str) be a much better option? It's both unambiguous and is the shortest of all. True C# has no support for such a feature today. But imagine if in C# I could say ``` using SomeNamespace.SomeStaticClass; ``` The result of doing this is that all methods on SomeStaticClass were now in the global namespace and available for binding. This seems to be what people want, but they're attaching it to an extension method which I'm not a huge fan of.
If I'm not mistaken, every answer here decries the fact that the extension method can be called on a null instance, and because of this they do not support believe this is a good idea. Let me counter their arguments. I don't believe AT ALL that calling a method on an object that may be null is confusing. The fact is that we only check for nulls in certain locations, and not 100% of the time. That means there is a percentage of time where every method call we make is potentially on a null object. This is understood and acceptable. If it wasn't, we'd be checking null before every single method call. So, how is it confusing that a particular method call may be happening on a null object? Look at the following code: ``` var bar = foo.DoSomethingResultingInBar(); Console.Writeline(bar.ToStringOr("[null]")); ``` Are you confused? You should be. Because here's the implementation of foo: ``` public Bar DoSomethingResultingInBar() { return null; //LOL SUCKER! } ``` See? You read the code sample without being confused at all. You understood that, potentially, foo would return a null from that method call and the ToStringOr call on `bar` would result in a NRE. Did your head spin? Of course not. Its understood that this can happen. Now, that ToStringOr method is not familiar. What do you do in these situations? You either read the docs on the method or examine the code of the call. Here it is: ``` public static class BarExtensions { public static string ToStringOr(this bar, string whenNull) { return bar == null ? whenNull ?? "[null]" : bar.ToString(); } } ``` Confusing? Of course not. Its obvious that the developer wanted a shorthand method of checking if `bar` is null and substituting a non-null string for it. Doing this can slash your code significantly and increase readability and code reuse. Of course you could do this in other ways, but this way would be no more confusing than any other. For example: ``` var bar = foo.DoSomethingResultingInBar(); Console.Writeline(ToStringOr(bar, "[null]")); ``` When you encounter this code, what do you have to differently than the original version? You still have to examine the code, you still have to determine its behavior when `bar` is null. You still have to deal with this possibility. Are extension methods confusing? Only if you don't understand them. And, quite frankly, the same can be said for ANY part of the language, from delegates to lambdas.
Is extending String class with IsNullOrEmpty confusing?
[ "", "c#", "string", "extension-methods", "" ]
I would like to match these lines: ``` ParameterINeed: 758 ParameterCount: 8695 ParameterText: 56 ``` And I would receive a parameter name and parameter value. Could you please tell me how to write Regex.Matches patter for this and how to process this data into Dictionary? I use this code: ``` string Text = "ParameterINeed: 758\r\nParameterCount: 8695\r\nParameterText: 56"; string Pattern = "^(\\w+):\\s+(\\d+)$"; MatchCollection ma = Regex.Matches(Text, Pattern, RegexOptions.Singleline); ``` And get ma.Count = 0
The `RegexOptions.SingleLine` only affects how the period token works, not how the ^ and $ tokens work. You need to use `RegexOptions.MultiLine` for that. The multiline mode doesn't understand the \r\n line breaks, it only considers the \n character as line break. You have to consume the \r character to get to the line break. ``` string text = "ParameterINeed: 758\r\nParameterCount: 8695\r\nParameterText: 56"; string pattern = @"^(\w+):\s+(\d+)\r?$"; MatchCollection ma = Regex.Matches(text, pattern, RegexOptions.Multiline); ``` Now `ma.Count` is 3. This is how you put the matches in a dictionary: ``` Dictionary<string, int> values = new Dictionary<string, int>(); foreach (Match match in ma) { values.Add(match.Groups[1].Value, int.Parse(match.Groups[2].Value)); } ```
Try this regex ``` "^Parameter(\w+):\s+(\d+)$" ``` You can then acces the name via Matches[1] and the value as Matches[2]. My answer is based on the idea that for the string ParameterINeed: 42 you want * Name: INeed * Value: 42 If instead you wanted ParameterINeed for the value, you could just remove the Parameter word from the regex. ``` "^(\w+):\s+(\d+)$" ``` **EDIT** Responding to added code sample Try the following sample instead ``` string Text = "ParameterINeed: 758\r\nParameterCount: 8695\r\nParameterText: 56"; string[] lines = Text.Split("\n"); string Pattern = @"^(\w+):\s+(\\d+)$"; foreach ( string line in lines ) { MatchCollection ma = Regex.Matches(line, Pattern, RegexOptions.Singleline); } ```
How to match "Parameter Name: Value" in C# Regex?
[ "", "c#", "regex", "" ]
I am using TinyMCE ([`http://tinymce.moxiecode.com/`](http://tinymce.moxiecode.com/)) in a .NET page. Whenever I load a text ``` myTMCE.value=mycontent; ``` I can see that my text gets wrapped in `<p></p>`. This is not desirable for me, so I am trying to avoid it. Trying to initialize in ``` <script> tinyMCE.init({ force_p_newlines: true }) </script> ``` did not work. Any idea? Thanks in advance, m.
You could strip <p> tags after the fact using .NET, or alternatively, just use a plain <textarea> field for data entry if that suits what you're trying to do.
You need to to do this : ``` <script> tinyMCE.init({ forced_root_block: false, //some other options here }) </script> ``` By default TinyMCE sets as a root block. By setting this property to false you remove any wrapper for the text. The below text is from TinyMCE documentation: > This option enables you to make sure that any non block elements or > text nodes are wrapped in block elements. For example > **something** will result in output like: > > **something** > > This option is enabled by default > as of 3.0a1. If you set this option to false it will never produce P tags on enter or automatically it will instead produce BR elements and Shift+Enter will produce a P. Note that not using P elements as root block can severely cripple the functionality of the editor. <http://www.tinymce.com/wiki.php/Configuration:forced_root_block>
TinyMCE wraps my text in <p></p>. Can I avoid this?
[ "", "asp.net", "javascript", "tinymce", "" ]
I have a database where a misspelled string appears in various places in different tables. Is there a SQL query that I can use to search for this string in every possible varchar/text column in the database? I was thinking of trying to use the information\_schema views somehow to create dynamic queries, but I'm not sure if that will work, or if there's a better way. I'm using MS SQL Server if that helps.
Using the technique found [here](https://stackoverflow.com/questions/755146/find-all-tables-with-a-field-containing-xml-string-values) the following script generates SELECT's for all ((n)var)char columns in the given database. Copy/paste the output, remove the very last 'union' and execute.. You'll need to replace MISSPELLING HERE with the string you're looking for. ``` select 'select distinct ''' + schem.name + '.' + tab.name + '.' + col.name + ''' from [' + schem.name + '].[' + tab.name + '] where [' + col.name + '] like ''%MISSPELLING HERE%'' union ' from [sys].tables tab join [sys].schemas schem ON (tab.schema_id = schem.schema_id) join [sys].columns col on (tab.object_id = col.object_id) join [sys].types types on (col.system_type_id = types.system_type_id) where tab.type_desc = 'USER_TABLE' and types.name IN ('CHAR', 'NCHAR', 'VARCHAR', 'NVARCHAR'); ```
Using queries for this will make this more complex than really needed. Why not consider some of the free SQL Search tools that exist out there. ApexSQL has [ApexSQL Search](http://www.apexsql.com/sql_tools_search.aspx), and there is also [SQL Search](http://www.red-gate.com/products/sql-development/sql-search/) from Red-Gate. Both of these will get the job done easily.
SQL: search for a string in every varchar column in a database
[ "", "sql", "sql-server", "string", "search", "" ]
I'm developing a windows application in C# using VS2005. Consider i need to call a non static method(Method1) which is in a class(Class1) from another class(Class2). In order to call the method, i need to create object for that class. But my class 'Class1' has more than 1000 variables. So every time i create object for 'Class1', all the variables are getting instantiated but my method 'Method1' uses very few of those variables. So unnecessarily all other variables are getting instantianted. How can i optimize this code, as its an over head in instantiating the variables that are not needed for the particular method which has to be called.? Or is there any other coding standard using which i can overcome this.? Thanks in advance. here is the list of my variables. edit: ``` private string m_sPath = String.Empty; private string m_sModule = String.Empty; private string m_sType = String.Empty; public static string strFileSave; private string fileName = "", strFactoryXML = "", strPriorityXml = "", strTempXml = ""; private string selMethod = ""; private string selClass = ""; private string selMethodName = ""; private string str, str1, str2; public static string strFolder; public static string strFilePath = ""; public static string sel1, sel2; private string strSetPrFileName = ""; private string results; private string strClassCompare, strMethodCompare, strTestResultCompare; public static string CurrWorkingDirectory = Environment.CurrentDirectory; private System.Threading.ThreadStart m_CummulativeTimeThreadStart = null; private System.Threading.Thread m_CummulativeTimeThread; private string[] OuterDelim = null; private string[] InnerDelim = null; public static ArrayList alObjectsNotDefined; public static ArrayList alSystemObjUnDefined = null; public static string objFileName = ""; public static string XmlFileName = ""; //Integers private int nMethodCount, index = 0; private static int nClearFlag, nExp = 0, cell; public static int flag; private static int nMemberCount, nPrevMemberCount; private static int classIndex, methodIndex; private static int[,] arrIndex = new int[100, 100]; private int indexThread; private int bFlag = 0; //private int nIndexClass=0,nIndexMethod=0; frmCreateProject cp = new frmCreateProject(); //Boolean private bool crFlag = false, tvAfter = true; private bool bSetPriority = false; private bool bFilter = false; private bool bCr = false; private bool snapShotFlag = false, factoryFlag = false, tvSel = false; private bool bResultsFlag = false, bSummaryFlag = false; public static bool bClick = true, rightMouse = false; private bool dataError = false; private bool bClassFilter = false, bMethodFilter = false;//,bTestResultFilter=false; private bool tvFact = false; //private bool bAssignFactory=false; //private bool factoryChanges=false; private bool bEntered = false; public static bool bAssign = false; private bool bChangeMethFactory = false; private bool bExecution = false; public bool bModule = false; public bool bClass = false; public bool bMethod = false; public bool bAssemLoaded = false; public bool bLoadClicked = false; public static bool bAssignCustom = false; public static string strPath; // public static int intRowCount; public bool bTestGen = false; //Others private Module[] mdls = null; private Assembly oAssembly; private DataTable dtSnapshot; private DataTable dtFactory; private DataTable dtFactoryGV private DataTable dtExceptions = new DataTable(); private DataTable dtResults = new DataTable(); private DataTable dtSummary = new DataTable(); private DataRow dr; private DataRow drGV; private DataColumn dc, dc1; private DataColumn dcGV; private Type m_Type; private Type[] types = new Type[100]; private XmlDocument doc = new XmlDocument(); //private XmlDocument docTemp=new XmlDocument(); private DataGridTextBoxColumn TextCol; private DataGridTextBoxColumn TextColGV; private object[] arguments = new object[20]; public static bool bSupport = false; DataGridTableStyle ts1 = null; DataGridTableStyle ts2 = null DateTime gridMouseDownTime; XmlElement gridElement = null; XmlNodeList gridList = null, gridCustom = null; public string testAssem; public string strXmlTestCase; public string Gen_dll_path; public static string curClass = ""; public static string curMethod = ""; public static string curTestResult = ""; public static bool comdll = false; public static bool bIncludeNullValue; public static string strMainExcep; public static string cmbFactoryClassSel = ""; public static string cmbFactoryMethodSel = ""; public static string dataGridParameter = ""; private static string strReferredTable = ""; public static string strExePath = ""; public static string strProjPath = ""; public static string strFactoryType = ""; public static string strParameterName = "", strParameterType = ""; public static string checkFactoryClass = ""; public static string strFileXml = ""; public static bool bEdit = false; public static bool bNumArr = false; public string checkType = ""; public static bool bThread = true; public static bool bObjectsDefined = false; public static bool bSystemObjDefined = false; public static string cmbFactoryNewMethodSel = ""; public static bool editAuto = false; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem mnuFile; public System.Windows.Forms.MenuItem mnuTest; private System.Windows.Forms.MenuItem mnuExit; private System.Windows.Forms.MenuItem mnuHelp; private System.Windows.Forms.MenuItem mnuAbout; public System.Windows.Forms.ToolBar toolBar1; private System.Windows.Forms.TabControl tcResults; private System.Windows.Forms.TabPage tpSummary; private System.Windows.Forms.TabPage tpExceptions; private System.Windows.Forms.DataGrid dataGridSummary; private System.Windows.Forms.RichTextBox rtbOutput; private System.Windows.Forms.DataGrid dataGridExceptions; private System.Windows.Forms.Splitter splitterDown; private System.Windows.Forms.Splitter splitterTV; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ToolBarButton toolBarOpen; private System.Windows.Forms.ToolBarButton toolBarTest; private System.Windows.Forms.Panel panelResults; private System.Windows.Forms.TabPage tpProblems; private System.Windows.Forms.RichTextBox rtbProblems; private System.Windows.Forms.MenuItem mnuCreateProject; private System.Windows.Forms.MenuItem mnuOpenProject; private System.Windows.Forms.ToolBarButton toolBarNew; private System.Windows.Forms.PictureBox pictureBox1; protected System.Windows.Forms.ContextMenu contextMenuTest; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.MenuItem mnuAssignFactory; private System.Windows.Forms.ContextMenu contextMenuFactory; private System.Windows.Forms.MenuItem mnuViewAutoFactory; private System.Windows.Forms.ContextMenu contextMenu1; private System.Windows.Forms.MenuItem mnuEditCustomFactory; private System.Windows.Forms.MenuItem mnuDeleteCustomFactory; private System.Windows.Forms.ToolBarButton toolBarPriority; private System.Windows.Forms.MenuItem mnuSetPriority; private System.Windows.Forms.ContextMenu contextMenuResults; private System.Windows.Forms.MenuItem mnuPerformance; private System.ComponentModel.IContainer components; public static System.Windows.Forms.TreeView tempTV public static string classNameGV; public string strAppPath = ""; public string strTempPath = ""; public bool bDllExists; public string smTemp1 = ""; public string strTestFolder = ""; public static bool bReloadNewDll = false; private string dllUnderTest = ""; private System.Threading.ThreadStart m_UpdateDBTimeThreadStart = null; private System.Threading.Thread m_UpdateDBTimeThread; private TabPage tabPage2; private TreeView tvTestAssemb; private TabPage tabPage1; private TreeView tv; private TabControl tabControl1; public static string Output; private MenuItem menuItem3; private MenuItem menuItem4; private MenuItem menuItem5; private MenuItem menuItem1; private MenuItem menuItem2; private TabPage tpTestGen; public StatusBar statusBar1; private TextBox txtTestGen; private TabPage tpTestCaseTable; private DataGrid dataGrid2; private Panel panel1; private Button btnGenerate; private Button btnSave; private Button btnTestCase; private Label label5; private ComboBox cmbTestCase; private DataGrid dataGrid1; private TabPage tpGlobalVariable; public DataGrid dataGridFactoryGV; private Panel panelGlobalVariable; private ComboBox cmbMethodNameGV; private Label label2; private Label label1; private ComboBox cmbClassNameGV; private TabPage tpFactorySettings; private Panel panelFactory; public DataGrid dataGridFactory; private Panel panelClassDetails; private Label lblClassName; private ComboBox cmbClassName; private Label lblMethodName; private ComboBox cmbMethodName; private TabPage tpSnapshot; private Panel panelUpdateMsg; private PictureBox pictureBox2; private Label label4; private DataGrid datagridSnapshot; public TabControl tcSnapshot; public StatusBar statBar; public ArrayList alMultiLevelTableName = new ArrayList(); public ArrayList alExpRes; public ArrayList alParVal; public ArrayList alTestCaseID public ArrayList alClassName; private MenuItem menuItem6 public ArrayList alMethSig; public ArrayList alComments; ```
It's hard to say what can be done to solve this particular problem. What *can* be said, though, is that having such a huge class is definitely a [code smell](http://en.wikipedia.org/wiki/Code_smell). Try refactoring your classes so that the class required for operation of a method in `Class2` is of a more "sane" size. **EDIT** Holy cow! You're obviously trying to invoke a method on a `Form`-derived class. Move required logic to a third class.
It would be very rare for a well-designed class to need 1000+ variables. So it sounds like there is something wrong with the design of `Class1`. If you need to call that non-static method, then you need to instantiate the class and there is no way around the performance hit. So, if you can, you need to refactor. You could: * Split `Class1` into smaller classes which are much more focussed on a single job. * You could refactor the method you need to call so it does not require the instantiation of the class (Might be possible as it doesn't use much fo the class data). Good luck.
Calling a Method of a Windows Form Without an Active Form Instance
[ "", "c#", "winforms", "optimization", "" ]
I have a Winforms project with a single .exe file as the primary output. I'm using a deployment project to distribute it, but the .exe file is not being updated when the new version is installed, meaning I have to ask the users to manually uninstall and then install the new version. Here's what I'm doing: * I increment the assembly version on the output project (which is the primary output of the deployment project) * I increment the deployment project version (and update the product code when prompted) * The deployment project is set to remove previous versions * the 'Permanent' property on the .exe is set to False I'm sure I've done this before successfully, but I can't seem to do it now. What am I doing wrong? Edit: I got it to work by changing the *file* version in the project properties, as in [this answer](https://stackoverflow.com/questions/511789/how-do-i-persuade-a-vs2005-msi-to-upgrade/1510353#1510353)
It's hard to say what may be causing this. How are you installing the MSI that does not remove the previous version? I would recommend running the install that is not working with verbose logging. I would run it from the command line like this: ``` msiexec /i "project.msi" /l*v "c:\install.log" ``` /l tells msiexec (which is the installer service) to create a log, \* tells it to log everything, and v tells it to use verbose mode. Run that, and take a look at the log file and it should tell you what is failing and why. You can post that log file here too and I bet we can find something together. **ADDITIONL QUESTIONS:** The log file makes it look like the installer thinks there is nothing to do. When you state you update the file version, what are you updating? How do you have the files included to be deployed? Do you have them included as "primary outputs" in the setup project, or are you including the assemblies directly? Do you have it determining the dependencies and automatically including them, or did you include a project output? **UPDATE** See this post for a description of what needs to change to automatically upgrade MSI's. [Question 511789](https://stackoverflow.com/questions/511789/how-do-i-persuade-a-vs2005-msi-to-upgrade/513169#513169)
Finally figured this out after banging my head against the wall for hours. My problem was identical to this one and ended up being very simple to solve. Two answers above led me in the right direction and helped me figure out my problem but here it is in a nutshell. If you have RemovePreviousVersion set to true then the problem is most likely in the application settings under the assembly information button. I ran the log as ***mohlsen*** showed in the answer above, **msiexec /i "project.msi" /l\*v "c:\install.log"** and ended up with the same response, **Won't Overwrite; Won't patch; Existing file is of an equal version** ***Inverse*** pointed me in the right direction but also threw me off a bit with the MFC reference. I am writing a windows app and finally put two and two together and went to the properties of the app I am writing under the Application tab. There is a button called Assembly Information that leads to the assembly version and file version. I incremented these and now my .exe file updates. So you do have to do two things, increment the actual assembly version in the app you are writing as well as the version of the install package.
Deployment project not updating .exe
[ "", "c#", "winforms", "deployment", "" ]
I have a table with 2.4M+ rows, and no indexes. I am 100% sure all the rows have one column (we'll call this `id`) that is unique, it is of type `VARCHAR(255)`. I now have a file of approximately 10,000 `id`'s and need to pull the entire row for each. Is using `IN(...)` my best option? Should I add an index? I was thinking for some thinking of something like this: ``` SELECT * FROM archive_table WHERE id IN('id1', 'id2', ... 'idn'); ``` This is effectively archived data and only accessed by me every few weeks. --- System: MySQL 5.0.45 Table: MyISAM
Yes, add an index over both tables (2.4mil and 10,000). Assuming transaction\_table is 10,000 rows, archive\_table is 2.4mil rows and you've built an index overr archive\_table you could code: ``` SELECT id FROM transaction_table a WHERE EXISTS( SELECT * FROM archive_table b WHERE a.id = b.id ) ``` Using an EXISTS clause over a JOIN is more readable and has the same performance as the join.
Since you have a file of the ids you want, I recommend importing it into a work table and then joining the table to your production table to get the results you want. Of course , before you do anything, you need to implement an index strategy.
Is using IN (...) the most efficient way to randomly access a MySQL table?
[ "", "sql", "mysql", "" ]
Is there a way to pass the DatePart parameter of DateDiff as a variable? So that I can write code that is similar to this? ``` DECLARE @datePart VARCHAR(2) DECLARE @dateParameter INT SELECT @datePart = 'dd' SELECT @dateParameter = 28 SELECT * FROM MyTable WHERE DATEDIFF(@datePart, MyTable.MyDate, GETDATE()) < @dateParameter ``` The only ways I can think of doing it are with a CASE statement checking the value of the parameter or by building the SQL as a string and running it in an EXEC. Does anyone have any "better" suggestions? The platform is MS SQL Server 2005
According to BOL entry on [DATEDIFF](http://msdn.microsoft.com/en-us/library/ms189794(SQL.90).aspx) (*arguments* section) for SQL Server 2005, > These dateparts and abbreviations cannot be supplied as a user-declared variable. So you are probably stuck with Dynamic SQL or using a CASE statement. But I would opt for a CASE version instead of dynamic SQL.
Old but still valid unfortunately. I did it the case way and just want to share the code so you don't have to do all the annoying typing I had to do. Covers all possible date parts. Just replace the name of the function and the date function to implement for other T-SQL date functions. ***Copy and paste section*** ``` -- SELECT dbo.fn_DateAddFromStringPart('year', 1, GETDATE()) CREATE FUNCTION fn_DateAddFromStringPart ( @Interval VARCHAR(11), @Increment INT, @Date SMALLDATETIME ) RETURNS DATETIME AS BEGIN -- Declare the return variable here DECLARE @NewDate DATETIME -- Add the T-SQL statements to compute the return value here SELECT @NewDate = CASE WHEN @Interval IN ('year', 'yy', 'yyyy') THEN DATEADD(YEAR, @Increment, @Date) WHEN @Interval IN ('quarter', 'qq', 'q') THEN DATEADD(QUARTER, @Increment, @Date) WHEN @Interval IN ('month', 'mm', 'm') THEN DATEADD(MONTH, @Increment, @Date) WHEN @Interval IN ('dayofyear', 'dy', '') THEN DATEADD(DAYOFYEAR, @Increment, @Date) WHEN @Interval IN ('day', 'dd', 'd') THEN DATEADD(DAY, @Increment, @Date) WHEN @Interval IN ('week', 'wk', 'ww') THEN DATEADD(WEEK, @Increment, @Date) WHEN @Interval IN ('weekday', 'dw', 'w') THEN DATEADD(WEEKDAY, @Increment, @Date) WHEN @Interval IN ('hour', 'hh') THEN DATEADD(HOUR, @Increment, @Date) WHEN @Interval IN ('minute', 'mi', 'n') THEN DATEADD(MINUTE, @Increment, @Date) WHEN @Interval IN ('second', 'ss', 's') THEN DATEADD(SECOND, @Increment, @Date) WHEN @Interval IN ('millisecond', 'ms') THEN DATEADD(MILLISECOND, @Increment, @Date) WHEN @Interval IN ('microsecond', 'mcs') THEN DATEADD(MICROSECOND, @Increment, @Date) WHEN @Interval IN ('nanosecond', 'ns') THEN DATEADD(NANOSECOND, @Increment, @Date) END -- Return the result of the function RETURN @NewDate END GO ```
Dynamic DatePart when using DateDiff
[ "", "sql", "sql-server", "t-sql", "datediff", "datepart", "" ]
I have this C# code: ``` abstract class MyList : IEnumerable<T> { public abstract IEnumerator<T> GetEnumerator(); //abstract IEnumerator IEnumerable.GetEnumerator(); } ``` As is, I get: > 'Type' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. remove the comment and I get: > The modifier 'abstract' is not valid for this item How do I make an explicit implementation abstract
Interesting - I'm not sure you can. However, if this is your real code, do you ever want to implement the non-generic `GetEnumerator()` in any way *other* than by calling the generic one? I'd do this: ``` abstract class MyList<T> : IEnumerable<T> { public abstract IEnumerator<T> GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } ``` That saves you from the tedium of having to implement it in every derived class - which would no doubt all use the same implementation.
While an explicit interface member may not be abstract (or virtual), it may be implemented in terms of an abstract (or virtual) member[1](http://msdn.microsoft.com/en-us/library/aa664593%28v=vs.71%29.aspx): ``` public abstract class Foo: IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return getEnumerator(); } protected abstract IEnumerator getEnumerator(); } public class Foo<T>: Foo, IEnumerable<T> { private IEnumerable<T> ie; public Foo(IEnumerable<T> ie) { this.ie = ie; } public IEnumerator<T> GetEnumerator() { return ie.GetEnumerator(); } protected override IEnumerator getEnumerator() { return GetEnumerator(); } //explicit IEnumerable.GetEnumerator() is "inherited" } ``` I've found the need for this in strongly typed ASP.NET MVC 3 partial views, which do not support generic type definition models (as far as I know).
abstract explicit interface implementation in C#
[ "", "c#", "interface", "abstract-class", "" ]
I have an assembly that contains several user controls. For this user controls assembly I want to have a resource dictionary. All the user controls within the assembly should be able to access the resource dictionary. Do I have to add ``` <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> ... </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> ``` to every user control that should utilize the resource dictionary, or is there some way of putting it in one place and just referencing it? can I then also reference it in my main application, or does that require a MergedDictionaries call as well? Edit: the main application is in a separate project/assembly than the user controls.
> is there some way of putting it in one place and just referencing it? Put your merged dictionaries reference to your resource dictionaries into your 'App.xaml' file and it will be accessible throughout your application, you will need no futher reference. > can I then also reference it in my main application, or does that require a MergedDictionaries call as well? No the scope of 'App.xaml' falls over the entire application, so this should work fine (does for me :) ). **Update: *How to reference resource dictionary stored items from user control.*** Within your main project add a reference to your user control library. Your user controls will be accessible and you can use them in you application as desired. The process of adding the resource dictionary reference in the App.xaml will mean that all controls can reference styles and data templates etc. defined in the resource dictionaries, so it it merely a matter of referencing them: e.g. ``` Style="{StaticResource MyButtonStyle}" ``` This method works for both composite applications and regular WPF applications. Note that Visual Studio is no good at loading these styles from Linked XAML files (resource dictionary) but expression blend deals with it and will give the editor preview.
You can use a *Pack URL* to reference resource dictionaries across assemblies. For example, in Prism projects (which have multiple modules, each in its own assembly), I store my common resource dictionaries in a *ResourceDictionaries* folder in a project titled *Common*. Then I merge these dictionaries as needed into the app's modules by using markup similar to this in each module's XAML view: ``` <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/Common;component/ResourceDictionaries/DemoDictionary.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> ``` You can find further information [here](http://books.google.com/books?id=XWu70Oqz6RIC&lpg=PP1&dq=Pro%20WPF%20in%20C%23%202008&pg=PA322#v=onepage&q=&f=false).
Shared resource dictionary between several user controls and across assemblies
[ "", "c#", "wpf", "resources", "" ]
I downloaded [Chromium](https://github.com/chromium/chromium)'s code base and ran across the [WTF namespace](https://github.com/chromium/chromium/tree/master/third_party/blink/renderer/platform/wtf). ``` namespace WTF { /* * C++'s idea of a reinterpret_cast lacks sufficient cojones. */ template<typename TO, typename FROM> TO bitwise_cast(FROM in) { COMPILE_ASSERT(sizeof(TO) == sizeof(FROM), WTF_wtf_reinterpret_cast_sizeof_types_is_equal); union { FROM from; TO to; } u; u.from = in; return u.to; } } // namespace WTF ``` Does this mean what I think it means? Could be so, the `bitwise_cast` implementation specified here will not compile if either `TO` or `FROM` is not a [POD](http://en.wikipedia.org/wiki/Plain_Old_Data_Structures) and is not (AFAIK) more powerful than C++ built in `reinterpret_cast`. The only point of light I see here is the nobody seems to be using `bitwise_cast` in the Chromium project.
It’s short for **W**eb **T**emplate **F**ramework and provides commonly used functions all over the WebKit codebase.
It is to avoid the strict-aliasing optimization problem: [gcc, strict-aliasing, and casting through a union](https://stackoverflow.com/questions/2906365/gcc-strict-aliasing-and-casting-through-a-union)
WTF does WTF represent in the WebKit code base?
[ "", "c++", "webkit", "chromium", "" ]
I have a method I am using to execute a command on the local host. I'd like to add a timeout parameter to the method so that if the command being called doesn't finish in a reasonable amount of time the method will return with an error code. Here's what it looks like so far, without the ability to timeout: ``` public static int executeCommandLine(final String commandLine, final boolean printOutput, final boolean printError) throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(commandLine); if (printOutput) { BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); System.out.println("Output: " + outputReader.readLine()); } if (printError) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); System.out.println("Error: " + errorReader.readLine()); } return process.waitFor(); } ``` Can anyone suggest a good way for me to implement a timeout parameter?
``` public static int executeCommandLine(final String commandLine, final boolean printOutput, final boolean printError, final long timeout) throws IOException, InterruptedException, TimeoutException { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(commandLine); /* Set up process I/O. */ ... Worker worker = new Worker(process); worker.start(); try { worker.join(timeout); if (worker.exit != null) return worker.exit; else throw new TimeoutException(); } catch(InterruptedException ex) { worker.interrupt(); Thread.currentThread().interrupt(); throw ex; } finally { process.destroyForcibly(); } } private static class Worker extends Thread { private final Process process; private Integer exit; private Worker(Process process) { this.process = process; } public void run() { try { exit = process.waitFor(); } catch (InterruptedException ignore) { return; } } } ```
If you're using Java 8 or later you could simply use the new [waitFor with timeout](https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html#waitFor-long-java.util.concurrent.TimeUnit-): ``` Process p = ... if(!p.waitFor(1, TimeUnit.MINUTES)) { //timeout - kill the process. p.destroy(); // consider using destroyForcibly instead } ```
How to add a timeout value when using Java's Runtime.exec()?
[ "", "java", "process", "timeout", "runtime", "exec", "" ]
I am trying to build an IVR and hook it up to my website, what are the different (inexpensive) ways that I can do it.
I am building a telephony system, am learning about this new technology released by voxeo, its called tropo. you can build telephony applications in Groovy, JavaScript, PHP, Python, and Ruby. <http://www.tropo.com/> Hope this helps.
I built an IVR app using [Twilio](http://www.twilio.com) in just a few days and it was a pleasure. They have a simple XML syntax (with good documentation), an awesome REST API, and small-project-friendly per-minute pricing which lets you concentrate on building your app and not building/hosting telephony infrastructure. You can even do international calling or get toll-free numbers. It reminds me of that Tropo project mentioned here but they're not so beta (even if the logo says "beta").
Is it possible to create Interactive voice response systems from home, if so, what is the best solution
[ "", "c#", "vb.net", "ivr", "" ]
For some time now when I am debugging Visual C++ applications and viewing any CString or char\* (or any other ascii char based type) variable in the Local, Auto, or Watch debug windows, the CR/LF characters in my variables are not displayed at all. In other words, if I have a string variable set to "This is a line\r\nThis is another line" in my code, the debug window will show "This is a lineThis is another line". What I would like it to show is "This is a line□□This is another line" so that I can see the two extra characters in that text. This has caused me to make some mistakes when trying to debug string parsing code. Note, the text visualizer properly breaks the text up into separate lines, but I don't want to use the text visualizer if I don't have to. Furthermore, some coworkers of mine are able to see CR/LF characters in the correct manner, but we cannot determine why they are not shown for me. Many thanks in advance.
This seems to be some sort of hard-to-reproduce bug (I'm not seeing them in 2k8 either) according to [this old link](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100850): > If we wanted to do this properly we'd need to issue the proper escape sequences for these characters. eg show "\r\n" in the string. The behavior of stripping special characters historical and will be fixed in a future release. If you are viewing text with newlines in it you can either view the string as a character array: type "str,100" to view a string of length 100 as an array. Or you can click on the magnifying glass glyph and view the string in a multiline edit control. A month later: > We cannot reproduce this problem on neither VS2003 nor VS2005. This looks like a machine-specific problem. So if your coworkers are really seeing it then there must be something weird going on in our setups.
Could it be the font you are using? are you all using the same (preferably default) font? I've had a number of pesky issues come up with people doing that. Not sure if that is your problem, but its something to check.
Visual C++ Debug window displaying of CR/LF in Visual Studio 2008
[ "", "c++", "visual-studio-2008", "debugging", "newline", "" ]
I want to set `DataTextField` and `DataValueField` of a `Dropdownlist` (languageList) using a Dictionary (list) of `languageCod` (en-gb) as key and language name (english) as the text to display. Relevant Code: ``` string[] languageCodsList= service.LanguagesAvailable(); Dictionary<string, string> list = new Dictionary<string, string>(languageCodsList.Length); foreach (string cod in languageCodsList) { CultureInfo cul = new CultureInfo(cod); list.Add(cod, cul.DisplayName); } languageList.DataSource = list; languageList.DataBind(); ``` How can I set `DataTextField` and `DataValueField`?
Like that you can set DataTextField and DataValueField of DropDownList using "Key" and "Value" texts : ``` Dictionary<string, string> list = new Dictionary<string, string>(); list.Add("item 1", "Item 1"); list.Add("item 2", "Item 2"); list.Add("item 3", "Item 3"); list.Add("item 4", "Item 4"); ddl.DataSource = list; ddl.DataTextField = "Value"; ddl.DataValueField = "Key"; ddl.DataBind(); ```
When a dictionary is enumerated, it will yield [`KeyValuePair<TKey,TValue>`](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) objects... so you just need to specify "Value" and "Key" for `DataTextField` and `DataValueField` respectively, to select the [Value](http://msdn.microsoft.com/en-us/library/ms224761.aspx)/[Key](http://msdn.microsoft.com/en-us/library/ms224760.aspx) properties. Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as: ``` list.Add(cul.DisplayName, cod); ``` (And then changing the binding to use "Key" for `DataTextField` and "Value" for `DataValueField`, of course.) In fact, I'd suggest that as it seems you really do want a *list* rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a `List<KeyValuePair<string, string>>`: ``` string[] languageCodsList = service.LanguagesAvailable(); var list = new List<KeyValuePair<string, string>>(); foreach (string cod in languageCodsList) { CultureInfo cul = new CultureInfo(cod); list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod)); } ``` Alternatively, use a list of plain `CultureInfo` values. LINQ makes this really easy: ``` var cultures = service.LanguagesAvailable() .Select(language => new CultureInfo(language)); languageList.DataTextField = "DisplayName"; languageList.DataValueField = "Name"; languageList.DataSource = cultures; languageList.DataBind(); ``` If you're not using LINQ, you can still use a normal foreach loop: ``` List<CultureInfo> cultures = new List<CultureInfo>(); foreach (string cod in service.LanguagesAvailable()) { cultures.Add(new CultureInfo(cod)); } languageList.DataTextField = "DisplayName"; languageList.DataValueField = "Name"; languageList.DataSource = cultures; languageList.DataBind(); ```
C# DropDownList with a Dictionary as DataSource
[ "", "c#", "dictionary", "drop-down-menu", "" ]
The problem I have is that I have multiple submit inputs in a single form. Each of these submit inputs has a different value and I would prefer to keep them as submit. Whenever the user presses `Enter`, it is as though the topmost submit input is being pressed, and so it is causing problems for the code checking which input was clicked. Is there a way for PHP to determine whether or not the input was clicked, or was just the input that was selected when the user pressed the `Enter` key?
You can identify which button was used provided you structure your HTML correctly ``` <input type="submit" name="action" value="Edit"> <input type="submit" name="action" value="Preview"> <input type="submit" name="action" value="Post"> ``` The `$_POST` array (or `$_GET/$_REQUEST`) will contain the key "action" with the value of the enacted button (whether clicked or not). Now, "clicking" is explicitly a client-side behavior - if you want to differentiate between a click and a keypress, you'll need to add some scripting to your form to aid in that determination. ## Edit Alternatively, you can be "sneaky" and use a hidden submit that should correctly identify a key-pressed for submission, but this probably has some significant impact on accessibility. ``` <?php if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) { echo '<pre>'; print_r( $_POST ); echo '</pre>'; } ?> <form method="post"> <input type="text" name="test" value="Hello World"> <input type="submit" name="action" value="None" style="display: none"> <input type="submit" name="action" value="Edit"> <input type="submit" name="action" value="Preview"> <input type="submit" name="action" value="Post"> </form> ```
Roberto, PHP is server-side technology and therefore runs on the server - so there is no way for it to determine what keys where pressed at the client (aka the user). That is, of course, unless you specifically code the client-side to include such information with the server requests (posting form data is a form of request too). One way to accomplish that is by using Javascript in your client code. See this page as a starting point regarding handling form submit events using Javascript. <http://www.w3schools.com/jsref/jsref_onSubmit.asp> You may also have to add a listener for key press events on your page in order to capture the user pressing the Enter key and then recording this information. <http://www.howtocreate.co.uk/tutorials/javascript/domevents> offers a discussion on the topic of adding/removing event listeners in Javascript but you have to be very careful when using events because improperly used they can be the source of memory leaks which are hard to debug and cause for unhappy users :)
How can PHP determine if the user pressed the Enter key or Submit button?
[ "", "php", "forms", "submit", "form-submit", "" ]
I'm creating a movies website, IMDB.com like.. I'm really new to PHP and programming at all but I have some books and StackOverflow of course :) I have already done lot of the work, but now I have more than 600 lines of code (PHO only) per page and more than 20 database tables only for storing and geting the movie data (many-to-many relationships) Most of the code are MySQLi queries (prepared statements) to insert/get data and loops. Nothing fancy, just basic PHP/MySQL. I have some questions: * It is recommended to use MySQLi prepared statements for every SQL query or is better just to use old MySQL for internal PHP/database queries and leave prepared statements for user input only? * To get all the movie data and show it I need to get the data from more than 16 different tables. I use one MySQL query per table (somethimes more) and lots of loops. This is the correct way a website need to work?? I mean.. this is normal??? * How can I simplify the code to simplify the reading? Can I separete all those queries to external files?? Can I create functions to handle each table query?? Hope you can give me a hand and maybe you have some more suggestions for correctly building such a website. Thanks!!
Consider looking at or using a web framework for your website. symfony CakePHP CodeIgniter Are some of the more mainstream ones. Learn from them if anything.
As mentioned in the anwsers above I would also point you to using a framework that impliments the MVC design pattern. Along with that most of the frameworks have an ORM built in but if they do not you can look at Symphony or EZPDO is another good ORM to tie into your Model in (M)VC. CodeIgniter is a very fast and light weight MVC framework that would allow you to bootstrap pretty quickly but you may also want to look into ZF (ZendFramework). ZF has a great framework feature set and is pretty flexible overall. Beyond that be sure to seperate your reads and your writes in either or Model or your calls to the ORM of choice. This will allow you to slave data to multiple MySQL Boxes for bigger performance but allows you to use one database engine to start out. Add in the ability to use Memcached so that you can cache your data/objects vs hitting the database. When using cache put some thought into how you would expire cache for a database update. In other words if your selecting data from a database to display in a view and that data is has not changed you should not need to hit the database every time but rather pull it from memory. Once the data actually does change you'd want to invalidate that cache so it's not stale and then re-cache the new data. memcached: <http://www.danga.com/memcached/>' -facebook also has a version CodeIgniter - <http://codeigniter.com/> EZPDO - <http://www.ezpdo.net/blog/?p=2> ZendFramework -<http://framework.zend.com/>
PHP/MySQL: The right way creating a big website database based
[ "", "php", "mysql", "database-design", "data-structures", "mysqli", "" ]
Since PHP's [`call_user_method()`](http://php.net/call_user_method) and [`call_user_method_array()`](http://php.net/manual/function.call-user-method-array.php) are marked deprecated I'm wondering what alternative is recommended? One way would be to use [`call_user_func()`](http://php.net/manual/function.call-user-func.php), because by giving an array with an object and a method name as the first argument does the same like the deprecated functions. Since this function is not marked deprecated I assume the reason isn't the non-OOP-stylish usage of them? The other way I can think of is using the [Reflection API](http://php.net/manual/language.oop5.reflection.php), which might be the most comfortable and future-oriented alternative. Nevertheless it's more code and I could image that it's slower than using the functions mentioned above. What I'm interested in: * Is there a completely new technique for calling an object's methods by name? * Which is the fastest/best/official replacement? * What's the reason for deprecation?
As you said [`call_user_func`](http://www.php.net/call_user_func) can easily duplicate the behavior of this function. What's the problem? The [`call_user_method`](http://us.php.net/call_user_method) page even lists it as the alternative: ``` <?php call_user_func(array($obj, $method_name), $parameter /* , ... */); call_user_func(array(&$obj, $method_name), $parameter /* , ... */); // PHP 4 ?> ``` As far as to *why* this was deprecated, [this posting explains it:](http://www.mail-archive.com/php-dev@lists.php.net/msg11576.html) > This is > because the `call_user_method()` and `call_user_method_array()` functions > can easily be duplicated by: > > old way: > `call_user_method($func, $obj, "method", "args", "go", "here");` > > new way: > `call_user_func(array(&$obj, "method"), "method", "args", "go", "here");` Personally, I'd probably go with the variable variables suggestion posted by Chad.
You could do it using [variable variables](http://php.net/manual/en/language.variables.variable.php), this looks the cleanest to me. Instead of: ``` call_user_func(array($obj, $method_name), $parameter); ``` You do: ``` $obj->{$method_name}($parameter); ```
Recommended replacement for deprecated call_user_method?
[ "", "php", "deprecated", "" ]
I have a C# project that imports a C dll, the dll has this function: ``` int primary_read_serial(int handle, int *return_code, int *serial, int length); ``` I want to get access to the serial parameter. I've actually got it to return one character of the serial parameter, but I'm not really sure what I'm doing and would like to understand what is going, and of course get it working. So, I'm very sure that the dll is being accessed, other functions without pointers work fine. How do I handle pointers? Do I have to marshal it? Maybe I have to have a fixed place to put the data it? An explanation would be great. Thanks! Richard
You will have to use an IntPtr and Marshal that IntPtr into whatever C# structure you want to put it in. In your case you will have to marshal it to an int[]. This is done in several steps: * Allocate an unmanaged handle * Call the function with the unamanged array * Convert the array to managed byte array * Convert byte array to int array * Release unmanaged handle That code should give you an idea: ``` // The import declaration [DllImport("Library.dll")] public static extern int primary_read_serial(int, ref int, IntPtr, int) ; // Allocate unmanaged buffer IntPtr serial_ptr = Marshal.AllocHGlobal(length * sizeof(int)); try { // Call unmanaged function int return_code; int result = primary_read_serial(handle, ref return_code, serial_ptr, length); // Safely marshal unmanaged buffer to byte[] byte[] bytes = new byte[length * sizeof(int)]; Marshal.Copy(serial_ptr, bytes, 0, length); // Converter to int[] int[] ints = new int[length]; for (int i = 0; i < length; i++) { ints[i] = BitConverter.ToInt32(bytes, i * sizeof(int)); } } finally { Marshal.FreeHGlobal(serial_ptr); } ``` Don't forget the try-finally, or you will risk leaking the unmanaged handle.
If I understand what you're trying to do, this should work for you. ``` unsafe { int length = 1024; // Length of data to read. fixed (byte* data = new byte[length]) // Pins array to stack so a pointer can be retrieved. { int returnCode; int retValue = primary_read_serial(0, &returnCode, data, length); // At this point, `data` should contain all the read data. } } ``` JaredPar gives you the easy way to do it however, which is just to change your external function declaration so that C# does the marshalling for you in the background. Hopefully this gives you an idea of what's happening at a slightly lower level anyway.
Passing pointers from unmanaged code
[ "", "c#", "interop", "dllimport", "" ]
Is there a way to turn a normal Eclipse Project into a JPA Project? I have a normal project with Entities in it and a Persistence.xml file, but it is not an eclipse recognized JPA project. What can I do?
project properties --> project facets. There you can click on the JPA check-box and you have an JPA project.
You could also Right Click the eclipse project and click on configure which allows you to convert to a JPA project. ![alt text](https://i.stack.imgur.com/w4qFc.gif)
Eclipse + Turn an Existing Project into a JPA Project
[ "", "java", "eclipse", "jpa", "jakarta-ee", "eclipse-plugin", "" ]
It looks like the lists returned by `keys()` and `values()` methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods). For example: ``` >>> d = {'one':1, 'two': 2, 'three': 3} >>> k, v = d.keys(), d.values() >>> for i in range(len(k)): print d[k[i]] == v[i] True True True ``` If you do not alter the dictionary between calling `keys()` and calling `values()`, is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.
Found this: > If `items()`, `keys()`, `values()`, > `iteritems()`, `iterkeys()`, and > `itervalues()` are called with no > intervening modifications to the > dictionary, the lists will directly > correspond. On [2.x documentation](https://docs.python.org/2/library/stdtypes.html#dict.items) and [3.x documentation](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects).
Yes, what you observed is indeed a guaranteed property -- `keys()`, `values()` and `items()` return lists in congruent order if the dict is not altered. `iterkeys()` &c also iterate in the same order as the corresponding lists.
Python dictionary: are keys() and values() always the same order?
[ "", "python", "" ]
I'm using the Intelligencia UrlRewriter on a project. It's working fine to rewrite urls typed into the browser. For example, if I enter ``` http://localhost/People ``` This is being correctly rewritten as: ``` http://localhost/People.aspx ``` Now, the problem is, when I am in the code behind I need to access the Friendly URL, but Request.ServerVariables seems to only have the unfriendly URL available. Does anyone know if there's anyway I can access this original, friendly Url in code? Or am I too late?
Got it guys. @Nick Allen and Pure.Krome: Thanks for the help!! I found the piece of data in: ``` HttpContext.Current.Request.RawUrl ``` If it exists in ServerVariables, I couldn't see it, but in conclusion, the data is there so I won't have to cry myself to sleep :) Okay. Thanks again!!
``` Request.PathInfo Request.QueryString ``` Which one you use depends on if you rewrite to `default.aspx?myvar` or `default.aspx/myvar`
Intelligencia.UrlRewriter
[ "", "c#", "asp.net", "friendly-url", "urlrewriter", "" ]
I have been a Half-Life lover for years. I have a BS in CS and have been informally programming since High-School. When I was still in college I tried to become a mod programmer for fun..using the first Half-Life engine...didn't work so good. So i figured after all my great college learrning :-) I would have more insight on how to tackle this problem and could finally do it. So here I am..finally out in the business world programming java...so I downloaded the HL2 SDk and started looking through the class structure. I feel like I did that last time I tried this...dazed and confused. Sorry about all the back ground. So what is the best way to systematically learn the code structure? I know java and I know c++..i just dont know what any of the classes do...the comments are few and far between and the documentation seems meager. Any good approahces? I \*\*don'\*\*t wanna start my own mod... I just wanna maybe be a spare-time mod programmer on some cool MOD one day...to keep the fun in learning programming along with the business side.
> the comments are few and far between > and the documentation seems meager. > Any good approahces? Welcome to the wonder that is the Source SDK. No, it's not documented. Experiment, hack, place breakpoints and see what happens if you change bits of code. There is a [wiki](http://developer.valvesoftware.com/wiki/Main%5FPage) you may find helpful in some cases, but it's filled in by the community, and not by Valve, which means that you won't find any actual documentation there, just explanations of how previous modders have hacked the engine. Honestly, it sucks. The only way around it is to dive in. Try to achieve various changes to the game and don't be afraid to rip the existing code apart. It won't be pretty, but if it works, who's going to complain? Their code is pretty horrible, and most likely, yours will be too.
You can start at the [Valve Developer Wiki](http://developer.valvesoftware.com/wiki/Main_Page).
What are some good approaches to learning the Half-Life 2 SDK?
[ "", "c++", "sdk", "" ]
I have a Projects table, which lists the client info. Then I have four related jobs tables, for jobs within that project - Roofing, Siding, Gutters and Misc. The four tables have a projectID field to link them to the Projects table, and they all have a 'status' field. A project can have any combination of jobs. I want to be able to select only the projects where all the job status fields are marked "completed." There's probably a simple way to do this, but my brain overheats sometimes with SQL.
maybe...: ``` SELECT * FROM Projects LEFT JOIN Roofing ON (projectID) LEFT JOIN Siding ON (projectID) LEFT JOIN Gutters ON (projectID) LEFT JOIN Misc ON (projectID) WHERE (Roofing.status IS NULL OR Roofing.status="completed") AND (Siding.status IS NULL OR Siding.status="completed") AND (Gutters.status IS NULL OR Gutters.status="completed") AND (Misc.status IS NULL OR Misc.status="completed") ```
``` select p.* from project as p where not exists (select 1 from roofing where projectId = p.projectId and status <> 'completed') and not exists (select 1 from siding where projectId = p.projectId and status <> 'completed') and not exists (select 1 from gutters where projectId = p.projectId and status <> 'completed') and not exists (select 1 from misc where projectId = p.projectId and status <> 'completed') ```
SQL statement for evaluating multiple related tables
[ "", "sql", "sql-server", "" ]
I'm looking for a RegEx to return either the first [n] words in a paragraph or, if the paragraph contains less than [n] words, the complete paragraph is returned. For example, assuming I need, at most, the first 7 words: ``` <p>one two <tag>three</tag> four five, six seven eight nine ten.</p><p>ignore</p> ``` I'd get: ``` one two <tag>three</tag> four five, six seven ``` And the same RegEx on a paragraph containing less than the requested number of words: ``` <p>one two <tag>three</tag> four five.</p><p>ignore</p> ``` Would simply return: ``` one two <tag>three</tag> four five. ``` My attempt at the problem resulted in the following RegEx: ``` ^(?:\<p.*?\>)((?:\w+\b.*?){1,7}).*(?:\</p\>) ``` However, this returns just the first word - "one". It doesn't work. I think the .\*? (after the \w+\b) is causing problems. Where am I going wrong? Can anyone present a RegEx that will work? FYI, I'm using .Net 3.5's RegEX engine (via C#) Many thanks
OK, complete re-edit to acknowledge the new "spec" :) I'm pretty sure you can't do that with one regex. The best tool definitely is an HTML parser. The closest I can get with regexes is a two-step approach. First, isolate each paragraph's contents with: ``` <p>(.*?)</p> ``` You need to set `RegexOptions.Singleline` if paragraphs can span multiple lines. Then, in a next step, iterate over your matches and apply the following regex once on each match's `Group[1].Value`: ``` ((?:(\S+\s+){1,6})\w+) ``` That will match the first seven items separated by spaces/tabs/newlines, ignoring any trailing punctuation or non-word characters. BUT it will treat a tag separated by spaces as one of those items, i. e. in ``` One, two three <br\> four five six seven ``` it will only match up until `six`. I guess that regex-wise, there's no way around that.
1. Use a HTML parser to get the first paragraph, flattening its structure (i.e. remove decorating HTML tags inside the paragraph). 2. Search for the position of the nth whitespace character. 3. Take the substring from 0 to that position. *edit:* I removed the regex proposal for step 2 and 3, since it was wrong (thanks to the commenter). Also, the HTML structure needs to be flattened.
Need RegEx to return first paragraph or first n words
[ "", "c#", "regex", "" ]