Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've been helping a colleague debug some strange behavior in their code. The following sample illustrates this: ``` static void Main(string[] args) { string answer = Sample(); Console.WriteLine(answer); } public static string Sample() { string returnValue = "abc"; try { return returnValue; } catch (Exception) { throw; } finally { returnValue = "def"; } } ``` What does this sample return? You'd think that because of the finally block, it returns "def" but in fact, it returns "abc"? I've stepped through the code and confirmed that the finally block is in fact invoked. The real answer is that you shouldn't write code like this in the first place but I'm still puzzled as to the behaviour. Edit: To clarify the flow based on some of the answers. When you step through the code, the finally is executed before the return. **Duplicate of:** [What really happens in a try { return x; } finally { x = null; } statement?](https://stackoverflow.com/questions/421797/what-really-happens-in-a-try-return-x-finally-x-null-statement)
Yes, the finally block runs after the function returns, but this doesn't matter. Remember that the return value is passed by value, so a new temporary variable is created for it at return time, thus the finally block does nothing to affect the actual return value. If you want to support the desired behavior you could use an out parameter, like so: ``` static void Main(string[] args) { string answer; Sample(out answer); Console.WriteLine(answer); } public static void Sample(out string answer) { try { answer = "abc"; return; } catch (Exception) { throw; } finally { answer = "def"; } } ``` Or, you could simply move the return statement outside of the try block, like so: ``` static void Main(string[] args) { string answer = Sample(); Console.WriteLine(answer); } public static string Sample() { string returnValue; try { returnValue = "abc"; } catch (Exception) { throw; } finally { returnValue = "def"; } return returnValue; } ``` However, given that the finally block will always override the return value, this is a questionable design.
Your "finally" block is assigning a value to returnValue and not actually returning a value. The "return" has already occurred before the finally block changes the value and therefore "abc" is returned. Whilst the code is confusing as what you've done doesn't make sense, what it's doing is correct.
Why is my finally block not working in C#?
[ "", "c#", "finally", "" ]
I'm rebuilding [Josh Smith's WPF CommandSink example](http://www.codeproject.com/KB/WPF/VMCommanding.aspx) and there are a few things that I don't understand about his databinding, especially about how datacontext is inherited when a view is contained in another view which is contained in a window which has a datacontext. * all databinding is declared in the XAML files, there is absolutely no code behind the Window or either of the Views (nice) * the top Window defines its DataContext as CommunityViewModel and simply displays the CommunityView * **Question:** so now in the CommunityViewModel, what does the `jas:CommandSinkBinding.CommandSink="{Binding}"` do actually? "CommandSink" is an attached property so is this "attaching" the inherited Binding that comes from DemoWindow as the value of the attached property called "CommandSink" on the CommandSinkBinding object? * **Question:** also, PersonView doesn't seem to have a DataContext yet it has lines such as `<TextBlock Text="{Binding Name}" Width="60" />` which assume that a binding is set. So does PersonView automatically get its binding from the line in CommunityView `ItemsSource="{Binding People}"`? Thanks for any clarification here. **DemoWindow.xaml:** ``` <Window x:Class="VMCommanding.DemoWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:view="clr-namespace:VMCommanding.View" xmlns:vm="clr-namespace:VMCommanding.ViewModel" FontSize="13" ResizeMode="NoResize" SizeToContent="WidthAndHeight" Title="ViewModel Commanding Demo" WindowStartupLocation="CenterScreen" > <Window.DataContext> <vm:CommunityViewModel /> </Window.DataContext> <Window.Content> <view:CommunityView /> </Window.Content> </Window> ``` **CommunityView.xaml:** ``` <UserControl x:Class="VMCommanding.View.CommunityView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:jas="clr-namespace:VMCommanding" xmlns:view="clr-namespace:VMCommanding.View" xmlns:vm="clr-namespace:VMCommanding.ViewModel" jas:CommandSinkBinding.CommandSink="{Binding}" > <UserControl.CommandBindings> <jas:CommandSinkBinding Command="vm:CommunityViewModel.KillAllMembersCommand" /> </UserControl.CommandBindings> <DockPanel Margin="4"> <ItemsControl DockPanel.Dock="Bottom" ItemsSource="{Binding People}"> <ItemsControl.ItemTemplate> <DataTemplate> <view:PersonView /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <Button Command="vm:CommunityViewModel.KillAllMembersCommand" Content="Kill All" Margin="0,0,0,8" /> </DockPanel> </UserControl> ``` **PersonView.xml:** ``` <UserControl x:Class="VMCommanding.View.PersonView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:jas="clr-namespace:VMCommanding" xmlns:vm="clr-namespace:VMCommanding.ViewModel" jas:CommandSinkBinding.CommandSink="{Binding}" > <UserControl.CommandBindings> <jas:CommandSinkBinding Command="vm:PersonViewModel.DieCommand" /> <jas:CommandSinkBinding Command="vm:PersonViewModel.SpeakCommand" /> </UserControl.CommandBindings> <UserControl.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Margin" Value="0,0,6,0" /> <Style.Triggers> <DataTrigger Binding="{Binding CanDie}" Value="False"> <Setter Property="Foreground" Value="#88000000" /> </DataTrigger> </Style.Triggers> </Style> </UserControl.Resources> <StackPanel Margin="2" Orientation="Horizontal"> <TextBlock Text="Name:" FontWeight="Bold" /> <TextBlock Text="{Binding Name}" Width="60" /> <TextBlock Text="Age:" FontWeight="Bold" /> <TextBlock Text="{Binding Age}" Width="40" /> <Button Command="vm:PersonViewModel.SpeakCommand" CommandParameter="Howdy partner!" Content="Speak" Margin="0,0,6,0" Width="60" /> <Button Command="vm:PersonViewModel.DieCommand" Content="Die" Width="60" /> </StackPanel> </UserControl> ```
If you set the `ItemsSource` of an ItemsControl, the DataContexts of the items in that control are directly mapped to the items of the `ItemsSource`.
A control inherits it's parents DataContext unless one is specified explicitly for the control. So the answer to your second question is yes.
How is DataContext inherited in Views which contain Views?
[ "", "c#", "wpf", "mvvm", "datacontext", "" ]
As I understand it, C#'s `foreach` iteration variable is immutable. Which means I can't modify the iterator like this: ``` foreach (Position Location in Map) { // We want to fudge the position to hide the exact coordinates Location = Location + Random(); // Compiler Error Plot(Location); } ``` I can't modify the iterator variable directly and instead, I have to use a `for` loop ``` for (int i = 0; i < Map.Count; i++) { Position Location = Map[i]; Location = Location + Random(); Plot(Location); i = Location; } ``` Coming from a C++ background, I see foreach as an alternative to the `for` loop. But with the above restriction, I usually fallback to using the `for` loop. I'm curious, what is the rationale behind making the iterator immutable? --- Edit: This question is more of a curiousity question and not as a coding question. I appreciated the coding answers but I can't mark them as answers. Also, the example above was over-simplified. Here is a C++ example of what I want to do: ``` // The game's rules: // - The "Laser Of Death (tm)" moves around the game board from the // start area (index 0) until the end area (index BoardSize) // - If the Laser hits a teleporter, destroy that teleporter on the // board and move the Laser to the square where the teleporter // points to // - If the Laser hits a player, deal 15 damage and stop the laser. for (int i = 0; i < BoardSize; i++) { if (GetItem(Board[i]) == Teleporter) { TeleportSquare = GetTeleportSquare(Board[i]); SetItem(Board[i], FreeSpace); i = TeleportSquare; } if (GetItem(Board[i]) == Player) { Player.Life -= 15; break; } } ``` I can't do the above in C#'s foreach because the iterator i is immutable. I think (correct me if I'm wrong), this is specific to the design of foreach in languages. I'm interested in why the `foreach` iterator is immutable.
Lets start out with a silly but illustrative example: ``` Object o = 15; o = "apples"; ``` At no point do we get the impression that we just turned the number 15 into a string of apples. We know that `o` is simply a pointer. Now lets do this in iterator form. ``` int[] nums = { 15, 16, 17 }; foreach (Object o in nums) { o = "apples"; } ``` Again, this really accomplishes nothing. Or at least it *would* accomplish nothing were it to compile. It certainly wouldn't insert our string into the int array -- that's not allowed, and we know that `o` is just a pointer anyway. Let's take your example: ``` foreach (Position Location in Map) { //We want to fudge the position to hide the exact coordinates Location = Location + Random(); //Compiler Error Plot(Location); } ``` Were this to compile, the `Location` in your example stars out referring to a value in `Map`, but then you change it to refer to a new `Position` (implicitly created by the addition operator). Functionally it's equivalent to this (which DOES compile): ``` foreach (Position Location in Map) { //We want to fudge the position to hide the exact coordinates Position Location2 = Location + Random(); //No more Error Plot(Location2); } ``` So, why does Microsoft prohibit you from re-assigning the pointer used for iteration? Clarity for one thing -- you don't want people assigning to it thinking they've changed your position within the loop. Ease of implementation for another: The variable might hide some internal logic indicating the state of the loop in progress. But more importantly, there is no reason for you to *want* to assign to it. It represents the current element of the looping sequence. Assigning a value to it breaks the "Single Responsibility Principle" or [Curly's Law](http://www.codinghorror.com/blog/archives/000805.html) if you follow Coding Horror. A variable should mean one thing only.
If the variable were mutable, that might give an incorrect impression. For example: ``` string[] names = { "Jon", "Holly", "Tom", "Robin", "William" }; foreach (string name in names) { name = name + " Skeet"; } ``` Some people *might* think that would change the array contents. It's reaching a bit, but it might be a reason. I'll look it up in my annotated spec tonight...
Why is The Iteration Variable in a C# foreach statement read-only?
[ "", "c#", "language-design", "" ]
I am playing around trying to call a simple SOAP webservice using the following code in the Python interpreter: ``` from SOAPpy import WSDL wsdl = "http://www.webservicex.net/whois.asmx?wsdl" proxy = WSDL.Proxy(wsdl) proxy.soapproxy.config.dumpSOAPOut=1 proxy.soapproxy.config.dumpSOAPIn=1 proxy.GetWhoIS(HostName="google.com") ``` (Yep, I'm new to Python, doing the diveintopython thing...) The call to the GetWhoIS method fails - otherwise I wouldn't be asking here, I guess. Here's my outgoing SOAP: ``` <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema"> <SOAP-ENV:Body> <GetWhoIS SOAP-ENC:root="1"> <HostName xsi:type="xsd:string">google.com</HostName> </GetWhoIS> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` And here's the incoming response. ``` <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <soap:Fault> <faultcode>soap:Server</faultcode> <faultstring> System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.ArgumentNullException: Value cannot be null. at whois.whois.GetWhoIS(String HostName) --- End of inner exception stack trace --- </faultstring> <detail /> </soap:Fault> </soap:Body> </soap:Envelope> ``` (manually formatted for easier reading) Can anyone tell me what am I doing wrong? Ideally both in terms of use of SOAPpy, and why the SOAP message is incorrect. Thanks!
Your call seems all right to me, i think this could be a soappy problem or misconfigured server (although i have not checked this thoroughly). This document also suggests incompatibilities between soappy and webservicex.net: <http://users.jyu.fi/~mweber/teaching/ITKS545/exercises/ex5.pdf> How i would work around this in this specific case? ``` import urllib url_handle = urllib.urlopen( "http://www.webservicex.net/whois.asmx/GetWhoIS?HostName=%s" \ % ("www.google.com") ) print url_handle.read() ```
As mentioned by @ChristopheD, SOAPpy seems to be buggy for certain configurations of WDSL. I tried using suds (sudo easy\_install suds on Ubuntu) instead, worked first time. ``` from suds.client import Client client = Client('http://www.webservicex.net/whois.asmx?wsdl') client.service.run_GetWhoIS(HostName="google.com") ``` Job's a good 'un.
What's wrong with my Python SOAPpy webservice call?
[ "", "python", "wsdl", "soappy", "" ]
I am writing the update system for my application and I need to shutdown the application to overwrite the exe but after it shuts down I need to run the update executable, how can I do this?
Could you just start the updater using `Process.Start` and have it wait until your main program closes? I think that would be the easiest solution. Or you could have a separate launcher program that will check for updates and update before launching the main application. But this leads to the same problem if you have to update the launcher. --- Along the lines of this: ``` static void Main(string[] args) { var haveToUpdate = ...; if (haveToUpdate) { Process.Start("update.exe"); Environment.Exit(0); } } static void Main(string[] args) { var processes = Process.GetProcessesByName("program.exe"); if (processes.Length > 1) throw new Exception("More than one program.exe running"); else if (processes.Length == 0) Update(); else processes[0].Exited += new EventHandler(Program_Exited); } static void Program_Exited(object sender, EventArgs e) { Update(); } static void Update() { // ... } ```
Do it in reverse. Get the entire updated file down using the old application (storing it temporarily) and then start the updater application using process start. All the update has to do is copy the new file over the old file and restart the application. The updater can catch the access denied exceptions and wait for the application to become available for being copyied over. Once the copy is done - it deletes the temporary new file and starts the application again before shutting down. Then you can update the updater (using the normal application) if you need to.
Closing application and running an external application
[ "", "c#", "" ]
I have a property that returns a `HashTable`. I would like to sort it without refactoring my property. *Please note*: I do not want to return another type. Code: ``` /// <summary> /// All content containers. /// </summary> public Hashtable Containers { get { Hashtable tbl = new Hashtable(); foreach (Control ctrl in Form.Controls) { if (ctrl is PlaceHolder) { tbl.Add(ctrl.ID, ctrl); } // Also check for user controls with content placeholders. else if (ctrl is UserControl) { foreach (Control ctrl2 in ctrl.Controls) { if (ctrl2 is PlaceHolder) { tbl.Add(ctrl2.ID, ctrl2); } } } } return tbl; } } ```
Another option is to construct the hash table as you're already doing, and then simply construct a sorted set from the keys. You can iterate through that sorted key set, fetching the corresponding value from the hash table as needed.
Hashtables work by mapping keys to values. Implicit in this mapping is the concept that the keys aren't sorted or stored in any particular order. However, you could take a look at [`SortedDictionary<K,V>`](http://msdn.microsoft.com/en-us/library/f7fta44c.aspx).
Is it possible to sort a HashTable?
[ "", "c#", "sorting", "hashtable", "" ]
I have a method call expression and try to invoke the method. I figured out a way, but I have problems in retrieving the parameter values since not every argument is described with a ConstantExpression. ``` Expression<Action<T>> = t => t.DoSomething(Par0, Par1, Par2); MethodCallExpression methodCallExpression = selector.Body as MethodCallExpression; // get the information which is needed to invoke the method from the provided // lambda expression. MethodInfo methodInfo = methodCallExpression.Method; object[] arguments = methodCallExpression.Arguments.OfType<ConstantExpression>() .Select(p => p.Value).ToArray(); // invoke the expression on every item within the enumerable foreach (TSource item in source) { methodInfo.Invoke(item, arguments); } ``` Additionally, I have seen some other ways to invoke the method, now I'm not sure what is the right way to do it. ``` var func = expression.Compile(); var success = func.Invoke(); ``` So my question is, how can I retrieve the method argument values from `methodCallExpression.Arguments`? Or is there an easier way to achieve my goal?
You don't need to worry about retrieving the arguments and calling the MethodInfo yourself, you can let .NET do it for you. All you need to do is create a Lambda expression containing that method. eg. ``` MethodCallExpression expression = GetExpressionSomeHow(); object result = Expression.Lambda(expression).Compile().DynamicInvoke(); ``` That's how I deal with nested queries in my Linq provider anyway. EDIT: Actually, it looks like you might already have a LambdaExpression in the selector variable. In that case, you should be able to just compile and invoke it directly: ``` object result = selector.Compile().DynamicInvoke(); ```
Compiling an expression is a very intensive operation, so I would only do that if you are planning on re-using the expression. I would recommend the reflection way otherwise; you will find it executes faster. Never call expression.Compile() in a tight loop.
How to call the method from a MethodCallExpression in c#
[ "", "c#", ".net", "lambda", "parameters", "" ]
I am working in a project where database items are not deleted, but only marked as deleted. Something like this: ``` id name deleted --- ------- -------- 1 Thingy1 0 2 Thingy2 0 3 Thingy3 0 ``` I would like to be able to define something like a UNIQUE constraint on the `name` column. Seems easy, right? Let's imagine a scenario in which "Thingy3" is deleted, and a new one is created (perhaps years later). We get: ``` id name deleted --- ------- -------- 1 Thingy1 0 2 Thingy2 0 3 Thingy3 1 ... 100 Thingy3 0 ``` From the user's point of view, he deleted an item and created a new one. Much like deleting a file, and creating a new file. So it's obvious to him that the new item is unrelated and unattached to any data connected to the old item. That's already handled, since the DB only cares about the `id`, and since the new item has an `id` of 100 instead of 3, they are utterly different. My difficulty arises when I want to prevent the user from creating *another* "Thingy3" item. If I had a UNIQUE constraint that only looked at items that aren't marked `deleted`, then I would have solved one problem. (Of course, then I'd have to deal with what happens when someone does an undo of the delete...) So, how can I define that sort of a constraint?
You could add the id value to the end of the name when a record is deleted, so when someone deletes id 3 the name becomes Thingy3\_3 and then when they delete id 100 the name becomes Thingy3\_100. This would allow you to create a unique composite index on the name and deleted fields but you then have to filter the name column whenever you display it and remove the id from the end of the name. Perhaps a better solution would be to replace your deleted column with a deleted\_at column of type DATETIME. You could then maintain a unique index on name and deleted at, with a non-deleted record having a null value in the deleted\_at field. This would prevent the creation of multiple names in an active state but would allow you to delete the same name multiple times. You obviously need to do a test when undeleting a record to ensure that there is no row with the same name and a null deleted\_at field before allowing the un-delete. You could actually implement all of this logic within the database by using an INSTEAD-OF trigger for the delete. This trigger would not delete records but would instead update the deleted\_at column when you deleted a record. The following example code demonstrates this ``` CREATE TABLE swtest ( id INT IDENTITY, name NVARCHAR(20), deleted_at DATETIME ) GO CREATE TRIGGER tr_swtest_delete ON swtest INSTEAD OF DELETE AS BEGIN UPDATE swtest SET deleted_at = getDate() WHERE id IN (SELECT deleted.id FROM deleted) AND deleted_at IS NULL -- Required to prevent duplicates when deleting already deleted records END GO CREATE UNIQUE INDEX ix_swtest1 ON swtest(name, deleted_at) INSERT INTO swtest (name) VALUES ('Thingy1') INSERT INTO swtest (name) VALUES ('Thingy2') DELETE FROM swtest WHERE id = SCOPE_IDENTITY() INSERT INTO swtest (name) VALUES ('Thingy2') DELETE FROM swtest WHERE id = SCOPE_IDENTITY() INSERT INTO swtest (name) VALUES ('Thingy2') SELECT * FROM swtest DROP TABLE swtest ``` The select from this query returns the following ``` id name deleted_at 1 Thingy1 NULL 2 Thingy2 2009-04-21 08:55:38.180 3 Thingy2 2009-04-21 08:55:38.307 4 Thingy2 NULL ``` So within your code you can delete records using a normal delete and let the trigger take care of the details. The only possible issue (That I could see) was that deleting already deleted records could result in duplicate rows, hence the condition in the trigger to not update the deleted\_at field on an already deleted row.
It might be worth considering using a "recycle bin" table. Instead of keeping the old records in the same table with a flag, move them to its own table with its own constraints. For instance, in the active table you do have a UNIQUE constraint on name, but in the recycle bin table you don't.
What to do when I want to use database constraints but only mark as deleted instead of deleting?
[ "", "sql", "sql-server-2005", "t-sql", "constraints", "" ]
I'm trying to open the zip code lookup page on the usps website and fill out the form using javascript, and I get the following error: `'Permission denied to get property Window.document'` Here's my script: ``` function lookupZipCode(line1, line2, city, state, zip) { var usps = window.open('http://zip4.usps.com/zip4/welcome.jsp'); usps.document.getElementById('address2').value = line1; usps.document.getElementById('address1').value = line2; usps.document.getElementById('city').value = city; usps.document.getElementById('state').value = state; usps.document.getElementById('zip5').value = zip); } ``` I understand that this is a security feature. Ideally I would use query string params but the page does not appear to support them. Anyone have any ideas for a workaround?
If you don't like the API (;-)), you **can** use the query-string params: <http://zip4.usps.com/zip4/welcome.jsp?address1=somethingelse&address2=something&state=FL&city=Miami&zip5=123456789&urbanization=>
You should be using the [APIs they provide](http://www.usps.com/webtools/?from=zclsearch&page=webtools&WT.z_zip4link=webtools) instead of trying to automate filling in a form.
javascript cross domain document.getElementById
[ "", "javascript", "browser", "" ]
I'm having trouble with an SMS message I am sending using a provider called Cymba. Basically I'm posting the message over to them as per their specifications URL encoded. However when the message is sent to my phone the £ appears with an A in front i.e. £A Now C# strings are Unicode by default, so I switched to ASCII encoding and the £ comes over as ?. I've tried converting the message string to hex starting form the Unicode and ASCII versions (as via this gateway you an also submit the message as hex). However the same behaviour occurs. I suspect it is something to do with the string encoding as SMS supports a 7bit encoding format: GSM 03.38 I suspect also that if I send over Unicode I'll only get a 70 or 140 char message instead of the standard 160. I'm quite new to SMS sending so any help or advice will be appreciated. So the question is, how can I get my C# strings into this format? **Update:** Looks like the Gateway is the one with the problem not my code as I tried replacing the offending £ with the 7bit equivalent hex value and this did not work either. See below for my test code which may help others in future: ``` byte pound = 0xA3; byte GSMPound = 0x01; string hexxedMsg = ""; System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] msgBytes = encoder.GetBytes(message); foreach (byte byt in msgBytes) { if(byt == pound) hexxedMsg += GSMPound.ToString("X"); else hexxedMsg += byt.ToString("X2"); ; } ```
There's a [GSM 03.38 to Unicode](http://www.unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT) mapping table available which suggests that £ should be encoded as 0x01 so you could try that (just hard-coding it for a single attempt). However, you should really check all of this with the gateway operator. Is the gateway genuinely expecting you to post in URL-encoded GSM 03.38? If so, that mapping table is probably the way to go - you may need to write your own implementation to map from a string to bytes (fully implementing `System.Text.Encoding` would be overkill). I'd try it with a hard-coded message first though.
[This page](http://www.dreamfabric.com/sms/) contains info on the ["7-bit default alphabet"](http://www.dreamfabric.com/sms/default_alphabet.html). The simplest solution may be to create a Dictionary that maps the Unicode code points encoded by the GSM 03.38 standard (approximately 140 glyphs) into 1 or 2 bytes (2 bytes are needed for the 0x27, 0x?? pairs). Once that's done (depending on your provider) you may also have to squeeze the 8-bit bytes into a stream of 7-bit sequences. There's a [visual sample](http://www.dreamfabric.com/sms/hello.html) here. And after you've achieved all of that (and had a couple of beers!) you might want to turn it into a System.Text.Encoding implementation. --- You might also want to have a look at [PDUDecoder](http://www.codeproject.com/KB/IP/PDUDecoder.aspx) on CodeProject for the reverse operation. There's an online version too.
Encoding £ in SMS message sent via Gateway not working correctly
[ "", "c#", ".net", "sms", "gsm", "" ]
I’m developing a Ray Tracer in C++ using SDL and Pthread. I’m having issues making my program utilize two cores. The threads work, but they don’t use both cores to 100%. To interface SDL I write directly to it's memory, SDL\_Surface.pixels, so I assume that it can't be SDL locking me. My thread function looks like this: ``` void* renderLines(void* pArg){ while(true){ //Synchronize pthread_mutex_lock(&frame_mutex); pthread_cond_wait(&frame_cond, &frame_mutex); pthread_mutex_unlock(&frame_mutex); renderLinesArgs* arg = (renderLinesArgs*)pArg; for(int y = arg->y1; y < arg->y2; y++){ for(int x = 0; x < arg->width; x++){ Color C = arg->scene->renderPixel(x, y); putPixel(arg->screen, x, y, C); } } sem_post(&frame_rendered); } } ``` Note: scene->renderPixel is const, so I assume both threads can read from the same memory. I have two worker threads doing this, in my main loop I make these work using: ``` //Signal a new frame pthread_mutex_lock(&frame_mutex); pthread_cond_broadcast(&frame_cond); pthread_mutex_unlock(&frame_mutex); //Wait for workers to be done sem_wait(&frame_rendered); sem_wait(&frame_rendered); //Unlock SDL surface and flip it... ``` Note: I've also tried creating and joining the threads instead of synchronizing them. I compile this with "-lpthread -D\_POSIX\_PTHREAD\_SEMANTICS -pthread" and gcc does not complain. My problem is best illustrated using a graph of the CPU usage during execution: [![CPU usage during execution.](https://i.stack.imgur.com/DFLFg.png)](https://i.stack.imgur.com/DFLFg.png) (source: [jopsen.dk](http://jopsen.dk/downloads/processor_usage.png)) As can be seen from the graph my program only uses one core at a time, then switching between the two every once in a while, but it doesn't drive both to 100% ever. What in the world have I done wrong? I'm not using any mutex or semaphors in scene. What can I do to find the bug? Also if I put while(true) around scene->renderPixel() I can push both cores to 100%. So I've suspected that this is caused by overhead, but I only synchronize every 0.5 second (e.g. FPS: 0.5), given a complex scene. I realize it might not be easy to tell me what my bug is, but an approach to debugging this would be great too... I haven't played with pthreads before... Also, can this be a hardware or kernel issue, my kernel is: ``` $uname -a Linux jopsen-laptop 2.6.27-14-generic #1 SMP Fri Mar 13 18:00:20 UTC 2009 i686 GNU/Linux ``` Note:
This is useless : ``` pthread_mutex_lock(&frame_mutex); pthread_cond_wait(&frame_cond, &frame_mutex); pthread_mutex_unlock(&frame_mutex); ``` if you wait to wait for a new frame do something like : int new\_frame = 0; First thread : ``` pthread_mutex_lock(&mutex); new_frame = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); ``` other thread : ``` pthread_mutex_lock(&mutex); while(new_frame == 0) pthread_cond_wait(&cond, &mutex); /* Here new_frame != 0, do things with the frame*/ pthread_mutex_unlock(&mutex); ``` pthread\_cond\_wait(), actually release the mutex, and unschedule the thread until the condition is signaled. When the condition is signaled the thread is waken up and the mutex is re-taken. All this happen inside the pthread\_cond\_wait() function
I'd take a wild stab in the dark and say your worker threads are spending lots of time waiting on the condition variable. To get good CPU performance in this kind of situation where your code is mostly CPU bound, it is understood to use a task oriented style of programming, where you treat the threads as a "pool" and you use a queue structure to feed work to them. They should spend a very small amount of time pulling work off the queue and most of their time doing the actual work. What you have right now is a situation where they are probably doing work for a while, then notifying the main thread via the semaphore that they are done. The main thread will not release them until both threads have finished working on the frame they are currently processing. Since you are using C++, have you considered using Boost.Threads? It makes working with multithreaded code much easier, and the API is actually kind of similar to pthreads, but in a "modern C++" kind of way.
Problem using pthread to utilize multiple cores
[ "", "c++", "pthreads", "mutex", "sdl", "semaphore", "" ]
When it comes to navigating through an HTML form by hitting the TAB key, Internet Explorer 7 treats an `INPUT` element with `TYPE=FILE` as *two* controls ([see MSDN for details](http://msdn.microsoft.com/en-us/library/ms535263(VS.85).aspx)). The first time you hit TAB it focusses on the text field, and the second time it focuesses on the Browse button. This is invisible to JavaScript. The problem is I want to use [Ajax Upload](http://valums.com/ajax-upload/) or something similar to allow the user to click what looks like a button and see the File chooser appear. This works by placing an invisible file-input element under the mouse. I have managed to change the script to allow you to TAB to the hidden file-input element and for this to trigger a CSS change so the fake button looks like it has focus, the upshot being that, on browsers other than IE7, it looks to the user as if you can tab to the button and activate it as you would expect. This cannot work on IE7 because the first TAB takes it to the invisible text field; pressing SPACE adds a space to the invisible file name instead of activating the file picker. I have tried adding an event handler for `keypress` that calls the `click` event, but when I do this the `change` event I am depending on seems not to be fired. I am beginning to think the only accessible solution on IE7 (and, I assume, IE8) will be to replace the whole dialogue with a two part form -- the first part with a (visible) file-input element and Upload button, the second part with all the other form items. This is unfortunate because (a) IE7 get a less slick user experience, and (b) I have to add all sorts of extra server-side code to allow the form to be submitted in two parts. So I would be interested to know if anyone has a way to make IE7's file-input element behave like a single control, or, alternatively, to allow JavaScript to access both controls of the element (something the DOM was not designed for!).
As should be obvious from my other answer, I have managed to build this widget with full keyboard accessibility. My sincere advice is to drop this pursuit. It is a maintenance *nightmare*. You are exploiting security holes in the browser to make this work and it is only a matter of time before vendors close something that you rely on.
This a bit complicated to do but here's how: Create a new button to use as your "fake" input control (you have this as the visible element). This element needs to be a button or a link for it to be able to get tab focus (I suggest button so that it works better on Safari). Remove the file input from the tabbing order by setting it's `.tabIndex` to -1. It should now be hidden from sight and tabbing order. Assign events to the file input so that on activity then the focus is moved back to the fake button, values are copied from it, and so forth. Assign a click event to the fake button that calls `.click` on the file input element. This will only work for IE. It will also very likely break in a future release. For mozilla style browsers you can move the focus from the fake button to the file input on *keydown*, the *keypress* event will the occur on the file control and you can then move the focus back to fake button on *change*. This should also give you del/backspace functionality (clear field). Clearing the field in IE can only be done by rebuilding a new file input control.
Can we make IE7 treat a FILE TYPE=INPUT element as a single control?
[ "", "javascript", "ajax", "forms", "internet-explorer-7", "" ]
Does Java have an easy way to reevaluate a heap once the priority of an object in a PriorityQueue has changed? I can't find any sign of it in `Javadoc`, but there has to be a way to do it somehow, right? I'm currently removing the object then re-adding it but that's obviously slower than running update on the heap.
You might need to implement such a heap yourself. You need to have some handle to the position of the item in the heap, and some methods to push the item up or down when its priority has changed. Some years ago I wrote such a heap as part of a school work. Pushing an item up or down is an O(log N) operation. I release the following code as public domain, so you may use it in any way you please. (You might want to improve this class so that instead of the abstract isGreaterOrEqual method the sort order would rely on Java's Comparator and Comparable interfaces, and also would make the class use generics.) ``` import java.util.*; public abstract class Heap { private List heap; public Heap() { heap = new ArrayList(); } public void push(Object obj) { heap.add(obj); pushUp(heap.size()-1); } public Object pop() { if (heap.size() > 0) { swap(0, heap.size()-1); Object result = heap.remove(heap.size()-1); pushDown(0); return result; } else { return null; } } public Object getFirst() { return heap.get(0); } public Object get(int index) { return heap.get(index); } public int size() { return heap.size(); } protected abstract boolean isGreaterOrEqual(int first, int last); protected int parent(int i) { return (i - 1) / 2; } protected int left(int i) { return 2 * i + 1; } protected int right(int i) { return 2 * i + 2; } protected void swap(int i, int j) { Object tmp = heap.get(i); heap.set(i, heap.get(j)); heap.set(j, tmp); } public void pushDown(int i) { int left = left(i); int right = right(i); int largest = i; if (left < heap.size() && !isGreaterOrEqual(largest, left)) { largest = left; } if (right < heap.size() && !isGreaterOrEqual(largest, right)) { largest = right; } if (largest != i) { swap(largest, i); pushDown(largest); } } public void pushUp(int i) { while (i > 0 && !isGreaterOrEqual(parent(i), i)) { swap(parent(i), i); i = parent(i); } } public String toString() { StringBuffer s = new StringBuffer("Heap:\n"); int rowStart = 0; int rowSize = 1; for (int i = 0; i < heap.size(); i++) { if (i == rowStart+rowSize) { s.append('\n'); rowStart = i; rowSize *= 2; } s.append(get(i)); s.append(" "); } return s.toString(); } public static void main(String[] args){ Heap h = new Heap() { protected boolean isGreaterOrEqual(int first, int last) { return ((Integer)get(first)).intValue() >= ((Integer)get(last)).intValue(); } }; for (int i = 0; i < 100; i++) { h.push(new Integer((int)(100 * Math.random()))); } System.out.println(h+"\n"); while (h.size() > 0) { System.out.println(h.pop()); } } } ```
PriorityQueue has the `heapify` method which re-sorts the entire heap, the `fixUp` method, which promotes an element of higher priority up the heap, and the `fixDown` method, which pushes an element of lower priority down the heap. Unfortunately, all of these methods are private, so you can't use them. I'd consider using the Observer pattern so that a contained element can tell the Queue that its priority has changed, and the Queue can then do something like `fixUp` or `fixDown` depending on if the priority increased or decreased respectively.
PriorityQueue/Heap Update
[ "", "java", "heap", "priority-queue", "" ]
What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that.
There's actually a very good mail on the python mailing list about this: [Iterators vs Lists](http://markmail.org/message/t2a6tp33n5lddzvy). It's a bit dated (from 2003), but as far as I know, it's still valid. Here's the summary: > For small datasets, iterator and list based approaches have similar > performance. > For larger datasets, iterators save both time and space. What I would draw from it is this: iterators are to be preferred over loading data into a list if possible. But unless you have a big dataset, don't contort your code to make something that should fit in a list to work with an iterator.
Iterators will be faster and have better memory efficiency. Just think of an example of `range(1000)` vs `xrange(1000)`. (This has been changed in 3.0, `range` is now an iterator.) With `range` you pre-build your list, but `xrange` is an iterator and yields the next item when needed instead. The performance difference isn't great on small things, but as soon as you start cranking them out getting larger and larger sets of information you'll notice it quite quickly. Also, not just having to generate and then step through, you will be consuming extra memory for your pre-built item whereas with the iterator, only 1 item at a time gets made.
Performance Advantages to Iterators?
[ "", "python", "performance", "iterator", "" ]
Hey, I've been writing a program (a sort of e-Book viewing type thing) and it loads text files from a folder within the folder of which the executable is located. This gives me a bit of a problem since if I run the program from another directory with the command "./folder/folder/program" for example, my program will not find the text, because the working directory isn't correct. I cannot have an absolute directory because I would like the program to be portable. Is there any way to get the precise directory that the executable is running from even if it has been run from a different directory. I've heard could combine argc[0] and getcwd() but argc is truncated when there is a space in the directory, (I think?) so I would like to avoid that if possible. I'm on Linux using g++, Thanx in advance
EDIT - don't use getcwd(), it's just where the user is not where the executable is. See [here for details](http://www.linuxquestions.org/questions/programming-9/how-do-i-get-the-application-path-in-c-426517/?highlight=executable+path). On linux /proc/<pid>/exe or /proc/self/exe should be a symbolic link to your executable. Like others, I think the more important question is "why do you need this?" It's not really UNIX form to use the executable path to find ancillary files. Instead you use an environment variable or a default location, or follow one of the other conventions for finding the location of ancillary files (ie, ~/.<myapp>rc).
When you add a book to your library you can remember its absolute path. It is not a bad when your program rely on the fact that it will be launched from the working dir and not from some other dir. That's why there are all kinds of "links" with "working dir" parameter. You don't have to handle such situations in the way you want. Just check if all necessary files and dirs structure are in place and log an error with the instructions if they are not. Or every time when your program starts and doesn't find necessary files the program can ask to point the path to the Books Library. I still don't see the reason to know your current dir name. ``` #include <boost/filesystem/convenience.hpp> #include <iostream> #include <ostream> int main(int argc, char** argv) { boost::filesystem::path argvPath( argv[0] ); boost::filesystem::path executablePath( argvPath.parent_path() ); boost::filesystem::path runPath( boost::filesystem::initial_path() ); std::cout << executablePath << std::endl; std::cout << runPath << std::endl; return 0; } ```
Directory of running program on Linux?
[ "", "c++", "linux", "unix", "" ]
Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http webserver or framework to emulate the 3rd party interface.
Use [cherrypy](http://cherrypy.org), take a look at Hello World: ``` import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True cherrypy.quickstart(HelloWorld()) ``` Run this code and you have a very fast Hello World server ready on `localhost` port `8080`!! Pretty easy huh?
You might be happiest with a WSGI service, since it's most like CGI. Look at [werkzeug](http://werkzeug.pocoo.org/).
Simple webserver or web testing framework
[ "", "python", "web-services", "testing", "web-applications", "" ]
How do I use [WinDbg](http://en.wikipedia.org/wiki/WinDbg) for analyzing a dump file?
Here are some general steps that will get you on your way: First, you must change your compiler's settings so that it creates PDB files, even for release builds. Later versions of the [Visual C++](http://en.wikipedia.org/wiki/Visual_C++) compiler do this by default, but in many versions of Visual C++ you must do this yourself. Create program database files, and then keep an archive of those files along with each build of your application. It is critical that every build of your applications has its own set of PDBs. You can't just reuse the same ones you made with build 10 to examining the dumps generated by build 15, for example. Over the life of your project, you will end up with a ton of PDBs, so be prepared for that. Next, you need to be able to identify the exact version of your application which generated the dump file. If you are creating your own MiniDumps (by calling [MiniDumpWriteDump()](http://msdn.microsoft.com/en-us/library/ms680360.aspx) for example), probably the easiest way to do this is to simply make part of the filename of the MiniDump the complete version number of your application. You'll need to have a reasonable version numbering scheme in place for this to work. In my shop, we increment the build number across all branches by one every time the autobuilder creates a build. Now that you have received the dump file from the customer, you know the precise version of the application that created the dump, and you have found the PDB files for this build. Now you need to go through your source control's history and find the source code for this exact version of the software. The best way to do this is to apply 'labels' to your branches every time you make a build. Set the value of the label to the exact version number, and it becomes easy to find in the history. You're almost ready to fire up WinDbg/Visual C++: 1. Get the complete source tree for that version of your application. Put it in a separate place on your hard drive, say `c:\app_build_1.0.100` for application version 1.0 build #100. 2. Get the binaries for that exact version of your application and put them somewhere on your hard drive. It might be easiest simply to install that version of your application to get the binaries. 3. Put the PDB files in the same location as the binaries in step 2. Now you have two options for viewing the dump file. You can use [Visual Studio](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio) or WinDbg. Using Visual Studio is easier, but WinDbg is much more powerful. Most of the time the functionality in Visual Studio will suffice. To use Visual Studio, all you have to do is open the dump file like it is a project. Once opened, "run" the dump file (`F5` by default) and if all the paths are set correctly it will take you right to the code that crashed, give you a call stack, etc. To use WinDbg, you have to jump through a couple of hoops: 1. Start WinDbg 2. Open the dump file. (`Ctrl` + `D` by default) 3. Tell WinDbg to go get the correct MicroSoft symbol files. Type `.symfix`. This may take a few moments as it will pull a ton of stuff down from the Internet. 4. Tell WinDbg where the symbols (PDB files) are. Type `.sympath+ c:\pdblocation`, substituting wherever you put the PDB files for the pathname. Make sure you get the plus sign in there with no whitespace between `.sympath` and the `+` sign or else you'll screw up step 3. 5. Tell WinDbg where the source code is. Type `.srcpath c:\app_build_1.0.100` substituting the path where you got code from source control for this version of the software. 6. Tell WinDbg to analyze the dump file. Type `!analyze -v` After a few moments, if everything is configured correctly, WinDbg will take you right to the location of your crash. At this point you have a million options for digging deep into your application's memory space, the state of critical sections, windows, etc. But that is *way* beyond the scope of this post. Good luck!
(see the "Dump" sections below) ## Basic Tutorials and Demonstrations of Using WinDbg * [Installing and Configuring WinDbg (Windows Debug Tools)](http://www.sysads.co.uk/2012/05/installing-and-configuring-windbg-windows-debug-tools%E2%80%8F/) * [Mike Taulty - A word for WinDBG](http://mtaulty.com/communityserver/blogs/mike_taultys_blog/archive/2004/08/03/4656.aspx) * [WinDbg Tutorials](http://blogs.msdn.com/b/iliast/archive/2006/12/10/windbg-tutorials.aspx) * [Windows Debuggers: Part 1: A WinDbg Tutorial](http://www.codeproject.com/Articles/6084/Windows-Debuggers-Part-1-A-WinDbg-Tutorial) ## Different Ways to "Start"/Attach WinDBG * [Start Debugging with Windbg (includes how to debug an .msi)](http://blogs.msdn.com/b/emreknlk/archive/2011/03/27/start-debugging-with-windbg.aspx) * [How to debug a Windows service](http://bugslasher.net/2010/10/14/how-to-debug-a-windows-service/) * [Setting up Windows Debugging](http://blogs.msdn.com/b/jankrivanek/archive/2012/10/26/setting-up-windows-debugging.aspx) ## Workspaces Understanding how Workspaces work... * [Pimp up your debugger: Creating a custom workspace for windbg debugging](http://blogs.msdn.com/b/tess/archive/2008/04/18/pimp-up-your-debugger-creating-a-custom-workspace-for-windbg-debugging.aspx?Redirected=true) * [Uncovering How Workspaces Work in WinDbg](http://blogs.msdn.com/b/ntdebugging/archive/2010/05/07/uncovering-how-workspaces-work-in-windbg.aspx) ## Cmdtree A "cmdtree" allows you to define a "menu" of debugger commands for easy access to frequently used commands without having to remember the terse command names. You don't have to put all the command definitions into the same cmdtree text file....you can keep them separate and load multiple ones if you wish (they then get their own window). * [Amazing helper .cmdtree](http://voneinem-windbg.blogspot.co.uk/2008/09/amazing-helper-cmdtree.html) * [How do I make a cmdtree window dock at startup in WinDBG](https://stackoverflow.com/questions/2655168/how-do-i-make-a-cmdtree-window-dock-at-startup-in-windbg) * [Making it easier to debug .net dumps in windbg using .cmdtree](http://blogs.msdn.com/b/tess/archive/2008/09/18/making-it-easier-to-debug-net-dumps-in-windbg-using-cmdtree.aspx) * [Microshaoft Cmdtree](http://www.cnblogs.com/Microshaoft/p/3183173.html) * [Special Command—Execute Commands from a Customized User Interface with .cmdtree](http://blogs.msdn.com/b/debuggingtoolbox/archive/2008/09/17/special-command-execute-commands-from-a-customized-user-interface-with-cmdtree.aspx) ## Startup Script You can use the -c option on the command line to automatically run a WinDBG script when you start WinDBG. Gives opportunity to turn on DML (Debugger markup language) mode, load particular extensions, set .NET exception breakpoints, set kernel flags (e.g. when kernel debugging you might need to change the DbgPrint mask so you see tracing information....ed nt!Kd\_DEFAULT\_Mask 0xffffffff), load cmdtrees, etc. * <http://yeilho.blogspot.co.uk/2012/10/windbg-init-script.html> * [Take Control of WinDBG](http://blogs.msdn.com/b/carloc/archive/2007/10/14/take-control-over-windbg.aspx) An example script: ``` $$ Include a directory to search for extensions $$ (point to a source controlled or UNC common directory so that all developers get access) .extpath+"c:\svn\DevTools\WinDBG\Extensions" $$ When debugging a driver written with the Windows Driver Framework/KMDF $$ load this extension that comes from the WinDDK. !load C:\WinDDK\7600.16385.1\bin\x86\wdfkd.dll !wdftmffile C:\WinDDK\7600.16385.1\tools\tracing\i386\wdf01009.tmf $$ load some extensions .load msec.dll .load byakugan.dll .load odbgext.dll .load sosex .load psscor4 $$ Make commands that support DML (Debugger Markup Language) use it .prefer_dml 1 .dml_start $$ Show NTSTATUS codes in hex by default .enable_long_status 1 $$ Set default extension .setdll psscor4 $$ Show all loaded extensions .chain /D $$ Load some command trees .cmdtree c:\svn\DevTools\WinDBG\cmdtree\cmdtree1.txt .cmdtree c:\svn\DevTools\WinDBG\cmdtree\cmdtree2.txt $$ Show some help for the extensions !wdfkd.help !psscor4.help .help /D ``` ## Command Cheat Sheets * [Crash Dump Analysis Poster v3.0](http://www.dumpanalysis.org/CDAPoster.html) * [SOS Cheat Sheet (.NET 2.0/3.0/3.5)](http://blogs.msdn.com/b/alejacma/archive/2009/06/30/sos-cheat-sheet-net-2-0-3-0-3-5.aspx) * [WinDbg cheat sheet (Art of Dev)](http://theartofdev.wordpress.com/windbg-cheat-sheet/) * [WinDbg Kernel-Mode Extension Commands Flashcards](http://quizlet.com/12326943/windbg-kernel-mode-extension-commands-flash-cards/) ## Extensions "Extensions" allow you to extend the range of commands/features supported inside WinDBG. * [bigLasagne (bldbgexts & blwdbgue)](http://dbgext.biglasagne.com/index.html) - assembly syntax highlighting and a driver mapping tool) * [BigLib Number Reader](http://rcejunk.blogspot.co.uk/2009/07/windbg-extension-to-read-biglib-numbers.html) * [Byakugan](https://community.rapid7.com/community/metasploit/blog/2008/08/20/byakugan-windbg-plugin-released) - detect antidebugging methods, vista heap visualization/emulation, track buffers in memory * [Call Flow Analyzer + KnExt](http://blog.naver.com/PostView.nhn?blogId=gloryo&logNo=110178730959) * [CmdHist](http://www.osronline.com/article.cfm?article=547) - records every command you executed in your debug session so you can re-execute easily * [Core Analyzer](http://core-analyzer.sourceforge.net/index_files/Page335.html) - check heap structures for corruption, detect objects shared by threads, etc * [dom WinDBG Extension](http://www.denismo.name/domdbg/WebPages/MainPage.htm) - (!stlpvector, !idt, !unhex, !grep, etc) * [dumppe](https://code.google.com/p/dumppe/) - dumps PE file from memory * [Image Viewer Extension (Vladimir Vukićević)](http://blog.vlad1.com/2010/07/18/windbg-image-viewer-extension/) * [Intel UEFI Development Kit Debugger Tool](http://www.intel.com/content/www/us/en/architecture-and-technology/unified-extensible-firmware-interface/intel-uefi-development-kit-debugger-tool.html) - debug UEFI firmware * [leaktrap](https://code.google.com/p/leaktrap/) - GDI/USER handle tracker to aid in leak detection * [Mona](http://redmine.corelan.be/projects/mona) (requires PyKD) - set of commands to aid in advanced analysis/find exploits * [MSEC](http://msecdbg.codeplex.com/) - provides automated crash analysis and security risk assessment * [narly](https://code.google.com/p/narly/) - lists info about loaded modules such as if using SafeSEH, ASLR, DEP, /GS (Buffer Security Checks) * [netext](http://www.infoq.com/news/2013/11/netext) (Rodney Viana) - (!wservice - list WCF service objects, !wconfig - show .config lines, !whttp - list HttpContexts, !wselect/!wfrom - support SQL like queries on arrays) * [ODbgExt](http://odbgext.codeplex.com/) - open debugger extensions * [OllyMigrate](http://low-priority.appspot.com/ollymigrate/) - pass debuggee to another debugger without restarting * [Psscor2](http://www.microsoft.com/en-gb/download/details.aspx?id=1073) - a superset of SOS for assisting in debugging .NET 2.0 managed code * [Psscor4](http://www.microsoft.com/en-us/download/details.aspx?id=21255) - a superset of SOS for assisting in debugging .NET 4 managed code * [PyDBGExt](http://sourceforge.net/projects/pydbgext/) - allows python scripting to be used * [PyKD](http://pykd.codeplex.com/) - allows Python to be used to script WinDBG * [sdbgext (Nynaeve)](http://www.nynaeve.net/?p=6) -(!valloc, !vallocrwx, !heapalloc, !heapfree, !remotecall, !remotecall64, !loaddll, !unloaddll, !close, !killthread, !adjpriv, !ret) * [SieExtPub](http://msdn.microsoft.com/en-us/library/windows/hardware/ff556890%28v=vs.85%29.aspx) -legacy extension...now built into WinDBG in ext.dll * [SOSEX](http://www.stevestechspot.com/SOSEXV40NowAvailable.aspx) - more commands for helping to debug managed NET 2.0 or 4.0 code * [SPT/SDBGExt2 (Steve Niemitz)](http://www.steveniemitz.com/Blog/post/SPT-A-WinDBG-extension-for-debugging-NET-applications.aspx) - (!DumpHttpContext, !DumpASPNetRequests, !DumpSqlConnectionPools, !DumpThreadPool, etc) * [Uniqstack](http://www.osronline.com/OsrDown.cfm/apexts.zip?name=apexts.zip&id=559) - source to a debugger extension (need an OSR Online account to access it) * [viscope](https://code.google.com/p/viscope/) - code coverage graph * [Wait Chain Traversal/wct.dll (Codeplex Debugging Extensions](http://debuggingextensions.codeplex.com/) - display wait chains of application threads (helps find [deadlocks](http://joeduffyblog.com/2006/07/06/new-to-vista-deadlock-detection/)) * [windbgshark](https://code.google.com/p/windbgshark/) - integrates Wireshark protocol analyser to enable VM traffic manipulation and analysis * [WinDBG Extensions (Sasha Goldstein)](https://github.com/goldshtn/windbg-extensions) - Tracer, WCT, heap\_stat, bkb, traverse\_map, traverse\_vector) * [WinDBG Highlight](http://hi.baidu.com/linx2008/item/0bee3aedc6d49e275b2d6441) (ColorWindbg.dll) [Use Google Translate to translate link] - asm syntax highlighting ## Write your own extension * [Tools of the Trade: Part IV - Developing WinDbg Extension DLLs](http://blogs.msdn.com/b/sqlblog/archive/2009/12/30/tools-of-the-trade-part-iv-developing-windbg-extension-dlls.aspx) * [The Basics of Debugger Extensions: Short Term Effort, Long Term Gain](http://www.osronline.com/custom.cfm?name=articlePrint.cfm&id=559) ## Using WinDBG to Debug Managed Code * [Breaking on an Exception](http://blogs.msdn.com/b/alejacma/archive/2009/08/24/managed-debugging-with-windbg-breaking-on-an-exception-part-1.aspx) * [Breaking on specific CLR Exception](http://blogs.msdn.com/b/rihamselim/archive/2012/11/15/windbg-breaking-on-specific-clr-exception.aspx) * [Debugging .Net framework source code within Windbg](http://naveensrinivasan.com/2010/03/10/debugging-net-framework-source-code-within-windbg/) * [Debugging exceptions in managed code using Windbg](http://blogs.msdn.com/b/kristoffer/archive/2007/01/03/debugging-exceptions-in-managed-code-using-windbg.aspx) * [Debugging managed code using WinDbg and SOS.dll](http://blogs.msdn.com/b/rextang/archive/2007/07/24/4026494.aspx) * [Debugging with WinDbg. Deadlocks in Applications.](http://blog.scriptico.com/04/debugging-with-windbg-deadlocks-in-applications/) * [MANAGED DEBUGGING with WINDBG. Introduction and Index](http://blogs.msdn.com/b/alejacma/archive/2009/07/07/managed-debugging-with-windbg-introduction-and-index.aspx) * [Setting .NET breakpoints in Windbg for applications that crash on startup](http://blogs.msdn.com/b/tess/archive/2008/06/05/setting-net-breakpoints-in-windbg-for-applications-that-crash-on-startup.aspx) ## Scripting (C#, PS, Python, WinDBG) * [KDAR (Kernel Debugger Anti Rootkit)](http://kdar.codeplex.com/) - a collection of WinDBG scripts * [Sysnative BSOD Scripts/Processing Apps](http://www.sysnative.com/forums/sysnative-news-and-announcements/2486-sysnative-blue-screen-of-death-scripts.html) * [WinDBG Script library](http://www.woodmann.com/collaborative/tools/index.php/WinDbg_Script) - a collection of WinDBG scripts * [Scripting MDbg and DbgHostLib](http://blog.diniscruz.com/2012/11/scripting-mdbg-and-dbghostlib.html) - allows managed code to script the Managed Debugger (MDBG) and the DbgEng * [ExtCS](http://extcs.codeplex.com/) - allows control of WinDBG via C# scripts * [PowerDBG](http://powerdbg.codeplex.com/) - allows control of WinDBG via Powershell scripts * [Pykd](http://pykd.codeplex.com/) - allows control of WinDBG via Python scripts * [windbglib](http://redmine.corelan.be/projects/windbglib) - python wrapper library around the pykd extension for WinDBG, mimicking immlib (so you can use scripts originally written for Immunity Debugger) ## Debuggers/Tools that use the dbgeng.dll API/WinDBG Tools * [A Simple Dbgeng Based User Mode Debugger](http://www.woodmann.com/forum/entry.php?246-A-Simple-Dbgeng-Based-User-Mode-Debugger) * [Acorns.Debugging NET Deadlock Detector](http://corneliutusnea.wordpress.com/2008/07/30/acornsdebugging-the-net-deadlock-detector/) (uses cdb.exe) ([download](http://web.archive.org/web/20090913063343/http://www.acorns.com.au/files/ACorns.Debugging.DeadlockTests.1.0.1.zip)) * [CLR Managed Debugger](http://www.microsoft.com/en-us/download/details.aspx?id=2282) (MDBG) * [DbgHost - How to control a debugging engine](http://codenasarre.wordpress.com/2011/06/14/how-to-control-a-debugger-engine/) * [Debug Diagnostic Tool v1.2](http://www.microsoft.com/en-us/download/details.aspx?id=26798) (DebugDiag), [Ver 2.0](http://www.microsoft.com/en-us/download/details.aspx?id=40336) + [DebugDiag Blog](http://blogs.msdn.com/b/debugdiag/) * [Dynamorio](http://dynamorio.org/) - dynamic binary instrumentation tool which can interact with WinDBG * [IDA](https://www.hex-rays.com/products/ida/index.shtml) + [WinDBG plugin](https://www.hex-rays.com/products/ida/support/idadoc/1520.shtml) * [GUI WinDBG](http://www.woodmann.com/collaborative/tools/index.php/GUI_WinDbg) * [LeakShell](http://codenasarre.wordpress.com/2011/05/18/leakshell-or-how-to-automatically-find-managed-leaks/) (find managed leaks) * [mdbglib - Managed Debug API](http://mdbglib.codeplex.com/) * [PyDbgEng](http://pydbgeng.sourceforge.net/) - python wrapper for Windows Debugging Engine * [SOSNET](https://bitbucket.org/grozeille/sosnet/wiki/Home) - a WinDBG Fork/alternative shell that concentrates on using the SOS extension and supports C# scripting * [SOSNET O2 fork](http://blog.diniscruz.com/2012/11/windbg-cdb-sun-of-strike-and-util-start.html) - fork of SOSNET that uses Rosyln for the C# REPL (read-eval-print-loop) scripting engine * [VDB/Vivisect](http://visi.kenshoto.com/viki/MainPage) (kenshoto) - provides a cross-platform debugging API layered on WinDBG * [WinAppDbg](http://winappdbg.sourceforge.net/) + [Heappie-WinAppDbg](http://breakingcode.wordpress.com/2012/03/18/heappie-winappdbg/) * [Writing a basic Windows debugger](http://www.codeproject.com/Articles/43682/Writing-a-basic-Windows-debugger) ## Different Ways to Generate Crash Dump Files for Post-Mortem Analysis * [DebugDiag 2.0](http://blogs.msdn.com/b/chaun/archive/2013/11/12/steps-to-catch-a-simple-crash-dump-of-a-crashing-process.aspx) * [Dump Cheat Sheet](http://nicholasconnolly.com/?p=293) - includes how to generate dump from Hyper-V, VMWare ESX, and XenServer VMs. * [Citrix SystemDump](http://support.citrix.com/article/CTX111072) * [Keyboard Keypress Combination](http://msdn.microsoft.com/en-us/library/windows/hardware/ff545499%28v=vs.85%29.aspx) * [MiniDumpWriteDump](http://msdn.microsoft.com/en-us/library/windows/desktop/ms680360%28v=vs.85%29.aspx) - (via WIN32 API call inside your application). [(Example for C# applications)](http://brakertech.com/howto-c-generate-dump-file-on-crash/) * [NMI Switch](http://support.microsoft.com/kb/927069), or [(here)](http://support.microsoft.com/kb/927069/en-us) (hardware based feature to generate an NMI...usually found on high-end servers e.g. [HP](http://h20195.www2.hp.com/V2/GetPDF.aspx/4AA4-7853ENW.pdf) or you can obtain an add-in PCI card ["Universal PCI Dump Switch"](http://www.dpie.com/manuals/pcbus/connecttech/manual_DumpSwitch-v.001.pdf)). Microsoft NMI technology [background](http://archive.is/ENCii). * [Procdump](http://technet.microsoft.com/en-gb/sysinternals/dd996900.aspx) * [System|Advanced System Settings|Startup and Recovery](http://www.sevenforums.com/tutorials/204214-dump-file-change-default-location.html) ([registry info](http://support.microsoft.com/kb/307973)), ([how to configure a Complete (Full) Memory Dump](http://www.symantec.com/business/support/index?page=content&id=HOWTO31321)), ([how to enable Complete Memory Dump](http://www.sophos.com/en-us/support/knowledgebase/111474.aspx)), ([how to enable Complete Memory Dump on Windows 7 when PC has lots of memory...normally not available when more than 2GB of memory](http://www.osronline.com/article.cfm?article=545)) * [Task Manager "Create Dump File"](http://blogs.msdn.com/b/debugger/archive/2009/12/30/what-is-a-dump-and-how-do-i-create-one.aspx) * [UserDump](http://support.microsoft.com/kb/253066), [instructions](http://support.microsoft.com/kb/241215) (very old tool) * [UserModeProcessDumper](http://www.microsoft.com/en-gb/download/details.aspx?id=4060), [instructions](http://www.symantec.com/business/support/index?page=content&id=TECH87208) * [Visual Studio "Save Dump As…"](http://blogs.msdn.com/b/debugger/archive/2009/12/30/what-is-a-dump-and-how-do-i-create-one.aspx) * [WER (Windows Error Reporting....local dumps)](http://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx) * [WinDBG](https://github.com/Windower/Issues/wiki/Creating-crash-dumps-with-Windbg) ## Dump Analysis Tools * [BlueScreenView](http://www.nirsoft.net/utils/blue_screen_view.html) - finds the minidump .dmp files saved by Windows after a BSOD, and extracts information about what caused the crash * [Debug.Analyzer](http://www.debuganalyzer.net/) (can analyse dump files and plug-ins can be written in .NET) * [SAD - Simple After Dump](http://codenasarre.wordpress.com/2011/06/26/s-a-d-or-simple-after-dump/) (postmortem analyzer) * [Volatility](https://code.google.com/p/volatility/) - framework for analyzing "memory" recorded in dump files ([cheat sheet](https://volatility.googlecode.com/files/CheatSheet_v2.3.pdf)) ## Dump related Tools * Citrix dumpcheck - checks consistency of dump file (looks like it's been abandoned [link](http://www.freelists.org/post/thin/KB-CTX108890-Citrix-DumpCheck-Utility-Command-Line) + [link](http://support.citrix.com/article/CTX138159)) * [dumpchk](http://support.microsoft.com/kb/156280) (part of Debugging Tools) - checks consistency of a Dump file * [MoonSols Windows Memory Toolkit](http://web.archive.org/web/20100119182120/http://windd.msuiche.net/) (formerly [windd](http://web.archive.org/web/20100119182120/http://windd.msuiche.net/)) - converts various raw memory dump files into WinDBG compatible dmp files * [vm2dmp](http://archive.msdn.microsoft.com/vm2dmp) - Microsoft Hyper-V VM State to Memory Dump Converter * [vmss2core](http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2003941) - converts VMWare snapshot file into a core dump file ([download](https://labs.vmware.com/flings/vmss2core)), ([instructions](http://www.vmware.com/pdf/snapshot2core_technote.pdf)) ## Kernel Debugging Virtual Machines * [VMKD](http://www.nynaeve.net/?page_id=168) - Virtual Machine KD Extensions * [VirtualKD](http://virtualkd.sysprogs.org/) - (kernel debugger support for OS's hosted in VMWare/VirtualBox) ## Videos * [.NET Cracking 101 #2 - WinDbg basics](http://www.youtube.com/watch?v=q-IWHHFQcXg) * [.NET Debugging for the Production Environment (Channel9)](http://channel9.msdn.com/Series/-NET-Debugging-Stater-Kit-for-the-Production-Environment) * [dotnetConf - Advanced Debugging with WinDbg and SOS](http://www.youtube.com/watch?v=yVzNrz1jJHU) * [David Truxall "Debugging with WinDBG"](http://blog.davidtruxall.com/2009/09/28/debugging-with-windbg/) * [Mike Taulty Debugging Memory Leaks](http://www.microsoft.com/uk/msdn/screencasts/screencast/102/Scenarios-Debugging-Memory-Leaks.aspx) * [oredev 2009 Session: Debugging .NET Applications with WinDbg](http://oredev.org/videos/debugging--net-apps-with-windbg) * [Pluralsight Advanced Windows Debugging](http://www.pluralsight.com/training/Courses/TableOfContents/adv-win-debug-part-1) * [Tess Ferrandez WinDBG (Channel9)](http://channel9.msdn.com/blogs/msdnsweden/vanliga-fel-som-grs-med-aspnet-och-hur-du-hittar-dem-med-windbg) ## Blogs Some blogs (mixture of native and managed code debugging). * [Advanced .NET Debugging](http://dotnetdebug.net/) * [All Your Base Are Belong To Us](http://blogs.microsoft.co.il/blogs/sasha/) (Sasha Goldshtein) * [Analyze-v](http://analyze-v.com/) * [ASP.NET Debugging](http://blogs.msdn.com/b/tom/) * [Cyberiafreak](http://maheshkumar.wordpress.com/) (threading and advanced windows prog and debugging) * [Debug Analyzer.NET](http://www.debuganalyzer.net/blog.aspx) * [Debug and Beyond](http://debugbeyond.blogspot.co.uk/) * [Debugging Experts Magazine Online](http://www.debuggingexperts.com/) * [Debugging Toolbox](http://blogs.msdn.com/b/debuggingtoolbox/) (Windbg scripts, debugging and troubleshooting tools and techniques to help you isolate software problems.) * [Decrypt my World](http://blogs.msdn.com/b/alejacma/) * [greggm's WebLog](http://blogs.msdn.com/b/greggm/) * [Junfeng Zhang's Windows Programming Notes](http://blogs.msdn.com/b/junfeng/) * [Kristoffer's tidbits](http://blogs.msdn.com/b/kristoffer/) * [Mark Russinovich's Blog](http://blogs.msdn.com/b/jmstall/) * [Mike Stalls .NET Debugging Blog](http://blogs.msdn.com/b/jmstall/) * [Naveen's Blog](http://naveensrinivasan.com/category/windbg/) * [Never Doubt Thy Debugger (Carlo)](http://blogs.msdn.com/b/carloc/) * [Notes from a Dark Corner](http://blogs.msdn.com/b/dougste/archive/tags/debugging/) * [Ntdebugging Blog](http://blogs.msdn.com/b/ntdebugging/) (Microsoft Global Escalation Services team) * [Nynaeve. Adventures in Windows debugging and reverse engineering](http://www.nynaeve.net/) * [PFE Developer Notes for the Field](http://blogs.msdn.com/b/pfedev/) * [Visual Studio Debugger Team](http://blogs.msdn.com/b/debugger/) * [WinDbg by Volker von Einem](http://voneinem-windbg.blogspot.co.uk/) ## Advanced Articles and Tutorial Resources * [Advanced Debugging Techniques in WinDbg](http://sourceforge.net/projects/windbguncovered/) * [Debugging Applications for MS.Net and Windows (Powerpoint Slides)](http://www.lcs.syr.edu/faculty/fawcett/handouts/testingseminar/) * [Debugging STL Containers with WinDbg](http://blogs.msdn.com/b/ambrosew/archive/2013/01/14/debugging-stl-containers-with-windbg-prolog.aspx) * [Debug Tutorials 1-7 (CodeProject-Toby Opferman)](http://www.codeproject.com/Articles/6469/Debug-Tutorial-Part-1-Beginning-Debugging-Using-CD) * [Debugging.tv](http://www.debugging.tv/) * [Developmentor WinDBG Tagged articles](http://browse.develop.com/cnsign/windbg/) * [Dr Fu's Security Blog - Malware Analysis Tutorials - Reverse Engineering Approach](http://fumalwareanalysis.blogspot.co.uk/p/malware-analysis-tutorials-reverse.html) * [Exploit writing tutorial part 5 : How debugger modules & plugins can speed up basic exploit development](http://www.corelan.be:8800/index.php/2009/09/05/exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-basic-exploit-development/) * [Hunting Rootkits](http://www.slideshare.net/frankboldewin/hunting-rootkits-with-windbg) * [Remote Microsoft Windows Server OS Kernel Debugging Using Dell Windows Debugger Utility (DWDU)](http://freedownloadb.net/pdf/remote-microsoftr-windows-server-os-kernel-debugging-using-29667909.html) ([DELL(TM) Windows(R) Debugger Utility 1.1 README](ftp://ftp.dell.com/FOLDER00634762M/1/readme_DWindbg_A00.txt)) ## Alternative Debuggers * [Bokken](http://inguma.eu/projects/bokken/files) - ([Inguma](http://ingumadev.blogspot.com.es/2012/01/bokken-16-is-more-stable-and-easier-to.html)) (GUI for radare) * [BugDbg](http://pespin.w.interia.pl/) * [Debug++](http://www.turboirc.com/debugpp/) (not released yet) * [Debuggy](http://web.vip.hr/inga.vip/) * [Discoloured Ring 0 Debugger](http://ai222.narod.ru/discoloured.html) ([download](http://ai222.narod.ru/discoloured/108.zip)) * [edb](http://codef00.com/projects#debugger) (Linux) * [FDBG](http://fdbg.x86asm.net/) * [GoBug](http://www.goprog.com/) * [Hades (Ring 3 debugger with anti debugger detection strategy)](https://github.com/jnraber/Hades) * [Hopper](http://www.hopperapp.com/) (Linux, OSX and Windows) (Windows debugging not currently implemented) * [Hyperdbg](https://code.google.com/p/hyperdbg/) * [IDA Debugger](https://www.hex-rays.com/products/ida/debugger/) * [ImmunityDebugger](http://www.immunitysec.com/products-immdbg.shtml) * [Nanomite](https://github.com/zer0fl4g/Nanomite) * [Obsidian (non-intrusive debugger)](http://www.deneke.biz/deneke/obsidian/) * [OllyDBG](http://www.ollydbg.de/) * [PEBrowse](http://www.smidgeonsoft.prohosting.com/pebrowse-pro-interactive-debugger.html) * [RaceVB6](http://www.racevb6.com/) (VB6 P-Code debugger) * [radare](http://radare.nopcode.org/) * [radare2ui](http://locklabs.com/?Products) (GUI for radare) * [Rasta Ring 0 Debugger](http://web.archive.org/web/20120702124850/http://rr0d.droids-corp.org/) (RR0D) * [Syser Kernel Debugger](http://www.sysersoft.com/) * [TRW 2000](http://www.softpedia.com/get/Programming/Debuggers-Decompilers-Dissasemblers/TRW.shtml) (very old debugger circa W9x) + [dions plugin archive](http://www.freewebz.com/daner/trw.htm) * [VisualDux Debugger](http://www.duxcore.com/index.php/prod/visual-duxdebugger/overview) * [Wintruder](http://www.woodmann.com/collaborative/tools/images/Bin_Wintruder_2008-10-24_22.21_wintruder.zip) (extendable debugger) * [WKTVDebugger](http://web.archive.org/web/20120205204128/http://members.fortunecity.com/blackfenix/wktvbdebug) (a debugger for Visual Basic P-Code) ([download](http://www.woodmann.com/collaborative/tools/images/Bin_Whiskey_Kon_Tequilla_VB_P-Code_Debugger_2007-12-28_8.57_WKTDBG13e.zip)) * [x64\_dbg](https://bitbucket.org/mrexodia/x64_dbg) * [Zeta Debugger](http://zeta-debugger.software.informer.com/) ## Other Links * [Collaborative RCE Tool Library](http://www.woodmann.com/collaborative/tools/index.php/Category:Debuggers) - huge collection of debugger and system level tools * [cr4zyserb](http://deroko.phearless.org/index.html) - huge collection of plugins and other debugging tools * [How to Write a Windows Debugger References (Devon Straw)](http://devonstrawntech.tumblr.com/post/15878429193/how-to-write-a-windows-debugger-references) - large collection of links giving you detailed information that you would need if you wanted to write your own debugger e.g. PDB file format, .DMP file formats, PE File structure, how to record stack traces, etc, etc. * [Tuts4You](http://tuts4you.com/) - unpackers, IDA, OllyDBG, Immunity Debugger plugins, etc.
How to use WinDbg to analyze the crash dump for VC++ application?
[ "", "c++", "visual-c++", "windbg", "crash-dumps", "" ]
Left and right shift operators (<< and >>) are already available in C++. However, I couldn't find out how I could perform circular shift or rotate operations. How can operations like "Rotate Left" and "Rotate Right" be performed? Rotating right twice here ``` Initial --> 1000 0011 0100 0010 ``` should result in: ``` Final --> 1010 0000 1101 0000 ``` An example would be helpful. (editor's note: Many common ways of expressing rotates in C suffer from undefined behaviour if the rotate count is zero, or compile to more than just a single rotate machine instruction. This question's answer should document best practices.)
See also an earlier version of [this answer on another rotate question](https://stackoverflow.com/a/31488147/224132) with some more details about what asm gcc/clang produce for x86. The most compiler-friendly way to express a rotate in C and C++ that avoids any Undefined Behaviour seems to be [John Regehr's implementation](http://blog.regehr.org/archives/1063). I've adapted it to rotate by the width of the type (using fixed-width types like `uint32_t`). ``` #include <stdint.h> // for uint32_t #include <limits.h> // for CHAR_BIT // #define NDEBUG #include <assert.h> static inline uint32_t rotl32 (uint32_t n, unsigned int c) { const unsigned int mask = (CHAR_BIT*sizeof(n) - 1); // assumes width is a power of 2. // assert ( (c<=mask) &&"rotate by type width or more"); c &= mask; return (n<<c) | (n>>( (-c)&mask )); } static inline uint32_t rotr32 (uint32_t n, unsigned int c) { const unsigned int mask = (CHAR_BIT*sizeof(n) - 1); // assert ( (c<=mask) &&"rotate by type width or more"); c &= mask; return (n>>c) | (n<<( (-c)&mask )); } ``` Works for any unsigned integer type, not just `uint32_t`, so you could make versions for other sizes. **See [also a C++11 template version](https://gist.github.com/pabigot/7550454) with lots of safety checks (including a `static_assert` that the type width is a power of 2)**, which isn't the case on some 24-bit DSPs or 36-bit mainframes, for example. I'd recommend only using the template as a back-end for wrappers with names that include the rotate width explicitly. **Integer-promotion rules mean that `rotl_template(u16 & 0x11UL, 7)` would do a 32 or 64-bit rotate, not 16** (depending on the width of `unsigned long`). Even `uint16_t & uint16_t` is promoted to `signed int` by C++'s integer-promotion rules, except on platforms where `int` is no wider than `uint16_t`. --- **On x86**, this version [inlines to a single `rol r32, cl`](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGe1wAyeAyYAHI%2BAEaYxCAArFykAA6oCoRODB7evnrJqY4CQSHhLFEx8baY9vkMQgRMxASZPn4JdpgO6bX1BIVhkdFxrXUNTdlD3b3FpYMAlLaoXsTI7BzmAMzByN5YANQma24KBPiCAHQI%2B9gmGgCC61g0ITuhACLYFnIA4td3ZhsMWy8u32biYCiUDXOlx%2B60220wewOtDwLEICihayutx%2BAHo8fiCTtUIlHCwxDsCABPRII/jEHbEVB1AiYAC0aC8gh29VAuIAVDsvMECGszAB9Ag7BjcxI0%2BoKIkklFiU47HZ4U6YVUMcwANn2LzJCgA1vsLDs0CxEnRMAqiDsAF7RVDqhgKN0/HYCuk7FgkBGiJQK1BUBlMgDueHQBAQEopCEMO0jMe5DEpRJj0Qp1NpJClqr5OJhtzxguFuskceloi8QZ2wGQyApLqYDi8Ylo6cwqMliZur1d7tIOwiXklW0MwB26FQtoYYA4BFOuJxZcEFarSYQNrDBEj0djkrwCtFEQtTFrtvVjdT6AtBiMzalTMFSh2ACUAPIBYs3HECoVBAADk3MRwyYSkFRrOtE0wVQCGIJgdn7F4dioRkWHrRth2ITBgHqdB6HBIlQ0ZPcoxjUhPQFQw72gq8J0fe0GBfS9uQ/b9B2lQtfwJPidmURkInoFgFWTBBpzwKgqGiRhJTI/cYwlfl70nW9rybGd50XetGGiJgWXYr8Ai4rdGF3RSJOPHYgKJekuF1Kjbi9Bk8IIojg1DbS7RzVUsM02d0WonZVCA3UdgUbcqAIHEyIMhFgiOYgvA6AQxMICTbNonYHJHQhFX0hh0FZVInWCo46FoIkGE7X0wWNeMAwWLlxJ2DRVC4AAxHYIDWLg5mfSUuFiOydgAdmXZyeOxW4qRpB41xFcV5IjCjDzNX8FLWuMyKqiAtoPONVGHTlUmAEI72FKUZhhMarGci00slLAtjmzAIAYGY6pNRFUIgNwAAkbnfMULAASQAFT5UrMBDCBVC%2B1kcputZ7puNVS20WtJTY068HOzBLq5H1M0ezlJSNBrOQ8nZKQWBdcJ2OCaWIFE5OCKdWsta16HpKIEwANycRZfzVMEIUlD6QQNSm9jMfV5blsw4sMiJ0z9RmY0TN6kzW8wzBRtG1WlPUDW%2B01UYx1cmAF1Ao0FIrMFDfmbeF%2BlWted4vkm9HXIIRZpXh6WDk%2BvYxrcHrVGhTEIB61lPr1WWZkN26Xl/WFQw0H4DqUlaEJ6nPDxCk63Xxi7XUlBPsTuz1HrdZ72loN6Pq%2B2Wzf%2BoGQfBqGYbhhGdiR/qNoe8XoklnUDhl%2Bq5YV8L9ZVhE1d9f1421nNdYPfWU4ek35bNynh993D/eIQOo8xS5Q5McPI%2BDtxY4geObvlpPt7uMa0%2BxP5XCkzbVsOvOYo0D132v/XOIUvrXyNn7AOu5aDw2HGNN%2B19P53C/hsUMYAwAPGCITCAYogEPmAAQyBe9FYQBwRdfBYpQq6jFBuMUkDw7XwjpQvBBC8BrDCiQsObgWHTidrg9A%2BCACyQg3BigAGrYHfMnFcOwDAsnpIxKcM4ryCwRGKXarp1QEAVLQ4UrMGBQhmr8DBC0xRiIkdI98MI/hwiBAiEEhjggYixGYyoSg7H/EBMCA4BjBBGLcVbZ4L4sZHERG4FEqJAmuIuJiNCeZuY2mIMGTM9ItbSjwI2bxP8qB/3IgAuBNDuEuNLsgUBhTwHHQdmdcuV8a4PTxMfWBBDRx0EcAwMUeAmCii0SQbcCDxqGxCQ5VkER8oL2HJ8UIcgdh8Iei00%2BOx%2BkEHgTUhOlsdilgbMgYc2S9m%2BgUALZAfkwaCEqKyNh6A/JuCIdOQK2lJQaPjMefYnVa7NMwCfaUBDGS0GERskZ2zVy7P2Y2H2ITRBPLQsEO8hhKQxg5ok5RRD3mp1yUVX%2BpjSwAHU8DGjwPNHpC4FRSQgDMdkCB2gNSYOgJgJJCYou5MQCZCF6jpgXhvGM8j8WEuJUhS8d4TC6g0HjAmRNJQCzEF4TAIqNDDmykhGgqgmWWRIjsUUw5wzbmQBJcCwYIhCwWAoWqLFJTJAaEwYScrbjivLldSM/LCY9NWfAwucZpXeEwPsrkkUpIECYdAtUwCImOrWr9eZndQaQ2hngJ0cMvWyrfmqENT0K7m0jeqweh9U3qlDFAf10UZ773qpAtYacK1tRug9PNSzpRJrlajWuap609UbZEkEEUoqBt4e2mVTiL4JIgNm7tAa5HNurqg/kPx7VMvDc6/ATBVnEEqZZT1A7fWSiLb2qBLa65hpahGs2gNgYxp7vG2GVAICNpTam0NR4uRtyraOrgubU1SR6hAHdJaq2U3LZW1CGga2%2Bzrd82Bjb32tvA8sm9A7ERXASTuphEc4Pes7QcHqo7kPII/j8QsHA5i0E4LEXgfgOBaFIKgTgfDLDWAigsJYTi/g8FIAQTQhG5jGhAGsXUpwACcY0HL8YrGNITFY1jSGIxwSQZGONUc4LwBQIAFXsYo4R0gcBYBIGSbzcglBdMDGALqNYfAOnRGUxACI8mJnMGIJSTgrHLRsEEJ%2BGqDn1OkCwGSIw4hPP4Fwh0AWtp5NwXaGOFYrHhSVHk8iCIiF7MeCwPJhCKJHMaaoAYYAChJF4EwOGT8NJyOsf4IIEQYh2BSBkIIRQKh1Ced0AkIhKBrDWH0HgCIynIBzGJNUZTHBWSfjWAPI46ADSmDo5YLgXAB64o7Epyo7RqguCKqMFopBAi4KmAMBIuQ0gCDWzkFI%2B2GCTH6DEVoi3Uo1GGI0TwzQ9BtGu10BoZ2Sg7dsLdw74xXtbfOxIOYChGPLD0AhTAkWNPSdI6QcjlHqMcFoayCs/kdh8eG/9Vrlhhy4EIHmdYCR5moCtCkuWfUZi8DU1oZOpBuNrA0KcNYdP5aSC4fx%2BWsRYhjX0JwWTMP5Pw6UyptjHG5haagDARAKAic82iPpiAhmYgqMkBoBVNAm4WcoNZzztmOXpdIM5uSbnOzye85OPzlGAtLbwMF/rlGwvIAi3r6L0nKNxYS5SJLKxKOpZYOluYmWmDZdy/lwrjA9eleEKIcQVWI%2B1bUPJ3QZh9CTha5NmwcWusUqo0qNKnBBvDZKsccbmOLDTdm/NioVR0grfcPdsYG2ipvemLt471RvtJFb%2BkJvH2nvVBe3drI63e%2BdFu93i7n3ujt6OBMP772LuA%2BB5VtjuEIdEZI3Jzz8PEfI5UTsSQpx6caB6rRqwWOdg46IPSfHw4PDE95qTg2FORdzGpXSgYWfadmFOLqfjQENBrH4y4EZ05w0Gm25xk14F911C4FODMCAMkAQN/0Ew0CAiAL5030U1sCF0pw0zFwgB02lxSTlwVxQFoC4H43oWkDVyUUsy10ox13sz1wN1c3cxN27DNy914EtyCxC083t0d24F4Gd1iw63d09xS1Zl90EP9yyxyzywKyK3D1kHK2jyoNkDj3q0o10FM2awm1P3Tw60zx6xzzdDz0/FUAWyr2cAgFcHb02yKH%2BxbzyHSHbz22qDH0eyuz7y%2BzryHy8JHxnwcLn0ex8MHxCMCL6GCP6nmEWBBwSDB1X3AOh1h14C32R1EhOR2AFnINOC4CPwgFxTBlCGwC%2BgxzT2x3wEv1JwJ1vxlyvz%2BDWHJ2F3U2p1fywBiCz2k1519y4VODGjCg51iFAI0DMEAKAi5xSIUw4EF1U2fxpx4y/x/z/wAKALWBALAOkzWA3zh0wJwOp2kzMG2NSN2LmOC1SWr0kCAA) (or `rol r32, imm8`) with compilers that grok it, because the compiler knows that [x86 rotate and shift instructions](http://felixcloutier.com/x86/RCL:RCR:ROL:ROR.html) mask the shift-count the same way the C source does. Compiler support for this UB-avoiding idiom on x86, for `uint32_t x` and `unsigned int n` for variable-count shifts: * clang: recognized for variable-count rotates since clang3.5, multiple shifts+or insns before that. * gcc: [recognized for variable-count rotates since gcc4.9](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157), multiple shifts+or insns before that. gcc5 and later optimize away the branch and mask in the wikipedia version, too, using just a `ror` or `rol` instruction for variable counts. * icc: [supported for variable-count rotates since ICC13 or earlier](https://software.intel.com/en-us/forums/intel-c-compilers-in-inde/topic/580884). Constant-count rotates use `shld edi,edi,7` which is slower and takes more bytes than `rol edi,7` on some CPUs (especially AMD, but also some Intel), when BMI2 isn't available for `rorx eax,edi,25` to save a MOV. * MSVC: x86-64 CL19: Only recognized for constant-count rotates. (The wikipedia idiom is recognized, but the branch and AND aren't optimized away). Use the `_rotl` / `_rotr` intrinsics from `<intrin.h>` on x86 (including x86-64). **gcc for ARM uses an `and r1, r1, #31` for variable-count rotates, but still does the actual rotate with a single instruction**: `ror r0, r0, r1`. So gcc doesn't realize that rotate-counts are inherently modular. As the ARM docs say, ["ROR with shift length, `n`, more than 32 is the same as ROR with shift length `n-32`"](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0552a/BABFFEJF.html). I think gcc gets confused here because left/right shifts on ARM saturate the count, so a shift by 32 or more will clear the register. (Unlike x86, where shifts mask the count the same as rotates). It probably decides it needs an AND instruction before recognizing the rotate idiom, because of how non-circular shifts work on that target. Current x86 compilers still use an extra instruction to mask a variable count for 8 and 16-bit rotates, probably for the same reason they don't avoid the AND on ARM. This is a missed optimization, because performance doesn't depend on the rotate count on any x86-64 CPU. (Masking of counts was introduced with 286 for performance reasons because it handled shifts iteratively, not with constant-latency like modern CPUs.) BTW, prefer rotate-right for variable-count rotates, to avoid making the compiler do `32-n` to implement a left rotate on architectures like ARM and MIPS that only provide a rotate-right. (This optimizes away with compile-time-constant counts.) Fun fact: ARM doesn't really have dedicated shift/rotate instructions, it's just MOV with the [source operand going through the barrel-shifter in ROR mode](https://cseweb.ucsd.edu/classes/wi14/cse30-c/lectures/PI_WI_14_CSE30_lecture_8_post.pdf): `mov r0, r0, ror r1`. So a rotate can fold into a register-source operand for an EOR instruction or something. --- **Make sure you use unsigned types for `n` and the return value, or else it won't be a rotate**. (gcc for x86 targets does arithmetic right shifts, shifting in copies of the sign-bit rather than zeroes, leading to a problem when you `OR` the two shifted values together. Right-shifts of negative signed integers is implementation-defined behaviour in C.) Also, **make sure the shift count is an unsigned type**, because `(-n)&31` with a signed type could be one's complement or sign/magnitude, and not the same as the modular 2^n you get with unsigned or two's complement. (See comments on Regehr's blog post). `unsigned int` does well on every compiler I've looked at, for every width of `x`. Some other types actually defeat the idiom-recognition for some compilers, so don't just use the same type as `x`. --- **Some compilers provide intrinsics for rotates**, which is far better than inline-asm if the portable version doesn't generate good code on the compiler you're targeting. There aren't cross-platform intrinsics for any compilers that I know of. These are some of the x86 options: * Intel documents that [`<immintrin.h>` provides `_rotl` and `_rotl64` intrinsics](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#techs=SSE,SSE2,SSE3,SSSE3,SSE4_1,SSE4_2,AVX,AVX2,FMA,Other&text=rotl), and same for right shift. MSVC requires `<intrin.h>`, while gcc require `<x86intrin.h>`. An `#ifdef` takes care of gcc vs. icc. Clang 9.0 also has it, but before that it doesn't seem to provide them anywhere, [except in MSVC compatibility mode with `-fms-extensions -fms-compatibility -fms-compatibility-version=17.00`](http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20160905/170179.html). And the asm it emits for them sucks (extra masking and a CMOV). * MSVC: [`_rotr8` and `_rotr16`](https://msdn.microsoft.com/en-us/library/yy0728bz(v=vs.140).aspx). * gcc and icc (not clang): `<x86intrin.h>` also provides `__rolb`/`__rorb` for 8-bit rotate left/right, `__rolw`/`__rorw` (16-bit), `__rold`/`__rord` (32-bit), `__rolq`/`__rorq` (64-bit, only defined for 64-bit targets). For narrow rotates, the implementation uses `__builtin_ia32_rolhi` or `...qi`, but the 32 and 64-bit rotates are defined using shift/or (with no protection against UB, because the code in [`ia32intrin.h`](https://github.com/gcc-mirror/gcc/blob/master/gcc/config/i386/ia32intrin.h#L146) only has to work on gcc for x86). GNU C appears not to have any cross-platform `__builtin_rotate` functions the way it does for `__builtin_popcount` (which expands to whatever's optimal on the target platform, even if it's not a single instruction). Most of the time you get good code from idiom-recognition. * Clang has `__builtin_rotateleft8`, `__builtin_rotateright8`, and similar for other widths. See [Clang's language extensions](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-rotateleft) documentation. There are also builtins / intrinsics for other bit-manipulation things like `__builtin_bitreverse32` (which can compile to `rbit` on ARM / AArch64). You can test for them with `__has_builtin`. ``` // For real use, probably use a rotate intrinsic for MSVC, or this idiom for other compilers. This pattern of #ifdefs may be helpful #if defined(__x86_64__) || defined(__i386__) #ifdef _MSC_VER #include <intrin.h> #else #include <x86intrin.h> // Not just <immintrin.h> for compilers other than icc #endif uint32_t rotl32_x86_intrinsic(rotwidth_t x, unsigned n) { //return __builtin_ia32_rorhi(x, 7); // 16-bit rotate, GNU C return _rotl(x, n); // gcc, icc, msvc. Intel-defined. //return __rold(x, n); // gcc, icc. // can't find anything for clang } #endif ``` Presumably some non-x86 compilers have intrinsics, too, but let's not expand this community-wiki answer to include them all. (Maybe do that in [the existing answer about intrinsics](https://stackoverflow.com/a/776573/224132)). --- (The old version of this answer suggested MSVC-specific inline asm (which only works for 32bit x86 code), or <http://www.devx.com/tips/Tip/14043> for a C version. The comments are replying to that.) **Inline asm defeats many optimizations**, [especially MSVC-style because it forces inputs to be stored/reloaded](https://stackoverflow.com/questions/3323445/what-is-the-difference-between-asm-and-asm/35959859#35959859). A carefully-written GNU C inline-asm rotate would allow the count to be an immediate operand for compile-time-constant shift counts, but it still couldn't optimize away entirely if the value to be shifted is also a compile-time constant after inlining. **<https://gcc.gnu.org/wiki/DontUseInlineAsm>**.
**C++20 `std::rotl` and `std::rotr`** It has arrived! <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0553r4.html> and should add it to the `<bit>` header. [cppreference says](https://en.cppreference.com/w/cpp/numeric/rotl) that the usage will be like: ``` #include <bit> #include <bitset> #include <cstdint> #include <iostream> int main() { std::uint8_t i = 0b00011101; std::cout << "i = " << std::bitset<8>(i) << '\n'; std::cout << "rotl(i,0) = " << std::bitset<8>(std::rotl(i,0)) << '\n'; std::cout << "rotl(i,1) = " << std::bitset<8>(std::rotl(i,1)) << '\n'; std::cout << "rotl(i,4) = " << std::bitset<8>(std::rotl(i,4)) << '\n'; std::cout << "rotl(i,9) = " << std::bitset<8>(std::rotl(i,9)) << '\n'; std::cout << "rotl(i,-1) = " << std::bitset<8>(std::rotl(i,-1)) << '\n'; } ``` giving output: ``` i = 00011101 rotl(i,0) = 00011101 rotl(i,1) = 00111010 rotl(i,4) = 11010001 rotl(i,9) = 00111010 rotl(i,-1) = 10001110 ``` I'll give it a try when support arrives to GCC, GCC 9.1.0 with `g++-9 -std=c++2a` still doesn't support it. The proposal says: > Header: > > ``` > namespace std { > // 25.5.5, rotating > template<class T> > [[nodiscard]] constexpr T rotl(T x, int s) noexcept; > template<class T> > [[nodiscard]] constexpr T rotr(T x, int s) noexcept; > ``` and: > 25.5.5 Rotating [bitops.rot] > > In the following descriptions, let N denote `std::numeric_limits<T>::digits`. > > ``` > template<class T> > [[nodiscard]] constexpr T rotl(T x, int s) noexcept; > ``` > > Constraints: T is an unsigned integer type (3.9.1 [basic.fundamental]). > > Let r be s % N. > > Returns: If r is 0, x; if r is positive, `(x << r) | (x >> (N - r))`; if r is negative, `rotr(x, -r)`. > > ``` > template<class T> > [[nodiscard]] constexpr T rotr(T x, int s) noexcept; > ``` > > Constraints: T is an unsigned integer type (3.9.1 [basic.fundamental]). > Let r be s % N. > > Returns: If r is 0, x; if r is positive, `(x >> r) | (x << (N - r))`; if r is negative, `rotl(x, -r)`. A `std::popcount` was also added to count the number of 1 bits: [How to count the number of set bits in a 32-bit integer?](https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/57285674#57285674)
Best practices for circular shift (rotate) operations in C++
[ "", "c++", "c", "rotation", "bit-manipulation", "c++-faq", "" ]
Put simply a Soundex Algorithm changes a series of characters into a code. Characters that produce the same Soundex code are said to sound the same. * The code is 4 characters wide * The first character of the code is always the first character of the word Each character in the alphabet belongs in a particular group (at least in this example, and code thereafter this is the rule I'll be sticking with): * b, p, v, f = 1 * c, g, j, k, q, s, x, z = 2 * d, t = 3 * l = 4 * m, n = 5 * r = 6 * Every other letter in the alphabet belongs to group 0. Other notable rules include: * All letters that belong to group 0 are ignored UNLESS you have run out of letters in the provided word, in which case the rest of the code is filled with 0's. * The same number cannot be used twice or more consecutively, thus the character is ignored. The only exception is the rule above with multiple 0's. For example, the word "Ray" will produce the following Soundex code: R000 (R is the first character of the provided word, a is apart of group 0 so it's ignored, y is apart of group 0 so it's ignored, there are no more characters so the 3 remaining characters in the code are 0). I've created a function that has passed to it 1) a 128 character array which is used in create the Soundex code and 2) an empty 5 character array which will be used to store the Soundex code at the completion of the function (and pass back by reference as most arrays do for use in my program). My problem is however, with the conversion process. The logic I've provided above isn't exactly working in my code. And I do not know why. ``` // CREATE A SOUNDEX CODE // * Parameter list includes the string of characters that are to be converted to code and a variable to save the code respectively. void SoundsAlike(const char input[], char scode[]) { scode[0] = toupper(input[0]); // First character of the string is added to the code int matchCount = 1; int codeCount = 1; while((matchCount < strlen(input)) && (codeCount < 4)) { if(((input[matchCount] == 'b') || (input[matchCount] == 'p') || (input[matchCount] == 'v') || (input[matchCount] == 'f')) && (scode[codeCount-1] != 1)) { scode[codeCount] = 1; codeCount++; } else if(((input[matchCount] == 'c') || (input[matchCount] == 'g') || (input[matchCount] == 'j') || (input[matchCount] == 'k') || (input[matchCount] == 'q') || (input[matchCount] == 's') || (input[matchCount] == 'x') || (input[matchCount] == 'z')) && (scode[codeCount-1] != 2)) { scode[codeCount] = 2; codeCount++; } else if(((input[matchCount] == 'd') || (input[matchCount] == 't')) && (scode[codeCount-1] != 3)) { scode[codeCount] = 3; codeCount++; } else if((input[matchCount] == 'l') && (scode[codeCount-1] != 4)) { scode[codeCount] = 4; codeCount++; } else if(((input[matchCount] == 'm') || (input[matchCount] == 'n')) && (scode[codeCount-1] != 5)) { scode[codeCount] = 5; codeCount++; } else if((input[matchCount] == 'r') && (scode[codeCount-1] != 6)) { scode[codeCount] = 6; codeCount++; } matchCount++; } while(codeCount < 4) { scode[codeCount] = 0; codeCount++; } scode[4] = '\0'; cout << scode << endl; } ``` I'm not sure if it's because of my overuse of strlen, but for some reason while the program is running within the first while loop none of the characters are actually converted to code (i.e. none of the if statements are actually run). So what am I doing wrong? Any help would be greatly appreciated.
Instead of ``` scode[codeCount] = 1; ``` you should write ``` scode[codeCount] = '1'; ``` as you are forming a char array, the former is actually the first ascii character while the latter is the character '1'.
C++ does not support dynamic arrays, which you seem to be attempting to use. You need to investigate the use of the std::string class. I essence your loop becomes something like this: ``` void Soundex( const string & input, string & output ) { for ( int i = 0; i < input.length(); i++ ) { char c = input[i]; // get character from input if ( c === .... ) { // if some decision output += 'X'; // add some character to output } else if ( ..... ) { // more tests } } } ```
Soundex Algorithm implementation using C++
[ "", "c++", "soundex", "algorithm", "" ]
ok, so I new to the C# way of doing things, I come from the ruby world. I have a one to many relationship, (parent to children for sake of this question), and for some reason L2S was wanting to create a new parent instead of using the one is already had. Here is the code. ``` Console.WriteLine(parent.Id); // this equals 1 foreach (string names in names) { Child new_child= new Child(); new_child.Parent = parent;//now parent.Id would equal the next in the sequence. new_child.Name= name db.CommitLogs.InsertOnSubmit(new_child); db.SubmitChanges(); } ``` but if I just say ``` new_child.ParentId = parent.Id ``` that works just fine. Can someone explain to me whats going on? PS. Parent was found from the database using L2S. all the keys and such are set up properly. Thanks for any insight.
you could possiblly do it as Freddy said: ``` foreach (string names in names) { Child new_child= new Child(); new_child.Name= name parent.Children.Add(child); db.SubmitChanges(); } ``` But maybe just make the 1 DB call outside the foreach loop: ``` foreach (string names in names) { Child new_child= new Child(); new_child.Name= name parent.Children.Add(child); } db.SubmitChanges(); ```
Both of these should work: //option 1: ``` foreach (string names in names) { Child new_child= new Child(); new_child.ParentId = parent.Id;//now parent.Id would equal the next in the sequence. new_child.Name= name db.CommitLogs.InsertOnSubmit(new_child); db.SubmitChanges(); } ``` //option 2: ``` foreach (string names in names) { Child new_child= new Child(); new_child.Name= name parent.Children.Add(child); db.SubmitChanges(); } ```
Linq to Sql Parent Child
[ "", "c#", "linq-to-sql", "" ]
What are the best practices to create a site, with ability to develop plugins for it? Like you want to create a blog module, and you want users or co-developers to add plugins to extend this module functionality. **Update:** Thanks for the ultra speed answers, but I think this is over kill for me. Isn't there a simpler solution, like I have seen blogengine plugin creation system is you just have to decorate the class plugin with [Extension]. I am kind of mid core developer, so I was thinking of base class, inheritance, interfaces, what do you think ?
**Edit** I completely rewrote my answer based on your question edit. Let me show you just how easy it is to implement a plugin architecture with just the minimal steps. **Step 1: Define an interface that your plugins will implement.** ``` namespace PluginInterface { public interface IPlugin { string Name { get; } string Run(string input); } } ``` **Step 2: Create a plugin that implements IPlugin.** ``` namespace PluginX { using PluginInterface; public class Plugin : IPlugin { public string Name { get { return "Plugin X"; } } public string Run(string input) { return input; } } } ``` **Step 3: Run the plugin.** ``` namespace PluginTest { using System; using System.IO; using System.Runtime.Remoting; using PluginInterface; class Program { static void Main( string[] args ) { string pluginFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PluginX.dll"); ObjectHandle handle = Activator.CreateInstanceFrom(pluginFile, "PluginX.Plugin"); IPlugin plugin = handle.Unwrap() as IPlugin; string pluginName = plugin.Name; string pluginResult = plugin.Run("test string"); } } } ``` Keep in mind, this is just the basic, most straightforward example of a plugin architechure. You can also do things such as * create a plugin host to run your plugin inside of it's own `AppDomain` * choose either interfaces, abstract classes, or attributes to decorate your plugins with * use reflection, interfaces, IL-emitted thunks or delegates to get the late binding job done if your design so dictates.
It's valuable to separate technical and architecturas perspectives: * In code level [MEF](http://www.codeplex.com/MEF) (Managed Extensibility Framework) is a good start. [Here](http://www.pnpguidance.net/post/ManagedExtensibilityFrameworkTutorialMEF.aspx) is a simple example. * Any other DI (Dependency Injection framework) can work well to (ie. Unity) And it's good to see this problem in architectural level: * [Web Client Software Factory](http://websf.codeplex.com/) from p&p. Here are not only technical but arcihtectural informations about "How to create composite web applications?". See [examples.](http://www.pnpguidance.net/Category/WebClientSoftwareFactory.aspx). There is *Modularity Boundle* package. * [Spring Framework](http://www.springframework.net/). I think it's a fast and efficient if you read&try some of those frameworks. And ofcoz read the source if you find something interessing. **Edit** if you are searching for an extensible blog engine then try **[Blog Engine](http://www.asp.net/Downloads/starter-kits/blog-engine/)** first. It's from ASP.NET community.
how to create pluggable ASP.Net website?
[ "", "c#", "asp.net", "" ]
Is there any easy (5 lines of code) way to do this?
The shortest code to delete the tab the middle mouse button was clicked on is by using LINQ. Make sure the event is wired up ``` this.tabControl1.MouseClick += tabControl1_MouseClick; ``` And for the handler itself ``` private void tabControl1_MouseClick(object sender, MouseEventArgs e) { var tabControl = sender as TabControl; var tabs = tabControl.TabPages; if (e.Button == MouseButtons.Middle) { tabs.Remove(tabs.Cast<TabPage>() .Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location)) .First()); } } ``` And if you are striving for least amount of lines, here it is in one line ``` tabControl1.MouseClick += delegate(object sender, MouseEventArgs e) { var tabControl = sender as TabControl; var tabs = tabControl.TabPages; if (e.Button == MouseButtons.Middle) { tabs.Remove(tabs.Cast<TabPage>().Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location)).First()); } }; ```
Solution without LINQ not so compact and beautiful, but also actual: ``` private void TabControlMainMouseDown(object sender, MouseEventArgs e) { var tabControl = sender as TabControl; TabPage tabPageCurrent = null; if (e.Button == MouseButtons.Middle) { for (var i = 0; i < tabControl.TabCount; i++) { if (!tabControl.GetTabRect(i).Contains(e.Location)) continue; tabPageCurrent = tabControl.TabPages[i]; break; } if (tabPageCurrent != null) tabControl.TabPages.Remove(tabPageCurrent); } } ```
Close tab on winforms tab control with middle mouse button
[ "", "c#", "winforms", "" ]
How many threads can a Java VM support? Does this vary by vendor? by operating system? other factors?
This depends on the CPU you're using, on the OS, on what other processes are doing, on what Java release you're using, and other factors. I've seen a Windows server have > 6500 Threads before bringing the machine down. Most of the threads were not doing anything, of course. Once the machine hit around 6500 Threads (in Java), the whole machine started to have problems and become unstable. My experience shows that Java (recent versions) can happily consume as many Threads as the computer itself can host without problems. Of course, you have to have enough RAM and you have to have started Java with enough memory to do everything that the Threads are doing and to have a stack for each Thread. Any machine with a modern CPU (most recent couple generations of AMD or Intel) and with 1 - 2 Gig of memory (depending on OS) can easily support a JVM with *thousands* of Threads. If you need a more specific answer than this, your best bet is to profile.
Um, lots. There are several parameters here. The specific VM, plus there are usually run-time parameters on the VM as well. That's somewhat driven by the operating system: what support does the underlying OS have for threads and what limitations does it put on them? If the VM actually uses OS-level threads at all, the good old red thread/green thread thing. What "support" means is another question. If you write a Java program that is just something like ``` class DieLikeADog { public static void main(String[] argv){ for(;;){ new Thread(new SomeRunaable).start(); } } } ``` (and don't complain about little syntax details, I'm on my first cup of coffee) then you should certainly expect to get hundreds or thousands of threads running. But *creating* a Thread is relatively expensive, and scheduler overhead can get intense; it's unclear that you could have those threads do anything useful. ### Update Okay, couldn't resist. Here's my little test program, with a couple embellishments: ``` public class DieLikeADog { private static Object s = new Object(); private static int count = 0; public static void main(String[] argv){ for(;;){ new Thread(new Runnable(){ public void run(){ synchronized(s){ count += 1; System.err.println("New thread #"+count); } for(;;){ try { Thread.sleep(1000); } catch (Exception e){ System.err.println(e); } } } }).start(); } } } ``` On OS/X 10.5.6 on Intel, and Java ~~6~~ 5 (see comments), here's what I got ``` New thread #2547 New thread #2548 New thread #2549 Can't create thread: 5 New thread #2550 Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) at java.lang.Thread.start(Thread.java:592) at DieLikeADog.main(DieLikeADog.java:6) ```
How many threads can a Java VM support?
[ "", "java", "multithreading", "" ]
I've thought of this before and it came to mind again when reading [this](https://stackoverflow.com/questions/652512/do-you-think-generic-properties-would-be-useful-in-net) question. Are there any plans for "extension properties" in a future version of C#? It seems to me they might be pretty stright-forward to implement with a little more "compiler magic". For example, using *get\_* and *set\_* prefixes on extension method names would turn that method into an extension property: ``` public class Foo { public string Text { get; set; } } public static class FooExtensions { public static string get_Name(this Foo foo) { return foo.Text; } public static void set_Name(this Foo foo, string value) { foo.Text = value; } } ``` Are there any technical restrictions which would prevent this? Would this create too much stuff going on behind the scenes? Not important enough to be worth the effort?
The official site for feature requests is <http://connect.microsoft.com/VisualStudio>. There has already been a request for extension properties [here](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=344478). Microsoft's answer on 7/29/2008 included the following: > Extension properties are a common > request, and we actually got quite far > with a design for the next version of > the language, but ultimately had to > scrap it because of various > difficulties. It is still on our > radar.
Generally I think this would encourage poor practice. Properties are supposed to represent some kind of state about the object in question, whereas methods should represent units of work. But many developers tend to put computationally intensive or relatively long-running code in the getters and setters where they would be much more appropriate as methods. Extending an object is *not* the same as deriving from it. If you need to add properties, from a philosophical perspective you're talking about needing to add stateful information to the object. That should be done by deriving from the class.
Are there any plans for "extension properties" in a future version of C#?
[ "", "c#", "properties", "extension-methods", "" ]
How do you read and display data from .txt files?
``` BufferedReader in = new BufferedReader(new FileReader("<Filename>")); ``` Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such: ``` String line; while((line = in.readLine()) != null) { System.out.println(line); } in.close(); ```
If your file is strictly text, I prefer to use the [`java.util.Scanner`](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html) class. You can create a [`Scanner`](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html) out of a file by: ``` Scanner fileIn = new Scanner(new File(thePathToYourFile)); ``` Then, you can read text from the file using the methods: ``` fileIn.nextLine(); // Reads one line from the file fileIn.next(); // Reads one word from the file ``` And, you can check if there is any more text left with: ``` fileIn.hasNext(); // Returns true if there is another word in the file fileIn.hasNextLine(); // Returns true if there is another line to read from the file ``` Once you have read the text, and saved it into a `String`, you can print the string to the command line with: ``` System.out.print(aString); System.out.println(aString); ``` The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
Reading and displaying data from a .txt file
[ "", "java", "" ]
I have a page that dynamically adds script references via jQuery's `$.getScript` function. The scripts load and execute fine, so I know the references are correct. However, when I add a "debugger" statement to any of the scripts to allow me to step through the code in a debugger (such as VS.Net, Firebug, etc.), it doesn't work. It appears that something about the way jQuery loads the scripts is preventing debuggers from finding the files. Does anybody have a work-around for this?
Ok, so it turns out that the default implementation of the `$.getScript()` function works differently depending on whether the referenced script file is on the same domain or not. External references such as: ``` $.getScript("http://www.someothersite.com/script.js") ``` will cause jQuery to create an external script reference, which can be debugged with no problems. ``` <script type="text/javascript" src="http://www.someothersite.com/script.js"></script> ``` However, if you reference a local script file such as any of the following: ``` $.getScript("http://www.mysite.com/script.js") $.getScript("script.js") $.getScript("/Scripts/script.js"); ``` then jQuery will download the script content asynchronously and then add it as inline content: ``` <script type="text/javascript">{your script here}</script> ``` This latter approach does *not* work with any debugger that I tested (Visual Studio.net, Firebug, IE8 Debugger). The workaround is to override the `$.getScript()` function so that it always creates an external reference rather than inline content. Here is the script to do that. I have tested this in Firefox, Opera, Safari, and IE 8. ``` <script type="text/javascript"> // Replace the normal jQuery getScript function with one that supports // debugging and which references the script files as external resources // rather than inline. jQuery.extend({ getScript: function(url, callback) { var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.src = url; // Handle Script loading { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function(){ if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) { done = true; if (callback) callback(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; } }; } head.appendChild(script); // We handle everything using the script element injection return undefined; }, }); </script> ```
With JQuery 1.6(maybe 1.5) you could switch to not using getScript, but using jQuery.ajax(). Then set crossDomain:true and you'll get the same effect. The error callback will not work. So you might as well not set it up like below. However, I do setup a timer and clear it with the success. So say after 10 seconds if I don't hear anything I assume the file was bad. ``` jQuery.ajax({ crossDomain: true, dataType: "script", url: url, success: function(){ _success(_slot) }, error: function(){ _fail(_slot); } }) ```
Debugging scripts added via jQuery getScript function
[ "", "javascript", "jquery", "visual-studio", "debugging", "" ]
### Background In my current project - a server product with no GUI front-end, I'm trying to write in better error handling support. Errors currently are outputted to the logs and are typically not read by users. We use PostgreSQL as our database backend and we access it using direct JDBC calls and DAOs via a database pooler. Most database related exceptions are wrapped in a generic `DatabaseException` class that implements `RuntimeException` and attempts to pull out debugging and state information from the exception it was passed. In our particular case, it will access the underlying PostgreSQL database driver - `PSQLException`. So far this approach has worked well for getting more verbose information about what caused the database error, with the notable exception described below. Furthermore, since we have very specific performance and legacy support requirements we have a lot of custom SQL ***magic*** that makes the following the stack trace back a bit more time intensive but not impossible or difficult. ### Problem Described I have noticed that when we get a `SQLException` as a result of a faulty SQL statement, the driver's implementation does not return the SQL statement that caused the error. After doing a little searching, I found out that there is a way to drop the PostgreSQL driver into a debug mode on startup and have it display properties about its internal query. However, it is undesirable for us to run the driver in debug mode in our production environment (and honestly I haven't been able to figure out how to get it into the freakin mode!). ### Question Has anyone else dealt with this same issue before and found a solution? If not, is there some OOP pattern out there for storing query information before execution and then assigning that information to the exception thrown? Or do most developers just feel that they don't need the full query to troubleshoot database issues? Honestly, I don't *need* it because I have the full stack trace and I can look up the invoking query, but it definitely speeds up my debugging by having it be the first thing that I see in the error logs.
I am assuming that when you make the call to execute the query you have the statement, and you receive the Exception, so at that point you have both. It seems like you could do your analysis there. However, maybe you're catching things further up. So, what you might do is on your own custom subclass of Exception, DatabaseException, add a triggeringSQLStatement member with a getter and setter, and then at the place where you attempt to execute the statement, catch the original Exception from PostgreSQL, create a new DatabaseException, set the triggeringSQLStatement to be the statement you just executed, and call initCause() on the DatabaseException to set the Exception caught from PostgreSQL as the cause of your exception; then throw your DatabaseException and the calling code which catches it will have an object that prints out a very decent stack trace of what happened plus provides access to the SQL statement that caused the problem. For more information on this approach, you might want to research Java Exception chaining. Even if you don't use all of what I just described, I think you should definitely be using Java Exception chaining already. If there's not a spot anywhere in the code where you have access to both the SQL statement that caused the problem and the Exception that gets thrown, I'd be very curious as to why, and how that is possible. And I'd suggest you redesign your code so that you do have such a spot. **Edit:** Since you're wanting to see the SQL statement first thing in the log, you could probably also override your DatabaseException's toString() method (or other appropriate methods; I'm not sure what gets called when an Exception is printed out) to print out the included SQL statement, assuming you included it as I described above.
I used to add the SQL query in my custome Exception object when ever there is an SQLException. In the code where ever I am logging the exception details in log file, I used to log the SQL also.
How do I get at the sql statement that caused an SQLException using the Postgres JDBC driver in Java?
[ "", "java", "postgresql", "jdbc", "exception", "" ]
I have a WAMP installation on my machine and I am developing a PHP website in that. Can anyone tell me what settings to be changed in order to show all errors / warning messages in the browser? Thanks in advance
You need to set both [error\_reporting](http://au.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) and [display\_errors](http://au.php.net/manual/en/errorfunc.configuration.php#ini.display-errors). These can be set in php.ini, in Apache (if you're using PHP as an Apache module) or during run-time, though if you set it during run-time then it won't effect some types of errors, such as parse errors. For portability - that is, if you want to set this in the application - try setting them in an .htaccess: ``` # note: PHP constants such as E_ALL can't be used when setting it in Apache php_value error_reporting 2147483647 php_flag display_errors on ``` Alternatively you could set these in httpd.conf **display\_errors** makes sure that all reported errors are actually output to the browser (on a live server, it's typical to log them to a file instead). **error\_reporting** specifies which types errors should be logged/displayed. For a live server, it's generally a good idea to not to display errors publicly (but you may still want to log them). Either way, it's still a good idea to set error\_reporting to a more inclusive value (2147483647 being the most inclusive value possible now and for the future according to the PHP docs) because ignoring errors is generally a bad idea.
First click on the wamp icon in the task panel. Then click on the 'PHP' folder followed by the 'PHP settings' folder. Make sure 'expose PHP' and 'display errors' are both checked. You can set other error settings like 'track errors' and 'display startup errors' as well.
WAMP: How to show warning messages in browser?
[ "", "php", "wamp", "" ]
how do i get the php to reconize that there is a file being uploaded to it by the vb webclient current php code is this ``` if(count($_FILES)==1) { //move_uploaded_file ( $_FILES[0]["tmp_name"] , "./imgs/curdesktop.png" ); file_put_contents("./nin.txt",print_r($_FILES)); } ``` all it does right now is check the FILE array and supposed to print the attributes out into a text file. however the vb program says that the file is uploaded with no errors and the $\_FILES array returns 1 which is invalid for that array
Try using [var\_export()](http://www.php.net/var_export): ``` file_put_contents("./nin.txt",var_export($_FILES,true)); ``` Passing **true** as the second argument will return the variable representation instead of outputing it, so the contents should write to the file.
You have print\_r() as a function which returns a value. Check first wat print\_r really prints on the screen. (I think it does print it now already)
using the webclient to upload a file in post and the php to recive and handle file
[ "", "php", "file-upload", "" ]
I got this code in a user control: ``` [DefaultValue(typeof(Color), "Red")] public Color MyColor { get; set; } ``` How can I change `MyColor` to be its default value?
It is informal, but you can use it via reflection, for example, place in your constructor the following: ``` foreach (PropertyInfo p in this.GetType().GetProperties()) { foreach (Attribute attr in p.GetCustomAttributes(true)) { if (attr is DefaultValueAttribute) { DefaultValueAttribute dv = (DefaultValueAttribute)attr; p.SetValue(this, dv.Value); } } } ```
The `DefaultValueAttribute` does not set the property to the value, it is purely informational. The Visual Studio designer will display this value as non-bold and other values as bold (changed), but you'll still have to set the property to the value in the constructor. The designer will generate code for the property if the value was set by the user, but you can remove that code by right clicking on the property and clicking `Reset`.
.Net DefaultValueAttribute on Properties
[ "", "c#", ".net", "" ]
What changes to a strong-named assembly necessitate a change in AssemblyVersionAttribute? Clearly, changing the public api in a way that could require a client to have to make a code change requires an increase in AssemblyVersion. But what about changes to the public API that don't require code changes in the client? For instance: * the addition of a public class or interface? * the addition of a public member to a public class or interface? (EDIT: drscroogemcduck correctly points out below that adding a member to an interface would hose all implementors. Silly me.) * an increase of visibility of a class member? There's got to be definitive documentation of this somewhere on MSDN (or, knowing MS, on some MSSE's personal blog). But I simply cannot find it. Please help!
It's pretty easy... as long as Types remain unchanged (in their public or protected layout) and method signatures are not changed (adding methods or types is fine), the JIT should be able to link the DLL just fine. That said, I think that even if it *does* work you *should not* do this. Make a new version and use a policy to map the old version to the new one, if required. Otherwise you drive yourself straight back to DLL hell... and I'm pretty sure you don't want that.
In response to Martijn's bounty: The best reference on binary compatibility is on the community Wiki. [A definite guide to API-breaking changes in .NET](https://stackoverflow.com/questions/1456785/a-definite-guide-to-api-breaking-changes-in-net)
.NET: with respect to AssemblyVersion, what defines binary compatibility?
[ "", "c#", ".net", "clr", "gac", "" ]
Requirements: * Calculate the number of months between two dates: receiveDate and dueDate. * Both optimistic and pessimistic calculations are needed Assumptions: * dueDate will always be the last day of the month. I've already figured out the pessimistic calculation (meaning a single day overdue counts as a whole month: ``` if(receiveDate > dueDate) receiveDate.Month - dueDate.Month + (receiveDate.Year - dueDate.Year) * 12; ``` Doing a search on the internet turned up several similar examples to confirm this. Now my instincts tell me the optimistic calculation will just be the same minus one month but for some reason it just doesn't feel right. Am I on the right track or am I missing something?
You're right; if you're looking for the number of *complete* months between the two dates, subtracting 1 (assuming the `receiveDate` doesn't fall on the last day of the month, in which case you will have a remainder of 0 days either way) will get you your answer.
If you don't need to keep days of month in your calculus I think it's the way to go.
How to calculate the number of months between two DateTimes?
[ "", "c#", "datetime", "" ]
Hypothetical example: I have Cars and Owners. Each Car belongs to one (and only one) Owner at a given time, but ownership may be transferred. Owners may, at any time, own zero or more cars. What I want is to store the historical relationships in a MySQL database such that, given an arbitrary time, I can look up the current assignment of Cars to Owners. I.e. At time X (where X can be now or anytime in the past): * Who owns car Y? * Which cars (if any) does owner Z own? Creating an M:N table in SQL (with a timestamp) is simple enough, but I'd like to avoid a correlated sub-query as this table will get large (and, hence, performance will suffer). Any ideas? I have a feeling that there's a way to do this by JOINing such a table with itself, but I'm not terribly experienced with databases. UPDATE: I would like to avoid using both a "start\_date" and "end\_date" field per row as this would necessitate a (potentially) expensive look-up each time a new row is inserted. (Also, it's redundant).
Make a third table called CarOwners with a field for carid, ownerid and start\_date and end\_date. When a car is bought fill in the first three and check the table to make sure no one else is listed as the owner. If there is then update the record with that data as the end\_date. To find current owner: ``` select carid, ownerid from CarOwner where end_date is null ``` To find owner at a point in time: ``` select carid, ownerid from CarOwner where start_date < getdate() and end_date > getdate() ``` getdate() is MS SQL Server specific, but every database has some function that returns the current date - just substitute. Of course if you also want additional info from the other tables, you would join to them as well. ``` select co.carid, co.ownerid, o.owner_name, c.make, c.Model, c.year from CarOwner co JOIN Car c on co.carid = c.carid JOIN Owner o on o.ownerid = co.ownerid where co.end_date is null ```
I've found that the best way to handle this sort of requirement is to just maintain a log of VehicleEvents, one of which would be ChangeOwner. In practice, you can derive the answers to all the questions posed here - at least as accurately as you are collecting the events. Each record would have a timestamp indicating when the event occurred. One benefit of doing it this way is that the minimum amount of data can be added in each event, but the information about the Vehicle can accumulate and evolve. Also, with the timestamp, events can be added after the fact (as long as the timestamp accurately reflects when the event occurred. Trying to maintain historical state for something like this in any other way I've tried leads to madness. (Maybe I'm still recovering. :D) BTW, the distinguishing characteristic here is probably that it's a Time Series or Event Log, not that it's 1:m.
What's the best way to store (and access) historical 1:M relationships in a relational database?
[ "", "sql", "mysql", "database-design", "" ]
I'd like to override a class method without inheriting the base class because it'd take a lot of time and modifications and, therefore, more and more tests. It's like this: ``` class TestClass{ public void initialMethod(){ ... } } ``` And somewhere on the code, I'd like to do something like this: ``` public testMethod() { return; } test(){ changeMethod(TestClass.initialMethod, testMethod); } ``` And this changeMethod function would override the TestClass initialMethod so that it'd call testMethod instead. Inheriting and overriding the method using normal practices is not an option, as this class A is a graphic component and, inhereting it (and changing it) would break lots of code. Edit: We don't have the base code for the TestClass, so it's not an option to modify the code there defining the initialMethod as a delegate. Edit 2: Since this is a graphical component, the designer added a lot of code automatically. If I were to inherit this code, I would have to replace all code added by the designer. That's why I wouldn't like to replace this component.
You need the [Strategy](http://www.dofactory.com/Patterns/PatternStrategy.aspx) pattern. Main steps: * Create an interface with ie. *Do()* signature * Your *initialMethod()* should call a *strategy.Do()*, where strategy is type of your interface * Create a class that implements this interface. *Do()* is your testmethod now. * Inject into your main class an instance of this class If the job it's not so big (let's say just a color replacement or something) then I agree with Jhonny D. Cano's solution with C# *(anonymous)delegate*s. **Edit** (after edit 2) May - just as proof-of-concept - you should inherit the class and replace all references from base class to this new. Do this, and nothing else. If it works, you can think about the next steps (new methods or delegates etc.) You need only a new checkout from your version control system, and if it maybe fails you can abandon it. It's worth trying.
Perhaps you can do it as a delegate. ``` class TestClass { public Action myAction; public void initialMethod(){ ... } initialMethod public TestClass() { myAction = initialMethod; } } ``` and then on TestMethod ``` public testMethod() { return; } test() { testClassInstance.myAction = testMethod; } ```
Modify C# Class method during execution
[ "", "c#", "oop", "tdd", "" ]
A new feature I wish to add to our local network is the ability to retrieve email from free email services such as Gmail, Yahoo and Hotmail using PHP. There are services we can pay for but I would rather hack it up myself! I find that Google only has an API but the rest do not. **What are the problems associated then with me just retrieving email using CURL?** I have even implemented the GMail part using CURL and PHP.
It almost certainly violates their terms of service to screen-scrape their websites for that purpose. If they redesign your site, the scripts you're using to parse out the e-mail contents etc. will probably break catastrophically, as well. Yahoo, Gmail, and Hotmail all support [POP3](http://en.wikipedia.org/wiki/Post_Office_Protocol), a standard protocol for retrieving e-mails. Why not use that instead?
When someone gives you an API, they're promising you that "if you run code X, Y will happen. When you screen scrape, there's no such promise from the provider, and many providers have items in their terms of service that explicitly forbid screen scraping. From a technical standpoint, this means their page/application may undergo changes that will break your screen scraping, wither accidently or purposefully by the provider. This is why CAPTCHA's exist. Also, increasingly, these applications are using more and more "AJAX" style architectures, which means you're committing yourself to reverse engineering how their application works, as well as keeping up with the changes each application makes. Finally, well, you're doing it wrong. Email is a set of protocols in and of itself. Most providers have a way to access email via POP3 and IMAP. I'd look into hacking PHP code to interact with the POP/IMAP servers which, like an API, are a promised set of behaviors. You also have the advantage that code written for one provider will likely work (with minor tweaks) for another.
What are the problems associated with retrieving email using CURL?
[ "", "php", "architecture", "curl", "implementation", "" ]
I am trying to send an email via GMail's SMTP server from a PHP page, but I get this error: > authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)] Can anyone help? Here is my code: ``` <?php require_once "Mail.php"; $from = "Sandra Sender <sender@example.com>"; $to = "Ramona Recipient <ramona@microsoft.com>"; $subject = "Hi!"; $body = "Hi,\n\nHow are you?"; $host = "smtp.gmail.com"; $port = "587"; $username = "testtest@gmail.com"; $password = "testtest"; $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject); $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { echo("<p>" . $mail->getMessage() . "</p>"); } else { echo("<p>Message successfully sent!</p>"); } ?> ```
``` // Pear Mail Library require_once "Mail.php"; $from = '<fromaddress@gmail.com>'; $to = '<toaddress@yahoo.com>'; $subject = 'Hi!'; $body = "Hi,\n\nHow are you?"; $headers = array( 'From' => $from, 'To' => $to, 'Subject' => $subject ); $smtp = Mail::factory('smtp', array( 'host' => 'ssl://smtp.gmail.com', 'port' => '465', 'auth' => true, 'username' => 'johndoe@gmail.com', 'password' => 'passwordxxx' )); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { echo('<p>' . $mail->getMessage() . '</p>'); } else { echo('<p>Message successfully sent!</p>'); } ```
Using [**Swift mailer**](http://swiftmailer.org/), it is quite easy to send a mail through Gmail credentials: ``` <?php require_once 'swift/lib/swift_required.php'; $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl") ->setUsername('GMAIL_USERNAME') ->setPassword('GMAIL_PASSWORD'); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance('Test Subject') ->setFrom(array('abc@example.com' => 'ABC')) ->setTo(array('xyz@test.com')) ->setBody('This is a test mail.'); $result = $mailer->send($message); ?> ```
Send email using the GMail SMTP server from a PHP page
[ "", "php", "email", "smtp", "gmail", "" ]
Below is a Class I created to track the current Person in my glorified Data Entry and retrieval app. Once they select a person it calls the constrtuctor which then calls the database to fill in all the rest of the info. Also, throughout the program they will be able to change the various fields. With this in mind do I have the below set up correctly? I am inexpierenced with properties and using Objects to store data across multiple forms and would appreciate any insight. Thanks! ``` class CurrentPerson { public string FirstName { get; set; } public string LastName { get; set; } public string MiddleName { get; set; } public string SuffixID { get; set; } public string TitleID { get; set; } public string SocialSn { get; set; } public string BirthDate { get; set; } public string Gender { get; set; } public string DlNumber { get; set; } public string DlStateID { get; set; } public string PrimaryRace { get; set; } public string SecondaryRace { get; set; } public string EmailAddress { get; set; } public string MaritalStatus { get; set; } public string InsertProgram { get; set; } public string InsertUserID { get; set; } public string UpdateProgram { get; set; } public string UpdateUserID { get; set; } public string LockID { get; set; } public int PersonID { get; set; } public int ClientID { get; set; } public int ResidencyCountyID { get; set; } public int ResponsibilityCountyID { get; set; } public bool HispanicOriginFlag { get; set; } public bool CitizenFlag { get; set; } public bool VeteranFlag { get; set; } public DateTime DeathDate { get; set; } public DateTime InsertDateTime { get; set; } public DateTime UpdateDateTime { get; set; } // Put the default Constructor back in public CurrentPerson(){} // Custom Constructor that needs the PersonID public CurrentPerson(int pID) { PersonID = pID; // Methods to get rest of data here } } ```
yup, looks good. you can, btw, set access on the get/set as well, to make it read/write only publicly ``` public DateTime DeathDate { get; private set; } ```
This is technically fine. They are all declared perfectly well. However, often, with DB apps, you'll want to not use automatic properties, since property setters are often a great place to do some validation, as well as potentially marking properties/objects as "dirty" and requiring saving of some sort.
Correct use of Object Properties
[ "", "c#", ".net", "oop", "properties", "" ]
When creating and modifying document templates in Documentum 6.5 my TBO for that object type is being triggered. In 5.3 creating a template did not trigger the TBO. This is a problem because I have the TBO doing all sorts of things with documents when they are checked in and saved. But I want it to do nothing if the document is just a template going into my templates cabinet. Has anyone else come across this issue? What strategies are there to get around this problem?
I got around this be using a script to rename the TBO's before creating my templates. This disabled the TBO's, then once my templates were created I named them back.
I would think there would be some way to programatically detect if the object being acted on is a template, thus you could wrap your custom tbo logic in an if check for this, and if it is a template none of your logic would be performed. However... ...In general it's not considered good practice to have heavy amounts of logic in your tbo, as tbo's run regardless of context and you often run into situations such as this, which you want to avoid. It is better to put this type of logic in an sbo and call the sbo from the context where you want this logic to be invoked. ie by extending webtop.
In Documentum 6.5 my TBO's are being triggered even when the document is a template
[ "", "java", "documentum", "documentum6.5", "" ]
I am stepping though some code and looking at a PropertyInfo object and want to know how to get its base.Name [alt text http://www.yart.com.au/stackoverflow/propertyinfo.png](http://www.yart.com.au/stackoverflow/propertyinfo.png) I can see this in the debugger but I am not sure how to do this as there is no "base" property on a PropertyInfo
You can access this property via property.Name. The fact that the debugger shows base.Name is a bit of a misnomer. In reality the C# EE is evaluating property.Name under the hood. It does not actually evaluate "base.Name". This is true regardless of whether or not the property / method is virtual. The reason being that the CLR deubgger provides no means by which the EE can invoke a virtual method in a non-virtual method. There are ways to call a method via relfection to achieve this effect but neither C# or VB.Net go this route in their respective EE's.
Just use `.Name`; `PropertyInfo` doesn't define this - it inherits it from `MemberInfo`
c# How do you get the base.Name from PropertyInfo
[ "", "c#", "propertyinfo", "" ]
I am looking for a simple in-memory (and in-process) cache for short-term caching of query data (but short-term meaning beyond request/response, i.e. session boundary). EhCache would probably work, but it looks as if it might not offer one thing that I need: limits not on number of objects cached, but (approximate) limit on amount of memory consumed by cached data. I understand that it is hard to figure out exact memory usage for given object without serialization (which I want to avoid in general case due to its slowness defeats the purpose for my uses), and I am fine with having to provide size estimate myself. So: is there a simple open source java cache that allows for defining "weight" of cached objects, to limit amount of things cached? EDIT (Nov 2010): For what it's worth, there is a new project called [Java CacheMate](https://github.com/cowtowncoder/java-cachemate) that tries to tackle this issue, along with some other improvement ideas (multi-level in-memory in-process caching)
I agree with Paul that this is often solved by using a soft reference cache, though it may evict entries earlier than you prefer. A usually acceptable solution is to use a normal cache that evicts to the soft cache, and recovers entries on a miss if possible. This victim caching approach works pretty well, giving you a lower bar but extra benefit if free memory is available. The memory size can be determined by enabling the Java agent, and usage is pretty simple when using the SizeOf utility (<http://sourceforge.net/projects/sizeof>). I've only used this for debugging purposes, and I'd recommend benchmarking the overhead before adopting it for normal usage. In my caching library, I am planning on adding the ability to plug in a evaluator once the core algorithm is implemented. This way you could store a collection as the value, but bound the cache by the sum of all collection sizes. I have seen unbounded collections as values in caches cause OutOfMemoryExceptions, so having control is quite handy. If you really need this, and I'd advise not to, we could enhance my current implementation to support this. You can email me, ben.manes-at-gmail.com.
How about using a simple LinkedHashMap with LRU algorithm enabled and put all data with a SoftReference in it... such as cache.out(key, new SoftReference(value)) ?? This would limit your cache to the amount of available memory but not kill the rest of your programm, because Java removes the soft references when there is a memory demand... not all.. the oldest first... usually. If you add a reference queue to your implementation, you can also remove the stall entries (only key, no value) from the map. This would free you from calculating the size of the entries and keeping track of the sum.
Any Java caches that can limit memory usage of in-memory cache, not just instance count?
[ "", "java", "caching", "memory-management", "ehcache", "" ]
I have three input boxes for entering a telephone number on a webpage: ``` XXX XXX XXXX ``` I need JavaScript that moves the user between the boxes as you type. After the third character, it moves you to the second box, etc... In the past, I've had trouble with the backspace. When I clicked backspace from the second box, it puts me in the first, but then shoots me back to the second. What is the best way to do this?
You should use **jQuery** [AutoTab](http://www.lousyllama.com/sandbox/jquery-autotab) **Example** code like this ``` <div><strong>Phone Number:</strong></div> <input type="text" name="area_code" id="area_code" maxlength="3" size="3" /> - <input type="text" name="number1" id="number1" maxlength="3" size="3" /> - <input type="text" name="number2" id="number2" maxlength="4" size="5" /> <script type="text/javascript"> $(document).ready(function() { $('#area_code').autotab({ target: 'number1', format: 'numeric' }); $('#number1').autotab({ target: 'number2', format: 'numeric', previous: 'area_code' }); $('#number2').autotab({ previous: 'number1', format: 'numeric' }); }); </script> ```
Personally, I'd just accept almost *anything* and worry about re-formatting it server-side. I've had to use so many bad javascript phone formatters that I'm not a big fan.
What JavaScript should I use for a telephone number entry in a webpage?
[ "", "javascript", "html", "user-input", "" ]
In terms of performance, what would work faster? Is there a difference? Is it platform dependent? ``` //1. Using vector<string>::iterator: vector<string> vs = GetVector(); for(vector<string>::iterator it = vs.begin(); it != vs.end(); ++it) { *it = "Am I faster?"; } //2. Using size_t index: for(size_t i = 0; i < vs.size(); ++i) { //One option: vs.at(i) = "Am I faster?"; //Another option: vs[i] = "Am I faster?"; } ```
Why not write a test and find out? **Edit:** My bad - I thought I was timing the optimised version but wasn't. On my machine, compiled with g++ -O2, the iterator version is slightly **slower** than the operator[] version, but probably not significantly so. ``` #include <vector> #include <iostream> #include <ctime> using namespace std; int main() { const int BIG = 20000000; vector <int> v; for ( int i = 0; i < BIG; i++ ) { v.push_back( i ); } int now = time(0); cout << "start" << endl; int n = 0; for(vector<int>::iterator it = v.begin(); it != v.end(); ++it) { n += *it; } cout << time(0) - now << endl; now = time(0); for(size_t i = 0; i < v.size(); ++i) { n += v[i]; } cout << time(0) - now << endl; return n != 0; } ```
Using an iterator results in incrementing a pointer (for incrementing) and for dereferencing into dereferencing a pointer. With an index, incrementing should be equally fast, but looking up an element involves an addition (data pointer+index) and dereferencing that pointer, but the difference should be marginal. `at()` also checks if the index is within the bounds, so it could be slower. Benchmark results for 500M iterations, vector size 10, with gcc 4.3.3 (-O3), linux 2.6.29.1 x86\_64: `at()`: 9158ms `operator[]`: 4269ms `iterator`: 3914ms YMMV, but if using an index makes the code more readable/understandable, you should do it. # 2021 update With modern compilers, all options are practically free, but iterators are very slightly better for iterating and easier to use with range-for loops (`for(auto& x: vs)`). Code: ``` #include <vector> void iter(std::vector<int> &vs) { for(std::vector<int>::iterator it = vs.begin(); it != vs.end(); ++it) *it = 5; } void index(std::vector<int> &vs) { for(std::size_t i = 0; i < vs.size(); ++i) vs[i] = 5; } void at(std::vector<int> &vs) { for(std::size_t i = 0; i < vs.size(); ++i) vs.at(i) = 5; } ``` The generated assembly for `index()` and `at()` is identical ([godbolt])(<https://godbolt.org/z/cv6Kv4b6f>), but the loop setup for `iter()` is three instructions shorter: ``` iter(std::vector<int, std::allocator<int> >&): mov rax, QWORD PTR [rdi] mov rdx, QWORD PTR [rdi+8] cmp rax, rdx je .L1 .L3: ; loop body mov DWORD PTR [rax], 5 add rax, 4 cmp rax, rdx jne .L3 .L1: ret index(std::vector<int, std::allocator<int> >&): mov rax, QWORD PTR [rdi] mov rdx, QWORD PTR [rdi+8] sub rdx, rax mov rcx, rdx shr rcx, 2 je .L6 add rdx, rax .L8: ; loop body mov DWORD PTR [rax], 5 add rax, 4 cmp rdx, rax jne .L8 .L6: ret ```
What's faster, iterating an STL vector with vector::iterator or with at()?
[ "", "c++", "performance", "stl", "vector", "iterator", "" ]
how would one implement a back-button as a commandbutton that works universally? with back button i don't mean the browser-button, but rather a button that sits somewhere on the page. it is not always possible to use the Post-redirect-get pattern. its quite impractial to pass around the information on every single where the button should point to. is there maybe a reserved keyword for a navigation rule that points to the last navigation rule applied?
I use a `h:commandLink` with attribute `onclick="history.go(-1)"` in this case. It works universally.
My first idea : on every ``` <h:commandLink .....> ``` and etc; store the navigation string in a bean, or even a stack, and then the back button can retrieve it and just return that as per faces-config.xml Second idea. But on reflection you should override or use a filter to intercept the navigation commands and push them onto a stack. Then the back button can just pop the navigation off and away you go.
back commandbutton in jsf
[ "", "java", "jsf", "navigation", "back-button", "" ]
I have a query that I wish to run through an ASP.NET TableAdapter that contains an 'IN' clause which is to receive it's values through a parameter. My question is, how do I specify this parameter? I thought of writing the conditional statement like this: ``` AND b.group_category_id in (@ParamList) ``` where the @ParamList is a String of the parameters, e.g. "4,12,45,23" but since the specified id is an Integer, it complains that it cannot convert String to Integer. This makes sense, but is there any way to specify such a list in a SQL statement in an ASP.NET TableAdapter?
Answering my own question with: it can't be done.
One workaround I've seen: ``` WHERE charindex(',' + cast(b.group_category_id as varchar) + ',', @ParamList) > 0 ``` In this case the @ParamList would be a string in the form ",4,12,45,23," It's not "pretty", but preserves the parameter and benefits of a compiled query. Since you are searching for numbers, the sub-string guarantees a unique match.
ADO.NET TableAdapter parameters
[ "", "asp.net", "sql", "ado.net", "tableadapter", "" ]
I have created a very simple program that uses recursion. I'm using the g++ compiler. I can compile it, but when I try to run it I get an error message that says SEGMENTATION FAULT. Here's my code: ``` #include <iostream.h> using namespace std; int Recurse(int); int main(int argc, char *argv[]) { Recurse(10); cout << endl; } int Recurse(int numTimes) { if (numTimes == 0) return 0; else { cout << numTimes << " "; Recurse(numTimes--); } } ```
In your recursive call, you're using the postfix `--` (`numTimes--`), rather than the prefix version (`--numTimes`). As a result, the value of `numTimes` is decremented after the recursive call. This means that Recurse is called with 10 infinitely. Use the prefix version (which will decrement it before the call), or just pass `numTimes-1` (since the numTimes value doesn't need to be modified). The reason you're seeing a segfault is that your stack overflows into protected memory.
It might be the "numTimes--" that is causing the infinite recursion. The postfix -- will decrement the value within the -- method, but will return the original value of the variable. Try changing it to --numTimes.
G++ Compiler won't allow recursion?
[ "", "c++", "recursion", "" ]
I'm rather beginner in C# world (and .Net as well), so I decided to get some advices from more experienced developers. Which free unit testing framework for C# would you advise? I came across NUnit, which seemed to look interestingly, but in it's documentation I found out, that there were versions for .Net 1.1 and .Net 2.0. I need to use it in project targeted to .Net 3.0. So, please let me know if: * I can use NUnit for .Net 3.0 project? or: * there is something better than NUnit?
Yes. NUnit works well on .NET 3.0 and 3.5 too. Your second question is pretty subjective. NUnit is a widely used unit testing framework for .NET. MSTest is another one that is shipped with Visual Studio. xUnit is another one. There is a comparison on xUnit project: [xUnit - Comparing xUnit.net to other frameworks](http://xunit.github.io/docs/comparisons.html)
[xUnit](https://xunit.github.io/) is worth a look (and is what I use the most), as is [MbUnit](http://www.mbunit.com/).
Which free unit testing framework for C#?
[ "", "c#", ".net", "unit-testing", "frameworks", "" ]
I have written a DLL which exports a function that creates a window using `RegisterClassExW` and `CreateWindowExW`. Every message is retrieved via ``` GetMessageW(&msg, wnd_handle, 0, 0); TranslateMessage(&msg); DispatchMessageW(&msg); ``` Also there is a program which loads the DLL and calls the function. Despite the Unicode window creation method, the `wParam` in the `WM_CHAR` message always contains ASCII characters, even if I type some non-ASCII symbols or use Alt+(code). Instead of UTF-16, the `wParam` contains some ASCII character between 'A' and 'z'. The `WndProc` is a static function inside the DLL. The problem doesn't occur when all the window-related code is inside one program. Is there a way to always have Unicode `WM_CHAR` messages inside the DLL's window?
the problem was in the message retrieval process. I used `GetMessage()` with the handle of my window instead of just 0, `GetMessageW(&msg, wnd_handle, 0, 0)` instead of `GetMessageW(&msg, 0, 0, 0)`. In this way, the `WM_INPUTLANGCHANGEREQUEST` messages were swallowed and the locale remained English.
Your approach seems like it should work. Is it possible that you're calling the ANSI DefWindowProc instead of the wide version? That would translate a `WM_UNICHAR` into ANSI `WM_CHAR` messages. Maybe that would explain what you're seeing. As an experiment, I'd handle the `WM_UNICHAR` messages directly, and see what the data looks like at that point.
non-unicode WM_CHAR in unicode windows
[ "", "c++", "windows", "winapi", "dll", "unicode", "" ]
Developing a C# .NET 2.0 WinForm Application. Need the application to close and restart itself. ``` Application.Restart(); ``` The above method has [proven to be unreliable](https://stackoverflow.com/questions/95098/why-is-application-restart-not-reliable). What is a better way to restart the application?
Unfortunately you can't use Process.Start() to start an instance of the currently running process. According to the Process.Start() docs: "If the process is already running, no additional process resource is started..." This technique will work fine under the VS debugger (because VS does some kind of magic that causes Process.Start to think the process is not already running), but will fail when not run under the debugger. (Note that this may be OS-specific - I seem to remember that in some of my testing, it worked on either XP or Vista, but I may just be remembering running it under the debugger.) This technique is exactly the one used by the last programmer on the project on which I'm currently working, and I've been trying to find a workaround for this for quite some time. So far, I've only found one solution, and it just feels dirty and kludgy to me: start a 2nd application, that waits in the background for the first application to terminate, then re-launches the 1st application. I'm sure it would work, but, yuck. Edit: Using a 2nd application works. All I did in the second app was: ``` static void RestartApp(int pid, string applicationName ) { // Wait for the process to terminate Process process = null; try { process = Process.GetProcessById(pid); process.WaitForExit(1000); } catch (ArgumentException ex) { // ArgumentException to indicate that the // process doesn't exist? LAME!! } Process.Start(applicationName, ""); } ``` (This is a very simplified example. The real code has lots of sanity checking, error handling, etc)
A much simpler approach that worked for me is: ``` Application.Restart(); Environment.Exit(0); ``` This preserves the command-line arguments and works despite event handlers that would normally prevent the application from closing. The Restart() call tries to exit, starts a new instance anyway and returns. The Exit() call then terminates the process without giving any event handlers a chance to run. There is a very brief period in which both processes are running, which is not a problem in my case, but maybe in other cases. The exit code 0 in `Environment.Exit(0);` specifies a clean shutdown. You can also exit with 1 to specify an error occurred.
How do I restart my C# WinForm Application?
[ "", "c#", ".net", "" ]
I need black forecolor in a disabled combobox. Is it possible?
I have searched around for information in the past about this, and as far as I can tell, the best solution is to change the **DrawMode** of the combo box to *OwnerDrawFixed* or *OwnerDrawVariable* and then write your own drawing code in the **DrawItem** event of the combo box. I found this [article](http://www.codeproject.com/KB/combobox/disabledcombodisplay.aspx) that goes into much more detail about it. Hope it helps.
A "hack" I've used in the past for textboxes is to leave the control enabled, but capture the "OnFocus" event and immediately set the focus to some other object on the form, preferably a label since it doesn't show as being selected. I think this should work for comboboxes, too.
Change forecolor of disabled combobox
[ "", "c#", ".net", "winforms", "combobox", "colors", "" ]
Groovy has a concept of GStrings. I can write code like this: ``` def greeting = 'Hello World' println """This is my first program ${greeting}""" ``` I can access the value of a variable from within the String. How can I do this in Python? -- Thanks
In Python, you have to explicitely pass a dictionary of possible variables, you cannot access arbitrary "outside" variables from within a string. But, you can use the `locals()` function that returns a dictionary with all variables of the local scope. For the actual replacement, there are many ways to do it (how unpythonic!): ``` greeting = "Hello World" # Use this in versions prior to 2.6: print("My first programm; %(greeting)s" % locals()) # Since Python 2.6, the recommended example is: print("My first program; {greeting}".format(**locals())) # Works in 2.x and 3.x: from string import Template print(Template("My first programm; $greeting").substitute(locals())) ```
``` d = {'greeting': 'Hello World'} print "This is my first program %(greeting)s" % d ```
GStrings in Python
[ "", "python", "gstring", "" ]
My C# application is running at system startup, and must wait for the local SQL Server instance until it can actually do anything. Right now, I just spin waiting for the server to respond (I used to get a wait handle on the service, but that wasn't reliable), then launch the app's main dialog. The problem with this, of course, is that the user can't tell anything is happening until the service starts, and because of the hardware we're using that can take up to a minute. So I'm thinking of throwing in a "Loading / Please Wait" indicator of some sort. The thing is, our project is nearing lockdown and a change as big as making a new class would cause a lot of headaches -- modifying an existing file (like Program.cs) is a lot less intrusive than making a new one. Long story short: is there a .NET class that would be well suited to being displayed (asynchronously, I guess) before I start plinking at the SQL Server, then removed when it starts to respond?
Here's a triple threaded version that I hacked together quickly that will do the trick. This can be dropped in anywhere in a visible form (or could be modified for program.cs) and will spawn a new, centered, modal dialog box with a smooth scrolling progress bar that will dominate user attention until FinishedProcessing in the parent thread is set to true. ``` //Update to true when finished loading or processing bool FinishedProcessing = false; System.Threading.AutoResetEvent DialogLoadedFlag = new System.Threading.AutoResetEvent(false); (new System.Threading.Thread(()=> { Form StockWaitForm = new Form() { Name = "StockWaitForm", Text = "Please Wait...", ControlBox = false, FormBorderStyle = FormBorderStyle.FixedDialog, StartPosition = FormStartPosition.CenterParent, Width = 240, Height = 80, Enabled = true }; ProgressBar ScrollingBar = new ProgressBar() { Style = ProgressBarStyle.Marquee, Parent = StockWaitForm, Dock = DockStyle.Fill, Enabled = true }; StockWaitForm.Load += new EventHandler((x, y) => { DialogLoadedFlag.Set(); (new System.Threading.Thread(()=> { while (FinishedProcessing == false) Application.DoEvents(); StockWaitForm.Invoke((MethodInvoker)(()=> StockWaitForm.Close())); })).Start(); }); this.Invoke((MethodInvoker)(()=>StockWaitForm.ShowDialog(this))); })).Start(); while (DialogLoadedFlag.WaitOne(100,true) == false) Application.DoEvents(); // //Example Usage //Faux Work - Have your local SQL server instance load here for (int x = 0; x < 1000000; x++) int y = x + 2; FinishedProcessing = true; ``` Customize to taste. Also, if you do use this in a production app, wrap the new thread contents in try...catch blocks to [CYA](http://www.rvenables.com/2009/01/threading-tips-and-tricks). One last thing, I'm releasing this code to you under the "Coderer Public License / SO v1.1", as follows: Coderer Public License / SO v1.0 I, Person known "Coderer" on the community "Stack Overflow", agree to thoroughly consider switching to a sane project management methodology that allows extra classes to be added to projects in the Executing phase. I understand that nazi-like change control is unhealthy for all parties involved.
Here's a .NET wrapper around the standard Windows progress dialog: <http://www.codeproject.com/KB/shell/iprogressdialognet.aspx> I haven't messed with it, but I'm sure there's a Flag to make the progress bar spin. If you want to get really fancy, you could even whip up your own AVI animation and plug it in.
Is there a "stock" idle / wait dialog?
[ "", "c#", "winforms", "dialog", "" ]
I use a factory pattern to create a custom object which is loaded from a cache if possible. There are no static members or functions on the custom object. Assuming 2 threads call the factory and are both returned references to the same object from the cache. (i.e. No new operator, in ref to answer below, object returned from a collection) If I want to modify a private instance member on inside the class: a) Shoulb I lock it first? b) Will the change be reflected in both threads? I assume yes for both questions, but at the same time it feels like the threads have different instances of the class. Have I must something fundamental here? Why do I feel like I have? =============== Following the first few answers I have confirmed what I thought, thanks. I guess what I really want to know is, if the objects are pretty much only read-only, i.e. after being created they only have one instance member that can change, do I need to do any locks when reading properties that are not affected by that one changeable instance member? Again I assume no, but I have to come to value the second-opinion of the collective StackOverflow brains trust :)
Reading and writing of most primitive types, string and object references is atomic (everything except non-volatile longs and doubles). This means locks are not necessary if you are simply reading or writing a field or other variable in isolation. So, if you ever see code like this (and I guaranteee you will), you can happily strip out the unnecessary and costly locking: ``` public SomeClass SomeProperty { get { lock (someLock) { return someField; } } set { lock (someLock) { someField = value; } } } ``` If, however, you want to change the value, increasing it by one for example, or if you want to read multiple, related variables then you need to lock if you want sensible results. It is also worth noting that the Hashtable and Dictionary support mulitple concurrent readers without the need for any kind of locking.
Yes, you should lock before setting the private member. This will be reflected in both threads (since they're the same object). However, you may want to take some time to consider how to handle the locks and threading. If your factory is creating the object and adding it to the collection, it will need a lock of some form around the routine to create the object. Otherwise, it's possible that the two threads could ask for the object at the same time, before it was created, and create 2 instances. Also, I wouldn't recommend setting the private member directly - it would be a good idea to have a single object inside of the returned class instance used just for locking, and use some form of accessor (method or property) that locks on that synchronization object and then sets the field. As for not "trusting" that its two instances - you can always just do something to check in the debugger. Add a check for reference equality, or even temporarily add a GUID to your class that's setup at construction - it's easy to verify that they're the same that way.
Thread safety across shared instances (C#)
[ "", "c#", "multithreading", "" ]
I am planning an application that must provide services that are very much like those of a Java EE container to third party extension code. Basically, what this app does is find a set of work items (currently, the plan is to use Hibernate) and dispatch them to work item consumers. The work item consumers load the item details, invoke third party extension code, and then if the third party code did not fail, update some state on the work item and commit all work done. I am explicitly not writing this as a Java EE application. Essentially, my application must provide many of the services of a container, however; it must provide transaction management, connection pooling and management, and a certain amount of deployment support. How do I either A) provide these directly, or B) choose a third party library to provide them. Due to a requirement of the larger project, the extension writers will be using Hibernate, if that makes any difference. It's worth noting that, of all of the features I've mentioned, the one I know least about is transaction management. How can I provide this service to extension code running in my container?
Spring does have transaction management. You can define a DataSource in your application context using Apache DBCP (using a `org.apache.commons.dbcp.BasicDataSourceorg.springframework.jdbc.datasource.DataSourceTransactionManager` for the DataSource. After that, any object in your application can define its own transactions programatically if you pass it the TransactionManager, or you can use AOP interceptors on the object's definition in your application context, to define which methods need to be run inside a transaction. Or, the easier approach nowadays with Spring is to use the @Transactional annotation in any method that needs to be run inside a transaction, and to add something like this to your application context (assuming your transactionManager is named txManager): `<tx:annotation-driven transaction-manager="txManager"/>` This way your application will easily accept new components later on, which can have transaction management simply by using the @Transactional annotation or by directly creating transactions through a PlatformTransactionManager that they will receive through a setter (so you can pass it when you define the object in your app context).
Hi I recommend using the Spring Framework. It provides a nice way to bring together a lot of the various services you are talking about. For instance to address your specific needs: 1. Transaction Management/Connection pooling * I built a spring-based stand-alone application that used Apache commons connection pooling. Also I believe spring has some kind of transaction mgmt built in. 2. Deployment support * I use ant to deploy and run things as a front-loader. It works pretty well. I just fork a seperate process using ant to run my Spring stand-alone app. 3. Threading. * Spring has support for Quartz which deals well with threads and thread pools 4. DAO * Spring integrates nicely with Hibernate and other similar projects 5. Configuration * Using its xml property definitions -- Spring is pretty good for multiple-environment configuration.
How do I write an application that more or less acts as a container?
[ "", "java", "hibernate", "transactions", "containers", "" ]
When trying to use the paging part of GridView in my application, I receive the following error: > The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.
I mixed your answers and I get my answer. I solved this problem whit this code : ``` protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; DataBind(); } ```
You need to add an eventhandler to tell the GridView which page it should be looking at as I'm guessing you have done the .DataBind() in code. An example would be: Markup: ``` <asp:GridView ID="GridView1" runat="server" EnablePagingAndSortingCallbacks="true" OnPageIndexChanged="GridView1_PageIndexChanged" /> ``` Code: ``` protected void GridView1_PageIndexChanged(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; GridView1.DataBind(); } ```
Error in Gridview application
[ "", "c#", "asp.net", "gridview", "page-index-changed", "" ]
Say for example that I create a Duck ``` Duck myDuck = DuckFactory.CreateDuck(); ``` In the past I've always check to see if myDuck is null ``` if (myDuck == null) { // Do stuff } ``` I've recently looked at some code that check for null first. ``` if (null == myDuck) { // Do stuff } ``` It seems to me that these are the same, but are there any differences between these two? Is there any performance benefits to one over the other? Is there a recommended best practice for checking if an object is null?
The second stems from C/C++ (and elsewhere) where this is a valid construct ``` if (myDuck = null) { } ``` That's not valid in C# (unless your expression resolves to a boolean). For example, this is valid C# ``` bool b = ... if (b = true) { } ``` Putting the constant first was defensive to stop accidental assignment when you wanted comparison. I'd say more people put the variable to the left but there is nothing wrong with putting the constant to the left either. Just pick one and be consistent about it.
The only difference occurs if you were to put this by accident: ``` if(myDuck = null) ... ``` But in reality, the C# compiler is smart enough to detect this. If you put this by accident: ``` if(null = myDuck) ... ``` Then this would result in an error back in the C or C++ days. Long story short: it makes no difference in C#.
Should I check to see if an object is null first or second?
[ "", "c#", "" ]
Do auto-properties work in VS 2005? I can't seem to get my C# classes to compile with them (same with the in-place initialisation). I have framework 3 sp1 installed. Are these features only available in VS 2008 or is there something I am doing wrong? By in-place initialisation i mean the following: ``` SomeClass c = new SomeClass() { Name = "", Value = 12345 }; ```
Automatically implemented properties and object initializers (the sample you showed) were both introduced in C# 3.0. Visual Studio 2005 only compiles C# 2.0. For more on what came in which version (and which C# 3.0 features you can use when targeting .NET 2.0), see [my article on the topic](http://csharpindepth.com/Articles/Chapter1/Versions.aspx).
You can use auto-properties in VS 2008 on projects that are targeted for .NET 2.0 as well. You can also use lambda expressions and the var keyword.
c# auto property VS 2005?
[ "", "c#", "c#-3.0", "" ]
How do I declare in C# a C function that returns a pointer to a structure? I believe following is one way to do that, followed by **Marshal.PtrToStructure** to get actual structure value. ``` // C-function SimpleStruct * Function(void); // C# import [DllImport("MyDll.dll")] public static extern IntPtr Function(); ``` 1. Am I correct about that? 2. Are there other ways to accomplish the same? (It would be OK to get struct back by value)
Since the function returns a pointer (hopefully not a locally allocated one?) your best bet is to manually marshal it (via [Marshal.PtrToStructure](http://msdn.microsoft.com/en-us/library/4ca6d5z7(v=vs.110).aspx)). If it were a parameter you could create a managed version of the structure using the PInvoke Interop Assistant then pass it via ref or out.
**Caveat: this will only work if the pointer returned is to memory already managed by the CLR** I believe what you are looking for is ``` // C# import [DllImport("MyDll.dll")] [return : MarshalAs(UnmanagedType.LPStruct)] public static extern StructureName Function(); [StructLayout(LayoutKind.Sequential)] public class StructureName {} ``` This should eliminate the need for any manual `Marshal.PtrToStructure` calls. Depending on what your structure contains, you may need to tag some fields with `MarshalAs` attributes as appropriate. [MSDN](http://msdn.microsoft.com/en-us/library/aa288468.aspx#pinvoke_example3) has a good example of this.
p/invoke C function that returns pointer to a struct
[ "", "c#", "interop", "pinvoke", "" ]
I have my dad's old PC from the 1980's. It's a Tandy 1000 PC SX: This computer doesn't have a modem, but I have another PC that has Windows XP on it and it also has a 5 3/4 inch floppy drive. So where can I find a C/C++ compiler for this old PC?
Oh my God, I haven't seen one of those in forever. Okay, that's running a version of MS/DOS, no later than about MS/DOS 3 as I recall. First thing is to make sure you can read and write a floppy on the XP computer that the Tandy will read. You'll need to look for a fairly old version of Turbo C, even, I'd guess. You probably should look into the [Tiny C Compiler](http://en.wikipedia.org/wiki/Tiny_C_Compiler).
YOu might be able to use [Turbo C 2.01](https://downloads.embarcadero.com/free/tc201). I could when I had a Tandy 1000HX.
C or C++ compiler for the Tandy 1000 PC SX?
[ "", "c++", "c", "compiler-construction", "" ]
Unclear on the sizeof for decimal types. Does the size in bytes vary by precision as in sql server? Is the precision variable for the c# type 'decimal'? I don't want to turn on unsafe code to just call sizeof on a decimal type. How would you approach this?
As others have said, `decimal` is always 16 bytes (128 bits). The precision of `decimal` is always 28/29 digits. It's a floating point type, unlike SQL's `DECIMAL` type. See [my article on it](https://csharpindepth.com/Articles/Decimal) for more details.
> The decimal keyword indicates a 128-bit data type. Source: [MSDN](http://msdn.microsoft.com/en-us/library/364x0z75(loband).aspx)
c# sizeof decimal?
[ "", "c#", "" ]
I am using a MS SQL db and I have 3 tables: 'base\_info', 'messages', 'config' ``` bases: ID Name NameNum ==================================== 1 Home 101 2 Castle 102 3 Car 103 messages: ID Signal RecBy HQ ============================ 111 120 Home 1 111 110 Castle 1 111 125 Car 1 222 120 Home 2 222 125 Castle 2 222 130 Car 2 333 100 Home 1 333 110 Car 2 config: ID SignalRec SignalOut RecBy HQ ==================================== 111 60 45 101 1 111 40 60 102 1 222 50 60 102 2 222 30 90 101 2 333 80 10 103 1 ``` Ok so now I have a subquery in which I select the 'SignalRec' and 'SignalOut' from the config table and match it on the messages table by ID and Date(not included above), the problem is that I need it to match where messages.RecBy = config.RecBy but config.RecBy is a string but it's equivalent Name is in the bases table. So I almost need to do a subquery inside a subquery or some type of join and compare the returned value. Here is what I have so far: ``` (SELECT TOP 1 config.SignalRec from config WHERE config.ID = messages.ID AND ||I need th other comparison here||...Order By...) As cfgSignalRec, (SELECT TOP 1 config.SignalOut from config WHERE config.ID = messages.ID AND ||I need th other comparison here||...Order By...) As cfgSignalOut ``` I tried to make this as clear as possible but if you need more info let me know.
I think I might have not been clear enough what I wanted to do, sorry about that. The data is actually different in the 2 tables, although the correlations are the same. It's kind of confusing to explain without going into detail about how the system works. I actually found a very fast way of doing this. Inside my sub-query I do this: ``` (SELECT TOP 1 config.Signal FROM config,bases WHERE config.ID = messages.ID AND bases.Name = messages.RecBy AND bases.NameNum = config.RecBy Order By...) ``` So this essentially compares the 2 RecBy's of different tables even though one is an integer and the other is a string. It reminds me of a match and look up in Excel.
I would normalize out RecBy in your messages table to reference the bases table. Why would you insert the string content there if it's also referenced in bases? This is exactly why normalization exists: reduce redundancy, reduce ambiguity, and enforce referential integrity. To make this more clear, RecBy in the messages table should be a foreign key to Bases.
Compare 2 values of different types inside of subquery
[ "", "sql", "join", "subquery", "" ]
How can we make a .com file using C/C++? Is it possible? Edit: I was able to successfully make a com file using darin's suggestions. But somehow the exe file of the following program cannot be converted to com file. I get the "File cannot be converted" message by exe2bin. I'm using Borland Turbo C++ 3.0. Any suggestions? ``` #include <dos.h> void interrupt (*oldint65)( ); char st[80] = {"Hello World$"}; void interrupt newint65(void); void main() { oldint65 = getvect(0x65); setvect(0x65, newint65); geninterrupt (0x65); geninterrupt (0x65); geninterrupt (0x65); setvect(0x65, oldint65); } void interrupt newint65( ) { _AH = 0x09; _DX=(unsigned int)st; geninterrupt (0x21); } ```
In C, you must compile your program with the [TINY memory model](http://www.digitalmars.com/ctg/ctgMemoryModel.html). Then you can use use [EXE2BIN](http://technet.microsoft.com/en-us/library/bb490635.aspx) or a similar program to convert an EXE file to a COM file.
That would depend on what you mean. Do you want to compile your program **into** a `.com` file? That would depend on your compiler, if it is possible at all. If you are writing a compiler (or something like that), and want to produce a `.com` file from your **own** program, you should have a look at the [COM article on Wikipedia](http://en.wikipedia.org/wiki/COM_file), or use the [NASM](http://nasm.us) assembler to assemble to a `.com` file: `nasm -o hello.com hello.asm`.
How to make a .com file using C/C++?
[ "", "c++", "c", "com", "" ]
I see functions/methods with a void return in the signature that have a return statement at the end of the function. What is the reason for this, and does this apply to other languages? For all I know, I can use return if I want to exit anywhere else but the end of the function. A C example: ``` void function(void) { int x = 1 + 2; return; // what do we need this for, if at all? } ```
This seems pointless here. But my guess is that this kind of thing can be used to put a breakpoint in IDEs which don't support putting a breakpoint at the closing brace and by putting a breakpoint here, some values can be checked in the watch window etc.
Someone took a 'a function must have a single return' coding guideline too literally.
What is the point of adding a return statement at end of a void function?
[ "", "c++", "c", "return", "void", "" ]
Beforehand : I have read indeed the other topics on SO, but I can't find an answer in them. (The others are about config-files, or a list of techniques) My question thus is very simple, though a bit subjective (I'll label it beforehand :-)) what is the *easiest* way..
[File.Encrypt](http://msdn.microsoft.com/en-us/library/system.io.file.encrypt.aspx) is pretty simple - one call (with one parameter). Of course, it really depends on what you want the encryption for. File.Encrypt encrypts to the current account, which isn't much use if you're passing the file around. But, given your spec - i.e. easiest way to encrypt a file - it has to be a candidate!
[Data Protection API in C#](http://msdn.microsoft.com/en-us/library/ms229741.aspx)
What's the easiest way to encrypt a file in c#?
[ "", "c#", "encryption", "" ]
Like you would do in php: ``` if (@$some_var_exists) // do stuff ``` How would you do something like this in Javascript without getting an error? Thanks EDIT: Thanks for the answers. However, the problem I'm trying to solve is how to check if a variable exists when it's deep in a object, for example: ``` if (someObj.something.foo.bar) // This gives an error in the browser if "someObj.something.foo" is not defined. ```
Check each part of the chain: ``` if (someObj && someObj.something && someObj.something.foo && someObj.something.foo.bar) { // stuff } ``` Because the expression is evaluated from left to right, and returns as soon as it finds false, it will not cause an error. So if "someObj" exists, but "sometObj.something" does not, it will return false and never execute the test for someObj.something.foo that would throw an error.
To check if a variable is defined, you could do: ``` if(self.somevar) { ... } ``` As pointed out by Mister in the comments, the `self` part is important here. Or, if you wish to be more explicit, you could do: ``` if(typeof somevar != "undefined") { ... } ``` The way you are checking the PHP var is also not very neat or really the best practice as the `@` error suppressor is expensive and not necessary in this case. You could use [`isset`](http://www.php.net/isset) like this: ``` if(isset($some_var_here)) { ... } ``` **EDIT**: For your more specific problem, I think @Ryan Watkins answer is the way to do it, although I'd have to wonder why you put yourself in such a position anyways. :)
How to do a "soft" if condition check in Javascript
[ "", "javascript", "" ]
I'm playing around with some JPA stuff, changing the mappings to see how they're supposed to be etc. It's basic experimentation. However I can't find a tool that will simply read my entities and then generate the table schema for me. I tried to find something like this in JBoss tools but nada. Eclipse integration will be a huge plus but i'll take a command line tool or an ant task. Any ideas?
I don't think there is an universal way of doing this with JPA, you have to directly use the underlying JPA implementation to achieve this. For **Hibernate**, there are several possibilities: * Use the method [duffymo](https://stackoverflow.com/questions/779479/reverse-engineer-ddl-from-jpa-entities/779629#779629) posted earlier, that makes Hibernate update the database schema automatically. * If you do not want that, you can use the *hbm2ddl* tool from [Hibernate Tools](http://www.hibernate.org/) (note: link sucks, but apparently their home page is a bit broken right now). You can use that to automatically generate database creation scripts from your JPA entities; there are also plugins for Maven and Ant that invoke `hbm2ddl` automatically. For **EclipseLink** (formerly Oracle TopLink, the JPA 2.0 RI) see [Using EclipseLink JPA Extensions for Schema Generation](http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#Using_EclipseLink_JPA_Extensions_for_Schema_Generation). In principle it is very similar to Hibernate, although at first glance I don't see anything that could be used as a stand-alone utility for creating a DB script. Other JPA implementations (BEA/Oracle Kodo, Apache OpenJPA) probably have their own specific methods of achieving this.
Try adding the following to your persistence.xml **For Hibernate:** To create: ``` <property name="hibernate.hbm2ddl.auto" value="update"/> ``` To drop and create: ``` <property name="hibernate.hbm2ddl.auto" value="create-drop"/> ``` **For Toplink:** To create: ``` <property name="toplink.ddl-generation" value="create-tables"/> ``` To drop and create: ``` <property name="toplink.ddl-generation" value="drop-and-create-tables"/> ``` **For EclipseLink:** To create: ``` <property name="eclipselink.ddl-generation" value="create-tables"/> ``` To drop and create: ``` <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/> ```
Reverse engineer DDL from JPA entities
[ "", "java", "hibernate", "orm", "jpa", "ddl", "" ]
Are there any Exceptions defined in the .NET Framework that I shouldn't throw in my own code, or that it is bad practice to? Should I write my own?
You shouldn't throw any exception that is automatically thrown by the CLR due to user errors. For instance * StackOverflowException * NullReferenceException * AccessViolationException * etc ... The reason being is to do so creates confusion for people calling your API. Users should be able to distinguish between actively thrown exceptions by an API and exceptions that are not actively thrown (thrown by CLR). The reason is that at actively thrown exception generally represents a known state in an API. If I call an API and it throwns an ArgumentException, I have a reasonable expectation that the given object is in a good state. It recognized a potentially bad situation and actively accounted for it. On the other hand if it throwns a NullRefrenceException, that is an indication that the API encountered an unknown error and is now in an unreliable state. Another lesser reason is that these exceptions behave differently when thrown by user code as opposed to the CLR. For instance it's possible to catch a StackOverflowException if thrown by user code, but not if it's thrown by the CLR. * <http://blogs.msdn.com/jaredpar/archive/2008/10/22/when-can-you-catch-a-stackoverflowexception.aspx> **EDIT** Responding to Michael's comment You also should not throw Exception, ApplicationException or SystemException directly. These exceptions types are too general to provide meaningful information to the code which calls your API. True you can put a very descriptive message into the message parameter. But it's not straight forward or maintainable to catch an exception based on a message. It's much better to catch it based on the type. FxCop rule on this subject: <http://msdn.microsoft.com/en-us/library/ms182338(VS.80).aspx>
Most exception classes in the framework are not meant for reuse since they usually are crafted to signal some Framework specific error. Like those [mentioned by @JaredPar](https://stackoverflow.com/questions/763627/in-c-are-there-any-built-in-exceptions-i-shouldnt-use/763634#763634), they are used by the framework to indicate certain states in the framework. There are literally tens, maybe hundreds, exceptions in the framework, so IMO it is more useful to list those that we *should* use. At the top of my head, these are those I actively use: * [ArgumentException](http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx), [ArgumentNullException](http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx) and [ArgumentOutOfRangeException](http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception.aspx) * [InvalidOperationException](http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx) * [NotSupportedException](http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx) * [NotImplementedException](http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx) For other error conditions in user code, best practice is to create your own exception classes.
In C#, are there any built-in exceptions I shouldn't use?
[ "", "c#", ".net", "exception", "" ]
I am writing a python package with modules that need to open data files in a `./data/` subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system. I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module. This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not `.py` files, so I can't use import functions and the like. Any suggestions? Right now my package directory looks like: ``` / __init__.py module1.py module2.py data/ data.txt ``` I am trying to access `data.txt` from `module*.py`!
You can use `__file__` to get the path to the package, like this: ``` import os this_dir, this_filename = os.path.split(__file__) DATA_PATH = os.path.join(this_dir, "data", "data.txt") print open(DATA_PATH).read() ```
The standard way to do this is with setuptools packages and pkg\_resources. You can lay out your package according to the following hierarchy, and configure the package setup file to point it your data resources, as per this link: <http://docs.python.org/distutils/setupscript.html#installing-package-data> You can then re-find and use those files using pkg\_resources, as per this link: <http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access> ``` import pkg_resources DATA_PATH = pkg_resources.resource_filename('<package name>', 'data/') DB_FILE = pkg_resources.resource_filename('<package name>', 'data/sqlite.db') ```
Access data in package subdirectory
[ "", "python", "package", "" ]
Is there a way to write a string directly to a tarfile? From <http://docs.python.org/library/tarfile.html> it looks like only files already written to the file system can be added.
I would say it's possible, by playing with `TarInfo` and `TarFile.addfile` passing a `StringIO` as a fileobject. Very rough, but it works ``` import tarfile import StringIO tar = tarfile.TarFile("test.tar","w") string = StringIO.StringIO() string.write("hello") string.seek(0) info = tarfile.TarInfo(name="foo") info.size=len(string.buf) tar.addfile(tarinfo=info, fileobj=string) tar.close() ```
As Stefano pointed out, you can use `TarFile.addfile` and `StringIO`. ``` import tarfile, StringIO data = 'hello, world!' tarinfo = tarfile.TarInfo('test.txt') tarinfo.size = len(data) tar = tarfile.open('test.tar', 'a') tar.addfile(tarinfo, StringIO.StringIO(data)) tar.close() ``` You'll probably want to fill other fields of `tarinfo` (e.g. `mtime`, `uname` etc.) as well.
python write string directly to tarfile
[ "", "python", "file", "file-io", "tar", "" ]
I would like to iterate over the data rows stored in a Zend\_Db\_Table\_Rowset object and then drop/unset some of the rows, if they don't fulfil certain criteria. I could use toArray() to get only the data rows from the object and then it would be easy to unset the rows I don't need. But since I want to keep my object for further use I don't want to do that. Of course one solution would be to adjust my query in order to retrieve only what I need, but that's not possible in this scenario. At least I wouldn't know how. I tried the following which didn't work: ``` foreach ($rowset as $key => $row) { if (!$condition == satisfied) { unset($rowset[$key]); } } ``` And of course it doesn't work, since there is no $rowset[$key]... the data is stored in a subarray [\_data:protected] but unset $rowset[\_data:protected][$key] didn't work either. Maybe my conception of a rowset object (or the representation of objects in general) is not mature enough to understand what I'm doing. Any clarification and tips would be welcome! [EDIT] $row->delete is NOT an option, I don't want to delete the row from the database! I don't want to create an array first, if I wanted to I would just do $rowset->toArray() [/EDIT] **Solution**: I ended up doing what I thought I wasn't able too, meaning I integrated everything into the initial query.
You could use a [custom Rowset class](http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.extending.row-rowset) This class would have then access to the protected $\_rows stored internally, and you could add a public method to applying your filtering
Example method for your [custom rowset class](http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.extending.row-rowset): ``` public function removeFromRowset($id) { foreach ($this->_rows as $i => $v) { if ($v->id == $id) { // found Row we want to remove unset($this->_rows[$i]); // delete both rowset unset($this->_data[$i]); // and original data break; // not necessary to iterate any more } } $this->_data = array_values($this->_data); // reindex both arrays (otherwise it breaks foreach etc.) $this->_rows = array_values($this->_rows); $this->_count = count($this->_data); // don't forget to update items count! } ``` It iterate through your Rowset, finds Row according to its id (supposing "id" is unique identifier) and than remove it from the Rowset. **Please note this doesn't delete the row from database, it just removes it from the Rowset!**
Zend Framework: How to unset data rows in a Zend_Db_Table_Rowset object
[ "", "php", "arrays", "zend-framework", "zend-db-table", "" ]
I'd like to be able to count instances of classes that belong in the same class hierarchy. For example, let's say I have this: ``` class A; class B: public A; class C: public B; ``` and then I have this code ``` A* tempA = new A; B* tempB = new B; C* tempC = new C; C* tempC2 = new C; printf(tempA->GetInstancesCount()); printf(tempB->GetInstancesCount()); printf(tempC->GetInstancesCount()); ``` the result of that should print 1 1 2 The counting, ideally, should be done internally. Each class, and not some kind of manager, should know how many instances it has. Any ideas? Thanks!
There is a problem with proposed solutions: when you create B you A constructor will be called automatically and thus increment count of A. ``` class A { public: A(bool doCount = true) { if (doCount) ++instanceCount_; } static std::size_t GetInstanceCount() { return instanceCount_; } virtual ~A(){} private: static std::size_t instanceCount_; }; class B: public A { public: B(bool doCount = true):A(false) { if (doCount) ++instanceCount_; } static std::size_t GetInstanceCount() { return instanceCount_; } private: static std::size_t instanceCount_; }; std::size_t A::instanceCount_ = 0; std::size_t B::instanceCount_ = 0; ```
Directly off my head: * Create an integer static field in each class. Watch out for integer overflow. * Initialize it to 0 in an [emulated static constructor](http://www.cpptalk.net/emulating-a-static-constructor-vt12077.html). * Increment it at each (nonstatic) constructor body. Decrement it in the destructor. * GetInstancesCount() is a static function that returns the value of your integer static field. **Note:** See Mykola's comments. This would print 4 for A, 3 for B and 2 for C i.e. it would count one instance of B as "one A and one B", and one C as "one A, one B and one C". Which is in a way true, but is not what the question asks for. In other words, my answer is wrong :)
Counting instances of individual derived classes
[ "", "c++", "" ]
What is mutex and semaphore in Java ? What is the main difference ?
Semaphore can be counted, while mutex can only count to 1. Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connections Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a ["Mutual Exclusion Semaphore"](http://www.javaworld.com/javaworld/jw-10-1998/jw-10-toolbox.html).
Unfortunately everyone has missed the most important difference between the semaphore and the mutex; the concept of "**ownership**". Semaphores have no notion of ownership, this means that any thread can release a semaphore (this can lead to many problems in itself but can help with "death detection"). Whereas a mutex does have the concept of ownership (i.e. you can only release a mutex you have acquired). Ownership is incredibly important for safe programming of concurrent systems. I would always recommend using mutex in preference to a semaphore (but there are performance implications). Mutexes also may support priority inheritance (which can help with the priority inversion problem) and recursion (eliminating one type of deadlock). It should also be pointed out that there are "binary" semaphores and "counting/general" semaphores. Java's semaphore is a counting semaphore and thus allows it to be initialized with a value greater than one (whereas, as pointed out, a mutex can only a conceptual count of one). The usefulness of this has been pointed out in other posts. So to summarize, unless you have multiple resources to manage, I would always recommend the mutex over the semaphore.
What is mutex and semaphore in Java ? What is the main difference?
[ "", "java", "multithreading", "concurrency", "mutex", "semaphore", "" ]
Is there a way to delete entire directories recursively in Java? In the normal case it is possible to delete an empty directory. However when it comes to deleting entire directories with contents, it is not that simple anymore. How do you delete entire directories with contents in Java?
You should check out [Apache's commons-io](//commons.apache.org/proper/commons-io/). It has a [FileUtils](//commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File)) class that will do what you want. ``` FileUtils.deleteDirectory(new File("directory")); ```
With Java 7, we can finally [do this with reliable symlink detection.](https://stackoverflow.com/a/27917071/3474) (I don't consider Apache's commons-io to have *reliable* symlink detection at this time, as it doesn't handle links on Windows created with `mklink`.) For the sake of history, here's a pre-Java 7 answer, which *follows symlinks.* ``` void delete(File f) throws IOException { if (f.isDirectory()) { for (File c : f.listFiles()) delete(c); } if (!f.delete()) throw new FileNotFoundException("Failed to delete file: " + f); } ```
Delete directories recursively in Java
[ "", "java", "file-io", "filesystems", "delete-directory", "" ]
I have a sorted array of double values in C++. Is there an STL function that will return the **index** of the **nearest** value in the array to a given double value? For example, given the following array ``` double myarray[5] = { 1.0, 1.2, 1.4. 1.5, 1.9 }; ``` the function call ``` search(myarray, 1.6); ``` should return `3`, the index of the element nearest to 1.6, instead of `-1` (or some other flag value) indicating that the value 1.6 wasn't found.
maybe `std::lower_bound` `std::upper_bound` will help you.
Here is a generic solution using `std::lower_bound`: ``` template <typename BidirectionalIterator, typename T> BidirectionalIterator getClosest(BidirectionalIterator first, BidirectionalIterator last, const T & value) { BidirectionalIterator before = std::lower_bound(first, last, value); if (before == first) return first; if (before == last) return --last; // iterator must be bidirectional BidirectionalIterator after = before; --before; return (*after - value) < (value - *before) ? after : before; } ``` You'll notice that I used Bidirectional Iterators, meaning that the function can only work with iterators that can be both incremented and decremented. A better implementation would only impose the Input Iterators concept, but for this problem this should be good enough. Since you want the index and not an iterator, you can write a little helper function: ``` template <typename BidirectionalIterator, typename T> std::size_t getClosestIndex(BidirectionalIterator first, BidirectionalIterator last, const T & value) { return std::distance(first, getClosest(first, last, value)); } ``` And now you end up with a code like this: ``` const int ARRAY_LENGTH = 5; double myarray[ARRAY_LENGTH] = { 1.0, 1.2, 1.4. 1.5, 1.9 }; int getPositionOfLevel(double level) { return getClosestIndex(myarray, myarray + ARRAY_LENGTH, level); } ``` which gives the following results: ``` level | index 0.1 | 0 1.4 | 2 1.6 | 3 1.8 | 4 2.0 | 4 ```
Search for nearest value in an array of doubles in C++?
[ "", "c++", "search", "stl", "" ]
Say I am echoing a large amount of variables in PHP and I wont to make it simple how do i do this? Currently my code is as follows but it is very tedious work to write out all the different variable names. ``` echo $variable1; echo $variable2; echo $variable3; echo $variable4; echo $variable5; ``` You will notice the variable name is the same except for an incrementing number at the end. How would I write a script that prints echo `$variable;` so many times and adds an incrementing number at the end to save me writing out multiple variable names and just paste one script multiple times.? Thanks, Stanni
You could use [Variable variables](http://us.php.net/language.variables.variable): ``` for($x = 1; $x <= 5; $x++) { print ${"variable".$x}; } ``` However, whatever it is you're doing there is almost certainly a better way: probably using Arrays.
I second Paolo Bergantino. If you can use an array that would be better. If you don't how to do that, here you go: Instead of making variables like: ``` $var1='foo'; $var2='bar'; $var3='awesome'; ``` ... etc... you can make a singe variable called an array like this: ``` $my_array = array('foo','bar','awesome'); ``` Just so you know, in an array, the first element is the 0th element (not the 1st). So, in order to echo out 'foo' and 'bar' you could do: ``` echo $my_array[0]; // echoes 'foo' echo $my_array[1]; // echoes 'bar' ``` But, the real benefits of putting value in an array instead of a bunch of variables is that you can loop over the array like this: ``` foreach($my_array as $item) { echo $item; } ``` And that's it. So, no matter how many items you have in your array it will only take those three lines to print them out. Good luck you with learning PHP!
"Large multiple variable echo's" way to make simpler?
[ "", "php", "arrays", "variables", "" ]
It seems that in IE8, if the page using https protocol needs to import a .js file, the .js file also needs to use the https protocol. ``` <script type="text/javascript" src="http://xxx/yourjs.js"></script> ``` works in all browsers except IE8 ``` <script type="text/javascript" src="https://xxx/yourjs.js"></script> ``` works in all browsers I am using a usercontrol which imports several .js files. This means that if one page uses https protocol, then I have to alter the usercontrol so that all imported .js files are using https protocol. How do you resolve this issue? How do you comment on this IE8 behavior?
Using this on HTTPS ``` <script type="text/javascript" src="http://xxx/yourjs.js"></script> ``` should throw up a warning to the user in all browsers - I'd expect IE8 to do the same but maybe it's a new "feature" to silently ignore it. You should use the same protocol that the request is on, or failing that always HTTPS (though this will be slower for the user and put more load on your server). You could specify the URL without the scheme - that should use the current one (http or https): ``` <script type="text/javascript" src="//xxx/yourjs.js"></script> ``` Edit: Found the reference saying this is valid: [RFC 2396](http://www.ietf.org/rfc/rfc2396.txt) > ``` > relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] > ``` > > A relative reference beginning with > two slash characters is termed a > network-path reference, as defined by > in Section 3. Such > references are rarely used.
This is correct behaviour. You don't want non-secure resources to be a part of your secure page. In previous versions of IE a warning was displayed, but I guess the feeling is that too many people just said "go ahead" without knowing what the implications were. The error is now silent. You can adjust your security settings, but that will only fix your browser (and as I mentioned, it's not a good idea). Make sure your page resources are all secure on your secure pages. (Images, Iframe sources, scripts... the lot!)
Importing js file in https page using http URL in IE8
[ "", "javascript", "internet-explorer", "" ]
Have a series of functions I am calling dynamically sort of like this: ``` $function = 'someFunction'; $x = $function(); ``` .. however, if the function expects parameters, and I don't code it in the call, I seem to crash the page. For example: ``` function someFunction( $in_param1 ) { return "SUCCESS"; } $function = 'someFunction'; // this next line does not work $x = $function() or die("error"); ``` How can I handle this kind of error? Thanks -
You can catch this using the [set\_error\_handler](http://us.php.net/manual/en/function.set-error-handler.php) function: ``` function handle_errors( $errno, $errstr ) { die( "Your error will be caught here" ); } set_error_handler( "handle_errors" ); $function = 'someFunction'; $x = $function(); ```
Suppress? Yes. Catch? [See don.neufeld's answer](https://stackoverflow.com/questions/779534/suppress-or-catch-invalid-function-call-php/779539#779539). ``` $x = @$function(); ``` According to [this page](http://us.php.net/operators.errorcontrol), you can enable a specific INI setting so that you can read errors suppressed in this manner.
Suppress or catch() invalid function call - PHP
[ "", "php", "" ]
I am using BeautifulSoup and urllib2 for downloading HTML pages and parsing them. Problem is with mis formed HTML pages. Though BeautifulSoup is good at handling mis formed HTML still its not as good as Firefox. Considering that Firefox or Webkit are more updated and resilient at handling HTML I think its ideal to use them to construct and normalize DOM tree of a page and then manipulate it through Python. However I cant find any python binding for the same. Can anyone suggest a way ? I ran into some solutions of running a headless Firefox process and manipulating it through python but is there a more pythonic solution available.
Perhaps [pywebkitgtk](http://code.google.com/p/pywebkitgtk/) would do what you need.
see <http://wiki.python.org/moin/WebBrowserProgramming> there are quite a lot of options - i'm maintaining the page above so that i don't keep repeating myself. you should look at pyjamas-desktop: see the examples/uitest example because we use exactly this trick to get copies of the HTML page "out", so that the python-to-javascript compiler can be tested by comparing the page results after each unit test. each of the runtimes supported and used by pyjamas-desktop is capable of allowing access to the "innerHTML" property of the document's body element (and a hell of a lot more). bottom line: it is trivial to do what you want to do, but you have to know where to look to find out how to do it. l.
Using Gecko/Firefox or Webkit got HTML parsing in python
[ "", "python", "html", "parsing", "" ]
save dialog saves file to the local machine. But after that, my page stand there and do nothing for the rest of my process. I use below code to open a save dialog ``` protected void lnkbtnDownload_Click(object sender, EventArgs e) { string fileName = startupPath + "bin\\Inbox.mdb"; System.IO.FileInfo targetFile = new System.IO.FileInfo(fileName); if (targetFile.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + targetFile.Name); Response.AddHeader("Content-Length", targetFile.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(targetFile.FullName); Response.End(); } } ``` the html code is : ``` <asp:Button id="lnkbtnDownload" runat="server" CausesValidation="false" Text="Download" CssClass="buttonstyle" OnClick="lnkbtnDownload_Click"></asp:Button> ``` but after the file is save to local machine and the save dialog is close, my page no response at all. May I know how to do a postback to the page after the save dialog is close.?
Because you are calling Response.End, this halts the response of the page.
Put this code within an HttpHandler and then link to that handler from the original page, passing in whatever information your handler needs.
Page Refresh in ASP.NET
[ "", "c#", "asp.net", "" ]
I have been interested in SSD drives for quite sometime. I do a lot of work with databases, and I've been quite interested to find benchmarks such as TPC-H performed with and without SSD drives. On the outside it sounds like there would be one, but unfortunately I have not been able to find one. The closest I've found to an answer was the first comment in this blog post. <http://dcsblog.burtongroup.com/data_center_strategies/2008/11/intels-enterprise-ssd-performance.html> The fellow who wrote it seemed to be a pretty big naysayer when it came to SSD technology in the enterprise, due to a claim of lack of performance with mixed read/write workloads. There have been other benchmarks such as [this](http://www.anandtech.com/storage/showdoc.aspx?i=3531&p=25) and [this](http://www.tomshardware.com/reviews/intel-x25-e-ssd,2158-5.html) that show absolutely ridiculous numbers. While I don't doubt them, I am curious if what said commenter in the first link said was in fact true. Anyways, if anybody can find benchmarks done with DBs on SSDs that would be excellent.
I've been testing and using them for a while and whilst I have my own opinions (which are very positive) I think that Anandtech.com's testing document is far better than anything I could have written, see what you think; <http://www.anandtech.com/show/2739> Regards, Phil.
The issue with SSD is that they make real sense only when the schema is normalized to 3NF or 5NF, thus removing "all" redundant data. Moving a "denormalized for speed" mess to SSD will not be fruitful, the mass of redundant data will make SSD too cost prohibitive. Doing that for some existing application means redefining the existing table (references) to views, encapsulating the normalized tables behind the curtain. There is a time penalty on the engine's cpu to synthesize rows. The more denormalized the original schema, the greater the benefit to refactor and move to SSD. Even on SSD, these denormalized schemas will run slower, likely, due to the mass of data which must be retrieved and written. Putting logs on SSD is not indicated; this is a sequential write-mostly (write-only under normal circumstances) operation, physics of SSD (flash type; a company named Texas Memory Systems has been building RAM based sub-systems for a long time) makes this non-indicated. Conventional rust drives, duly buffered, will do fine. Note the anandtech articles; the Intel drive was the only one which worked right. That will likely change by the end of 2009, but as of now only the Intel drives qualify for serious use.
TPC or other DB benchmarks for SSD drives
[ "", "sql", "database", "hardware", "benchmarking", "solid-state-drive", "" ]
Something I have found myself doing often lately is declaring typedefs relevant to a particular class inside that class, i.e. ``` class Lorem { typedef boost::shared_ptr<Lorem> ptr; typedef std::vector<Lorem::ptr> vector; // // ... // }; ``` These types are then used elsewhere in the code: ``` Lorem::vector lorems; Lorem::ptr lorem( new Lorem() ); lorems.push_back( lorem ); ``` Reasons I like it: * It reduces the noise introduced by the class templates, `std::vector<Lorem>` becomes `Lorem::vector`, etc. * It serves as a statement of intent - in the example above, the Lorem class is intended to be reference counted via `boost::shared_ptr` and stored in a vector. * It allows the implementation to change - i.e. if Lorem needed to be changed to be intrusively reference counted (via `boost::intrusive_ptr`) at a later stage then this would have minimal impact to the code. * I think it looks 'prettier' and is arguably easier to read. Reasons I don't like it: * There are sometimes issues with dependencies - if you want to embed, say, a `Lorem::vector` within another class but only need (or want) to forward declare Lorem (as opposed to introducing a dependency on its header file) then you end up having to use the explicit types (e.g. `boost::shared_ptr<Lorem>` rather than `Lorem::ptr`), which is a little inconsistent. * It may not be very common, and hence harder to understand? I try to be objective with my coding style, so it would be good to get some other opinions on it so I can dissect my thinking a little bit.
I think it is excellent style, and I use it myself. It is always best to limit the scope of names as much as possible, and use of classes is the best way to do this in C++. For example, the C++ Standard library makes heavy use of typedefs within classes.
> It serves as a statement of intent - > in the example above, the Lorem class > is intended to be reference counted > via boost::shared\_ptr and stored in a > vector. This is exactly what it does *not* do. If I see 'Foo::Ptr' in the code, I have absolutely no idea whether it's a shared\_ptr or a Foo\* (STL has ::pointer typedefs that are T\*, remember) or whatever. *Esp.* if it's a shared pointer, I don't provide a typedef at all, but keep the shared\_ptr use explicitly in the code. Actually, I hardly ever use typedefs outside Template Metaprogramming. > The STL does this type of thing all the time The STL design with concepts defined in terms of member functions and nested typedefs is a historical cul-de-sac, modern template libraries use free functions and traits classes (cf. Boost.Graph), because these do not exclude built-in types from modelling the concept and because it makes adapting types that were not designed with the given template libraries' concepts in mind easier. Don't use the STL as a reason to make the same mistakes.
Internal typedefs in C++ - good style or bad style?
[ "", "c++", "coding-style", "typedef", "" ]
When a user log in into my application i want to show his name throughout the whole application. I am using the asp.net MVC framework. But what i don't want is that is have to put in every controller something like: ``` ViewData["User"] = Session["User"]; ``` This because you may not repeat yourself. (I believe this is the DRY [Don't Repeat Yourself] principle of OO programming.) The ViewData["User"] is on my masterpage. So my question is, what is a neat way to handle my ViewData["User"] on one place?
You can do this fairly easily in either a controller base-class, or an action-filter that is applied to the controllers/actions. In either case, you get the chance to touch the request before (or after) the action does - so you can add this functionality there. For example: ``` public class UserInfoAttribute : ActionFilterAttribute { public override void OnActionExecuting( ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); filterContext.Controller.ViewData["user"] = "Foo"; } } ... [HandleError, UserInfo] public class HomeController : Controller {...} ``` (can also be used at the *action* (method) level) --- or with a common base-class: ``` public abstract class ControllerBase : Controller { protected override void OnActionExecuting( ActionExecutingContext filterContext) { ViewData["user"] = "Bar"; base.OnActionExecuting(filterContext); } } [HandleError] public class HomeController : ControllerBase {...} ```
It's been a year, but I've just stumbled across this question and I believe there's a better answer. Jimmy Bogard describes the solution described in the accepted answer as an anti-pattern and offers a better solution involving `RenderAction`: <http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/18/the-filter-viewdata-anti-pattern.aspx>
C# Centralizing repeating VIewData in MVC
[ "", "c#", "asp.net-mvc", "viewdata", "" ]
I've got a medium sized (25k lines code, 25k lines tests) codebase in java, and would like to port it to run on a CLR as well as the JVM. Only the main class, and a few testing utilities deal with the file system or OS in any way. The rest of the code uses the generic collections APIs extensively, java.util.regex, java.net (but not URL or URLConnection), java.io for charset encoding/decoding, java.text for unicode normalization, and org.w3c.dom for XML manipulation. Is it possible to get most of the codebase compiling under both J# and Java, and then port the rest? If so, what kind of pitfalls am I likely to run into? thanks in advance, mike
Check out IKVM: <http://www.ikvm.net/> It allows you to run (specially compiled) Java code inside the .Net CLR. Some of my colleages have used it successfully with a Java codebase of 1 million+ lines of code.
Pitfalls: * Anything like this scares the heck out of me. The number of really subtle bugs waiting to happen is huge. * J# only supports Java 1.1.4 AFAIK - goodbye generics etc. * Visual Studio 2008 doesn't support J# - basically it's a dead project. I suspect that you'd actually find it simpler to rewrite it in C# (including learning C# if you don't already know it - it's a joy). You'll end up with a more idiomatically .NET-like library that way as well, if that's relevant: if you ever want another .NET developer to consume your code, they're likely to be far happier with a "pure" .NET project than one using J#. The downside is that going forward, any changes would also need to be made in two places. There's certainly pain there, but I really think you'll have a better experience using "normal" .NET.
Problems porting Java to J#
[ "", "java", "clr", "j#", "" ]
I'm having a problem with the ID property of dynamically loaded UserControls changing during the Page lifecycle. More specifically the ID property changes when the system calls Page.Form.RenderControl(htmlTextWriter); Before it is called the control has ID "ctl84", but after the call it has ID "ctl99". The output from htmlTextWriter contains the original ID, however inspecting the Control's ID property in the VS 2008 debugger reveals that it has changed. The application is running inside an MCMS 2002 (Microsoft CMS 2002) framework using .NET 2.0, converted from 1.1 and xhtmlConformance="Legacy" is not enabled. I need the ID to be constant throughout the Page lifecycle. Edit: Setting the ID property manually is not an option.
Are you explicitly assigning an ID to the control from code? If you are the ID should stay the same. It doesn't explain why it's changing though - my guess is ... is not the **same** control. Chances are for some reason you control generation routine is running twice or smt like that. Put a breakpoint where the control is genretated and see if it gets hit twice - If so, there you go, that's your problem.
to be sure it's the same instance of the control and not another, check the GetHashCode() method of the control.
ASP.NET Dynamic UserControl ID generation problem
[ "", "c#", ".net", "asp.net", "user-controls", "" ]
I have a long list of SPs (stored procedure) and Functions in my SQL server db. I could save them one by one by right clicking and script XXX to Alter To. Is there any way in TSQL to query all SPs and functions save them to xxx.sql files? For example, for sp\_mySP1, I would like to save it to sp\_mySP1.sql which is a text file. The database is too big and I would like save only SPs and functions as a backup of source codes.
In management studio; find the database, right-click, tasks, generate scripts; next-next-next until you "Choose Object Types". Select "Stored procedures" and "User-defined functions", next, Select All; choose an output; go!
1) Right-click on your Database name in the Object Explorer 2) Select "Tasks > Generate Scripts..." from the Context menu 3) Select your Database in the list and click Next 4) Click Next on the Chose Script Options 5) In Object Types, check Stored Procedures and User-defined functions, click Next 6) Click Select All on the Stored Procedures selection screen, click Next 7) Click Select All on the Functions selection screen, click Next 8) Select 'Script to New Query Window' and click Finish
Quick way to backup SQL SP and Functions?
[ "", "sql", "sql-server", "t-sql", "" ]
Say I want to print: ``` ============ Some message ============ ``` And: ``` ======================= Other Message long one ======================= ``` The number of "=" changes based on the message length. What is the most efficient way to print this sort of a thing? No boost, just STL please.
``` std::string line(msg.length(), '='); cout << line << "\n" << msg << "\n" << line << endl; ```
You don't specify how you are measuring "efficiency" in this context. Here's one solution that is efficient in terms of code you must write and number of allocations: ``` #include <string> #include <iostream> using namespace std; void format(const std::string& msg) { std::string banner(msg.length(), '='); cout << banner << endl << msg << endl << banner << endl; } int main(int argc, char *argv[]) { format("Some message"); format("Other message long one"); return 0; } ``` I can imagine other alternatives that avoid allocating a temporary string for the banners, but those might come at an increased cost of the actual printing.
Printing a custom number of header delimiters based on message length
[ "", "c++", "stl", "" ]
I've just finished [my entry](http://tametick.com/fwod/) for the 14th Ludum Dare 48-hours game making competition yesterday, and decided to do it in java using java2d for the graphics. I'm not that familiar with the API and haven't done a lot of graphics programming, but my game is quite small (only a dozen or so very small moving object) so I assumed I could program it naively and still encounter no performance problems. Needless to say, I was wrong. The game performs alright most of the time but once there are a bit too many 'enemies' moving around on the screen or the resolution is cranked up too high it start getting visibly slower. I've determined the performance bottleneck to be the screen drawing functions, when those are commented out the game is very fast. Could someone give me a heads up on what I might be doing wrong here? The (very short) source code is located [here](http://github.com/ido/ludum-dare-2009/tree/master) with most of it the [Main](http://github.com/ido/ludum-dare-2009/blob/b3e8d300227c52f890ad72f9708a5e717a903386/src/Main.java) class, with the usual suspects being the [draw()](http://github.com/ido/ludum-dare-2009/blob/b3e8d300227c52f890ad72f9708a5e717a903386/src/Main.java#L123) function that is called in the [inner game loop](http://github.com/ido/ludum-dare-2009/blob/b3e8d300227c52f890ad72f9708a5e717a903386/src/Main.java#L285). I already use a [BufferStrategy](http://github.com/ido/ludum-dare-2009/blob/b3e8d300227c52f890ad72f9708a5e717a903386/src/Main.java#L337) to update the screen, so that shouldn't be the problem unless I'm doing it wrong. Thanks in advance, Ido.
A few observations, although I don't think any of them will help much. The main thing is that you're painting off of the AWT thread. Override paintComponent() and instead call repaint() on the object. This can cause all sorts of problems otherwise. You recreate colors every frame. This may or may not be one of those things that you want to cache. I don't think though that having a constant for your colors is likely to screw up GCing and will make things easier to keep straight when you want to reuse colors later. You redraw the entire window every frame. You just need to repaint the sections that changed. You don't need to draw the background. Set the background color and let the parent take care of everything. As a design thing, the bodies should be in charge of drawing themselves. Their owner should notify them that they need to be drawn rather than drawing them. The bodies recreate their state every time. Consider having them store it between times and mutate them as needed. You may be spending a lot of time doing trig calculations in the drawCircleBody() Something to consider is setting up a timer rather than using a sleep in a while loop. This will get you a more consistent frame rate, but you need to make sure that you can actually meet your obligations (or coalesce multiple frames into one if you miss a deadline) or you'll end up creating too many threads. Consider using a [SwingWorker](http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html) to do the calculations, then update the state in the done() method, finishing by calling repaint(). These are just a few things. You should experiment to see what works and what doesn't. It's been a while since I've done Java graphics drawing.
Your code isn't following the single threading rule: <http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html> I'm not sure if this will cause the specific performance problems that you are seeing, but it stands out as a big potential problem, imo.
Horrendous Performance in a Simple Java2D App
[ "", "java", "performance", "java-2d", "" ]
Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily. For instance, if I set my settings so that the line: ``` print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message) ``` is displayed when wrapped as: ``` print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message) ``` then if I write a block of code like this: ``` def __repr__(self): return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message) ``` it wraps to something like this: ``` def __repr__(self): return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message) ``` I would prefer for it to be displayed as: ``` def __repr__(self): return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message) ``` **Edit:** after reading Don Werve's response, it seems that I am indeed looking for the `breakindent` option, but the option is still on the "Awaiting updated patches" list (see [Vim TODO](http://vimdoc.sourceforge.net/htmldoc/todo.html)). So what I'd like to know is what is the *easiest way* to get vim working with `breakindent`? (I don't care what version of vim I have to use.)
You're looking for `breakindent` You may want to also refer to [this thread](http://newsgroups.derkeiler.com/Archive/Comp/comp.editors/2005-07/msg00056.html).
I asked the [same question on SuperUser](https://superuser.com/questions/72714/vim-line-wrap-with-indent), eventually found this question, found the patch, and [updated the patch](https://retracile.net/blog/2009/11/20/12.00) to work with Vim 7.2.148 from Fedora 11. You can use `yumdownloader --source vim` to get the source RPM. Then add a `Patch3312:` line and a `%patch3012 -p1` line to the spec file, and build the rpm.
How do I make text wrapping match current indentation level in vim?
[ "", "python", "vim", "word-wrap", "" ]
I am new to SQL programming. I have a table job where the fields are `id`, `position`, `category`, `location`, `salary range`, `description`, `refno`. I want to implement a **keyword search** from the front end. The keyword can reside in any of the fields of the above table. This is the query I have tried but it consist of so many duplicate rows: ``` SELECT a.*, b.catname FROM job a, category b WHERE a.catid = b.catid AND a.jobsalrange = '15001-20000' AND a.jobloc = 'Berkshire' AND a.jobpos LIKE '%sales%' OR a.jobloc LIKE '%sales%' OR a.jobsal LIKE '%sales%' OR a.jobref LIKE '%sales%' OR a.jobemail LIKE '%sales%' OR a.jobsalrange LIKE '%sales%' OR b.catname LIKE '%sales%' ```
For a single keyword on VARCHAR fields you can use [`LIKE`](http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html): ``` SELECT id, category, location FROM table WHERE ( category LIKE '%keyword%' OR location LIKE '%keyword%' ) ``` For a description you're usually better adding a full text index and doing a [Full-Text Search](http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html) (MyISAM only): ``` SELECT id, description FROM table WHERE MATCH (description) AGAINST('keyword1 keyword2') ```
``` SELECT * FROM yourtable WHERE id LIKE '%keyword%' OR position LIKE '%keyword%' OR category LIKE '%keyword%' OR location LIKE '%keyword%' OR description LIKE '%keyword%' OR refno LIKE '%keyword%'; ```
How to implement a Keyword Search in MySQL?
[ "", "sql", "mysql", "search", "" ]
I'm looking for an open source project written in Java with a relatively low barrier to entry, ie. not hugely complex, friendly, etc. My background is mostly in web apps so, that'd be the best place for me to start. Mostly, I'm just looking for some place I can do some stuff in free time and keep my chops polished. I plan on browsing through various public listings but thought I'd see if the Stack Overflow community had any suggestions. Maybe someone even has a pet project...
Many of the [Apache Foundation](http://www.apache.org/) projects are Java. Take a look at them and see what you are interested in.
It depends on field of intrest e.g. medical, engineering, communications, etc. [SourceForge](http://www.sourceforge.net) classifies open source projects as such. Check it out.
What is an open source Java project I could contribute to?
[ "", "java", "open-source", "" ]
Instead of doing the following everytime ``` start(); // some code here stop(); ``` I would like to define some sort of macro which makes it possible to write like: ``` startstop() { //code here } ``` Is it possible in C++?
You can do something very close using a small C++ helper class. ``` class StartStopper { public: StartStopper() { start(); } ~StartStopper() { stop(); } }; ``` Then in your code: ``` { StartStopper ss; // code here } ``` When execution enters the block and constructs the `ss` variable, the `start()` function will be called. When execution leaves the block, the `StartStopper` destructor will be automatically called and will then call `stop()`.
The idiomatic way of doing this in C++ is called [Resource Acquisition Is Initialization](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization), or shortly RAII. In addition to providing what you want, it also has the added benefit of being exception safe: the `stop` function will be called even if your code throws an exception. Define a guard struct: ``` struct startstop_guard { startstop_guard() { start(); } ~startstop_guard() { stop(); } }; ``` and then rewrite your code this way: ``` { startstop_guard g; // your code } ``` The guard's destructor (and thus the `stop` function) will be called automatically at the end of the enclosing block.
c++ #define a macro with brackets?
[ "", "c++", "macros", "" ]
I'm trying to scale a rectangle from its center using AffineTransform. I'm sure the solution is obvious but I cannot make it work ! Here is what I've tested so far... ``` import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import javax.swing.JOptionPane; import javax.swing.JPanel; public class Test extends JPanel { Test() { super(null); setOpaque(true); setBackground(Color.WHITE); setPreferredSize(new Dimension(200,200)); } @Override protected void paintComponent(Graphics g1) { super.paintComponent(g1); Rectangle r= new Rectangle(5,5,getWidth()-10,getHeight()-10); double cx= r.getCenterX(); double cy= r.getCenterY(); Graphics2D g=(Graphics2D)g1; g.setColor(Color.BLACK); AffineTransform old= g.getTransform(); for(double zoom=0.9; zoom>=0.5; zoom-=0.1) { AffineTransform tr2= new AffineTransform(old); tr2.translate(-cx, -cy); tr2.scale(zoom, zoom); tr2.translate(cx/zoom,cy/zoom); g.setTransform(tr2); g.draw(r); g.setTransform(old); } } public static void main(String[] args) { JOptionPane.showMessageDialog(null, new Test()); } } ``` But it doesn't work.... Any suggestion ?
I see what you mean when you're dealing with rectangles. The reason is because the initial calculation for the translation didn't take into account the size of the container object. Use this instead: ``` tr2.translate( (this.getWidth()/2) - (r.getWidth()*(zoom))/2, (this.getHeight()/2) - (r.getHeight()*(zoom))/2 ); tr2.scale(zoom,zoom); g.setTransform(tr2); ``` What this is doing is translating the rectangle to the center of the panel before scaling it. In my tests it works just fine.
Assuming scaling fixes the location of the top lefthand corner of the rectangle (which I think is right but it's been a long time since I've done graphics in Java), you need to translate the rectangle in the direction opposite to the scaling. ``` tr2.translate( r.getWidth()*(1-zoom)/2, r.getHeight()*(1-zoom)/2 ); tr2.scale(zoom,zoom); g.setTransform(tr2); ``` So you move the rectangle left and up half of the change in width and height.
AffineTransform: scaling a Shape from its center
[ "", "java", "swing", "geometry", "shapes", "affinetransform", "" ]
I am looking for an good explanation, maybe with some examples. In my understanding, something is "generic" when it can be used for multiple purposes. But I may be wrong...
Do you want a "generic" definition, or within a specific context? In a general sense, "generic" describes a process or structure that does not itself enforce a rigid context within which it must be called. At the same time, it must understand enough about its context to be meaningful. For example, a generic structure for adding numbers would not care whether given floating-point or integer arguments, but would have difficulty adding Q + Pi. To some extent, this is foundational to object-oriented programming. However, many programming languages use the term "generic" in a much more restrictive sense. Within those languages, a generic class can be strongly typed at run-time to any class that implements a known "interface" (in a general sense...) that the subscriber knows how to interact with. Languages vary widely on how they implement and support this, so concrete examples may not provide much more insight unless you identify the desired language up front.
The root is the same as "genus" -- it means describing all the members of a group of related things. In programming terms, it means you're describing a whole collection of things that share a common pattern or template, with only small variations. C++ templates and Java generics are, to the programmer, more or less the same thing: a way of saying "whatever the underlying type is, I want to be able to do these things." The implementaiton methods are different, but the idea is the same. So the idea is, itself, somewhat generic.
What is the best explanation for the term "generic"?
[ "", "java", "objective-c", "generics", "terminology", "" ]
I'm writing my own scripting language in C#, with some features I like, and I chose to use MSIL as output's bytecode (Reflection.Emit is quite useful, and I dont have to think up another bytecode). It works, emits executable, which can be run ( even decompiled with Reflector :) )and is quite fast. But - I want to run multiple 'processes' in one process+one thread, and control their assigned CPU time manually (also implement much more robust IPC that is offered by .NET framework) Is there any way to entirely disable JIT and create own VM, stepping instruction-after-instruction using .NET framework (and control memory usage, etc.), without need to write anything on my own, or to achieve this I must write entire MSIL interpret? EDIT 1): I know that interpreting IL isn't the fastest thing in the universe :) EDIT 2): To clarify - I want my VM to be some kind of 'operating system' - it gets some CPU time and divides it between processes, controls memory allocation for them, and so on. It doesnt have to be fast, nor effective, but just a proof of concept for some of my experiments. I dont need to implement it on the level of processing every instruction - if this should be done by .NET, I wont mind, i just want to say : step one instruction, and wait till I told you to step next. EDIT 3): I realized, that ICorDebug can maybe accomplish my needs, now looking at implementation of Mono's runtime.
You could use [Mono](http://mono-project.com/Main_Page) - I believe that allows an option to interpret the IL instead of JITting it. The fact that it's open source means (subject to licensing) that you should be able to modify it according to your needs, too. Mono doesn't have all of .NET's functionality, admittedly - but it *may* do all you need.
Beware that MSIL was designed to be parsed by a JIT compiler. It is not very suitable for an interpreter. A good example is perhaps the ADD instruction. It is used to add a wide variety of value type values: byte, short, int32, int64, ushort, uint32, uint64. Your compiler knows what kind of add is required but you'll lose that type info when generating the MSIL. Now you need to find it back at runtime and that requires checking the types of the values on the evaluation stack. Very slow. An easily interpreted IL has dedicated ADD instructions like ADD8, ADD16, etc.
Turning off JIT, and controlling codeflow in MSIL (own VM)
[ "", "c#", "interpreter", "jit", "cil", "" ]
I'm wondering if `string.Length` in C# is an instant variable. By instant variable I mean, when I create the string: ``` string A = ""; A = "Som Boh"; ``` Is length being computed now? OR Is it computed only after I try to get A.Length?
Firstly, note that strings in .NET are very different to strings stored in unmanaged languages (such as C++)... 1. In the CLR, the length of the string (in chars and in bytes) is in fact stored in memory so that the CLR knows how large the block of memory (array of chars) containing the string is. This is done upon creation of the string and doesn't get changed given that the `System.String` type is immutable. 2. In C++ this is rather different, as the length of a string is discovered by reading up until the first null character. Because of the way memory usage works in the CLR, you can essentially consider that getting the `Length` property of a string is just like retrieving an `int` variable. The performance cost here is going to be absolutely minimal, if that's what you're considering. If you want to read up more about strings in .NET, try [Jon Skeet's article](http://www.yoda.arachsys.com/csharp/strings.html) on the topic - it seems to have all the details you might ever want to know about strings in .NET.
The length of the string is not computed, it is known at construction time. Since String is immutable, there will be no need for calculating it later. A .NET string is stored as a field containing the count of characters, and a corresponding series of unicode characters.
Is string.Length in C# (.NET) instant variable?
[ "", "c#", ".net", "string", "" ]
I am wondering if it is possible to write php code to a file. For example: ``` fwrite($handle, "<?php $var = $var2 ?>"); ``` I would like it produce the exact string in the file and not the eval'ed code. Is this possible? I am currently getting the following output (where $var = 1 and $var2 = 2): ``` <?php 1 = 2 ?> ``` Whereas I want the actual string: ``` <?php $var = $var2 ?> ``` Thanks for the help
You can use single quotes instead of double quotes, which do not expand inline variable names: ``` fwrite($handle, '<?php $var = $var2 ?>'); ```
Just escape the $ symbol ``` <?php fwrite($handle, "<?php \$var = \$var2 ?>"); ?> ```
Writing PHP Code to a File
[ "", "php", "quotes", "" ]
I think this is a situation every Java programmer runs into if they do it long enough. You're doing some debugging and make a change to class. When you go to re-run the program, these changes don't seem to be picked up but rather the old class still seems to be running. You clean and rebuild everything, same issue. Sometimes, this can come down to a classpath issue, of the same class being on the classpath more than once, but there doesn't seem to be an easy way to figure out where the class being loaded is coming from... Is there any way to find the file path for the class that was loaded? Preferable something that would work either if the class was loaded from a `.class` file or a `.jar` file. Any Ideas?
Simply run `java` using the standard command line switch"`-verbose:class`" (see [the `java` documentation](http://java.sun.com/javase/6/docs/technotes/tools/solaris/java.html)). This will print out each time a class is loaded and tell you where it's loaded from.
If you wanted to do it programmatically from inside the application, try: ``` URL loc = MyClass.class.getProtectionDomain().getCodeSource().getLocation(); ``` (Note, getCodeSource() may return null, so don't actually do this all in one line :) )
Where on the file system was my Java class loaded from?
[ "", "java", "debugging", "classloader", "" ]
Is it any easy way to use CherryPy as an web server that will display `.html` files in some folder? All CherryPy introductory documentation states that content is dynamically generated: ``` import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True cherrypy.quickstart(HelloWorld()) ``` Is it any easy way to use `index.html` instead of HelloWorld.index() method?
This simple code will serve files on current directory. ``` import os import cherrypy PATH = os.path.abspath(os.path.dirname(__file__)) class Root(object): pass cherrypy.tree.mount(Root(), '/', config={ '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': PATH, 'tools.staticdir.index': 'index.html', }, }) cherrypy.quickstart() ```
Here is some information on serving static content with CherryPy: <http://docs.cherrypy.org/stable/progguide/files/static.html> BTW, here is a simple way to share the current directory over HTTP with python: ``` # Python 3 $ python -m http.server [port] # Python 2 $ python -m SimpleHTTPServer [port] ```
How to use cherrypy as a web server for static files?
[ "", "python", "cherrypy", "" ]
I have a div: ``` <div class="test" id="someElement" style="position: absolute"></div> ``` Is there any way to check if the certain element: ``` $("#someElement") ``` has a particular class (in my case, "test"). Alternately, is there a way to check that en element has a certain style? In this example, I'd like to know if the element has "`position: absolute`". Thank you very much!
``` if($('#someElement').hasClass('test')) { ... do something ... } else { ... do something else ... } ```
CSS Styles are key-value pairs, not just "tags". By default, each element has a full set of CSS styles assigned to it, most of them is implicitly using the browser defaults and some of them is explicitly redefined in CSS stylesheets. To get the value assigned to a particular CSS entry of an element and compare it: ``` if ($('#yourElement').css('position') == 'absolute') { // true } ``` If you didn't redefine the style, you will get the browser default for that particular element.
Jquery: How to check if the element has certain css class/style
[ "", "javascript", "jquery", "css", "" ]
Following is a part of my code for a project: ``` public class Body extends Point{ public double x, y, mass; public Body() { x = y = mass = 0; } public Body(double x, double y, double mass) { this.mass = mass; this.x = x; this.y = y; } } public class Point { public double x; public double y; public Point(double x, double y) { this.x = x; this.y = y; } } ``` I quickly realized that doing this will create **two** variables inside the Body class called x and two other variables in Body called y. How is this even possible, and why on earth does Java even allow it? I assume this is the correct code of class Body: ``` public class Body extends Point{ public double mass; public Body() { super(); mass = 0; } public Body(double x, double y, double mass) { super(x,y); this.mass = mass; } } ``` Thanks for your time
In a sense, you are overriding fields of the super class. But it's far easier to do accidentally because there is no overloading of fields (you only have one variable of a given name, the type doesn't matter). This is referred to as variable 'hiding' or 'shadowing'. So, you're correct, you'll end up with two fields with the same name. Your second example is correct. They are inherited from the super-class and since they are not declared private, they are visible to the subclass. It's generally bad practice to refer directly to a super-class's fields, and unless there is good reason, they should declared private. Your example of invoking the super constructor is the best approach. Also, if you hide a field with another of the same name, you can still refer to them as super.x, super.y, vs. this.x, this.y, you should avoid this situation if at all possible.
Yes, you'll have two variables, with one hiding the other. It makes sense to allow it for two reasons: 1. Suppose you've got a base class `Base` and a derived class `Derived` which the author of `Base` has no idea about. Should the author of `Base` never be able to add any fields, just because a derived class *might* share the fields? Or should `Derived` stop compiling when the change to `Base` doesn't actually affect the correctness? 2. Your fields should almost always be private, at which point it doesn't matter whether the names are duplicated or not - neither "side" will know about the variables of the other.
Having 2 variables with the same name in a class that extends another class in Java
[ "", "java", "class", "variables", "scope", "extends", "" ]
I've been using Emacs for quite some time for basic text editing but as of today I am attempting to use it for c++ compilation. I have looked for the past few hours about how to go about this but I keep hitting roadblocks in their techniques (I think some of this is having to do with the tutorials being outdated). Basically, all I want to do is be able to compile C++ programs that I write in Emacs through the 'M-x compile' command. So far I have installed Cygwin and downloaded the packages for gcc. I have attempted some other solutions presented by tutorials online but they didn't pan out. Thank you.
The `M-x compile` command calls out to a shell (e.g. linux `bash`, windows `cmd.exe`, etc) to run the `make` command. On windows I think emacs defaults to the `cmd.exe` shell (through a special `C:/Program Files/Emacs/emacs/bin/cmdproxy.exe` executable). If you want your `M-x compile` to use a different shell (probably cygwin `bash` in your case) then you need to tell emacs through changing `shell-file-name` variable or using the `SHELL` environment variable. You will also need to make sure that the cygwin `make` is found by changing `exec-path` variable (or using `PATH` environment variable). To do this: ``` (setq shell-file-name "C:/cygwin/bin/bash.exe") (setq exec-path (cons "C:/cygwin/bin" exec-path)) ``` And you could also look at [setup-cygwin.el](http://www.emacswiki.org/emacs/setup-cygwin.el) to set this up and some other things for cygwin.
After installing a compiler. You can use the following snippet to customize compile command ``` (add-hook 'c++-mode-hook (lambda () (unless (file-exists-p "Makefile") (set (make-local-variable 'compile-command) (let ((file (file-name-nondirectory buffer-file-name))) (concat "g++ -g -O2 -Wall -o " (file-name-sans-extension file) " " file)))))) ```
Compiling C++ Programs with Emacs on Windows
[ "", "c++", "emacs", "gcc", "ide", "" ]