Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
There is large website all data comes from database , I want to remove all instances of "(MHC)" from next to company name on this page, and also more than 12 other pages. like "**Northfield Bancorp Inc. (MHC)**" to "Northfield Bancorp Inc." Is there any JavaScript for this? I have tried [xslt solution](https://stackoverflow.com/questions/1003981/replacing-xml-value-in-xslt), but still prefer a JavaScript solution.
First of all, I'd just change the database entry... Furthermore, you should be doing this removal on the server side. For example, you can use PHP to reformat the data before outputting it to the user. Simply use PHP to make the database query, store it in a PHP variable, and then parse the string appropriately.
Just do a replace: ``` var data = "Northfield Bancorp Inc. (MHC)"; var newData = data.replace(" (MHC)", "", "ig"); ```
How to replace text using JavaScript?
[ "", "javascript", "xhtml", "" ]
Im currently adding toolstrips from my seperate modules like: ``` this.toolStripContainer.TopToolStripPanel.Controls.Add(module.Instance.Toolbar) ``` Buy they are then in the order that the modules are loaded which isnt very good. Is there any way to re-order them? Or should I be looking at adding some sort of index to my modules and laoding them in the order that I want the toolstrips?
I ended up adding all the toolstrips to a list... sorting the list by ToolStrip.Tag... and then adding them to the control list... This allows the module writer to set a priority for the toolstrip, kind of like toolstrip merging
The Controls collection has a [SetChildIndex(Control child, int newIndex)](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.setchildindex.aspx) method. See if you can use that method to order the controls as per your need. **EDIT:** Just did a quick test. You need to call SuspendLayout() before adding the controls and then ResumeLayout() once you're done: ``` this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.Controls.Add(t1); this.toolStripContainer1.TopToolStripPanel.Controls.Add(t2); this.toolStripContainer1.TopToolStripPanel.Controls.SetChildIndex(t1, 1); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(); ```
Change Toostrip Order
[ "", "c#", "toolstrip", "" ]
I need to use a DLL (Hardware ID Extractor) made in Delphi 7 in my C# application. The functions exported by this DLL are: Exported functions: ``` // CPU function GetCPUSpeed: Double; function CPUFamily: ShortString; { Get cpu identifier from the windows registry } function GetCpuTheoreticSpeed: Integer; { Get cpu speed (in MHz) } function IsCPUIDAvailable: Boolean; Register; function GetCPUID (CpuCore: byte): ShortString; Function GetCPUVendor: ShortString; // RAM function MemoryStatus (MemType: Integer): cardinal; { in Bytes } function MemoryStatus_MB (MemType: Integer): ShortString; { in MB } // HDD function GetPartitionID (Partition : PChar): ShortString; { Get the ID of the specified patition. Example of parameter: 'C:' } function GetIDESerialNumber(DriveNumber: Byte ): PChar; { DriveNr is from 0 to 4 } ``` --- I know (obviously) that string in Delphi are not null terminated and are byte (ASCII). But I have no clue on how to map these Delphi string to C#. Thanks.
Here's an example of how you could declare the GetCPUSpeed function in C#: ``` class Program { [DllImport("the_name_of_the_delphi_library.dll")] public static extern double GetCPUSpeed(); static void Main(string[] args) { double cpuSpeed = GetCPUSpeed(); Console.WriteLine("CPU speed: {0}", cpuSpeed); } } ``` And there are the other declarations you could try: ``` [DllImport("the_name_of_the_delphi_library.dll")] public static extern string CPUFamily(); [DllImport("the_name_of_the_delphi_library.dll")] public static extern int GetCpuTheoreticSpeed(); [DllImport("the_name_of_the_delphi_library.dll")] public static extern bool IsCPUIDAvailable(); [DllImport("the_name_of_the_delphi_library.dll")] public static extern string GetCPUID(byte cpuCore); [DllImport("the_name_of_the_delphi_library.dll")] public static extern string GetCPUVendor(); [DllImport("the_name_of_the_delphi_library.dll")] public static extern uint MemoryStatus(int memType); [DllImport("the_name_of_the_delphi_library.dll")] public static extern string MemoryStatus_MB(int memType); [DllImport("the_name_of_the_delphi_library.dll")] public static extern string GetPartitionID(char partition); [DllImport("the_name_of_the_delphi_library.dll")] public static extern string GetIDESerialNumber(byte driveNumber); ```
The problem comes from the way you designed your exported functions. DLLs are (among other things) a mechanism to provide code in a way that it can be used from applications (or other DLLs) written in different programming languages. Have a look at the Windows API, there are lots of functions returning text. Unfortunately this is done in a lot of different ways, the Windows API has no real standard for it. However, I'm quite sure that you will not find a single function that returns a "string" (either a Pascal or a C (null-terminated) string) in the way you did. The reason is simple: This would make it very difficult or even impossible to use different programming languages for different modules. Your DLL would allocate the memory for the string, and once the caller is done with the string it would need to free the memory. Thus both modules need to share the manager for this slice of memory. How could the C# program use your DLL, seeing that they use completely different memory managers? The customary way to get a string value from a DLL is to call the function with a preallocated buffer and the buffer length in parameters, let the function fill that buffer with the string contents, and let the function result denote success or failure. Passing a buffer of insufficient size for example would be one cause of failure. Different Windows API functions deal with this in different ways, the easiest one for you would probably to define your maximum string length with a constant, similar to `MAX_PATH` for example. To solve your problem you should take one Windows API function that you know how to call from C#, and which returns a string result in a buffer, as the example. Model your exported functions after this example, and it should be easy to call them from the C# program. **Edit:** I remembered that I'd seen a similar question ([How to import a function from a DLL made in Delphi?](https://stackoverflow.com/questions/609970/how-to-import-a-function-from-a-dll-made-in-delphi)) some time ago, and now that I looked I found it to be yours as well. You wrote then that you don't have the source code for that DLL, so changing the exported functions is out of the question. What you could do is create a wrapper DLL (or COM object) in Delphi, call the original `HardwareIDExtractor.dll` and provide a sane API on top of it. That would allow you to provide both AnsiChar and WideChar versions of the exported functions at the same time. If you want to reduce the clutter (two DLLs necessary instead of one) you could also put the original `HardwareIDExtractor.dll` as a resource into your wrapper DLL, as described in this blog posting: [Using DLLs stored as Resources in Delphi programs](http://www.jasontpenny.com/blog/2009/05/01/using-dlls-stored-as-resources-in-delphi-programs/)
Use DLL compiled in Delphi 7 in C#
[ "", "c#", "delphi", "dll", "" ]
I have this anchor locating regex working pretty well: ``` $p = '%<a.*\s+name="(.*)"\s*>(?:.*)</a>%im'; ``` It matches `<a` followed by zero or more of anything followed by a space and `name="` It is grabbing the names even if a class or an id precedes the name in the anchor. What I would like to add is the ability to match on `name='` with a single quote (') as well since sooner or later someone will have done this. Obviously I could just add a second regex written for this but it seems inelegant. Anyone know how to add the single quote and just use one regex? Any other improvements or recommendations would be very welcome. I can use all the regex help I can get! Thanks very much for reading, ``` function findAnchors($html) { $names = array(); $p = '%<a.*\s+name="(.*)"\s*>(?:.*)</a>%im'; $t = preg_match_all($p, $html, $matches, PREG_SET_ORDER); if ($matches) { foreach ($matches as $m) { $names[] = $m[1]; } return $names; } } ```
Try this: ``` /<a(?:\s+(?!name)[^"'>]+(?:"[^"]*"|'[^']*')?)*\s+name=("[^"]*"|'[^']*')\s*>/im ``` Here you just have to strip the surrounding quotes: ``` substr($match[1], 1, -1) ``` But using a real parser like [DOMDocument](http://docs.php.net/manual/en/class.domdocument.php) would be certainly better that this regular expression approach.
James' comment is actually a very popular, but wrong regex used for string matching. It's wrong because it doesn't allow for escaping of the string delimiter. Given that the string delimiter is ' or " the following regex works ``` $regex = '([\'"])(.*?)(.{0,2})(?<![^\\\]\\\)(\1)'; ``` \1 is the starting delimeter, \2 is the contents (minus 2 characters) and \3 is the last 2 characters and the ending delimiter. This regex allows for escaping of delimiters as long as the escape character is \ and the escape character hasn't been escaped. IE., ``` 'Valid' 'Valid \' String' 'Invalid ' String' 'Invalid \\' String' ```
Regex Question: Matching this pattern with hard or soft quotes
[ "", "php", "regex", "" ]
I am writing a C# console application that connects to a server trough TCP, it uses a separate thread to listen for incoming messages from the server and I want it to write them to the console while at the same time reading a message from the console. I was able to do that, but I have a problem. The console displays this while I type and a messages comes in: > msg from server > msg from server > my msmsg from server > g to server And i want it to separate my message from the servers mesages like so: > msg from server > msg from server > msg from server > my msg to server *If I receive a message I still want to keep my typed message, but I don't want it to mix up with the received message, I want it to remain complete on the last line.* Can I do that? And how? Can I shift my message to the end of the console, when a message from the server comes in?
I believe this is in fact possible with the standard .NET Console API, using a bit of hackery. What you need to do is create an asynchronous Read/ReadLine method (which I assume you have already done, judging by your post) and allow it to be cancelled as soon as new data arrives. I'm going to assume you're sending input line by line for now. The pseudocode for the "new data handler" might be something like this: ``` Save the current input buffer. Cancel the current asynchronous read. Reset the cursor position to the end of the last writing of new data. Output the new data. Save the cursor position. Restart the asynchronous read event. ``` In particular, you'll need to mess around with [Console.CursorLeft](http://msdn.microsoft.com/en-us/library/system.console.cursorleft.aspx) and [Console.CursorTop](http://msdn.microsoft.com/en-us/library/system.console.cursortop.aspx) properties. You might be able to avoid *some* of the hackery by interfacing with the Win32 API console functions directly, but it's possibly not worth the bother. Hope that helps.
You can't do this directly via the BCL in C#. There are two main alternatives, though. 1) Turn this into a GUI app, and have separate input/output areas. This is the most "clear" option from a user's POV, but requires a GUI app instead of a console app. 2) P/Invoke into the [console API](http://msdn.microsoft.com/en-us/library/ms682073(VS.85).aspx) directly. This gives you complete control of the console's view, point by point. See SetConsoleCursorPosition and WriteConsole, etc.
C# Console: Write while reading and retain structure
[ "", "c#", "multithreading", "console", "client-server", "" ]
I have a simple `Converter` that adds a "+" symbol to a positive number that is entered in a `TextBox`. When the number is entered I want to initiate some action, but I don't want to wait until the `TextBox` loses focus: I want to update the binding immediately as the user enters the text. The default behaviour of a `TextBox` is that when a user navigates away from the box, the binding source is updated (UpdateSourceTrigger=LostFocus). In this scenario, my converter works as expected, and the + is added. However, when I change it to the following, the + is *never* added. ``` <TextBox Text="{Binding Value, Converter={StaticResource PlusConverter}, UpdateSourceTrigger=PropertyChanged}" /> ``` I can imagine that there is a good reason why my converter.Convert() method is not called. I would like to have the following behaviour: 1. When the users enters text, the source is updated immediately 2. When the `TextBox` loses focus, the + is added. Now I'm looking for a nice, but especially GENERIC way of doing this (as I have a lot of these TextBoxes in my app). So far I haven't been able to come up with a proper solution.
Thanks for your answers! I looked into this issue myself a bit futher and came up with the following solution (which I'm not entirely satisfied with, but it works fine) I've created a CustomControl that adds functionality to the TextBox. It provided an event handler for the LostFocus event When this event occurs, my converter is called. However, the way I resolve the Converter is not very satisfying (I take it from the Style that is associated with my TextBox). The Style has a Setter for the Text property. From that setter I can access my Converter. Of course I could also make a "PlusTextBox", but I use different converters and I wanted a generic solution. ``` public class TextBoxEx : TextBox { public TextBoxEx() { AddHandler(LostFocusEvent, new RoutedEventHandler(CallConverter), true); } public Type SourceType { get { return (Type)GetValue(SourceTypeProperty); } set { SetValue(SourceTypeProperty, value); } } // Using a DependencyProperty as the backing store for SourceType. This enables animation, styling, binding, etc... public static readonly DependencyProperty SourceTypeProperty = DependencyProperty.Register("SourceType", typeof(Type), typeof(TextBoxEx), new UIPropertyMetadata(null)); private static void CallConverter(object sender, RoutedEventArgs e) { TextBoxEx textBoxEx = sender as TextBoxEx; if (textBoxEx.Style == null) { return; } if (textBoxEx.SourceType == null) { } foreach (Setter setter in textBoxEx.Style.Setters) { if (setter.Property.ToString() == "Text") { if (! (setter.Value is Binding) ) { return; } Binding binding = setter.Value as Binding; if (binding.Converter == null) { return; } object value = binding.Converter.ConvertBack(textBoxEx.Text, textBoxEx.SourceType, binding.ConverterParameter, System.Globalization.CultureInfo.CurrentCulture); value = binding.Converter.Convert(value, typeof(string), binding.ConverterParameter, System.Globalization.CultureInfo.CurrentCulture); if (!(value is string)) { return; } textBoxEx.Text = (string)value; } } } } ```
Agree w/Kent B, you need to post your Converter code. I've been able to get part 1 to work with a simple converter (I'm binding a second unconverted TextBlock to show that the value is indeed getting updated). However, if I understand your part 2, you're trying to get the **TextBox**'s text to update with a "+" after it loses focus. This is a little trickier and I don't think you'll be able to do it with just an IConverter. If it can be done, I'd love to know the answer as well. What you're essentially asking for is watermarked input behavior e.g. allow a user to enter some data, and have it get formatted correctly (both in the underlying DataBinding and in the UI). The quickest/dirtiest solution to this is to handle the TextBoxes' LostFocus but since you're using that all over your app, this may not be feasible. You could also consider wrapping the TextBox in your own UserControl. If you look at WPFToolkit's implementation of a DatePicker it has similar behavior: allow the user to enter free form text, then auto-convert the value to a DateTime (if valid) and show the DateTime in a localized format. HTH.
UpdateSourceTrigger=PropertyChanged and Converter
[ "", "c#", ".net", "wpf", "xaml", "converters", "" ]
I have a script that requires the postcode input to have a space in it, if not it will fail. Straight forward, but UK postcodes can have gaps in different places, i.e W1 4SB, NW2 6PT or SG14 1LB how would I change users input, if there is no gap entered to the correct format using PHP?
The solution that worked is: ``` $postcode = trim(strip_tags($_REQUEST['postcode'])); $test = $postcode; if(substr($test, -3) == " ") { $postcode = $postcode; } else { function stringrpl($x,$r,$str) { $out = ""; $temp = substr($str,$x); $out = substr_replace($str,"$r",$x); $out .= $temp; return $out; } $test = stringrpl(-3," ",$test); $postcode = $test; } ```
[Postcodes always end with digit-letter-letter](http://www.govtalk.gov.uk/gdsc/html/frames/Postcode.htm). Simply look for a space at the 4th character before the end of the string and if it's not there, insert it.
Space in Postcode
[ "", "php", "" ]
I have a multi-threading Python program, and a utility function, `writeLog(message)`, that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. I would like `writeLog()` to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of `os.getpid()` that I could use?
[`threading.get_ident()`](https://docs.python.org/3/library/threading.html#threading.get_ident) works, or [`threading.current_thread().ident`](https://docs.python.org/3/library/threading.html#threading.current_thread) (or `threading.currentThread().ident` for Python < 2.6).
Using the [logging](http://docs.python.org/library/logging.html) module you can automatically add the current thread identifier in each log entry. Just use one of these [LogRecord](http://docs.python.org/library/logging.html#logging.LogRecord) mapping keys in your logger format string: > *%(thread)d :* Thread ID (if available). > > *%(threadName)s :* Thread name (if available). and set up your default handler with it: ``` logging.basicConfig(format="%(threadName)s:%(message)s") ```
How to obtain a Thread id in Python?
[ "", "python", "multithreading", "python-multithreading", "python-logging", "" ]
I am looking for the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like? Defined interface: ``` public interface IXMLUtils { string RemoveAllNamespaces(string xmlDocument); } ``` Sample XML to remove NS from: ``` <?xml version="1.0" encoding="utf-16"?> <ArrayOfInserts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <insert> <offer xmlns="http://schema.peters.com/doc_353/1/Types">0174587</offer> <type2 xmlns="http://schema.peters.com/doc_353/1/Types">014717</type2> <supplier xmlns="http://schema.peters.com/doc_353/1/Types">019172</supplier> <id_frame xmlns="http://schema.peters.com/doc_353/1/Types" /> <type3 xmlns="http://schema.peters.com/doc_353/1/Types"> <type2 /> <main>false</main> </type3> <status xmlns="http://schema.peters.com/doc_353/1/Types">Some state</status> </insert> </ArrayOfInserts> ``` After we call RemoveAllNamespaces(xmlWithLotOfNs), we should get: ``` <?xml version="1.0" encoding="utf-16"?> <ArrayOfInserts> <insert> <offer >0174587</offer> <type2 >014717</type2> <supplier >019172</supplier> <id_frame /> <type3 > <type2 /> <main>false</main> </type3> <status >Some state</status> </insert> </ArrayOfInserts> ``` Preffered language of solution is C# on .NET 3.5 SP1.
Well, here is the final answer. I have used great Jimmy idea (which unfortunately is not complete itself) and complete recursion function to work properly. Based on interface: ``` string RemoveAllNamespaces(string xmlDocument); ``` I represent here final clean and universal C# solution for removing XML namespaces: ``` //Implemented based on interface, not part of algorithm public static string RemoveAllNamespaces(string xmlDocument) { XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument)); return xmlDocumentWithoutNs.ToString(); } //Core recursion function private static XElement RemoveAllNamespaces(XElement xmlDocument) { if (!xmlDocument.HasElements) { XElement xElement = new XElement(xmlDocument.Name.LocalName); xElement.Value = xmlDocument.Value; foreach (XAttribute attribute in xmlDocument.Attributes()) xElement.Add(attribute); return xElement; } return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); } ``` It's working 100%, but I have not tested it much so it may not cover some special cases... But it is good base to start.
The tagged most useful answer has two flaws: * It ignores attributes * It doesn't work with "mixed mode" elements Here is my take on this: ``` public static XElement RemoveAllNamespaces(XElement e) { return new XElement(e.Name.LocalName, (from n in e.Nodes() select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)), (e.HasAttributes) ? (from a in e.Attributes() where (!a.IsNamespaceDeclaration) select new XAttribute(a.Name.LocalName, a.Value)) : null); } ``` Sample code [here](https://gist.github.com/dalegaspi/9ef8a241339c1de62413#file-removexmlnamespace-cs).
How to remove all namespaces from XML with C#?
[ "", "c#", "xml", "" ]
Is there a way with the .NET Framework to send emails through an SSL SMTP server on port 465? The usual way: ``` System.Net.Mail.SmtpClient _SmtpServer = new System.Net.Mail.SmtpClient("tempurl.org"); _SmtpServer.Port = 465; _SmtpServer.EnableSsl = true; _SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password"); _SmtpServer.Timeout = 5000; _SmtpServer.UseDefaultCredentials = false; MailMessage mail = new MailMessage(); mail.From = new MailAddress(from); mail.To.Add(to); mail.CC.Add(cc); mail.Subject = subject; mail.Body = content; mail.IsBodyHtml = useHtml; _SmtpServer.Send(mail); ``` times out: ``` System.Net Verbose: 0 : [1024] SmtpClient::.ctor(host=ssl0.ovh.net, port=465) System.Net Information: 0 : [1024] Associating SmtpClient#64923656 with SmtpTransport#44624228 System.Net Verbose: 0 : [1024] Exiting SmtpClient::.ctor() -> SmtpClient#64923656 System.Net Information: 0 : [1024] Associating MailMessage#17654054 with Message#52727599 System.Net Verbose: 0 : [1024] SmtpClient#64923656::Send(MailMessage#17654054) System.Net Information: 0 : [1024] SmtpClient#64923656::Send(DeliveryMethod=Network) System.Net Information: 0 : [1024] Associating SmtpClient#64923656 with MailMessage#17654054 System.Net Information: 0 : [1024] Associating SmtpTransport#44624228 with SmtpConnection#14347911 System.Net Information: 0 : [1024] Associating SmtpConnection#14347911 with ServicePoint#51393439 System.Net.Sockets Verbose: 0 : [1024] Socket#26756241::Socket(InterNetwork#2) System.Net.Sockets Verbose: 0 : [1024] Exiting Socket#26756241::Socket() System.Net.Sockets Verbose: 0 : [1024] Socket#23264094::Socket(InterNetworkV6#23) System.Net.Sockets Verbose: 0 : [1024] Exiting Socket#23264094::Socket() System.Net.Sockets Verbose: 0 : [1024] Socket#26756241::Connect(20:465#337754884) System.Net.Sockets Verbose: 0 : [1024] Exiting Socket#26756241::Connect() System.Net.Sockets Verbose: 0 : [1024] Socket#23264094::Close() System.Net.Sockets Verbose: 0 : [1024] Socket#23264094::Dispose() System.Net.Sockets Verbose: 0 : [1024] Exiting Socket#23264094::Close() System.Net Information: 0 : [1024] Associating SmtpConnection#14347911 with SmtpPooledStream#14303791 System.Net.Sockets Verbose: 0 : [1024] Socket#26756241::Receive() System.Net.Sockets Verbose: 0 : [2404] Socket#26756241::Dispose() System.Net.Sockets Error: 0 : [1024] Exception in the Socket#26756241::Receive - A blocking operation was interrupted by a call to WSACancelBlockingCall System.Net.Sockets Verbose: 0 : [1024] Exiting Socket#26756241::Receive() -> 0#0 System.Net Error: 0 : [1024] Exception in the SmtpClient#64923656::Send - Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall. System.Net Error: 0 : [1024] at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) System.Net Verbose: 0 : [1024] Exiting SmtpClient#64923656::Send() System.Net Information: 0 : [1024] Associating MailMessage#49584532 with Message#19699911 ``` I googled around and found that `System.Net.Mail` supports connections on port 587 (default port for Explicit SSL that starts unencrypted then issues a `STARTTLS` then switches to an Encrypted connection: RFC 2228), but doesn't support Implicit SSL (entire connection is wrapped in an SSL layer) ...
Here is an example of how to send email through GMail which also uses SSL/465. Minor tweaking of the code below should work! ``` using System.Web.Mail; using System; public class MailSender { public static bool SendEmail( string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath) { try { System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); //sendusing: cdoSendUsingPort, value 2, for sending the message using //the network. //smtpauthenticate: Specifies the mechanism used when authenticating //to an SMTP //service over the network. Possible values are: //- cdoAnonymous, value 0. Do not authenticate. //- cdoBasic, value 1. Use basic clear-text authentication. //When using this option you have to provide the user name and password //through the sendusername and sendpassword fields. //- cdoNTLM, value 2. The current process security context is used to // authenticate with the service. myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1"); //Use 0 for anonymous myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); myMail.From = pGmailEmail; myMail.To = pTo; myMail.Subject = pSubject; myMail.BodyFormat = pFormat; myMail.Body = pBody; if (pAttachmentPath.Trim() != "") { MailAttachment MyAttachment = new MailAttachment(pAttachmentPath); myMail.Attachments.Add(MyAttachment); myMail.Priority = System.Web.Mail.MailPriority.High; } System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465"; System.Web.Mail.SmtpMail.Send(myMail); return true; } catch (Exception ex) { throw; } } } ```
I'm late to this party but I'll offer my approach for any passersby that might be interested in an alternative. As noted in previous answers, the `System.Net.Mail` `SmtpClient` class does not support *Implicit SSL*. It does support *Explicit SSL*, which requires an insecure connection to the SMTP server over port 25 in order to negotiate the transport level security (TLS). I blogged about my travails with this subtlety [here](http://blog.ramsoftsolutions.com/2015/04/sending-mail-via-smtp-over-implicit-ssl.html). In short, SMTP over Implict SSL port 465 requires TLS to be negotiated *before* connecting to the SMTP server. Rather than write a .Net SMTPS implementation I turned to a utility named [Stunnel](https://www.stunnel.org/index.html). It's a small service that will let you redirect traffic on a local port to a remote port via SSL. > DISCLAIMER: Stunnel uses portions of the OpenSSL library, which recently had a high-profile exploit published in all major tech news media. I believe the latest version uses the patched OpenSSL but please use at your own risk. Once the utility is installed a small addition to the configuration file: ``` ; Example SSL client mode services [my-smtps] client = yes accept = 127.0.0.1:465 connect = mymailserver.com:465 ``` ...instructs the Stunnel service to reroute local requests to port 465 to my mail server on port 465. This happens over TLS, which satisfies the SMTP server on the other end. Using this utility, the following code will successfully transmit over port 465: ``` using System; using System.Net; using System.Net.Mail; namespace RSS.SmtpTest { class Program { static void Main( string[] args ) { try { using( SmtpClient smtpClient = new SmtpClient( "localhost", 465 ) ) { // <-- note the use of localhost NetworkCredential creds = new NetworkCredential( "username", "password" ); smtpClient.Credentials = creds; MailMessage msg = new MailMessage( "joe@schmoe.com", "jane@schmoe.com", "Test", "This is a test" ); smtpClient.Send( msg ); } } catch( Exception ex ) { Console.WriteLine( ex.Message ); } } } } ``` So the advantage here is that you can use Implict SSL and port 465 as the security protocol while still using the send mail methods built into the framework. The disadvantage is that it requires the use of a third party service that may not be useful for anything but this specific function.
How can I send emails through SSL SMTP with the .NET Framework?
[ "", "c#", ".net", "email", "ssl", "smtp", "" ]
I was wondering if anyone knew how to convert an mp3 audio file to an ogg audio file. I know there are programs you can buy online, but I would rather just have my own little app that allowed me to convert as many files I wanted.
It's realtive simple. I wouldn't use the Windows Media Format SDK. Simply because of the fact that it's overkill for the job. You need a MP3 decoder and a OGG encoder and a little bit of glue code around that (opening files, setting up the codecs, piping raw audio data around ect.) For the MP3 decoder I suggest that you take a look at the liblame library or use this decoding lib <http://www.codeproject.com/KB/audio-video/madlldlib.aspx> as a starting point. For OGG there aren't many choices. You need libogg and libvorbis. Easy as that. The example codes that come with the libs show you how to do the encoding. Good luck.
It's a bad idea. To quote from the Vorbis FAQ > You can convert any audio format to > Ogg Vorbis. However, converting from > one lossy format, like MP3, to another > lossy format, like Vorbis, is > generally a bad idea. Both MP3 and > Vorbis encoders achieve high > compression ratios by throwing away > parts of the audio waveform that you > probably won't hear. However, the MP3 > and Vorbis codecs are very different, > so they each will throw away different > parts of the audio, although there > certainly is some overlap. Converting > a MP3 to Vorbis involves decoding the > MP3 file back to an uncompressed > format, like WAV, and recompressing it > using the Ogg Vorbis encoder. The > decoded MP3 will be missing the parts > of the original audio that the MP3 > encoder chose to discard. The Ogg > Vorbis encoder will then discard other > audio components when it compresses > the data. At best, the result will be > an Ogg file that sounds the same as > your original MP3, but it is most > likely that the resulting file will > sound worse than your original MP3. In > no case will you get a file that > sounds better than the original MP3. > > Since many music players can play both > MP3 and Ogg files, there is no reason > that you should have to switch all of > your files to one format or the other. > If you like Ogg Vorbis, then we would > encourage you to use it when you > encode from original, lossless audio > sources (like CDs). When encoding from > originals, you will find that you can > make Ogg files that are smaller or of > better quality (or both) than your > MP3s. > > (If you must absolutely must convert > from MP3 to Ogg, there are several > conversion scripts available on > [Freshmeat](http://freshmeat.net/search/?q=convert%20ogg%20mp3).) <http://www.vorbis.com/faq/#transcode> And, for the sake of accuracy, from the same FAQ: > **Ogg** Ogg is the name of Xiph.org's > container format for audio, video, and > metadata. > > **Vorbis** Vorbis is the name of > a specific audio compression scheme > that's designed to be contained in > Ogg. Note that other formats are > capable of being embedded in Ogg such > as FLAC and Speex. I imagine it's theoretically possible to embed MP3 in Ogg, though I'm not sure why anyone would want to. FLAC is a lossless audio codec. Speex is a very lossy audio codec optimised for encoding speech. Vorbis is a general-use lossy audio codec. "Ogg audio" is, therefore, a bit of a misnomer. Ogg Vorbis is the proper term for what I imagine you mean. All that said, if you still want to convert from MP3 to Ogg Vorbis, you could (a) try the Freshmeat link above, (b) look at the other answers, or (c) look at FFmpeg. FFmpeg is a general-purpose library for converting lots of video and audio codecs and formats. It can do a lot of clever stuff. I have heard that its default Vorbis encoder is poor quality, but it can be configured to use libvorbis instead of its inbuilt Vorbis encoder. (That last sentence may be out of date now. I don't know.) Note that FFmpeg will be using LAME and libvorbis, just as you already are. It won't do anything new for you that way. It just gives you the option to do all sorts of other conversions too.
c++ audio conversion ( mp3 -> ogg ) question
[ "", "c++", "audio", "" ]
I'm trying to run a report on our database. We want to know the new registrations per industry per month. I've written this query: ``` SELECT COUNT(j.jobseeker_id) as new_registrations, i.description as industry_name, MONTHNAME(j.created_at) FROM tb_jobseeker as j, tb_industry as i WHERE YEAR(j.created_at) = 2009 AND i.industry_id = j.industry_id GROUP BY i.description, MONTHNAME(j.created_at) HAVING MONTHNAME(j.created_at) = MONTHNAME(NOW()); ``` When I run this query, I get an empty result set. However, if I run the following: ``` SELECT COUNT(j.seeker_id) as new_registrations, i.description as industry_name, MONTHNAME(j.created_at) FROM tb_seeker as j, tb_industry as i WHERE YEAR(j.created_at) = 2009 AND i.industry_id = j.industry_id GROUP BY i.description, MONTHNAME(j.created_at) HAVING MONTHNAME(j.created_at) = 'June'; ``` It returns the results I'm looking for. Any help please? I'm stumped. Update: the query will be run at the end of every month or start of the next for the past month. So, we're now in June, but it needs to run for May. Hope that makes sense.
Errr.... it's not May O\_o Your query will be much more efficient if you write it like this: ``` SELECT COUNT(j.jobseeker_id) as new_registrations, i.description as industry_name, MONTHNAME(j.created_at) FROM tb_jobseeker as j, tb_industry as i WHERE j.created_at BETWEEN '2009-05-01' AND '2009-05-31' AND i.industry_id = j.industry_id GROUP BY i.description, MONTH(j.created_at) ``` You should only use HAVING if you absolutely HAVE to. It would be even better if you could group by i.id instead of i.description, but that depends on whether i.description is unique.
What does: ``` SELECT MONTHNAME(NOW()) ``` Return on your server?
Problems with MONTHNAME() on MySQL 5
[ "", "sql", "mysql", "" ]
I have a `String` that provides an absolute path to a file (including the file name). I want to get just the file's name. What is the easiest way to do this? It needs to be as general as possible as I cannot know in advance what the URL will be. I can't simply create a URL object and use `getFile()` - all though that would have been ideal if it was possible - as it's not necessarily an `http://` prefix it could be c:/ or something similar.
``` new File(fileName).getName(); ``` or ``` int idx = fileName.replaceAll("\\\\", "/").lastIndexOf("/"); return idx >= 0 ? fileName.substring(idx + 1) : fileName; ``` Notice that the first solution is system dependent. It only takes the system's path separator character into account. So if your code runs on a Unix system and receives a Windows path, it won't work. This is the case when processing file uploads being sent by Internet Explorer.
``` new File(absolutePath).getName(); ```
Get file name from a file location in Java
[ "", "java", "url", "string", "path", "filenames", "" ]
This is what WordPad looks like in Windows 7: [![](https://i.stack.imgur.com/yvRSh.jpg)](https://i.stack.imgur.com/yvRSh.jpg) (source: [gawker.com](http://cache.gawker.com/assets/images/lifehacker/2009/01/win7_wordpad.jpg)) The ribbon is also in paint. Which leads me to think that the ribbon is "hidden" somewhere in a dll file that I could import into my C# apps. Is this true? If not how did Microsoft make the ribbon. Yes I'm aware that there are already companies who have made the ribbon for C# but I want to just use P/Invoke to add it to my apps.
As Matthew Flaschen mentions, you can download a CTP of the WPF Ribbon Control from CodePlex. However, it is important to point out that this is currently *very incomplete*. I tried it out recently and found it to be decent, but rather buggy. You won't be able to properly use the WPF Ribbon control (to its full extent at least) until .NET 4.0 is released. I'm not sure whether it's included in the current Beta 1, but it should (almost) definitely be part of the core WPF library in the final release. This ought to be much more stable and complete in terms of features. Whether the feature set will match that of the Microsoft Office Ribbon is another question - doubtful, in my mind, though you might expect WPF by nature to provide some sort of extensibility. **Update:** Indeed, the [Beta 1 release](http://www.microsoft.com/downloads/details.aspx?FamilyID=ee2118cc-51cd-46ad-ab17-af6fff7538c9&displaylang=en) of the .NET Framework 4.0 details (in the overview section) that a WPF Ribbon control is included. Worth checking it out, as I would strongly suspect it is significantly more advanced than the one on CodePlex.
You can use the [WPF wrapper](http://www.codeplex.com/wpf/Wiki/View.aspx?title=WPF%20Ribbon%20Preview).
How to use the ribbon in my .NET applications?
[ "", "c#", "windows-7", "ribbon", "wordpad", "" ]
I can't figure out how to phrase this question to be honest. :/ But I'm trying to get the following effect: <http://zack.scudstorm.com/example.png> I was wondering if anyone here could help me try to figure out how to accomplish this effect as seen in the image? :/ The effect, as seen in the image, is that when I hover over an image, or whatever I bind "onmouseover" event to, a "popup" is displayed showing text and other information that I may need to display. Thanks in advance! -Zack P.S. Sorry for the example being from WoW; it's the only thing I could think of when trying to describe this effect.
Heres some pseudo code to get you started: bind mouseover event to link - in jquery: `$('a.popup').mouseover(function(){ /* code here */ });` in the event find position of mouse create (or use already created) div to hold your information place div into the body element directly so you can absolutely position it use the mouse position you found earlier to position your div at the mouse (or relative to the mouse) bind mouse out event to link in the event hide the absolutely positioned info div apply nice styles in the stylesheet :) Thats all there is to it. Its not that difficult - if you're using jquery all of this stuff is in the docs. Hope this helps
Check out any of the many jQuery tooltip plugins. [qTip](http://craigsworks.com/projects/qtip/) seems to be pretty good.
mini-screen popups on mouse over
[ "", "javascript", "html", "css", "mouseover", "onmouseover", "" ]
I was reading a tutorial and the author mentioned to include JavaScript files near the closing `body` tag (`</body>`) in HTML. For what type of functionality should I not declare/define JavaScript include in the `head` section? It makes sense to me include JavaScript like [Google Analytics](https://en.wikipedia.org/wiki/Google_Analytics) near the closing `body` tag. Where should I be careful in defining JavaScript include near the closing `body` tag?
It will often be argued that for speed purposes you should put script tags right at the end of the document (before the closing body tag). While this will result in the fastest page load, it has some serious downsides. Firstly, a common idiom with Webpage development is to have a header file, a footer file and your content in the middle. To keep unnecessary JavaScript code to a minimum, you'll often want to put code snippets in individual pages. If you include [jQuery](https://en.wikipedia.org/wiki/JQuery), for example, at the end of the document, your jQuery code snippets (like document ready stuff) must happen **after** that. That can be awkward from a development point of view. Secondly, in my experience, because the page load is faster, you can end up noticing certain effects being applied because the page has already loaded by the time they are applied. For example, if you put a table in a document and right before the body close tag put: ``` $(function() { $("tr:nth-child(odd)").addClass("odd"); }); ``` with appropriate styling, that effect being applied will often be visible. Personally I think that makes for a bad user experience potentially. I think often you're better off having the page load **slightly** slower (by putting scripts at the top) if you don't get disconcerting visual effects. I generally advocate effective caching strategies so you only have to download JavaScript files when they change, as in [Supercharging JavaScript in PHP](http://www.cforcoding.com/2009/05/supercharging-javascript.html) (but the principles apply to any language, not just PHP) and still putting scripts at the top. It's far more convenient.
By putting them in the `<head/>` you force the browser to download the files before it can render a page. That causes the perceived load time to slow down. By placing them in the footer, right before the closing body tag, the browser will not load them until it reaches that point in the parsing of the HTML. That means that the scripts will run later in the page load process but will not block the asset download and rendering process. Which works best is up to you and how you develop your code.
Where should I declare JavaScript files used in my page? In <head></head> or near </body>?
[ "", "javascript", "html", "" ]
I have a requirement to apply the `??` C# operator to JavaScript and I don't know how. Consider this in C#: ``` int i?=null; int j=i ?? 10;//j is now 10 ``` Now I have this set up in JavaScript: ``` var options={ filters:{ firstName:'abc' } }; var filter=options.filters[0]||'';//should get 'abc' here, it doesn't happen var filter2=options.filters[1]||'';//should get empty string here, because there is only one filter ``` How do I do it correctly? Thanks. EDIT: I spotted half of the problem: I can't use the 'indexer' notation to objects (`my_object[0]`). Is there a way to bypass it? (I don't know the names of the filters properties beforehand and don't want to iterate over them).
Here’s the JavaScript equivalent: ``` var i = null; var j = i || 10; //j is now 10 ``` Note that the [logical operator `||`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Logical_Operators) does not return a boolean value but the first value that can be converted to *true*. Additionally use an array of objects instead of one single object: ``` var options = { filters: [ { name: 'firstName', value: 'abc' } ] }; var filter = options.filters[0] || ''; // is {name:'firstName', value:'abc'} var filter2 = options.filters[1] || ''; // is '' ``` That can be accessed by index.
## ES2020 Answer The new [Nullish Coalescing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) Operator, is finally available on JavaScript. However, do take note of the [browser support](https://caniuse.com/mdn-javascript_operators_nullish_coalescing). You may need to use a JavaScript compiler like [Babel](https://babeljs.io/) to convert it into something more backward compatible. According to the documentation, > The nullish coalescing operator (??) is a logical operator that > returns its right-hand side operand when its left-hand side operand is > null or undefined, and otherwise returns its left-hand side operand. ``` const options={ filters:{ firstName:'abc' } }; const filter = options.filters[0] ?? ''; const filter2 = options.filters[1] ?? ''; ``` This will ensure that both of your variables will have a fallback value of `''` if `filters[0]` or `filters[1]` are `null`, or `undefined`. Do take note that the nullish coalescing operator does not return the default value for other types of falsy value such as `0` and `''`. If you wish to account for all falsy values, you should be using the OR operator `||`.
Replace a value if null or undefined in JavaScript
[ "", "javascript", "" ]
How do I reference a file relatively to a package's directory? My directory structure is: ``` /foo package1/ resources/ __init__.py package2/ resources/ __init__.py script.py ``` `script.py` imports packages `package1` and `package2`. Although the packages can be imported by any other script on the system. How should I reference resources inside, say, `package1` to ensure it would work in case `os.path.curdir` is arbitrary?
If you want to reference files from the `foo/package1/resources` folder you would want to use the `__file__` variable of the module. Inside `foo/package1/__init__.py`: ``` from os import path resources_dir = path.join(path.dirname(__file__), 'resources') ```
A simple/safe way to do this is using the `resource_filename` method from [pkg\_resources](http://setuptools.readthedocs.io/en/latest/pkg_resources.html) (which is distributed with [setuptools](https://pypi.python.org/pypi/setuptools)) like so: ``` from pkg_resources import resource_filename filepath = resource_filename('package1', 'resources/thefile') ``` Or, if you're implementing this inside `package1/___init___.py`: ``` from pkg_resources import resource_filename filepath = resource_filename(__name__, 'resources/thefile') ``` This gives you a clean solution that is also (if I'm not mistaken) zip safe.
Relative file paths in Python packages
[ "", "python", "reference", "package", "relative-path", "" ]
Is there any way to easily make a HTTP request with C++? Specifically, I want to download the contents of a page (an API) and check the contents to see if it contains a 1 or a 0. Is it also possible to download the contents into a string?
I had the same problem. [libcurl](http://curl.haxx.se/libcurl/) is really complete. There is a C++ wrapper [curlpp](http://www.curlpp.org/) that might interest you as you ask for a C++ library. [neon](https://notroj.github.io/neon/) is another interesting C library that also support [WebDAV](https://fr.wikipedia.org/wiki/WebDAV). curlpp seems natural if you use C++. There are many examples provided in the source distribution. To get the content of an URL you do something like that (extracted from examples) : ``` // Edit : rewritten for cURLpp 0.7.3 // Note : namespace changed, was cURLpp in 0.7.2 ... #include <curlpp/cURLpp.hpp> #include <curlpp/Options.hpp> // RAII cleanup curlpp::Cleanup myCleanup; // Send request and get a result. // Here I use a shortcut to get it in a string stream ... std::ostringstream os; os << curlpp::options::Url(std::string("http://example.com")); string asAskedInQuestion = os.str(); ``` See the `examples` directory in [curlpp source distribution](https://github.com/jpbarrette/curlpp), there is a lot of more complex cases, as well as a [simple complete minimal one](https://github.com/jpbarrette/curlpp/blob/master/examples/example22.cpp) using curlpp. my 2 cents ...
Windows code: ``` #include <string.h> #include <winsock2.h> #include <windows.h> #include <iostream> #include <vector> #include <locale> #include <sstream> using namespace std; #pragma comment(lib,"ws2_32.lib") int main( void ){ WSADATA wsaData; SOCKET Socket; SOCKADDR_IN SockAddr; int lineCount=0; int rowCount=0; struct hostent *host; locale local; char buffer[10000]; int i = 0 ; int nDataLength; string website_HTML; // website url string url = "www.google.com"; //HTTP GET string get_http = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n"; if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0){ cout << "WSAStartup failed.\n"; system("pause"); //return 1; } Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); host = gethostbyname(url.c_str()); SockAddr.sin_port=htons(80); SockAddr.sin_family=AF_INET; SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr); if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){ cout << "Could not connect"; system("pause"); //return 1; } // send GET / HTTP send(Socket,get_http.c_str(), strlen(get_http.c_str()),0 ); // recieve html while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){ int i = 0; while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'){ website_HTML+=buffer[i]; i += 1; } } closesocket(Socket); WSACleanup(); // Display HTML source cout<<website_HTML; // pause cout<<"\n\nPress ANY key to close.\n\n"; cin.ignore(); cin.get(); return 0; } ``` Here is a much better implementation: ``` #include <windows.h> #include <string> #include <stdio.h> using std::string; #pragma comment(lib,"ws2_32.lib") HINSTANCE hInst; WSADATA wsaData; void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename); SOCKET connectToServer(char *szServerName, WORD portNum); int getHeaderLength(char *content); char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut); int main() { const int bufLen = 1024; char *szUrl = "http://stackoverflow.com"; long fileSize; char *memBuffer, *headerBuffer; FILE *fp; memBuffer = headerBuffer = NULL; if ( WSAStartup(0x101, &wsaData) != 0) return -1; memBuffer = readUrl2(szUrl, fileSize, &headerBuffer); printf("returned from readUrl\n"); printf("data returned:\n%s", memBuffer); if (fileSize != 0) { printf("Got some data\n"); fp = fopen("downloaded.file", "wb"); fwrite(memBuffer, 1, fileSize, fp); fclose(fp); delete(memBuffer); delete(headerBuffer); } WSACleanup(); return 0; } void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename) { string::size_type n; string url = mUrl; if (url.substr(0,7) == "http://") url.erase(0,7); if (url.substr(0,8) == "https://") url.erase(0,8); n = url.find('/'); if (n != string::npos) { serverName = url.substr(0,n); filepath = url.substr(n); n = filepath.rfind('/'); filename = filepath.substr(n+1); } else { serverName = url; filepath = "/"; filename = ""; } } SOCKET connectToServer(char *szServerName, WORD portNum) { struct hostent *hp; unsigned int addr; struct sockaddr_in server; SOCKET conn; conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (conn == INVALID_SOCKET) return NULL; if(inet_addr(szServerName)==INADDR_NONE) { hp=gethostbyname(szServerName); } else { addr=inet_addr(szServerName); hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET); } if(hp==NULL) { closesocket(conn); return NULL; } server.sin_addr.s_addr=*((unsigned long*)hp->h_addr); server.sin_family=AF_INET; server.sin_port=htons(portNum); if(connect(conn,(struct sockaddr*)&server,sizeof(server))) { closesocket(conn); return NULL; } return conn; } int getHeaderLength(char *content) { const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r"; char *findPos; int ofset = -1; findPos = strstr(content, srchStr1); if (findPos != NULL) { ofset = findPos - content; ofset += strlen(srchStr1); } else { findPos = strstr(content, srchStr2); if (findPos != NULL) { ofset = findPos - content; ofset += strlen(srchStr2); } } return ofset; } char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut) { const int bufSize = 512; char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize]; char *tmpResult=NULL, *result; SOCKET conn; string server, filepath, filename; long totalBytesRead, thisReadSize, headerLen; mParseUrl(szUrl, server, filepath, filename); ///////////// step 1, connect ////////////////////// conn = connectToServer((char*)server.c_str(), 80); ///////////// step 2, send GET request ///////////// sprintf(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str()); strcpy(sendBuffer, tmpBuffer); strcat(sendBuffer, "\r\n"); sprintf(tmpBuffer, "Host: %s", server.c_str()); strcat(sendBuffer, tmpBuffer); strcat(sendBuffer, "\r\n"); strcat(sendBuffer, "\r\n"); send(conn, sendBuffer, strlen(sendBuffer), 0); // SetWindowText(edit3Hwnd, sendBuffer); printf("Buffer being sent:\n%s", sendBuffer); ///////////// step 3 - get received bytes //////////////// // Receive until the peer closes the connection totalBytesRead = 0; while(1) { memset(readBuffer, 0, bufSize); thisReadSize = recv (conn, readBuffer, bufSize, 0); if ( thisReadSize <= 0 ) break; tmpResult = (char*)realloc(tmpResult, thisReadSize+totalBytesRead); memcpy(tmpResult+totalBytesRead, readBuffer, thisReadSize); totalBytesRead += thisReadSize; } headerLen = getHeaderLength(tmpResult); long contenLen = totalBytesRead-headerLen; result = new char[contenLen+1]; memcpy(result, tmpResult+headerLen, contenLen); result[contenLen] = 0x0; char *myTmp; myTmp = new char[headerLen+1]; strncpy(myTmp, tmpResult, headerLen); myTmp[headerLen] = NULL; delete(tmpResult); *headerOut = myTmp; bytesReturnedOut = contenLen; closesocket(conn); return(result); } ```
How do you make a HTTP request with C++?
[ "", "c++", "httprequest", "" ]
Audio processing is pretty new for me. And currently using Python Numpy for processing wave files. After calculating FFT matrix I am getting noisy power values for non-existent frequencies. I am interested in visualizing the data and accuracy is not a high priority. Is there a safe way to calculate the clipping value to remove these values, or should I use all FFT matrices for each sample set to come up with an average number ? regards Edit: ``` from numpy import * import wave import pymedia.audio.sound as sound import time, struct from pylab import ion, plot, draw, show fp = wave.open("500-200f.wav", "rb") sample_rate = fp.getframerate() total_num_samps = fp.getnframes() fft_length = 2048. num_fft = (total_num_samps / fft_length ) - 2 temp = zeros((num_fft,fft_length), float) for i in range(num_fft): tempb = fp.readframes(fft_length); data = struct.unpack("%dH"%(fft_length), tempb) temp[i,:] = array(data, short) pts = fft_length/2+1 data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts] x_axis = arange(pts)*sample_rate*.5/pts spec_range = pts plot(x_axis, data[0]) show() ``` Here is the plot in non-logarithmic scale, for synthetic wave file containing 500hz(fading out) + 200hz sine wave created using Goldwave. ![](https://i.stack.imgur.com/rr9OE.png)
Simulated waveforms shouldn't show FFTs like your figure, so something is very wrong, and probably not with the FFT, but with the input waveform. The main problem in your plot is not the ripples, but the harmonics around 1000 Hz, and the subharmonic at 500 Hz. A simulated waveform shouldn't show any of this (for example, see my plot below). First, you probably want to just try plotting out the raw waveform, and this will likely point to an obvious problem. Also, it seems odd to have a wave unpack to unsigned shorts, i.e. "H", and especially after this to not have a large zero-frequency component. I was able to get a pretty close duplicate to your FFT by applying clipping to the waveform, as was suggested by both the subharmonic and higher harmonics (and Trevor). You could be introducing clipping either in the simulation or the unpacking. Either way, I bypassed this by creating the waveforms in numpy to start with. Here's what the proper FFT should look like (i.e. basically perfect, except for the broadening of the peaks due to the windowing) [![alt text](https://i.stack.imgur.com/HF2zs.png)](https://i.stack.imgur.com/HF2zs.png) Here's one from a waveform that's been clipped (and is very similar to your FFT, from the subharmonic to the precise pattern of the three higher harmonics around 1000 Hz) [![alt text](https://i.stack.imgur.com/HxYrO.png)](https://i.stack.imgur.com/HxYrO.png) Here's the code I used to generate these ``` from numpy import * from pylab import ion, plot, draw, show, xlabel, ylabel, figure sample_rate = 20000. times = arange(0, 10., 1./sample_rate) wfm0 = sin(2*pi*200.*times) wfm1 = sin(2*pi*500.*times) *(10.-times)/10. wfm = wfm0+wfm1 # int test #wfm *= 2**8 #wfm = wfm.astype(int16) #wfm = wfm.astype(float) # abs test #wfm = abs(wfm) # clip test #wfm = clip(wfm, -1.2, 1.2) fft_length = 5*2048. total_num_samps = len(times) num_fft = (total_num_samps / fft_length ) - 2 temp = zeros((num_fft,fft_length), float) for i in range(num_fft): temp[i,:] = wfm[i*fft_length:(i+1)*fft_length] pts = fft_length/2+1 data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts] x_axis = arange(pts)*sample_rate*.5/pts spec_range = pts plot(x_axis, data[2], linewidth=3) xlabel("freq (Hz)") ylabel('abs(FFT)') show() ```
FFT's because they are windowed and [sampled](http://en.wikipedia.org/wiki/Sampling_(signal_processing)) cause [aliasing](http://en.wikipedia.org/wiki/Aliasing) and sampling in the frequency domain as well. Filtering in the time domain is just multiplication in the frequency domain so you may want to just apply a filter which is just multiplying each frequency by a value for the function for the filter you are using. For example multiply by 1 in the passband and by zero every were else. The unexpected values are probably caused by aliasing where higher frequencies are being folded down to the ones you are seeing. The [original signal needs to be band limited to half your sampling rate](http://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem) or you will get [aliasing](http://en.wikipedia.org/wiki/Aliasing). Of more concern is aliasing that is distorting the area of interest because for this band of frequencies you want to know that the frequency is from the expected one. The other thing to keep in mind is that when you grab a piece of data from a wave file you are mathmatically multiplying it by a square wave. This causes a sinx/x to be convolved with the frequency response to minimize this you can multiply the original windowed signal with something like a [Hanning window](http://en.wikipedia.org/wiki/Window_function).
Clipping FFT Matrix
[ "", "python", "audio", "signal-processing", "fft", "" ]
Is there a PHP implementation of markdown suitable for using in public comments? Basically it should only allow a subset of the markdown syntax (bold, italic, links, block-quotes, code-blocks and lists), and strip out all inline HTML (or possibly escape it?) I guess one option is to use the normal markdown parser, and run the output through an HTML sanitiser, but is there a better way of doing this..? We're using PHP markdown Extra for the rest of the site, so we'd already have to use a secondary parser (the non-"Extra" version, since things like footnote support is unnecessary).. It also seems nicer parsing only the `*bold*` text and having everything escaped to `&lt;a href="etc"&gt;`, than generating `<b>bold</b>` text and trying to strip the bits we don't want.. Also, on a related note, we're using the WMD control for the "main" site, but for comments, what other options are there? WMD's javascript preview is nice, but it would need the same "neutering" as the PHP markdown processor (it can't display images and so on, otherwise someone will submit and their working markdown will "break") Currently my plan is to use the PHP-markdown -> HTML santiser method, and edit WMD to remove the image/heading syntax from `showdown.js` - but it seems like this has been done countless times before.. Basically: * Is there a "safe" markdown implementation in PHP? * Is there a HTML/javascript markdown editor which could have the same options easily disabled? **Update:** I ended up simply running the `markdown()` output through [HTML Purifier](http://htmlpurifier.org/). This way the Markdown rendering was separate from output sanitisation, which is much simpler (two mostly-unmodified code bases) more secure (you're not trying to do both rendering and sanitisation at once), and more flexible (you can have multiple sanitisation levels, say a more lax configuration for trusted content, and a much more stringent version for public comments)
PHP Markdown has a sanitizer option, but it doesn't appear to be advertised anywhere. Take a look at the top of the `Markdown_Parser` class in `markdown.php` (starts on line 191 in version 1.0.1m). We're interested in lines 209-211: ``` # Change to `true` to disallow markup or entities. var $no_markup = false; var $no_entities = false; ``` If you change those to `true`, markup and entities, respectively, should be escaped rather than inserted verbatim. There doesn't appear to be any built-in way to change those (e.g., via the constructor), but you can always add one: ``` function do_markdown($text, $safe=false) { $parser = new Markdown_Parser; if ($safe) { $parser->no_markup = true; $parser->no_entities = true; } return $parser->transform($text); } ``` Note that the above function creates a new parser on every run rather than caching it like the provided `Markdown` function (lines 43-56) does, so it might be a bit on the slow side.
JavaScript Markdown Editor Hypothesis: * Use a JavaScript-driven Markdown Editor, e.g., based on showdown * Remove all icons and visual clues from the Toolbar for unwanted items * Set up a JavaScript filter to clean-up unwanted markup on submission * Test and harden all JavaScript changes and filters locally on your computer * Mirror those filters in the PHP submission script, to catch same on the server-side. * Remove all references to unwanted items from Help/Tutorials I've created a Markdown editor in JavaScript, but it has enhanced features. That took a big chunk of time and SVN revisions. But I don't think it would be that tough to alter a Markdown editor to limit the HTML allowed.
"Safe" markdown processor for PHP?
[ "", "php", "security", "user-input", "markdown", "" ]
I am using MSXMl library to parse xml after I call put\_text and then get\_xml the output will have < & > converted to `&lt;` & `&gt;` How can i get rid of this?
< and > are prohibited to use inside the text and need to be encoded as &gt and &lt. The only way to avoid this is creating a CDATA section for the text containing those. But you really don't need to if you intend to read the XMLT with MS XML - it will decode those symbols just fine and you will get your < and > perfectly fine in the extracted text.
Well you are converting from plain text to XML encoded text. This is the behavior I would expect. If you want the original string you put in try converting back to text with get\_text(). If you do not want the put\_text() to encode the text without encoding the < and > then it must be inside a CData section. ``` <![CDATA[ Text that can include < and > without encoding ]]> ```
< & > are converted to &gt; &lt; etc
[ "", "c++", "xml", "msxml", "" ]
I was wondering if anyone has any strategies for optimizing the pre-loading of images via javascript? I'm porting a Flash application into html/css, attempting to recreate the UI as close to the original site as possible. It's essentially a photo browser application, where a high-res image is shown when the user hovers over a link. There's about 50-80 of these images per page. Pre-loading all the images individually creates a load time significantly longer than that of the Flash application. The amount of data is the same, but I have to assume the longer load time is due to the number of round trips that have to be made to the server for each image. Also, I'm looking at a significant load time for each page even after the images have been cached, because the page still needs to contact the server for each image to receive the 304 Not Modified code. Does anyone have any suggestions for speeding this up? Would it make sense to possibly try creating one huge image sprite that gets downloaded in a single request rather than 50-80 smaller images that each take a single request? The goal here is achieve a similar load time to the Flash site. Thanks. I know this doesn't sound like an ideal way to do things.
As you pointed out - one of the most common factors that influences load times for modern web pages are the huge number of small images being sent between the client and server. Some recent studies indicate that for more than 20 images, 80% of your load time is going to be spent in the latency of doing these many gets, not actually doing the downloading! A tool called SmartSprites is a very handy way to "compile" a single large image from all of your many little images which will accomplish both much faster load times and the prefetching of images. Here's the link <http://smartsprites.osinski.name/>
I would say using CSS sprites is a big one. Having all your images, or images of a similar nature come down on the one HTTP request really helps load time. Downloading 10 images with a total file size of 100kb is going to be slower than downloading 1 image the same size. It also helps images come down before they are required in the case of hovers and mouse over events and they generally make things a lot smoother. [Here is an article on them.](http://www.alistapart.com/articles/sprites)
Optimize javascript pre-load of images
[ "", "javascript", "flash", "optimization", "" ]
**Current Implementation** Sql Server 2005 Database with a table called messages with a column called MessageXml of type xml. C# Library project with a Linq to Sql class that generates a class called Message with a field called MessageXml of type XElement. WCF Webservice that exposes a MessagePayload class with a property called MessageXml of type XElement. The webservice doesn't serve up my Message class created by Linq to Sql. I use a light weight object as a go between. **Question** Is XElement really the type I want to be using in my WCF Service or is there a better type. The xml that is intended to be passed into the service should be a full doc. Also, I'm having a bit of trouble loading xml documents as an XElement. I think that I should expose a full xml document type in the light weight class for the service but I'm a bit confused on the differences between XDocument and XmlDocument. On top of that, I can't expose the WCF Message class with a property of XDocument type because it contains a property of XDeclaration type that can't be serialized. If I use XmlDocument than I have to do this weird conversion of xml types in my translation between the Linq class and the lightweight class. ``` XmlDocument doc = new XmlDocument(); doc.LoadXml(message.MessageXml.ToString()); MessageEnvelope retVal = new MessageEnvelope() { MessageXml = doc, }; ``` XmlDocument seems like the right one and I know I'll have to do some translation but want to get as close to appropriate as possible.
You can use either XElement or XmlElement: ``` public XmlElement GetXmlElement() { var doc = new XmlDocument(); doc.Load(PREFIX + @"Enumerations.wsdl"); return doc.DocumentElement; } public XElement GetXElement() { var doc = XDocument.Load(PREFIX + @"Enumerations.wsdl"); return doc.Root; } ``` You do not want either `XDocument` nor `XmlDocument`. Remember that whatever you return will be in the middle of an XML document containing the SOAP envelope. You can't have a document inside a document, so what you want is an element.
John Saunders is on the money here. To elaborate slightly, if you look at the WSDL that is generated when you return either an `XmlElement` or an `XElement`, you'll see something like this: ``` <xs:complexType> <xs:sequence> <xs:any minOccurs="0" processContents="lax"/> </xs:sequence> </xs:complexType> ``` That's it. It basically means any XML can go here. It also means that, contrary to Chansik's suggestion, it does not bind the return type to a .NET specific type. So yeah, you don't need to use a string.
What is an appropriate XML type for web service?
[ "", "c#", "xml", "wcf", "xmldocument", "xelement", "" ]
We have a Java project which contains a large number of English-language strings for user prompts, error messages and so forth. We want to extract all the translatable strings into a properties file so that they can be translated later. For example, we would want to replace: *Foo.java* ``` String msg = "Hello, " + name + "! Today is " + dayOfWeek; ``` with: *Foo.java* ``` String msg = Language.getString("foo.hello", name, dayOfWeek); ``` *language.properties* ``` foo.hello = Hello, {0}! Today is {1} ``` I understand that doing in this in a completely automated way is pretty much impossible, as not every string should be translated. However, we were wondering if there was a semi-automated way which removes some of the laboriousness.
What you want is a tool that replaces every expression involving string concatenations with a library call, with the obvious special case of expressions involving just a single literal string. A program transformation system in which you can express your desired patterns can do this. Such a system accepts rules in the form of: ``` lhs_pattern -> rhs_pattern if condition ; ``` where patterns are code fragments with syntax-category constraints on the pattern variables. This causes the tool to look for syntax matching the lhs\_pattern, and if found, replace by the rhs\_pattern, where the pattern matching is over langauge structures rather than text. So it works regardless of code formatting, indentation, comments, etc. Sketching a few rules (and oversimplifying to keep this short) following the style of your example: ``` domain Java; nationalize_literal(s1:literal_string): " \s1 " -> "Language.getString1(\s1 )"; nationalize_single_concatenation(s1:literal_string,s2:term): " \s1 + \s2 " -> "Language.getString1(\s1) + \s2"; nationalize_double_concatenation(s1:literal_string,s2:term,s3:literal_string): " \s1 + \s2 + \s3 " -> "Language.getString3(\generate_template1\(\s1 + "{1}" +\s3\, s2);" if IsNotLiteral(s2); ``` The patterns are themselves enclosed in "..."; these aren't Java string literals, but rather a way of saying to the multi-computer-lingual pattern matching engine that the suff inside the "..." is (domain) Java code. Meta-stuff are marked with \, e.g., metavariables \s1, \s2, \s3 and the embedded pattern call \generate with ( and ) to denote its meta-parameter list :-} Note the use of the syntax category constraints on the metavariables s1 and s3 to ensure matching only of string literals. What the meta variables match on the left hand side pattern, is substituted on the right hand side. The sub-pattern generate\_template is a procedure that at transformation time (e.g., when the rule fires) evaluates its known-to-be-constant first argument into the template string you suggested and inserts into your library, and returns a library string index. Note that the 1st argument to generate pattern is this example is composed entirely of literal strings concatenated. Obviously, somebody will have to hand-process the templated strings that end up in the library to produce the foreign language equivalents. You're right in that this may over templatize the code because some strings shouldn't be placed in the nationalized string library. To the extent that you can write programmatic checks for those cases, they can be included as conditions in the rules to prevent them from triggering. (With a little bit of effort, you could place the untransformed text into a comment, making individual transformations easier to undo later). Realistically, I'd guess you have to code ~~100 rules like this to cover the combinatorics and special cases of interests. The payoff is that the your code gets automatically enhanced. If done right, you could apply this transformation to your code repeatedly as your code goes through multiple releases; it would leave previously nationalized expressions alone and just revise the new ones inserted by the happy-go-lucky programmers. A system which can do this is the [DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html). DMS can parse/pattern match/transform/prettyprint many langauges, include Java and C#.
Eclipse will externalize every individual string and does not automatically build substitution like you are looking for. If you have a very consistent convention of how you build your strings you could write a perl script to do some intelligent replacement on .java files. But this script will get quite complex if you want to handle * String msg = new String("Hello"); * String msg2 = "Hello2"; * String msg3 = new StringBuffer().append("Hello3").toString(); * String msg4 = "Hello" + 4; * etc. I think there are some paid tools that can help with this. I remember evaluating one, but I don't recall its name. I also don't remember if it could handle variable substitution in external strings. I'll try to find the info and edit this post with the details. **EDIT:** The tool was [Globalyzer](http://www.lingoport.com/software-internationalization-products/globalyzer) by Lingport. The website says it supports string externalization, but not specifically how. Not sure if it supports variable substitution. There is a free trial version so you could try it out and see.
Is there a semi-automated way to perform string extraction for i18n?
[ "", "java", "string", "internationalization", "" ]
I have some SQL similar to the following, which joins four tables and then orders the results by the "status" column of the first: ``` SELECT * FROM a, b, c, d WHERE b.aid=a.id AND c.id=a.cid AND a.did=d.id AND a.did='XXX' ORDER BY a.status ``` It works. However, it's slow. I've worked out this is because of the ORDER BY clause and the lack of any index on table "a". All four tables have the PRIMARY KEYs set on the "id" column. So, I know I need to add an index to table a which includes the "status" column but what else does it need to include? Should "bid", "cid" and "did" be in there too? I've tried to ask this in a general SQL sense but, if it's important, the target is SQLite for use with Gears. Thanks in advance, Jake (noob)
I would say it's slow because the engine is doing scans all over the place instead of seeks. Did you mean to do SELECT a.\* instead? That would be faster as well, SELECT \* here is equivalent to a.\*, b.\*, c.\*, d.\*. You will probably get better results if you put a separate index on each of these columns: * a.did (so that a.did = 'XXX' is a seek instead of a scan, also helps a.did = d.id) * a.cid (for a.cid = c.id) * b.aid (for a.id = b.aid) You could try adding Status to the first and second indexes with ASCENDING order, for additional performance - it doesn't hurt.
I'd be curious as to how you worked out that the problem is 'the ORDER BY clause and the lack of any index on table "a".' I find this a little suspicious because there is an index on table a, on the primary key, you later say. Looking at the nature of the query and what I can guess about the nature of the data, I would think that this query would generally produce relatively few results compared to the size of the tables it's using, and that thus the ORDER BY would be extremely cheap. Of course, this is just a guess. Whether an index will even help at all is dependent on the data in the table. What indices your query optimizer will use when doing a query is dependent on a lot of different factors, one of the big ones being the expected number of results produced from a lookup. One thing that would help a lot is if you would post the output of EXPLAINing your query.
How To Create a SQL Index to Improve ORDER BY performance
[ "", "sql", "sqlite", "indexing", "sql-order-by", "" ]
I'm having a little trouble working out how to display a running total of sales that have gone through my website. I have no problem working out how to do this with a single output from one table, but unfortunately for my website the results of total sales are spread across 2 tables in the database. I normally get the total sales manually using a Union query in SQL (whenever I feel like checking it). I am trying to devise a means of displaying the total figure on my website as a single number formatted with comma's for thousands. So far I have managed to create some code which displays the total's from each table as a separate figure. Apart from the 2 separate figures, this is perfect. All I need to do is join up the 2 rows of output into a single figure. The code I currently have is below: ``` $sql= "SELECT sum(price) AS total_price FROM `table_A` UNION ALL SELECT sum(price) AS total_price FROM `table_B`"; $res= mysql_query($sql); if (mysql_num_rows($res)>0) { while ($row=mysql_fetch_array($res)) { echo '<h3>'.number_format($row["total_price"], 0).'</h3>'; }; }; echo mysql_error(); ``` Can anyone help me with this problem?
Just add them up: ``` $sql = <<<END SELECT sum(price) AS total_price FROM `table_A` UNION ALL SELECT sum(price) AS total_price FROM `table_B' END; $res = mysql_query($sql); if (!$res) { die('Error: ' . mysql_error() . ' in query ' . $sql); } $total = 0; while ($row = mysql_fetch_array($res)) { $total += $row[0]; } $total = number_format($total, 0); echo '<h3>Total Sales are $' . $total . '</h3>'; ``` Alternatively, it can be done in one query: ``` SELECT SUM(total_price) FROM ( SELECT sum(price) AS total_price FROM `table_A` UNION ALL SELECT sum(price) AS total_price FROM `table_B' ) ``` Personally I'd just add it in code but either works.
``` SELECT sum(price) AS total_price FROM (SELECT price FROM table_A UNION SELECT price FROM table_B ) ```
Displaying a running total on my website?
[ "", "php", "" ]
Is it possible to do this: ``` myfile.js: function foo() { alert(<my-function-name>); // pops-up "foo" // or even better: "myfile.js : foo" } ``` I've got the Dojo and jQuery frameworks in my stack, so if either of those make it easier, they're available.
In ES5 and above, there is no access to that information. In older versions of JS you can get it by using `arguments.callee`. You may have to parse out the name though, as it will probably include some extra junk. Though, in some implementations you can simply get the name using `arguments.callee.name`. Parsing: ``` function DisplayMyName() { var myName = arguments.callee.toString(); myName = myName.substr('function '.length); myName = myName.substr(0, myName.indexOf('(')); alert(myName); } ``` > Source: [Javascript - get current function name](http://www.tek-tips.com/viewthread.cfm?qid=1209619).
For non-anonymous functions ``` function foo() { alert(arguments.callee.name) } ``` But in case of an error handler the result would be the name of the error handler function, wouldn't it?
Can I get the name of the currently running function in JavaScript?
[ "", "javascript", "jquery", "dojo-1.6", "" ]
I'm using Reflection to set a property value via PropertyInfo.SetValue(); The property in question is a string, and the object from which I'm getting the value is actually a GUID. I'd like to convert from a GUID to a string in the process - is there any way of defining some kind of implicit cast which will enable this? At the moment I'm getting an error: ``` "Object of type 'System.Guid' cannot be converted to type 'System.String'." ``` I guess I could do a type check and manually convert if necessary, but if there's an elegant way of doing it behind the scenes then that would be preferable! Many thanks. --- **Edit:** I can't really just call the .ToString() method on a GUID as I'd very much like my code to look like this: ``` propertyInfoInstance.SetValue(classInstance, objectWithValue, null) ``` where objectWithValue is an int/bool/string/GUID. This works fine for everything except a GUID, as (I think!!) there's an implicit cast available. I could do a type check beforehand and just convert the GUID to a string, but I just get that "There must be a better way..." feeling.
It's my understanding (someone please correct me if this is wrong,) that you can only define implicit cast operators for your own objects. You'll need to manually handle dumping the GUID to a string w/ `guid.ToString();`
I don't believe there is an implicit cast between string and guid. Try this: ``` guid.ToString(); ``` For question 2: ``` if(propertyInfoInstance.PropertyType == typeof(string) && objectWithValue != null) { objectWithValue = objectWithValue.ToString(); } propertyInfoInstance.SetValue(classInstance, objectWithValue, null); ``` I don't think it's too messy.
Converting GUID to String via Reflection
[ "", "c#", "reflection", "properties", "" ]
I'm looking for a way to call a python script from a batch file and getting a return code from the python script. Confusing I know, but it's based on a system that's currently in use. I'd re-write it, but this way would be much, much quicker. So: ``` Bat ---------------------> Python * call python file * Bat <--------------------------------- Python * python does a load of work * * and returns a return code * ```
The windows shell saves the return code in the `ERRORLEVEL` variable: ``` python somescript.py echo %ERRORLEVEL% ``` In the python script you can exit the script and set the return value by calling `exit()`: ``` exit(15) ``` In older versions of python you might first have to import the `exit()` function from the `sys` module: ``` from sys import exit exit(15) ```
Try: ``` import os os._exit(ret_value) ``` You should also check: * [sys.exit()](http://bytes.com/groups/python/585533-sys-exit-versus-raise-systemexit)
Call Python From Bat File And Get Return Code
[ "", "python", "batch-file", "" ]
How do I do an inverse join with more than one key column? In this baby-toy SqlServer example, I have the following ``` CREATE TABLE [dbo].[CarList]( [myID] [int] IDENTITY(1,1) NOT NULL, [CarColour] [varchar](32) NOT NULL, [CarName] [varchar](128) NOT NULL, [CarCompany] [varchar](32) NOT NULL, CONSTRAINT [PK_CarList] PRIMARY KEY CLUSTERED( [myID] ASC, [CarColour] ASC, [CarName] ASC, [CarCompany] ASC ) ) GO INSERT INTO CarList (CarColour, CarName, CarCompany) VALUES('blue', 'Abe', 'Ford') ``` Elsewhere in the DB I have a table like ``` CREATE TABLE [dbo].[NewCars]( [CarColour] [varchar](32) NOT NULL, [CarName] [varchar](128) NOT NULL, [CarCompany] [varchar](32) NOT NULL, ) GO INSERT INTO NewCars (CarColour, CarName, CarCompany) SELECT 'blue', 'Abe', 'Ford' UNION ALL SELECT 'blue', 'Abe', 'GM' UNION ALL SELECT 'blue', 'Betty', 'Ford' UNION ALL SELECT 'green', 'Abe', 'Honda' ``` Now I want to insert cars I don't already have in the CarList table Something like... ``` INSERT INTO CarList ( CarColour, CarName, CarCompany) SELECT DISTINCT new.CarColour, new.CarName, new.CarCompany FROM NewCars new, CarList old WHERE new.CarColour <> old.CarColour AND new.CarName <> old.CarName AND new.CarCompany <> old.CarCompany ``` Which doesn't work because the "blue', 'Betty', 'Ford' row will get filtered out... If this were just a single ID of some kind it would be really easy ``` INSERT INTO myTable (myID, param1, param2, etc) SELECT param1, param2, etc FROM someOtherTable new WHERE new.myID NOT IN (SELECT myID FROM myTable) ``` For reasons I don't really want to get into, I cannot remove rows from NewCars that match CarList. I also need to do this in one pass if possible. [edit] Thanks guys!
thanks for DDL and DML Here is one way ``` INSERT INTO CarList ( CarColour, CarName, CarCompany) SELECT DISTINCT * FROM NewCars n where not exists (select 1 from CarList c where c.CarColour =n.CarColour and c.CarName = n.CarName and c.CarCompany = n.CarCompany) ``` There are at least 4 different way to do this * NOT IN (will not work for more than 1 column like you have) * NOT EXISTS * LEFT and RIGHT JOIN * OUTER APPLY (2005+) * EXCEPT (2005+) Read [Select all rows from one table that don't exist in another table](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/the-ten-most-asked-sql-server-questions--1#4)
``` INSERT INTO CarList ( CarColour, CarName, CarCompany) SELECT CarColour, CarName, CarCompany FROM NewCars nc WHERE NOT EXISTS ( SELECT 1 FROM CarList cl WHERE cl.CarColor = nc.CarColor AND cl.CarName = nc.CarName AND cl.CarCompany = nc.CarCompany ) ```
How to INSERT using an inverse JOIN on multiple keys?
[ "", "sql", "sql-server", "" ]
I'm trying to make sure that my understanding of `IDisposable` is correct and there's something I'm still not quite sure on. `IDisposable` seems to serve two purpose. 1. To provide a convention to "shut down" a managed object on demand. 2. To provide a convention to free "unmanaged resources" held by a managed object. My confusion comes from identifying which scenarios have "unmanaged resources" in play. Say you are using a Microsoft-supplied `IDisposable`-implementing (managed) class (say, database or socket-related). 1. How do you know whether it is implementing `IDisposable` for just **1** or **1&2** above? 2. Are you responsible for making sure that unmanaged resources it may or may not hold internally are freed? Should you be adding a finalizer (would that be the right mechanism?) to your own class that calls instanceOfMsSuppliedClass.Dispose()?
> 1. How do you know whether it is implementing IDisposable for just 1 or > 1&2 above? The answer to your first question is "you shouldn't need to know". If you're using third party code, then you are its mercy to some point - you'd have to trust that it's disposing of itself properly when you call Dispose on it. If you're unsure or you think there's a bug, you could always try using Reflector() to disassemble it (if possible) and check out what it's doing. > 2. Am I responsible for making sure that unmanaged resources it may or may > not hold internally are freed? Should > I be adding a finalizer (would that be > the right mechanism?) to my own class > that calls > instanceOfMsSuppliedClass.Dispose()? You should rarely, if ever, need to implement a finalizer for your classes if you're using .Net 2.0 or above. Finalizers add overhead to your class, and usually provide no more functionality then you'd need with just implementing Dispose. I would [highly recommend visiting this article](http://www.codeproject.com/KB/cs/idisposable.aspx) for a good overview on disposing properly. In your case, you would want to call `instanceofMSSuppliedClass.Dispose()` in your own Dispose() method. Ultimately, calling Dispose() on an object is good practice, because it explictly lets the GC know that you're done with the resource and allows the user the ability to clean it up immediately, and indirectly documents the code by letting other programmers know that the object is done with the resources at that point. But even if you forget to call it explicitly, it will happen eventually when the object is unrooted (.Net is a managed platform after all). Finalizers should only be implemented if your object has unmanaged resources that will need implicit cleanup (i.e. there is a chance the consumer can forget to clean it up, and that this will be problematic).
You should always call Dispose on objects that implement IDisposable (unless they specifically tell you' it's a helpful convention, like ASP.NET MVC's HtmlHelper.BeginForm). You can use the "using" statement to make this easy. If you hang on to a reference of an IDisposable in your class as a member field then you should implement IDisposable using the [Disposable Pattern](http://www.codeproject.com/KB/cs/idisposable.aspx) to clean up those members. If you run a static-analysis tool like FxCop it will tell you the same. You shouldn't be trying to second-guess the interface. Today that class might not use an unmanaged resource but what about the next version?
IDisposable, Finalizers and the definition of an unmanaged resource
[ "", "c#", ".net", "garbage-collection", "idisposable", "finalizer", "" ]
I have a set of classes written in C++. What would be best way to call them from a Perl script? Thanks.
I'm not particularly fond of SWIG and prefer to write the interfacing code myself. Perl comes with a sort of pseudo language called 'XS' for interfacing to C or C++. Unfortunately, in order to use it, you will need to know at least C, Perl, and then learn something about the interpreter API, too. If you already know Perl and C well, it's not *such* a big step. Have a look at the following core documents on XS: 1. [perlxstut](http://perldoc.perl.org/perlxstut.html) (XS tutorial) 2. [perlxs](http://perldoc.perl.org/perlxs.html) (XS reference) 3. [perlapi](http://perldoc.perl.org/perlapi.html) (Interpreter API) Additionally, there's plenty of tutorials and how-tos on the internet. Now, interfacing to C++ using XS requires some additional steps. It can be a bit frustrating to work out at first, but neatly falls into place once you get it. In this regard, the core documentation is sparse at best. But all is not lost. Mattia Barbon, the creator of the wxWidgets bindings for Perl, wrote a great tool "XS++" that makes this almost dead simple (or as simple as XS). It's included in Wx, but we're working on splitting it out into its own distribution. This is work in progress. You can find [Mattia's XS++ code](http://github.com/mbarbon/extutils-xspp/tree/master) and a [modified version of mine](http://github.com/mbarbon/extutils-xspp/network) on github. Barring a release of a standalone XS++ to CPAN, I would suggest learning to write XS for C++ from other resources: * Quite a long time ago, John Keiser wrote an excellent [tutorial on XS and C++](http://www.johnkeiser.com/perl-xs-c++.html). It also includes further pointers to useful tools and documentation. * I learned XS&C++ from that tutorial and some examples I found on CPAN. I don't recall what I looked at then. But now I can point to my own work as a (good or bad, I don't know) example: [Math::SymbolicX::FastEvaluator](http://search.cpan.org/dist/Math-SymbolicX-FastEvaluator). * Similarly, the planned XS++ distribution contains a [complete (albeit pointless) example](http://github.com/tsee/extutils-xspp/tree/0deb4fce1858701d09da4dfb30569e4de8132070/examples/Object-WithIntAndString) of using XS++ to interface C++ and Perl. Since XS++ is translated to plain XS, you can use it to *generate* examples. PS: There's also the Inline::CPP module. If that works, it is probably the easiest solution. I doubt it can handle templates, though.
Check <http://www.swig.org> : > "SWIG is a software development tool > that connects programs written in C > and C++ with a variety of high-level > programming languages. SWIG is used > with different types of languages > including common scripting languages > such as Perl, PHP, Python, Tcl and > Ruby."
How can I use a C++ class from Perl?
[ "", "c++", "perl", "xs", "" ]
Is there a way in C/C++ to find the location (full path) of the current executed program? (The problem with `argv[0]` is that it does not give the full path.)
To summarize: * On Unixes with `/proc` really straight and realiable way is to: + `readlink("/proc/self/exe", buf, bufsize)` (Linux) + `readlink("/proc/curproc/file", buf, bufsize)` (FreeBSD) + `readlink("/proc/self/path/a.out", buf, bufsize)` (Solaris) * On Unixes without `/proc` (i.e. if above fails): + If argv[0] starts with "/" (absolute path) this is the path. + Otherwise if argv[0] contains "/" (relative path) append it to cwd (assuming it hasn't been changed yet). + Otherwise search directories in `$PATH` for executable `argv[0]`. Afterwards it may be reasonable to check whether the executable isn't actually a symlink. If it is resolve it relative to the symlink directory. This step is not necessary in /proc method (at least for Linux). There the proc symlink points directly to executable. Note that it is up to the calling process to set `argv[0]` correctly. It is right most of the times however there are occasions when the calling process cannot be trusted (ex. setuid executable). * On Windows: use `GetModuleFileName(NULL, buf, bufsize)`
Use [GetModuleFileName()](http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx) function if you are using Windows.
How do I find the location of the executable in C?
[ "", "c++", "c", "linux", "unix", "path", "" ]
Or possibly there is a better way. I am building a dynamic query builder for NHibernate, we don't want to put HQL directly into the application, we want it as ORM agnostic as possible. It looks like this currently: ``` public override IEnumerable<T> SelectQuery(Dictionary<string, string> dictionary) { string t = Convert.ToString(typeof (T).Name); string criteria = string.Empty; foreach (KeyValuePair<string, string> item in dictionary) { if (criteria != string.Empty) criteria += " and "; criteria += item.Key + " = '" + item.Value + "'"; } string query = " from " + t; if (criteria != string.Empty) query += " where " + criteria; return FindByHql(query); } ``` ok, great, however.... there are two things in here that pose a problem: 1. This query only handles "and," my initial thought is to pass is to build a method to dynamically build the dictionary that takes the property name, value, and an operator "and" or "or" and builds the dictionary along with an array of operators. Does that sound like the right thing to do? 2. Ok, so, this works GREAT, however, when there is an integer it fails because of the single quotes. What I think would be the BEST way is have the dictionary accept `<T.Property, string>` and then reflect into T.Property to find the datatype and behave accordingly. Am I over complicating this? Thank you.
What about something like this. Where you have an enum for the operation. Instead of passing a string for the dictionary you pass a type of QueryObject that has the type of the value and an operation for the value. You can see below. ``` public enum Operation { And, Or } public class QueryObject { public string Value { get; set; } public Type Type { get; set; } public Operation Operation { get; set; } } public override IEnumerable<T> SelectQuery(Dictionary<string, QueryObject> dictionary) { string t = Convert.ToString(typeof(T).Name); string criteria = string.Empty; foreach (KeyValuePair<string, QueryObject> item in dictionary) { if (!string.IsNullOrEmpty(criteria)) { switch (item.Value.Operation) { case Operation.And: criteria += " and "; break; case Operation.Or: criteria += " or "; break; default: break; } } if (item.Value.Type == typeof(int)) { criteria += item.Key + " = " + item.Value + " "; } else { criteria += item.Key + " = '" + item.Value + "'"; } } string query = " from " + t; if (criteria != string.Empty) query += " where " + criteria; return FindByHql(query); } ```
I would suggest possibly creating a class that has all the properties you need: ``` Name, Value, Type, JoinType (possibly an enum with Or / And) ``` then, have your method take a collection of these types as opposed to a Dictionary. This way, you can easily check if you need to do and / or, as well as check if you need quotes...
Can I pass in T.Property? Also, ideas for improving this method?
[ "", "c#", ".net", "nhibernate", ".net-3.5", "orm", "" ]
Given this declaration: ``` using System; using System.Collections; using System.Collections.Generic; namespace AProject.Helpers { public static class AClass { ``` and this declaration ``` namespace AProject.Helpers { using System; using System.Collections; using System.Collections.Generic; public static class AClass { ``` are there any difference in any sense between them? Or is just a difference in coding styles? I allways used to declared my classes like the first, but recently noticed that Microsoft [uses the second](http://www.google.com/codesearch/p?hl=es#ygP0YMz4l9U/MVC/src/MvcFutures/Mvc/ImageExtensions.cs&q=url%20content&exact_package=https://aspnet.svn.codeplex.com/svn).
In the latter version the using directives only apply within the namespace declaration. In most cases you'll only have a single namespace declaration: ``` // Using directives ... namespace X { // Maybe more using directives // Code } // End of file ``` The main difference is if you have multiple namespaces in the same file: ``` // Using directives ... namespace X { // Maybe more using directives // Code } namespace Y { // Maybe more using directives // Code } // End of file ``` In this case the using directives in the namespace X declaration don't affect the code inside the namespace Y declaration, and vice versa. However, that's not the only difference - there's a [subtle case which Eric Lippert points out](http://blogs.msdn.com/ericlippert/archive/2007/06/25/inside-or-outside.aspx) where it can affect the code even with just a single namespace declaration. (Basically if you write `using Foo;` inside the namespace X declaration, and there's a namespace `X.Foo` as well as `Foo`, the behaviour changes. This can be remedied using a namespace alias, e.g. `using global::Foo;` if you really want.) Personally I'd stick to: * One namespace declaration per file (and usually one top-level type per file) * Using directives outside the namespace declaration
It makes the using directives local to that namespace, which in practice should make no difference since you're (hopefully) not declaring multiple types in multiple namespaces in a single source file. Details [here](https://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace).
What is the difference between these two declarations?
[ "", "c#", "coding-style", "" ]
I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... WindowsError: [Error 3] The system cannot find the path specified. Here's a bit of the code: ``` exepath = os.path.join(EXE file localtion) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] ``` I have imported subprocess and also from subprocess import \* For example, This is how my exe file location looks like in the first line of the code I show: ``` exepath= os.path.join('/Program Files','next folder','next folder','blah.exe') ``` Am I missing something?
You need to properly escape the space in the executable path
Besides properly escaping spaces and other characters that could cause problems (such as /), you can also use the 8 character old DOS paths. For example, Program Files would be: Progra~1 , making sure to append ~1 for the last two characters. EDIT: You could add an r to the front of the string, making it a raw literal. Python would read the string character for character. Like this: r " \Program files"
Windows error and python
[ "", "python", "popen", "" ]
I've got an aspx page with a simple databound datagrid on it; some users get the page just fine. Others get 404s. If there was something wrong with the page, wouldn't I get an asp.net error, instead of a 404?
For security reasons IIS6 can send 404 when in fact the result should be permission denied or forbidden. Someone trying to gain malicious access will not be alerted to the existance of a page that they may then concentrate efforts on. I can't remember if this is default config or needs to be switched on.
What kind of 404 is it? (Is it from IIS or from ASP .Net?) If it's an ASP .Net 404, it's possible (but unlikely) that your code is throwing a fake 404 (search for `throw new HttpException`) Do you have a server cluster? If so, one server might have an out-of-date copy.
When would you get a 404 when a page actually exists?
[ "", "c#", "asp.net", "iis", "" ]
I'm running the following code : ``` RunspaceConfiguration config = RunspaceConfiguration.Create(); PSSnapInException warning; config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning); if (warning != null) throw warning; Runspace thisRunspace = RunspaceFactory.CreateRunspace(config); thisRunspace.Open(); string alias = usr.AD.CN.Replace(' ', '.'); string letter = usr.AD.CN.Substring(0, 1); string email = alias + "@" + (!usr.Mdph ? Constantes.AD_DOMAIN : Constantes.MDPH_DOMAIN) + "." + Constantes.AD_LANG; string db = "CN=IS-" + letter + ",CN=SG-" + letter + ",CN=InformationStore,CN=" + ((char)letter.ToCharArray()[0] < 'K' ? Constantes.EXC_SRVC : Constantes.EXC_SRVD) + Constantes.EXC_DBMEL; string cmd = "Enable-Mailbox -Identity \"" + usr.AD.CN + "\" -Alias " + alias + " -PrimarySmtpAddress " + email + " -DisplayName \"" + usr.AD.CN + "\" -Database \"" + db + "\""; Pipeline thisPipeline = thisRunspace.CreatePipeline(cmd); thisPipeline.Invoke(); ``` The code is running in a thread created that way : ``` t.WorkThread = new Thread(cu.CreerUser); t.WorkThread.Start(); ``` If I run the code directly (not through a thread), it's working. When in a thread it throws the following exception : ObjectDisposedException "The safe handle has been closed." (Translated from french) I then replaced "Open" wirh "OpenAsync" which helped not getting the previous exception. But when on Invoke I get the following exception : InvalidRunspaceStateException "Unable to call the pipeline because its state of execution is not Opened. Its current state is Opening." (Also translated from french) I'm clueless... Any help welcome !!! Thanks !!! --- With Open: ``` à Microsoft.Win32.Win32Native.GetTokenInformation(SafeTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength) à System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, UInt32& dwLength) à System.Security.Principal.WindowsIdentity.get_User() à System.Security.Principal.WindowsIdentity.GetName() à System.Security.Principal.WindowsIdentity.get_Name() à System.Management.Automation.MshLog.GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity) à System.Management.Automation.MshLog.GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo) à System.Management.Automation.MshLog.LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState, InvocationInfo invocationInfo) à System.Management.Automation.MshLog.LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState) à System.Management.Automation.Runspaces.LocalRunspace.OpenHelper() à System.Management.Automation.Runspaces.RunspaceBase.CoreOpen(Boolean syncCall) à System.Management.Automation.Runspaces.RunspaceBase.Open() à Cg62.ComposantsCommuns.ActiveDirectory.Exchange.BoitesAuxLettres.CreationBAL(User usr, IList`1 log) dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\Exchange.cs:ligne 141 à Cg62.ComposantsCommuns.ActiveDirectory.ComptesUtilisateurs.CreationUser.CreerUser() dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\ComptesUtilisateurs.cs:ligne 199 à System.Threading.ThreadHelper.ThreadStart_Context(Object state) à System.Threading.ExecutionContext.runTryCode(Object userData) à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) à System.Threading.ThreadHelper.ThreadStart() ``` With OpenAsync: ``` à System.Management.Automation.Runspaces.RunspaceBase.AddToRunningPipelineList(PipelineBase pipeline) à System.Management.Automation.Runspaces.RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(PipelineBase pipeline, Boolean syncCall) à System.Management.Automation.Runspaces.PipelineBase.CoreInvoke(IEnumerable input, Boolean syncCall) à System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input) à System.Management.Automation.Runspaces.Pipeline.Invoke() à Cg62.ComposantsCommuns.ActiveDirectory.Exchange.BoitesAuxLettres.CreationBAL(User usr, IList`1 log) dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\Exchange.cs:ligne 149 à Cg62.ComposantsCommuns.ActiveDirectory.ComptesUtilisateurs.CreationUser.CreerUser() dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\ComptesUtilisateurs.cs:ligne 199 à System.Threading.ThreadHelper.ThreadStart_Context(Object state) à System.Threading.ExecutionContext.runTryCode(Object userData) à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) à System.Threading.ThreadHelper.ThreadStart() ``` Sorry for the late reply... I had a lot going on --- Upgraded to Powershell 2.0 and I got past the Open error but now I have the following on the Invoke. I changed my command to : ``` Enable-Mailbox -Identity "Aagtest Abe" -Alias Aagtest.Abe -PrimarySmtpAddress smtp.address@domain.com -DisplayName "Aagtest Abe" -Database "myDb" -DomainController adc.domain.int ``` The command works fine from powershell. I get the following exception CmdletInvocationException : "Une exception a été levée par l'initialiseur de type pour '<Module>'." No idea on how to translate that... StackTrace : ``` à Microsoft.Exchange.Data.Directory.DSAccessTopologyProvider..ctor(String machineName) à Microsoft.Exchange.Data.Directory.DSAccessTopologyProvider..ctor() à Microsoft.Exchange.Data.Directory.DirectoryServicesTopologyProvider.DiscoverConfigDC() à Microsoft.Exchange.Data.Directory.DirectoryServicesTopologyProvider..ctor() à Microsoft.Exchange.Data.Directory.TopologyProvider.InitializeInstance() à Microsoft.Exchange.Data.Directory.TopologyProvider.GetInstance() à Microsoft.Exchange.Data.Directory.ADSession.GetConnection(String preferredServer, Boolean isWriteOperation, Boolean isNotifyOperation, ADObjectId& rootId) à Microsoft.Exchange.Data.Directory.ADSession.GetReadConnection(String preferredServer, ADObjectId& rootId) à Microsoft.Exchange.Data.Directory.ADSession.IsReadConnectionAvailable() à Microsoft.Exchange.Configuration.Tasks.RecipientObjectActionTask`2.InternalBeginProcessing() à Microsoft.Exchange.Management.RecipientTasks.EnableMailbox.InternalBeginProcessing() à Microsoft.Exchange.Configuration.Tasks.Task.BeginProcessing() à System.Management.Automation.Cmdlet.DoBeginProcessing() à System.Management.Automation.CommandProcessorBase.DoBegin() ```
So the final answer to that problem is you can't execute remote Exchange powershell commands if you impersonate through advapi32 LogonUser. Wether the commands are executed in a thread or not don't matter at all as far as I tested. What seem to be the correct way - well the one that works for me - is to authenticate right after you connect to the Runspace. As to why this happens... feel free to tell me !! This code **must not** be executed while impersonating. ``` IContexteRemotePowerShell crp: crp.ConfigurationName = "Microsoft.Exchange"; crp.RemoteUri = "http://exhangeserver/powershell"; crp.User = "account who has rights to do stuff on the exchange server"; crp.Password = "its password"; crp.Domaine = "Domain"; private static void Connect(IContexteRemotePowerShell contexte) { try { Espace = RunspaceFactory.CreateRunspace(); Espace.Open(); } catch (InvalidRunspaceStateException ex) { throw new TechniqueException(MethodBase.GetCurrentMethod(), "Error while creating runspace.", ex); } // Create secure password SecureString password = new SecureString(); foreach (char c in contexte.Password) { password.AppendChar(c); } // Create credential PSCredential psc = new PSCredential(contexte.User, password); PSCommand command = new PSCommand(); command.AddCommand("New-PSSession"); command.AddParameter("Credential", psc); if (!String.IsNullOrEmpty(contexte.Serveur)) command.AddParameter("computername", contexte.Serveur); if (!String.IsNullOrEmpty(contexte.RemoteUri)) command.AddParameter("ConnectionUri", new Uri(contexte.RemoteUri)); if (!string.IsNullOrEmpty(contexte.ConfigurationName)) command.AddParameter("ConfigurationName", contexte.ConfigurationName); //// Create the session PowerShell powershell = PowerShell.Create(); powershell.Commands = command; powershell.Runspace = Espace; Collection<PSObject> result = ExecuterCommande(command); if (result.Count != 1) throw new TechniqueException(MethodBase.GetCurrentMethod(), "Error while connecting."); // Create session variable command = new PSCommand(); command.AddCommand("Set-Variable"); command.AddParameter("Name", "ra"); command.AddParameter("Value", result[0]); ExecuterCommande(command); } private const string InvokeCommand = "Invoke-Command -ScriptBlock {{ {0} }} -Session $ra"; private static string ExecuteRemoteScript(string cmd) { PSCommand command = new PSCommand(); command.AddScript(string.Format(InvokeCommand, cmd)); Collection<PSObject> result = ExecuterCommande(command); StringBuilder sb = new StringBuilder(); foreach (PSObject obj in result) { sb.AppendLine(obj.ToString()); } return sb.ToString().Trim(); } ```
Did you try this? ``` //set the default runspace for this thread System.Management.Automation.Runspaces.Runspace.DefaultRunspace = runspace; ```
powershell / runspace in a thread
[ "", "c#", "multithreading", "powershell", "" ]
I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason. ``` #!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ] programs = [ subprocess.Popen(c) for c in commands ] while True: for i in range(len(programs)): if programs[i].returncode is None: continue # still running else: # restart this one programs[i]= subprocess.Popen(commands[i]) time.sleep(1.0) ``` Upon executing the code the following exception is thrown: ``` Traceback (most recent call last): File "./marp.py", line 82, in <module> programs = [ subprocess.Popen(c) for c in commands ] File "/usr/lib/python2.6/subprocess.py", line 595, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory ``` I think I'm missing something obvious, can anyone see what's wrong with the code above?
Use `["screen", "-dmS", "RealmD", "top"]` instead of `["screen -dmS RealmD top"]`. Maybe also use the complete path to `screen`.
Only guess is that it can't find `screen`. Try `/usr/bin/screen` or whatever `which screen` gives you.
Python OSError: [Errno 2]
[ "", "python", "subprocess", "" ]
In C++ I have a file A.cpp that has the following in it: ``` namespace Foo { bool Bar() { return true; } } ``` How would I declare this function in A.h? How do I handle the namespace?
``` namespace Foo { bool Bar(); } ```
``` namespace Foo { bool Bar(); } ```
Header file for functions inside of a namespace?
[ "", "c++", "namespaces", "header", "" ]
We have a very large JavaScript application, where after many months of coding there have inevitably sprung a couple scope slip ups where a variable is defined without using the `var` keyword in the following fashion: ``` function() { x = 5; ... } ``` instead of: ``` function() { var x = 5; ... } ``` This is happening somewhere - we're not sure where - and searching for the variable name in question is difficult, since it's a common word that appears 1000s of times in our source. Is there a way to ask Firebug to break on the line that first creates a given global variable? To clarify, I would like to break at exactly the instant when `window.x` switches from `undefined` to a defined value, and to break statement. I've tried creating a watch expression and hoped I could turn it into a breakpoint, but I can't seem to create watch expressions without some kind of context or scope. If this isn't possible with Firebug, I'd be interested in anything that can accomplish this in Firefox in general.
Provided a few things 1. You know the name of the variable 2. You don't have a variable with that name in the global scope (declared outside functions), but only inside functions. 3. There are calls to the function that declares the variable. this little script would do the trick: ``` <script type="text/javascript"> window.__defineSetter__("x", function(value) { console.trace(); }); x = 1; </script> ``` You'll get a trace of the executed code before that assignment. It may fail to report some situations, so take a look at [JSLint](http://www.jslint.com/). Load all your JS files right there and lint them.
Here's the solution I ended up using by modifying Ionut G. Stan's solution: ``` window.__defineSetter__("name", function(value) { if (value=="div") { debugger; } }); ``` I used `debugger` instead of `console.trace()`, so I could stop and look at it mid-execution. With `console.trace()` I got a bazillion trace statements due to this line executing many times. The leaky scope turned out to be buried in Dojo, where Dojo is setting that variable to the name of a processed element.
Have Firebug break when a global variable x is defined
[ "", "javascript", "debugging", "firefox", "scope", "firebug", "" ]
I would like to create a REST interface for my Java Google App Engine program. I figured I would start by generating some XML from my POJOS. However, it seems that XStream is bitten by GAE's restrictions. What can I use to generate an XML string in Google App Engine? Thanks. Edit 1: Here is the beginning of the exception: ``` javax.servlet.ServletContext log: Exception while dispatching incoming RPC call com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String com.mydomain.client.ObjectService.sendObject(com.mydomain.client.models.myobject)' threw an unexpected exception: java.security.AccessControlException: access denied (java.io.SerializablePermission enableSubclassImplementation) ```
The exception is caused by a java.io.SerializablePermission, which according the javadoc is for allowing: > Subclass implementation of > ObjectOutputStream or > ObjectInputStream to override the > default serialization or > deserialization, respectively, of > objects XStream might be using Object streams under the covers, and falling foul of this permission not being granted. Does Google App Engine actually have a whitelist, or just a set of restricted permissions? JAXB2 doesn't use Object streams, so have you actually tried that?
For the same restriction (a patch is underway however) I ended producing JSON using org.json library. Also JAXB seems not to be in the whitelist.
POJO to an XML string in Google App Engine?
[ "", "java", "google-app-engine", "xml-serialization", "" ]
How to check current machine type? laptop or desktop ? I got this from <http://blog.csdn.net/antimatterworld/archive/2007/11/11/1878710.aspx> ,it works well on my home machine(Win2003 on laptop), it returns "Portable", but failed on my work machine(Vista on laptop), it returns "Other". here is the code: ``` public enum ChassisTypes { Other = 1, Unknown, Desktop, LowProfileDesktop, PizzaBox, MiniTower, Tower, Portable, Laptop, Notebook, Handheld, DockingStation, AllInOne, SubNotebook, SpaceSaving, LunchBox, MainSystemChassis, ExpansionChassis, SubChassis, BusExpansionChassis, PeripheralChassis, StorageChassis, RackMountChassis, SealedCasePC } public static ChassisTypes GetCurrentChassisType() { ManagementClass systemEnclosures = new ManagementClass("Win32_SystemEnclosure"); foreach (ManagementObject obj in systemEnclosures.GetInstances()) { foreach (int i in (UInt16[ ])(obj["ChassisTypes"])) { if (i > 0 && i < 25) { return (ChassisTypes)i; } } } return ChassisTypes.Unknown; } ```
read registry key from HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services\pcmcia, the ‘Start’ value, it's laptop if start =0, otherwise it's desktop machine if start doesn't exist or start != 0.
Well, I may be attempting to raise the dead here, but I would suggest that the most reliable method of determining a laptop would be the present of a lid status switch. See [GetPwrCapabilities](http://msdn.microsoft.com/en-us/library/aa372691%28v=vs.85%29.aspx) and [System\_power\_Capabilities](http://msdn.microsoft.com/en-us/library/aa373215%28v=vs.85%29.aspx)
How to check the machine type? laptop or desktop?
[ "", "c#", "wmi", "" ]
I am using SPFieldCurrency column in one of my lists. My custom code receives a string value as a parameter, which contains the field's value as returned by the GetFormattedValue() method. Now my problem is that the value received by my method contain currency symbols in them, Eg, 10$, 10¥, 10€ etc. Because of the presence of the currency symbols in my code, when I do a Double.TryParse() on these values, it fails. How do I extract the numerical value from the display string value of an SPFieldCurrency object, without knowing the culture info of the currency?
Got it. The gotcha is to use NumberStyles.Any. This removes all currency symbols. I used Double.TryParse(valueString, NumberStyles.Any, CultureInfo.CurrentCulture.NumberFormat, out value) It worked for me. Thanks
"You can do this by creating a NumberFormatInfo instance and setting the properties on that to handle the particular aspects of your string. For example, you want to set the CurrencySymbol property to "$", the NumberDecimalDigits property to 2, etc." [source](http://bytes.com/groups/net-c/239804-parse-currency-string-decimal) The only issue you have i guess is that there are multiple types of currency in the field...
Get the numerical value of an SPFieldCurrency field
[ "", "c#", ".net", "sharepoint", "type-conversion", "currency", "" ]
Do you know of a precise and concise online C++ syntax reference? Please provide the link...
Try <http://www.cplusplus.com/reference/> for the library. Try <http://www.kuzbass.ru:8086/docs/isocpp/> for the Final Draft International Standard for C++98. Try <http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2798.pdf> for the Working Draft Standard for C++0X.
[cppreference.com](http://www.cppreference.com/wiki/) Microsoft specific [reference](http://msdn.microsoft.com/en-us/library/3bstk3k5.aspx).
Good online C++ syntax reference?
[ "", "c++", "syntax", "" ]
I recently moved a bunch of tables from an existing database into a new database due to the database getting rather large. After doing so I noticed a dramatic decrease in performance of my queries when running against the new database. **The process I took to recreate the new database is this:** 1. Generate Table CREATE scripts using sql servers automatic script generator. 2. Run the create table scripts 3. Insert all data into new database using INSERT INTO with a select from the existing database. 4. Run all the alter scripts to create the foreign keys and any indexes **Does anyone have any ideas of possible problems with my process, or some key step I'm missing that is causing this performance issue?** Thanks.
Did you script the indexes from the tables in the original database? Missing indexes could certainly account for poor performance.
first I would an a mimimum make sure that **auto create statistics** is enabled you can also set **auto update statistics** to true after that I would update the stats by running ``` sp_updatestats ``` or ``` UPDATE STATISTICS ``` Also realize that the first time you hit the queries it will be slower because nothing will be cached in RAM. On the second hit should be much faster
SQL Server slow down after duplicating database
[ "", "sql", "sql-server", "database", "performance", "" ]
In this case the application which sets the environment variable is executed in/from the application that needs to access the env.var. The [Main() Return Values (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/0fwzzxz2(VS.80).aspx) msdn article discusses its use within a batch file. If I try the same, everything is fine; but what is required is to run not from a batch script but from within an application. ``` Process.Start("app","args"); // app sets the env.var. string envVar = System.Environment.GetEnvironmentVariable("ERRORLEVEL"); ``` was obviously unsuccessful. Process.Start made the "app" work in a completely different environment I believe. In other words, I need to run "app" in the same environment as the caller application in order to reach the environment variable it sets.
If you're just trying to set the child's environment from the parent: ``` var p = new Process(); p.StartInfo.EnvironmentVariables["TEST_ENV"] = "From parent"; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = @"C:\src\bin\Debug\ChildProc.exe"; p.Start(); ``` If you don't want the child to inherit the parent process environment: ``` var psi = new ProcessStartInfo(); psi.EnvironmentVariables["TEST_ENV"] = "From parent"; psi.UseShellExecute = false; psi.FileName = @"C:\src\bin\Debug\ChildProc.exe"; Process.Start(psi); ```
The environment variables are inherited to child processes but each child gets a copy - if you change the parent's environment afterwards, this will not reflect in the child. This is for security reasons: If the variables were shared, processes could see into each other's memory which would cause all kinds of problems. So the solution is to set the variable before starting the new process. If you need to communicate with an existing child process, use a pipe.
How can an application access the environment variable set by another application?
[ "", "c#", "environment-variables", "environment", "" ]
What is difference betwwen /MD and /MDD( multi threaded debug dll ) in c/c++->code generation propertis of visual studio ....
They specify which runtime to use. Both use mmulti-threaded dynamic (DLL) runtimes, but the /MDD version uses the debug version and also defines the \_DEBUG symbol for you. See [this MSDN page](https://stackoverflow.com/questions/17903/should-developers-be-specialists-or-generalists) for details.
The debug version (MDD) allows you to step into the C and C++ libraries, during debugging. There are additional checks for incorrect heap operations and memory leaks. Having dependencies (eg. DLL) to both the release and debug versions can lead to problems so it is recommended that you stick to /MDD for debug version and /MD for release versions. For Visual Studio 2005/2008, if your application uses /MDD, but depends on DLLs that are built with the release libraries, you will also need to include the manifest for the release libraries in your project settings.
what is difference btw /MD and /MDD in VisualStudio C++?
[ "", "c++", "visual-studio", "visual-studio-2005", "" ]
I'm developing this project for a device (let's say) 'Prototype X' and it has manufacturer provided .Net API. This API fires events (which I should subscribe to) upon receiving some special -signal- from the device in real world. What I want/asked to do is, update the asp page (which the user sees) with proper information when this event is fired. By update I mean also refreshing user's page if possible at all... How do I do this in asp.net?
You cannot trigger a page update from the server side. What you must do is use a timer on the client side (javascript) to refresh the page (or get the new data via AJAX) on a regular interval.
You can force the page to refresh by using a meta tag, or javascript. Or AJAX.
Updating a page from server-triggered event
[ "", "c#", ".net", "asp.net", "events", "" ]
I'm using [`Zend_Validate`](http://framework.zend.com/manual/en/zend.validate.html) to validate some form input (Zend Framework version is 1.8.2). For some reason, using the [`Zend_Filter_Input`](http://framework.zend.com/manual/en/zend.filter.input.html) interface as described [here](http://framework.zend.com/manual/en/zend.filter.input.html) does not work: ``` $data = $_POST; $filters = array('*' => array('StringTrim')); $validators = array('driverName' => array('NotEmpty','messages' => 'This should override the default message but does not!')); $inputFilter = new Zend_Filter_Input($filters,$validators,$data); $messages = $inputFilter->getMessages(); debug($messages); //show me the variable contents ``` Output from `debug($messages)`: ``` Array ( [driverName] => Array ( [isEmpty] => You must give a non-empty value for field 'driverName' ) ) ``` No matter what I do, I cannot override that message. If I use the validator directly, i.e.: ``` $notEmpty = new Zend_Validate_NotEmpty(); $notEmpty->setMessage('This WILL override the default validation error message'); if (!$notEmpty->isValid($_POST['driverName'])) { $messages = $notEmpty->getMessages(); debug($messages); } ``` Output from `debug($messages)`: ``` Array ( [isEmpty] => Please enter your name ) ``` Bottom line. I can get validators to work, but without the benefits of the `Zend_Filter_Input` interface method of validation I might as well write my own validation class! Does anyone have a clue as to why this is happening, and how to fix it? Could it be a bug?
The `messages` key in the validator array must be passed an array of key/value pairs, where the key is the validation message constant, and the value is your custom error message. Here's an example: ``` $validators = array( 'excerpt' => array( 'allowEmpty' => true, array('StringLength', 0, Ctrl::getOption('blog/excerpt/length')), 'messages' => array(Zend_Validate_StringLength::TOO_LONG => 'The post excerpt must not exceed '.Ctrl::getOption('blog/excerpt/length').' characters.') ), ); ``` However, in your case, the error message you are receiving is coming from the the `allowEmpty` meta command of Zend\_Filter\_Input. This isn't really a standard validator. You can set it like so: ``` $options = array( 'notEmptyMessage' => "A non-empty value is required for field '%field%'" ); $input = new Zend_Filter_Input($filters, $validators, $data, $options); // alternative method: $input = new Zend_Filter_Input($filters, $validators, $data); $input->setOptions($options); ``` If you need a different not empty message per field, I'd recommend setting `allowEmpty => true` and adding a `NotEmpty` validator with a custom message. For your reference, the correct message key for the `NotEmpty` validator is `Zend_Validate_NotEmpty::IS_EMPTY`
The MESSAGES argument takes an array, not a string. Try this: ``` $validators = array('driverName' => array('NotEmpty', 'messages' => array( 0 => 'This should override the default message but does not!' ) ) ); ```
Why can't I override the default validation error message?
[ "", "php", "zend-framework", "validation", "" ]
I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work. As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the \*.a file in `C:/Program Files (x86)/python/2.6/libs`. Therefore, I compile the file with this command: ``` gcc -shared -o mod_python.dll mod_python.o "-LC:\Program Files (x86)\python\2.6\libs" -lpython26 -Wl,--out-implib,libmod_python.a -Wl,--output-def,mod_python.def ``` and I get those errors: ``` Creating library file: libmod_python.a mod_python.o: In function `module_init': mod_python.c:34: undefined reference to `__imp__Py_Initialize' mod_python.c:35: undefined reference to `__imp__PyEval_InitThreads' ... and so on ... ``` * My Python "root" folder is `C:\Program Files (x86)\python\2.6` * The Devsystem is a Windows Server 2008 * GCC Information: `Reading specs from C:/Program Files (x86)/MinGW/bin/../lib/gcc/mingw32/3.4.5/specs Configured with: ../gcc-3.4.5-20060117-3/configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-libgcj --disable-java-awt --without-x --enable-java-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchronization --enable-libstdcxx-debug Thread model: win32 gcc version 3.4.5 (mingw-vista special r3)` What I do wrong? How I get it compiled and linked :-)? Cheers, gregor --- **Edit:** I forgot to write information about my Python installation: It's the official python.org installation 2.6.1 ... and how I created the python.a file: ``` dlltool -z python.def --export-all-symbols -v c:\windows\system32\python26.dll dlltool --dllname c:\Windows\system32\python26.dll --def python.def -v --output-lib python26.a ```
Well on Windows the python distribution comes already with a `libpython26.a` in the libs subdir so there is no need to generate `.a` files using dll tools. I did try a little example with a single C file toto.c: ``` gcc -shared -o ./toto.dll ./toto.c -I/Python26/include/ -L/Python26/libs -lpython26 ``` And it works like a charm. Hope it will help :-)
Python (at least my distribution) comes with a "python-config" program that automatically creates the correct compiler and linker options for various situations. However, I have never used it on Windows. Perhaps this tool can help you though?
How to link C lib against python for embedding under Windows?
[ "", "python", "c", "windows", "gcc", "linker", "" ]
I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this? For example: ``` import my_module my_module.super_fast_written_in_C() my_module.written_in_Python__easy_to_maintain() ``` I'm primarily interested in Python 2.x.
The usual way of doing this is: mymod.py contains the utility functions written in Python, and imports the goodies in the \_mymod module which is written in C and is imported from \_mymod.so or \_mymod.pyd. For example, look at .../Lib/csv.py in your Python distribution.
Prefix your native extension with an underscore. Then, in Python, create a wrapper module that imports that native extension and adds some other non-native routines on top of that.
Combining C and Python functions in a module
[ "", "python", "cpython", "" ]
If I have a list in Python like ``` [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] ``` How do I calculate the greatest number of repeats for any element? In this case `2` is repeated a maximum of 4 times and `1` is repeated a maximum of 3 times. Is there a way to do this but also record the index at which the longest run began?
Use [groupby](http://docs.python.org/library/itertools.html#itertools.groupby), it group elements by value: ``` from itertools import groupby group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]) print max(group, key=lambda k: len(list(k[1]))) ``` And here is the code in action: ``` >>> group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]) >>> print max(group, key=lambda k: len(list(k[1]))) (2, <itertools._grouper object at 0xb779f1cc>) >>> group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3]) >>> print max(group, key=lambda k: len(list(k[1]))) (3, <itertools._grouper object at 0xb7df95ec>) ``` From python documentation: > The operation of groupby() is similar > to the uniq filter in Unix. It > generates a break or new group every > time the value of the key function > changes ``` # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D ``` If you also want the index of the longest run you can do the following: ``` group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3]) result = [] index = 0 for k, g in group: length = len(list(g)) result.append((k, length, index)) index += length print max(result, key=lambda a:a[1]) ```
Loop through the list, keep track of the current number, how many times it has been repeated, and compare that to the most times youve seen that number repeated. ``` Counts={} Current=0 Current_Count=0 LIST = [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] for i in LIST: if Current == i: Current_Count++ else: Current_Count=1 Current=i if Current_Count>Counts[i]: Counts[i]=Current_Count print Counts ```
How do you calculate the greatest number of repetitions in a list?
[ "", "python", "list", "" ]
I have a Python script that writes data packets to an Arduino board through [pySerial](http://pyserial.sourceforge.net/). Sometimes while writing the code to the board pySerial raises an input/output error with errno 5. Some research says that this indicates an error while writing in the file representing the connection to the Arduino board. The code that sends, sends only single byte packets: ``` try: # Check if it's already a single byte if isinstance(byte, str): if len(byte) == 1: # It is. Send it. self.serial.write(byte) else: # It's not raise PacketException # Check if it's an integer elif isinstance(byte, int): self.serial.write(chr(byte)) # It is; convert it to a byte and send it else: raise PacketException # I don't know what this is. except Exception as ex: print("Exception is: " + ex.__getitem__() + " " + ex.__str__()) ``` The error printed by this code is: > OS Error Input/Output Error Errno 5 Is there something wrong in my code while sending? Do I need to check if the serial connection is ready to send something or should there be a delay after the sending? Or could there be a problem with the hardware or the connection with the hardware? **Edit**: I looked into the Linux implementation from pyserial and the implementation is only passing the error to my code. So no new real insights from there. Is there a good way to test what is happening in the program?
Sorry to have bothered you but I'm very sure that the error is caused by the arduino resetting itself and therefore closing the connection to the computer.
If you are running this on Windows, you can't have the Arduino IDE open with a serial connection at the same time that you run your Python script. This will throw the same error.
Getting an input/output error from Python with pySerial
[ "", "python", "serial-port", "arduino", "pyserial", "" ]
I parse an XML file to load data, and when i have an attribute that has an unrecognized value, i throw an InvalidDataException. Is this the correct one or is there a better/more descriptive one
That exception suggests that it's an error in the format of the file itself, like an error in the encoding of the characters. An XmlException would be a better fit. Consider throwing an ApplicationException instead, as it's not really an error in the XML format, but rather something that the XML contains that your application does not accept.
That seems reasonable to me. It's not an exception I'm particularly familiar with (i.e. I haven't come across it in other APIs) but it gets the point across. I guess the only question is whether an `IOException` of some form would be more appropriate. It's not the actual *transfer* that's the problem here, of course - it's the content that's being transferred. It's a grey area, certainly.
Is this the right exception?
[ "", "c#", "xml", "exception", "" ]
In my `JTabbedPane`, I am removing tabs in 2 different ways: ``` tabbedPane.remove(index) ``` and ``` tabbedPane.removeAll() ``` Both work fine in terms of closing the tabs. However, I have a change listener on my `TabbedPane` that calls back to another module to report on tab changes. This is where the problem is. When adding and removing tabs using `remove(index)`, the source TabbedPane in the `stateChanged()` method contains the correct number of tabs when checking `tabbedPane.getTabCount()`. However, when calling `tabbedPane.getTabCount()` after `tabbedPane.removeAll()`, the count is still the count that was present immediately before the `removeAll()`. Does anyone have any suggestions?
After looking at the source code, I see what's happening. `JTabbedPane` fires `ChangeEvents` when the selected tab is changed. But to remove all tabs, it first sets the selected tab to -1 and *then* removes all the tabs. So when the `ChangeListener` catches the event, all the tabs are still there. If you want to know the number of tabs at all times, I'm afraid you'll have to iterate through the tabs yourself and remove them one by one. ``` while (myTabbedPane.getTabCount() > 0) myTabbedPane.remove(0); ```
Here you go; use ContainerListener instead: ``` import java.awt.event.ContainerEvent; import java.awt.event.ContainerListener; import javax.swing.JPanel; import javax.swing.JTabbedPane; import junit.framework.TestCase; public class JTabbedPaneTest extends TestCase { private JTabbedPane pane; private int count = 0; protected void setUp() throws Exception { pane = new JTabbedPane(); ContainerListener containerListener = new ContainerListener() { public void componentAdded(ContainerEvent e) { count++; } public void componentRemoved(ContainerEvent e) { count--; } }; pane.addContainerListener(containerListener); JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); pane.add(panel1); pane.add(panel2); } public void testOne() throws Exception { assertEquals(2, count); assertEquals(2, pane.getTabCount()); pane.remove(0); pane.remove(0); assertEquals(0, count); assertEquals(0, pane.getTabCount()); } public void testMany() throws Exception { assertEquals(2, count); assertEquals(2, pane.getTabCount()); pane.removeAll(); assertEquals(0, count); assertEquals(0, pane.getTabCount()); } } ```
After calling JTabbedPane.removeAll(), the JTabbedPane still has x number of tabs?
[ "", "java", "swing", "jtabbedpane", "" ]
In Europe decimals are separated with '**,**' and we use optional '**.**' to separate thousands. I allow currency values with: * US-style 123,456.78 notation * European-style 123.456,78 notation I use the next regular expression (from RegexBuddy library) to validate the input. I allow optional two-digits fractions and optional thousands separators. ``` ^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{0,2})?|(?:,[0-9]{3})*(?:\.[0-9]{0,2})?|(?:\.[0-9]{3})*(?:,[0-9]{0,2})?)$ ``` I would like to parse a currency string to a float. For example 123,456.78 should be stored as 123456.78 123.456,78 should be stored as 123456.78 123.45 should be stored as 123.45 1.234 should be stored as 1234 12.34 should be stored as 12.34 and so on... Is there an easy way to do this in Java? ``` public float currencyToFloat(String currency) { // transform and return as float } ``` **Use BigDecimal instead of Float** --- Thanks to everyone for the great answers. I have changed my code to use BigDecimal instead of float. I will keep previous part of this question with float to prevent people from doing the same mistakes I was gonna do. **Solution** --- The next code shows a function which transforms from US and EU currency to a string accepted by BigDecimal(String) constructor. That it is to say a string with no thousand separator and a point for fractions. ``` import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestUSAndEUCurrency { public static void main(String[] args) throws Exception { test("123,456.78","123456.78"); test("123.456,78","123456.78"); test("123.45","123.45"); test("1.234","1234"); test("12","12"); test("12.1","12.1"); test("1.13","1.13"); test("1.1","1.1"); test("1,2","1.2"); test("1","1"); } public static void test(String value, String expected_output) throws Exception { String output = currencyToBigDecimalFormat(value); if(!output.equals(expected_output)) { System.out.println("ERROR expected: " + expected_output + " output " + output); } } public static String currencyToBigDecimalFormat(String currency) throws Exception { if(!doesMatch(currency,"^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{0,2})?|(?:,[0-9]{3})*(?:\\.[0-9]{0,2})?|(?:\\.[0-9]{3})*(?:,[0-9]{0,2})?)$")) throw new Exception("Currency in wrong format " + currency); // Replace all dots with commas currency = currency.replaceAll("\\.", ","); // If fractions exist, the separator must be a . if(currency.length()>=3) { char[] chars = currency.toCharArray(); if(chars[chars.length-2] == ',') { chars[chars.length-2] = '.'; } else if(chars[chars.length-3] == ',') { chars[chars.length-3] = '.'; } currency = new String(chars); } // Remove all commas return currency.replaceAll(",", ""); } public static boolean doesMatch(String s, String pattern) { try { Pattern patt = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); Matcher matcher = patt.matcher(s); return matcher.matches(); } catch (RuntimeException e) { return false; } } } ```
To answer a slightly different question: *don't* use the float type to represent currency values. [It will bite you](http://www.javapractices.com/topic/TopicAction.do?Id=13). Use a base-10 type instead, like `BigDecimal`, or an integer type like `int` or `long` (representing the quantum of your value - penny, for example, in US currency). You will not be able to store an exact value - 123.45, say, as a float, and mathematical operations on that value (such as multiplication by a tax percentage) will produce rounding errors. Example from that page: ``` float a = 8250325.12f; float b = 4321456.31f; float c = a + b; System.out.println(NumberFormat.getCurrencyInstance().format(c)); // prints $12,571,782.00 (wrong) BigDecimal a1 = new BigDecimal("8250325.12"); BigDecimal b1 = new BigDecimal("4321456.31"); BigDecimal c1 = a1.add(b1); System.out.println(NumberFormat.getCurrencyInstance().format(c1)); // prints $12,571,781.43 (right) ``` You don't want to muck with errors when it comes to money. With respect to the original question, I haven't touched Java in a little while, but I know that I'd like to stay away from regex to do this kind of work. I see this recommended; it may help you. Not tested; caveat developer. ``` try { String string = NumberFormat.getCurrencyInstance(Locale.GERMANY) .format(123.45); Number number = NumberFormat.getCurrencyInstance(locale) .parse("$123.45"); // 123.45 if (number instanceof Long) { // Long value } else { // too large for long - may want to handle as error } } catch (ParseException e) { // handle } ``` Look for a locale with rules that match what you expect to see. If you can't find one, use multiple sequentially, or create your own [custom NumberFormat](http://www.exampledepot.com/egs/java.text/FormatNum.html). I'd also consider forcing users to enter values in a single, canonical format. 123.45 and 123.456 look *way* too similar for my tastes, and by your rules would result in values that differ by a factor of 1000. [This is how millions are lost](http://blogs.msdn.com/oldnewthing/archive/2009/06/08/9705184.aspx).
As a generalized solution you can try ``` char[] chars = currency.toCharArray(); chars[currency.lastIndexOf(',')] = '.'; currency = new String(chars); ``` instead of ``` if(currency.length()>=3) { char[] chars = currency.toCharArray(); if(chars[chars.length-2] == ',') { chars[chars.length-2] = '.'; } else if(chars[chars.length-3] == ',') { chars[chars.length-3] = '.'; } currency = new String(chars); } ``` so that fractional part can be of any length.
How to parse a currency Amount (US or EU) to float value in Java
[ "", "java", "currency", "" ]
I need some help with parsing the response from `ListDirectoryDetails` in C#. I only need the following fields. * File Name/Directory Name * Date Created * and the File Size. Here's what some of the lines look like when I run `ListDirectoryDetails`: ``` d--x--x--x 2 ftp ftp 4096 Mar 07 2002 bin -rw-r--r-- 1 ftp ftp 659450 Jun 15 05:07 TEST.TXT -rw-r--r-- 1 ftp ftp 101786380 Sep 08 2008 TEST03-05.TXT drwxrwxr-x 2 ftp ftp 4096 May 06 12:24 dropoff ``` Thanks in advance.
Not sure if you still need this, but this is the solution i came up with: ``` Regex regex = new Regex ( @"^([d-])([rwxt-]{3}){3}\s+\d{1,}\s+.*?(\d{1,})\s+(\w+\s+\d{1,2}\s+(?:\d{4})?)(\d{1,2}:\d{2})?\s+(.+?)\s?$", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace ); ``` Match Groups: 1. object type: * d : directory * - : file 2. Array[3] of permissions (rwx-) 3. File Size 4. Last Modified Date 5. Last Modified Time 6. File/Directory Name
For this specific listing, the following code will do: ``` var request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/"); request.Credentials = new NetworkCredential("user", "password"); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; var reader = new StreamReader(request.GetResponse().GetResponseStream()); string pattern = @"^([\w-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+" + @"(\w+\s+\d+\s+\d+|\w+\s+\d+\s+\d+:\d+)\s+(.+)$"; Regex regex = new Regex(pattern); IFormatProvider culture = CultureInfo.GetCultureInfo("en-us"); string[] hourMinFormats = new[] { "MMM dd HH:mm", "MMM dd H:mm", "MMM d HH:mm", "MMM d H:mm" }; string[] yearFormats = new[] { "MMM dd yyyy", "MMM d yyyy" }; while (!reader.EndOfStream) { string line = reader.ReadLine(); Match match = regex.Match(line); string permissions = match.Groups[1].Value; int inode = int.Parse(match.Groups[2].Value, culture); string owner = match.Groups[3].Value; string group = match.Groups[4].Value; long size = long.Parse(match.Groups[5].Value, culture); string s = Regex.Replace(match.Groups[6].Value, @"\s+", " "); string[] formats = (s.IndexOf(':') >= 0) ? hourMinFormats : yearFormats; var modified = DateTime.ParseExact(s, formats, culture, DateTimeStyles.None); string name = match.Groups[7].Value; Console.WriteLine( "{0,-16} permissions = {1} size = {2, 9} modified = {3}", name, permissions, size, modified.ToString("yyyy-MM-dd HH:mm")); } ``` You will get (as of year 2016): ``` bin permissions = d--x--x--x size = 4096 modified = 2002-03-07 00:00 TEST.TXT permissions = -rw-r--r-- size = 659450 modified = 2016-06-15 05:07 TEST03-05.TXT permissions = -rw-r--r-- size = 101786380 modified = 2008-09-08 00:00 dropoff permissions = drwxrwxr-x size = 4096 modified = 2016-05-06 12:24 ``` --- But, actually trying to parse the listing returned by the `ListDirectoryDetails` is not the right way to go. You want to use an FTP client that supports the modern `MLSD` command that returns a directory listing in a machine-readable format specified in the [RFC 3659](https://datatracker.ietf.org/doc/html/rfc3659). Parsing the human-readable format returned by the ancient `LIST` command (used internally by the `FtpWebRequest` for its `ListDirectoryDetails` method) should be used as the last resort option, when talking to obsolete FTP servers, that do not support the `MLSD` command (like the Microsoft IIS FTP server). Many servers use a different format for the `LIST` command response. Particularly IIS can use DOS format. See [C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response](https://stackoverflow.com/q/7060983/850848#39771146). --- For example with [WinSCP .NET assembly](https://winscp.net/eng/docs/library), you can use its [`Session.ListDirectory`](https://winscp.net/eng/docs/library_session_listdirectory) or [`Session.EnumerateRemoteFiles`](https://winscp.net/eng/docs/library_session_enumerateremotefiles) methods. They internally use the `MLSD` command, but can fall back to the `LIST` command and support dozens of different human-readable listing formats. The returned listing is presented as collection of [`RemoteFileInfo` instances](https://winscp.net/eng/docs/library_remotefileinfo) with properties like: * `Name` * `LastWriteTime` (with correct timezone) * `Length` * `FilePermissions` (parsed into individual rights) * `Group` * `Owner` * `IsDirectory` * `IsParentDirectory` * `IsThisDirectory` *(I'm the author of WinSCP)* --- Most other 3rd party libraries will do the same. Using the [`FtpWebRequest` class](https://learn.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest) is not reliable for this purpose. Unfortunately, there's no other built-in FTP client in the .NET framework.
Parsing FtpWebRequest ListDirectoryDetails line
[ "", "c#", "parsing", "ftp", "ftpwebrequest", "" ]
Many programming languages have a coalesce function (returns the first non-NULL value, [example](http://www.postgresql.org/docs/9.3/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL)). PHP, sadly in 2009, does not. What would be a good way to implement one in PHP until PHP itself gets a coalesce function?
PHP 7 introduced a real [coalesce operator](http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op): ``` echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback' ``` If the value before the `??` does not exists or is `null` the value after the `??` is taken. The improvement over the mentioned `?:` operator is, that the `??` also handles undefined variables without throwing an `E_NOTICE`.
There is a new operator in php 5.3 which does this: `?:` ``` // A echo 'A' ?: 'B'; // B echo '' ?: 'B'; // B echo false ?: 'B'; // B echo null ?: 'B'; ``` Source: <http://www.php.net/ChangeLog-5.php#5.3.0>
Coalesce function for PHP?
[ "", "php", "optimization", "null-coalescing-operator", "" ]
I have the following class ``` class CItem { public: CItem(CRegistry &Registry) _Registry(Registry) {Registry.Register();} ~CItem() {_Registry.Unregister()}; private: CRegistry &_Registry; } ``` After a while it turns out that not all CItem objects need to be registered so I need a version of CItem which does not requires Registry in constructor (and of course of the registration code). How can I implement this? The only solution I can see here is to get and keep Registry as a pointer. Is there more elegant solution, like using templates, etc (I don't like switching from reference to pointer)?
If you want to keep a single class, just change the attribute into a raw pointer and allow it to be null. As Neil points out, there is a widespread unjustified jihad against raw pointers that is not fully justified. Use a raw pointer and clearly document (comment) that the object holds no ownership of the pointed memory so that no one feels like adding a `delete` in your destructor at a later time. All other solutions will be worse than using a pointer internally. It is an implementation detail. Also consider whether it makes sense. Your code will no longer be able to assume that the pointer is valid and it will complicate the logic inside your class. ``` class CItem { public: CItem(CRegistry &Registry) : _Registry(&Registry) {Registry->Register();} CItem() : _Registry(0) {} ~CItem() { if ( _Registry ) _Registry->Unregister(); } private: CRegistry *_Registry; // Pointer is not owned. Do not delete! }; ``` As a last note: do not prefix attributes with a single underscore as they are reserved by the standard for C++ implementations (compiler and standard libraries)
The only other alternative would be to create a CItem base class and then derive ItemWithRef (which has a reference) and ItemWithoutRef from it. But ir's much easier and clearer to use a pointer. From the number of questions regarding references as members, it seems that somewhere, someone is spreading the view that references are good and pointers are bad. This is simply not the case, particularly when it comes to data members. And just to clarify the underscore thing: * names that begin with an underscore and a lowervcase letter are reserved for the C++ compile/library writers when they occur at namespace (i.e. outside of classes) scope * names thatb begin with an underscore and an uppercase letter, or contain two consecutive underscores are unconditionally reserved for the compiler/library writers - you must not use them in your own code
Optional reference member - is it possible?
[ "", "c++", "class", "constructor-overloading", "" ]
Im trying to save a path into my input varaible, but its not reading my input! Im debugging and its completely skipping the line! ``` public static void OpenFile(int FileSize) { char GetLines = ' '; char[] FileContents = new char[FileSize]; Console.WriteLine("Enter a Path Name: "); GetLines = (char)Console.Read(); GetLines = (char)Console.Read(); // Getting No Input Y? StreamReader MyStream = File.OpenText(GetLines.ToString()); while (GetLines != null) { Console.WriteLine(FileContents); GetLines = (char)MyStream.Read(); } MyStream.Close(); } ``` Everything else works fine. This function is being called in Main... My Goals is still to try and read the contents of the file into an array. THIS IS NOT A HOMEWORK ASSIGNMENT! =)
You can achieve your goal using Console.Read(). Read here <http://msdn.microsoft.com/en-us/library/system.console.read.aspx>.
Why don't you just use Console.ReadLine() and MyStream.Readline() ? Here is a StreamReader example: ``` public class ReadTextFile { public static int Main(string[] args) { Console.Write("Enter a File Path:"); string fileName = Console.Readline(); StreamReader reader = File.OpenText(fileName); string input = reader.ReadLine(); while (input != null) { Console.WriteLine(input); input = reader.ReadLine(); } reader.close; return 0; } } ```
C# Not Reading my Input
[ "", "c#", ".net", "" ]
I'm currently using PHP and a regular expression to strip out all HTML comments from a page. The script works well... a little too well. It strips out all comments including my conditional comments in the . Here's what I've got: ``` <?php function callback($buffer) { return preg_replace('/<!--(.|\s)*?-->/', '', $buffer); } ob_start("callback"); ?> ... HTML source goes here ... <?php ob_end_flush(); ?> ``` Since my regex isn't too hot I'm having trouble trying to figure out how to modify the pattern to exclude Conditional comments such as: ``` <!--[if !IE]><!--> <link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen" /> <!-- <![endif]--> <!--[if IE 7]> <link rel="stylesheet" href="/css/ie7.css" type="text/css" media="screen" /> <![endif]--> <!--[if IE 6]> <link rel="stylesheet" href="/css/ie6.css" type="text/css" media="screen" /> <![endif]--> ``` Cheers
Since comments cannot be nested in HTML, a regex can do the job, in theory. Still, using some kind of parser would be the better choice, especially if your input is not guaranteed to be well-formed. Here is my attempt at it. To match only normal comments, this would work. It has become quite a monster, sorry for that. I have tested it quite extensively, it seems to do it well, but I give no warranty. ``` <!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*--> ``` Explanation: ``` <!-- #01: "<!--" (?! #02: look-ahead: a position not followed by: \s* #03: any number of space (?: #04: non-capturing group, any of: \[if [^\]]+] #05: "[if ...]" |<! #06: or "<!" |> #07: or ">" ) #08: end non-capturing group ) #09: end look-ahead (?: #10: non-capturing group: (?!-->) #11: a position not followed by "-->" . #12: eat the following char, it's part of the comment )* #13: end non-capturing group, repeat --> #14: "-->" ``` Steps #02 and #11 are crucial. #02 makes sure that the following characters do not indicate a conditional comment. After that, #11 makes sure that the following characters do not indicate the end of the comment, while #12 and #13 cause the actual matching. Apply with "global" and "dotall" flags. To do the opposite (match only conditional comments), it would be something like this: ``` <!(--)?(?=\[)(?:(?!<!\[endif\]\1>).)*<!\[endif\]\1> ``` Explanation: ``` <! #01: "<!" (--)? #02: two dashes, optional (?=\[) #03: a position followed by "[" (?: #04: non-capturing group: (?! #05: a position not followed by <!\[endif\]\1> #06: "<![endif]>" or "<![endif]-->" (depends on #02) ) #07: end of look-ahead . #08: eat the following char, it's part of the comment )* #09: end of non-capturing group, repeat <!\[endif\]\1> #10: "<![endif]>" or "<![endif]-->" (depends on #02) ``` Again, apply with "global" and "dotall" flags. Step #02 is because of the "downlevel-revealed" syntax, see: ["MSDN - About Conditional Comments"](http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx). I'm not entirely sure where spaces are allowed or expected. Add `\s*` to the expression where appropriate.
If you can't get it to work with one regular expression or you find you want to preserve more comments you could use [`preg_replace_callback`](http://php.net/preg_replace_callback). You can then define a function to handle the comments individually. ``` <?php function callback($buffer) { return preg_replace_callback('/<!--.*-->/U', 'comment_replace_func', $buffer); } function comment_replace_func($m) { if (preg_match( '/^\<\!--\[if \!/i', $m[0])) { return $m[0]; } return ''; } ob_start("callback"); ?> ... HTML source goes here ... <?php ob_end_flush(); ?> ```
Stripping HTML Comments With PHP But Leaving Conditionals
[ "", "php", "regex", "comments", "conditional-statements", "strip", "" ]
Say I have a Person class with Name, Age, Level properties. I know how to order by one of the properties, with ``` PersonList.Sort(delegate(Person p1, Person p2) { return p1.Name.CompareTo(p2.Name); }); ``` But how can I order by Name, Age and Level. An equivalente of the sql sentence : ORDER BY Name, Age, Level Thank you
Adapting your current code: ``` PersonList.Sort(delegate(Person p1, Person p2) { int r = p1.Name.CompareTo(p2.Name); if (r == 0) r = p1.Age.CompareTo(p2.Age); if (r == 0) r = p1.Level.CompareTo(p2.Level); return r; }); ``` or, a simple linq-ish solution: ``` PersonList = PersonList.OrderBy(p => p.Name) .ThenBy(p => p.Age) .ThenBy(p => p.Level).ToList(); ```
Have you considered switching to .NET 3.5 and using LINQ? Things like this are really easy in LINQ: ``` personList = personList.OrderBy(p => p.Name). ThenBy(p => p.Age).ThenBy(p => p.Level).ToList(); ```
C# List<> Order with 3 properties .Net 2.0
[ "", "c#", ".net", "sorting", ".net-2.0", "" ]
When using FormsAuthentication, where is the Authcookie placed? On the server or on the client? And when the client has cookies disabled, does FormsAuthentication still work?
It's placed on the client, if you use firebug it should look something like this in the response: .ASPXFORMSAUTH=C8390F0E68890DF5C731DB2B.... Forms authentication can still work, but everything will be set in the browser's url. Decent documentation [here](http://msdn.microsoft.com/en-us/library/aa480476.aspx)
On the client. Supposedly cookieless is supported by changing the web.config, but I haven't had success in implementing it. If cookieless is used, the cookie is stored in the URI of the web page, such as <http://MySite.com/MyWebApplication/F(XXXX))/home.aspx>. ``` <forms cookieless="[UseUri|UseCookie|AutoDetect|UseDeviceProfile]" </forms> ``` From [forms Element for authentication (ASP.NET Settings Schema)](http://msdn.microsoft.com/en-us/library/1d3t3c61.aspx): > *In AJAX-enabled ASP.NET Web sites, use the default value UseCookies for the cookieless attribute. Settings that use cookies encoded in the URL are not supported by the ASP.NET AJAX client-script libraries.* > > **UseCookies** Specifies that cookies will always be used, regardless of the device. > > **UseUri** Specifies that cookies will never be used. > > **AutoDetect** Specifies that cookies are used, if the device profile supports cookies; otherwise, cookies are not used. For desktop browsers that are known to support cookies, a probing mechanism will be used to try to use cookies, when enabled. If a device does not support cookies, no probing mechanism will be used. > > **UseDeviceProfile** Specifies that cookies are used, if the browser supports cookies; otherwise, cookies are not used. For devices that support cookies, no attempt is made to probe to determine whether cookie support is enabled. > > This attribute is new in the .NET Framework version 2.0. > > The default is UseDeviceProfile. Using cookieless can be less secure than requiring cookies. From [Understand How the ASP.NET Cookieless Feature Works](http://msdn.microsoft.com/en-us/library/aa479315.aspx): > One big issue that is unique to the cookieless feature (not present when using cookies), is the vulnerability linked to users sending URLs to other users (via Email and IM, for example). When this feature is turned on, for, say, FormsAuthentication, and the user emails his (or her) URL to some other user, the second user will automatically log on to the server with the credentials of the first user. One countermeasure is to reduce the time-window in which this can happen, by reducing the cookie timeout for forms authentication (as described previously in point (b)).
C# Where is the Authcookie set?
[ "", "c#", "asp.net", "forms-authentication", "" ]
I've been asked to do Facebook apps. Before I commit to anything, I want to know how easily a game can be moved to Facebook? (I'm completely comfortable making games in JavaScript in the browser.) Does Facebook filter the JavaScript in some way? Can I use jQuery or other JS libraries? Can I do animation by altering the DOM on the fly? Is it best to go with an iFrame or use FBML? I've done some poking around the Facebook dev site. But I'd like to hear from someone who's done it what the learning curve is like.
JavaScript in the Facebook context is different inasmuch as it all will get rewritten as it goes through Facebook. To get a sense of the differences (of which there are many), start with the [FBJS Documentation](https://developers.facebook.com/docs/fbjs/). The [getting started](https://developers.facebook.com/docs/guides/canvas/) guide is a good primer. The site that will become your bible is [wiki.developers.facebook.com](https://developers.facebook.com/), it is canonical in terms of the FB platform. Additionally, as we all have come to know and (love? hate?) the Facebook platform is a moving target, so it's useful to keep up with things via the Developers Group on Facebook. I also like the blog [Inside Facebook](http://www.insidefacebook.com/). > Most providers who allow developers to > embed JavaScript within their domain > force developers to use iframes to > sandbox their code. Facebook has taken > a different approach to this problem. > JavaScript that you give us gets > parsed, and any identifiers (function > and variable names) get prepended with > your application ID. For example, the > following code block: > > ``` > function foo(bar) { var obj = {property: bar}; return obj.property; > ``` > > } > > becomes: > > ``` > function a12345_foo(a12345_bar) { var a12345_obj = {property: a12345_bar}; return a12345_obj.property; } > ``` > > This creates a virtual scope for every > application that runs within Facebook. > From there we expose certain > functionality through a collection of > JavaScript objects that allow you to > modify your content on Facebook. Our > objects are made to mimic the > functionality of JavaScript as closely > as possible, but it may take some > getting used to for people who are > already adept with JavaScript. Many items which are simply elements in plain JavaScript must be accomplished with special method calls in FBJS. For example when referring to a form field's value in JS you use `.value`, whereas in FBJS you need to do `.getValue()`. It's these differences that prevent simply cutting and pasting JS from elsewhere into Facebook. That's a basic primer. That should get you started. Best to you!
The simple solution is to wrap your entire game inside an iFrame. FB itself filters out a lot of javascript calls - basically, anything involving the window or document objects probably won't work.
In what ways is JavaScript restricted when making a Facebook app?
[ "", "javascript", "facebook", "" ]
I'm trying to create a messaging system where a message's sender and recipients can be generic entities. This seems fine for the sender, where there is only object to reference (GenericForeignKey) but I can't figure out how to go about this for the recipients (GenericManyToManyKey ??) Below is a simplified example. PersonClient and CompanyClient inherit attributes from Client but have their own specific details. The last line is the sticking point. How do you allow message recipients to be a set of CompanyClients and PersonClients ``` class Client(models.Model): city = models.CharField(max_length=16) class Meta: abstract = True class PersonClient(Client): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) class CompanyClient(Client): name = models.CharField(max_length=32) tax_no = PositiveIntegerField() class Message(models.Model): msg_body = models.CharField(max_length=1024) sender = models.ForeignKey(ContentType) recipients = models.ManyToManyField(ContentType) ```
You can implement this using generic relationships by manually creating the junction table between message and recipient: ``` from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType class Client(models.Model): city = models.CharField(max_length=16) # These aren't required, but they'll allow you do cool stuff # like "person.sent_messages.all()" to get all messages sent # by that person, and "person.received_messages.all()" to # get all messages sent to that person. # Well...sort of, since "received_messages.all()" will return # a queryset of "MessageRecipient" instances. sent_messages = generic.GenericRelation('Message', content_type_field='sender_content_type', object_id_field='sender_id' ) received_messages = generic.GenericRelation('MessageRecipient', content_type_field='recipient_content_type', object_id_field='recipient_id' ) class Meta: abstract = True class PersonClient(Client): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) def __unicode__(self): return u'%s %s' % (self.last_name, self.first_name) class CompanyClient(Client): name = models.CharField(max_length=32) tax_no = models.PositiveIntegerField() def __unicode__(self): return self.name class Message(models.Model): sender_content_type = models.ForeignKey(ContentType) sender_id = models.PositiveIntegerField() sender = generic.GenericForeignKey('sender_content_type', 'sender_id') msg_body = models.CharField(max_length=1024) def __unicode__(self): return u'%s...' % self.msg_body[:25] class MessageRecipient(models.Model): message = models.ForeignKey(Message) recipient_content_type = models.ForeignKey(ContentType) recipient_id = models.PositiveIntegerField() recipient = generic.GenericForeignKey('recipient_content_type', 'recipient_id') def __unicode__(self): return u'%s sent to %s' % (self.message, self.recipient) ``` You'd use the above models like so: ``` >>> person1 = PersonClient.objects.create(first_name='Person', last_name='One', gender='M') >>> person2 = PersonClient.objects.create(first_name='Person', last_name='Two', gender='F') >>> company = CompanyClient.objects.create(name='FastCompany', tax_no='4220') >>> company_ct = ContentType.objects.get_for_model(CompanyClient) >>> person_ct = ContentType.objects.get_for_model(person1) # works for instances too. # now we create a message: >>> msg = Message.objects.create(sender_content_type=person_ct, sender_id=person1.pk, msg_body='Hey, did any of you move my cheese?') # and send it to a coupla recipients: >>> MessageRecipient.objects.create(message=msg, recipient_content_type=person_ct, recipient_id=person2.pk) >>> MessageRecipient.objects.create(message=msg, recipient_content_type=company_ct, recipient_id=company.pk) >>> MessageRecipient.objects.count() 2 ``` As you can see, this is a far more verbose (complicated?) solution. I'd probably keep it simple and go with Prariedogg's solution below.
The absolute best way to go about this is to use a library called django-gm2m ``` pip install django-gm2m ``` Then if we have our models ``` >>> from django.db import models >>> >>> class Video(models.Model): >>> class Meta: >>> abstract = True >>> >>> class Movie(Video): >>> pass >>> >>> class Documentary(Video): >>> pass ``` And a user ``` >>> from gm2m import GM2MField >>> >>> class User(models.Model): >>> preferred_videos = GM2MField() ``` We can do ``` >>> user = User.objects.create() >>> movie = Movie.objects.create() >>> documentary = Documentary.objects.create() >>> >>> user.preferred_videos.add(movie) >>> user.preferred_videos.add(documentary) ``` Sweet right? For more info go here: <http://django-gm2m.readthedocs.org/en/stable/quick_start.html>
Generic many-to-many relationships
[ "", "python", "django", "generics", "django-models", "many-to-many", "" ]
I generated a configure script with autoconf to build my project. It works fine unless I don't have some needed library installed. Make returns error when lacking some files, but it should be actually checked by the configure script i think? So my question is: How to modify an autoconf generated script to seek for dependencies and tell the user which libraries it lacks?
Depends on the dependency, there is no generic solution. There are [`AC_CHECK_LIB` and `AC_SEARCH_LIBS` macros](http://www.gnu.org/software/hello/manual/autoconf/Libraries.html) that may work for you if the libraries and headers are installed in standard locations. Many packages nowadays support [`pkg-config`](http://pkg-config.freedesktop.org/wiki/) or something similar which allows you to check for existence of libraries, and also can supply you the compiler and linker flags required. With packages that do not work with AC macros and do not support `pkg-config` or similar, you'll probably have to write a ton of scripts yourself to find out whether the dependency is available and what compiler and linker options it requires. And even then it is hard to make it portable.
Yes, you want to perform the check at configure time. Stick code such as the following ([thanks to Shlomi Fish](http://www.shlomifish.org/lecture/Autotools/slides/common_macros/AC_CHECK_LIB.html)) in your `configure.ac`: ``` if test "x$requires_libavl" = "xyes" ; then AC_CHECK_LIB(avl, avl_create, [], [ echo "Error! You need to have libavl around." exit -1 ]) fi ``` Note that if you have a pre-2.5 autoconf, you'll use `configure.in` instead.
How to make configure script check the dependencies
[ "", "c++", "makefile", "dependencies", "gnu", "autoconf", "" ]
I've been having some weird issues when it comes to make an AJAX request and handling the response. I am making an ajax call for an xml file. however when i get the response the xhr.responseText property works fine in firefox but not in IE. Another thing is that I am trying to access the xhr.responseXML as XMLDocument, but it tells me in firefox it tells me that xhr.responseXML is undefined in ie it doesnt even show me the undefined error or displays the output. This is the code I am using to make the request: ``` var ajaxReq = function(url, callback) { //initialize the xhr object and settings var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(), //set the successful connection function httpSuccess = function(xhr) { try { // IE error sometimes returns 1223 when it should be 204 // so treat it as success, see XMLHTTPRequest #1450 // this code is taken from the jQuery library with some modification. return !xhr.status && xhr.status == 0 || (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || xhr.status == 1223; } catch (e) { } return false; }; //making sure the request is created if (!xhr) { return 404; // Not Found } //setting the function that is going to be called after the request is made xhr.onreadystatechange = function() { if (!httpSuccess(xhr)) { return 503; //Service Unavailable } if (xhr.responseXML != null && xhr.responseText != null && xhr.responseXML != undefined && xhr.responseText != undefined) { callback(xhr); } }; //open request call xhr.open('GET', url, true); //setup the headers try { xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Accept", "text/xml, application/xml, text/plain"); } catch ( ex ) { window.alert('error' + ex.toString()); } //send the request try { xhr.send(''); } catch (e) { return 400; //bad request } return xhr; }; ``` and this is how i am calling the function to test for results: ``` window.onload = function() { ajaxReq('ConferenceRoomSchedules.xml', function(xhr) { //in firefox this line works fine, //but in ie it doesnt not even showing an error window.document.getElementById('schedule').innerHTML = xhr.responseText; //firefox says ''xhr.responseXML is undefined'. //and ie doesn't even show error or even alerts it. window.alert(xhr.reponseXML.documentElement.nodeName); }); } ``` This is also my first attempt to work with AJAX so there might be something that I am not looking at right. I've been searching crazy for any indications of why or how to fix it, but no luck there. any ideas would be great. **EDIT:** I know this would be better with a framework, but the boss doesn't want to add a framework for just an ajax functionality ('just' is not a fair word for ajax :P). So I am doing it with pure javascript. The XML file is well-formed, I see it well in the web browser, but for completion this is the testing file I am using: ``` <?xml version="1.0" encoding="utf-8"?> <rooms> <room id="Blue_Room"> <administrator>somebody@department</administrator> <schedule> <event> <requester> <name>Johnny Bravo</name> <email>jbravo@department</email> </requester> <date>2009/09/03</date> <start_time>11:00:00 GMT-0600</start_time> <end_time>12:00:00 GMT-0600</end_time> </event> </schedule> </room> <room id="Red_Room"> <administrator>somebody@department</administrator> <schedule> </schedule> </room> <room id="Yellow_Room"> <administrator>somebody@department</administrator> <schedule> </schedule> </room> </rooms> ``` **EDIT 2:** Well the good news is that I convinced my boss to use jQuery, the bad news is that AJAX still perplexes me. I'll read more about it just for curiousity. Thanks for the tips and I gave the answer credit to Heat Miser because he was the closest working tip.
I was having the same problem a few years ago, then I gave up on responseXML and began always using responseText. This parsing function has always worked for me: ``` function parseXml(xmlText){ try{ var text = xmlText; //text = replaceAll(text,"&lt;","<"); //text = replaceAll(text,"&gt;",">"); //text = replaceAll(text,"&quot;","\""); //alert(text); //var myWin = window.open('','win','resize=yes,scrollbars=yes'); //myWin.document.getElementsByTagName('body')[0].innerHTML = text; if (typeof DOMParser != "undefined") { // Mozilla, Firefox, and related browsers var parser=new DOMParser(); var doc=parser.parseFromString(text,"text/xml"); //alert(text); return doc; }else if (typeof ActiveXObject != "undefined") { // Internet Explorer. var doc = new ActiveXObject("Microsoft.XMLDOM"); // Create an empty document doc.loadXML(text); // Parse text into it return doc; // Return it }else{ // As a last resort, try loading the document from a data: URL // This is supposed to work in Safari. Thanks to Manos Batsis and // his Sarissa library (sarissa.sourceforge.net) for this technique. var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text); var request = new XMLHttpRequest(); request.open("GET", url, false); request.send(null); return request.responseXML; } }catch(err){ alert("There was a problem parsing the xml:\n" + err.message); } } ``` With this XMLHttpRequest Object: ``` // The XMLHttpRequest class object debug = false; function Request (url,oFunction,type) { this.funct = ""; // this.req = ""; this.url = url; this.oFunction = oFunction; this.type = type; this.doXmlhttp = doXmlhttp; this.loadXMLDoc = loadXMLDoc; } function doXmlhttp() { //var funct = ""; if (this.type == 'text') { this.funct = this.oFunction + '(req.responseText)'; } else { this.funct = this.oFunction + '(req.responseXML)'; } this.loadXMLDoc(); return false; } function loadXMLDoc() { //alert(url); var functionA = this.funct; var req; req = false; function processReqChange() { // alert('reqChange is being called'); // only if req shows "loaded" if (req.readyState == 4) { // only if "OK" if (req.status == 200) { // ...processing statements go here... eval(functionA); if(debug){ var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes'); debugWin.document.body.innerHTML = req.responseText; } } else { alert("There was a problem retrieving the data:\n" + req.statusText + '\nstatus: ' + req.status); if(debug){ var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes'); debugWin.document.body.innerHTML = req.responseText; } } } } // branch for native XMLHttpRequest object if(window.XMLHttpRequest) { try { req = new XMLHttpRequest(); } catch(e) { req = false; } // branch for IE/Windows ActiveX version } else if(window.ActiveXObject) { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } } } if(req) { req.onreadystatechange = processReqChange; if(this.url.length > 2000){ var urlSpl = this.url.split('?'); req.open("POST",urlSpl[0],true); req.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); req.send(urlSpl[1]); } else { req.open("GET", this.url, true); req.send(""); } } } function browserSniffer(){ if(navigator.userAgent.toLowerCase().indexOf("msie") != -1){ if(navigator.userAgent.toLowerCase().indexOf("6")){ return 8; }else{ return 1; } } if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1){ return 2; } if(navigator.userAgent.toLowerCase().indexOf("opera") != -1){ return 3; } if(navigator.userAgent.toLowerCase().indexOf("safari") != -1){ return 4; } return 5; } ``` Granted, this is very old code, but it is still working for me on a site I built a few years ago. I agree with everyone else though I typically use a framework nowadays so I don't have to use this code or anything like it anymore. You can ignore some of the particulars with the split, etc... in the Request onreadystate function. It was supposed to convert the request to a post if it was longer than a certain length, but I just decided it was always better to do a post.
This problem occurs mostly when content type is mis-detected by the browser or it's not sent correctly. Its easier to just override it: ``` var request = new XMLHttpRequest(); request.open("GET", url, false); request.overrideMimeType("text/xml"); request.send(null); return request.responseXML; ``` Not sure why... This problem occurs only with Safari and Chrome (WebKit browsers, the server sends the headers correctly).
AJAX responseXML errors
[ "", "javascript", "ajax", "cross-browser", "" ]
I have a DataGridView that I want to use to store generic data. I want to keep a typed data list in the DataGridView class so that all of the sorts, etc. can be handled internally. But I don't want to have to set the type on the DataGridView since I won't know the data type until the InitializeData method is called. ``` public class MyDataGridView : DataGridView { private List<T> m_data; public InitializeData<T>(List<T> data) { m_data = data; } ... internal events to know when the datagrid wants to sort ... m_data.Sort<T>(...) } ``` Is this possible? If so, how?
If you won't know the type until you call `InitializeData`, then the type clearly can't be a compile-time part of the object. Do you know everything you need to know about the sorting when you call `InitializeData<T>`? If so, how about you do something like: ``` private IList m_data; private Action m_sorter; public InitializeData<T>(List<T> data) { m_data = data; // This captures the data variable. You'll need to // do something different if that's not good enough m_sorter = () => data.Sort(); } ``` Then when you need to sort later, you can just call `m_sorter()`. If you might sort on different things, you could potentially change it from an `Action` to `Action<string>` or whatever you'd need to be able to sort on.
If Jon's answer isn't sufficient, here's a more general (but more involved, and probably somewhat more confusing) approach: ``` /// <summary> /// Allows a list of any type to be used to get a result of type TResult /// </summary> /// <typeparam name="TResult">The result type after using the list</typeparam> interface IListUser<TResult> { TResult Use<T>(List<T> list); } /// <summary> /// Allows a list of any type to be used (with no return value) /// </summary> interface IListUser { void Use<T>(List<T> list); } /// <summary> /// Here's a class that can sort lists of any type /// </summary> class GenericSorter : IListUser { #region IListUser Members public void Use<T>(List<T> list) { // do generic sorting stuff here } #endregion } /// <summary> /// Wraps a list of some unknown type. Allows list users (either with or without return values) to use the wrapped list. /// </summary> interface IExistsList { TResult Apply<TResult>(IListUser<TResult> user); void Apply(IListUser user); } /// <summary> /// Wraps a list of type T, hiding the type itself. /// </summary> /// <typeparam name="T">The type of element contained in the list</typeparam> class ExistsList<T> : IExistsList { List<T> list; public ExistsList(List<T> list) { this.list = list; } #region IExistsList Members public TResult Apply<TResult>(IListUser<TResult> user) { return user.Use(list); } public void Apply(IListUser user) { user.Use(list); } #endregion } /// <summary> /// Your logic goes here /// </summary> class MyDataGridView { private IExistsList list; public void InitializeData<T>(List<T> list) { this.list = new ExistsList<T>(list); } public void Sort() { list.Apply(new GenericSorter()); } } ```
Store generic data in a non-generic class
[ "", "c#", "generics", "" ]
Will making WPF forms in VS2010 be easier than it is now? I’m just a beginner and I’m finding just learning C# itself is a ton of info to get my head around. But I’ve seen some projects done with WPF and they look awesome. Is it worth my time to start looking into WPF now, or wait till VS2010 where, if I understand correctly, there are better tools for working with it? Thanks
Even given its improvements, VS 2010 will not suddenly become the holy grail of WPF application creation. You're better off learning the fundamentals (binding, templates, commands, etc) of .NET 3.0/3.5 now. I'd also recommend downloading the trial of [Expression Blend](http://www.microsoft.com/Expression/products/Overview.aspx?key=blend) if you're interested in the visual aspects of WPF. While you can certainly do most everything coding XAML by hand, Blend makes it much quicker.
Visual Studio will provided better tools to work with WPF, see [here for details.](http://blogs.msdn.com/tims/archive/2008/11/03/wpf-developers-pdc-wrap-up-and-visual-studio-tooling-update.aspx)
Will making WPF forms in VS2010 be easier than it is now?
[ "", "c#", "wpf", "" ]
I'm trying to map an @Embeddable object in a subclass whose parent class already has a field of that @Embeddable type. The hibernate [Embeddable Objects documentation](http://docs.jboss.org/ejb3/app-server/HibernateAnnotations/reference/en/html_single/index.html#d0e483) claims I can use the @AttributeOverrides to override the column names of an @Embeddable object: e.g. ``` @Entity public class Person implements Serializable { // Persistent component using defaults Address homeAddress; @Embedded @AttributeOverrides( { @AttributeOverride(name="iso2", column = @Column(name="bornIso2") ), @AttributeOverride(name="name", column = @Column(name="bornCountryName") ) } ) Country bornIn; ... } ``` Here's the case I have: ``` @Embeddable public class ContentID implements Serializable { @Column(name="contentID") private String contentPath; } @MappedSuperclass public abstract class BaseDomainObject implements Serializable { @Embedded private ContentID contentID; } public class Achievement extends BaseDomainObject { @Embedded @AttributeOverrides( { @AttributeOverride(name="contentID", column = @Column(name="awardedItem") ), } ) private ContentID awardedItem; } ``` The error I get is: > org.hibernate.MappingException: > Repeated column in mapping for entity: > Achievement column: contentID (should > be mapped with insert="false" > update="false") at > org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:652) > at > org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:674) > at > org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:670) > at > org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:696) > at > org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:450) > at > org.hibernate.mapping.SingleTableSubclass.validate(SingleTableSubclass.java:43) > at > org.hibernate.cfg.Configuration.validate(Configuration.java:1108) > at > org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1293) > at > org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867) **UPDATE:** I looked in for Hibernate issues relating to this and the GRAILS project claimed they fixed this issue but their annotation solution doesn't seem to be valid javax.persistence annotations (maybe it's a new version). [JPA @Embeddable/@Embedded throws org.hibernate.MappingException: Repeated column in mapping for entity](http://jira.codehaus.org/browse/GRAILS-3225)
The problem seems to be this: ``` public class ContentID implements Serializable { @Column(name="contentID") private String contentPath; } ``` You are making the contentPath column name to be "contentId" and that is clashing with your AttributeOverride annotation later on. Try this: ``` public class ContentID implements Serializable { @Column(name="contentPath") private String contentPath; } ``` **UPDATE** I am also wondering about this: ``` @Embedded @AttributeOverrides( { @AttributeOverride(name="contentID", column = @Column(name="awardedItem") ), } ) private ContentID awardedItem; ``` You seem to be changing the name of the contentId column here to awardedItem. Is that really necessary?
Vincent is right. The `attributeOverride` Name field is referring to a column name when it should be a attribute/property of a class. ``` @AttributeOverrides( { @AttributeOverride(name="contentPath", column = @Column(name="awardedItem") ), } ) ``` Notice that the name is for the class property not the database column. See [documentation](http://docs.oracle.com/javaee/6/api/javax/persistence/AttributeOverride.html)
Hibernate mapping a second @Embeddable field in a subclass
[ "", "java", "database", "hibernate", "orm", "annotations", "" ]
In the code below I am giving the function a sTransactionDate="1999" and I am trying to covert it to a date x/x/1999. ``` DateTime dTransactionDate = new DateTime(); if(DateTime.TryParse(sTransactionDate, out dTransactionDate)) { //Happy }else { //Sad } ``` if the string is "1999" it will always end up in sad. Any ideas?
Try something like this (adjust the `CultureInfo` and `DateTimeStyles` appropriately): ``` DateTime.TryParseExact ("1999", "yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dTransactionDate) ```
How about... ``` DateTime dTransactionDate = new DateTime(); if (DateTime.TryParseExact(sTransactionDate, "yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dTransactionDate)) { // Happy } else { // Sad } ``` ...or even just... ``` DateTime dTransactionDate = new DateTime(int.Parse(sTransactionDate), 1, 1); // Happy ```
Why DateTime.TryParse returning false when given a real year string?
[ "", "c#", ".net", "datetime", "tryparse", "" ]
From Java Malik textbook- determine if an number is divisible by 11.. Code Solution provided: ``` import java.util.*; public class Divby11 { static Scanner console = new Scanner(System.in); public static void main (String[] args) { int num, temp, sum; char sign; System.out.print("Enter a positive integer: "); num = console.nextInt(); System.out.println(); temp = num; sum = 0; sign = '+'; do { switch (sign) { case '+' : sum = sum + num % 10; sign = '-'; break; case '-' : sum = sum - num % 10; sign = '+'; } num = num / 10; //remove the last digit } while (num > 0); if (sum % 11 == 0) System.out.println(temp + " is divisible by 11"); else System.out.println(temp + " is not divisible by 11"); } ``` Why go through all the effort above and just say... ``` if (sum % 11 == 0) System.out.println(temp + " is divisible by 11"); else System.out.println(temp + " is not divisible by 11"); ``` Can any of you experts see why the author would do it this way (long way)?
This code example isn't actually dividing by eleven. If you see, it's alternating between adding and subtracting each digit, then checks at the very end if the result is divisible by 11. For example, look at the following number and how this algorithm works with it: ``` Start with sum=0, sign='+', num=517 First iteration: sum=7, sign='-', num=51 Second iteration: sum=6, sign='+', num=5 Final iteration: sum=11, sign='-', num=0 ``` The final result is divisible by eleven. EDIT: The algorithm does indeed look to be implementing the divisibility rule for 11 as **dfa** mentions in his answer.
for the [Divisibility Rule of 11](http://en.wikipedia.org/wiki/Divisibility_rule): * form the alternating sum of the digits * if this sum is divisible for 11 then the number is divisible for 11 ## Examples * 68090 = 0 - 9 + 0 - 8 + 6 = -11 => TRUE * 493827 = 7 - 2 + 8 - 3 + 9 - 4 = 15 = 4 => FALSE
Why is the solution like this?
[ "", "java", "" ]
Why does this code fail to compile with VS 2005: ``` #include <boost/bind.hpp> #include <boost/function.hpp> struct X { typedef std::auto_ptr<int> IntType; // typedef int IntType; // this works IntType memfunc () const { return IntType (); } X () { boost::bind (&X::memfunc, this); } }; ``` with this warning & error: ``` 1>j:\libraries\boost\boost_1_37_0\boost\bind.hpp(1643) : warning C4180: qualifier applied to function type has no meaning; ignored 1> j:\libraries\boost\boost_1_37_0\boost\bind.hpp(1677) : see reference to class template instantiation 'boost::_bi::add_cref<Pm,I>' being compiled 1> with 1> [ 1> Pm=std::auto_ptr<int> (__thiscall X::* )(void), 1> I=1 1> ] 1> j:\dev\test\test\listtest.cpp(16) : see reference to class template instantiation 'boost::_bi::dm_result<Pm,A1>' being compiled 1> with 1> [ 1> Pm=X::IntType (__thiscall X::* )(void), 1> A1=X * 1> ] ``` ? Changing the IntType typedef to just an int allows it to compile.
It seems, that, despite the documentation claiming they are equivalent, the following alternative works: ``` boost::bind<IntType> (boost::mem_fn (&X::memfunc), this); ``` Go figure...
FYI: gcc 4.3.3 compiles the code fine.
Problem with boost::bind and member function returning auto_ptr
[ "", "c++", "boost-bind", "" ]
A bit confused, I was watching some video where some guy was using sqllite as an in-memory database. From the sqllite.org site it seems as though it is a real db? Can it be both or is the in-memory db that I saw something else? (used with NUnit).
Have a [read of this](http://www.sqlite.org/inmemorydb.html) Sqlite is a real embedded DB which is used in lots and lots of places (including the iphone and firefox) the apis allow you to specify if you want to hold your db in memory.
Yes, just use `":memory:"` as the database path.
Can sqlite be an inmemory database also?
[ "", "sql", "sqlite", "nunit", "" ]
I am trying to figure out a way to query a property feature lookup table. I have a property table that contains rental property information (address, rent, deposit, # of bedrooms, etc.) along with another table (Property\_Feature) that represents the features of this property (pool, air conditioning, laundry on-site, etc.). The features themselves are defined in yet another table labeled Feature. ``` Property pid - primary key other property details Feature fid - primary key name value Property_Feature id - primary key pid - foreign key (Property) fid - foreign key (Feature) ``` Let say someone wants to search for property that has air conditioning, and a pool and laundry on-site. How do you query the Property\_Feature table for multiple features for the same property if each row only represents one feature? What would the SQL query look like? Is this possible? Is there a better solution? Thanks for the help and insight.
In terms of database design, yours is the right way to do it. It's correctly normalized. For the query, I would simply use exists, like this: ``` select * from Property where exists (select * from Property_Feature where pid = property.pid and fid = 'key_air_conditioning') and exists (select * from Property_Feature where pid = property.pid and fid = 'key_pool') ``` Where key\_air\_conditioning and key\_pool are obviously the keys for those features. The performance will be OK even for large databases.
Here's the query that will find all the properties with a pool: ``` select p.* from property p inner join property_feature pf on p.pid = pf.pid inner join feature f on pf.fid = f.fid where f.name = 'Pool' ``` I use inner joins instead of `EXISTS` since it tends to be a bit faster.
Best Practice to querying a Lookup table
[ "", "sql", "lookup-tables", "" ]
In all the years I have been developing in PHP, I have always heard that using `eval()` is evil. Considering the following code, wouldn't it make sense to use the second (and more elegant) option? If not, why? ``` // $type is the result of an SQL statement, e.g. // SHOW COLUMNS FROM a_table LIKE 'a_column'; // hence you can be pretty sure about the consistency // of your string. $type = "enum('a','b','c')"; // option one $type_1 = preg_replace('#^enum\s*\(\s*\'|\'\s*\)\s*$#', '', $type); $result = preg_split('#\'\s*,\s*\'#', $type_1); // option two eval('$result = '.preg_replace('#^enum#','array', $type).';'); ```
**I would be cautious in calling eval() pure evil.** Dynamic evaluation is a powerful tool and can sometimes be a life saver. With eval() one can work around shortcomings of PHP (see below). The main problems with eval() are: * **Potential unsafe input.** Passing an untrusted parameter is a way to fail. It is often not a trivial task to make sure that a parameter (or part of it) is fully trusted. * **Trickiness.** Using eval() makes code clever, therefore more difficult to follow. To quote Brian Kernighan "*Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it*" The main problem with actual use of eval() is only one: * Inexperienced developers who use it without enough consideration. As a rule of thumb I tend to follow this: 1. Sometimes eval() is the only/the right solution. 2. For most cases one should try something else. 3. If unsure, goto 2. 4. Else, **be very, very careful.**
eval is evil when there is only the slightest possibility that userinput is included in the evaluated string. When you do eval without content that came from a user, you should be safe. Nevertheless you should think at least twice before using eval, it looks deceivingly simple, but with error handling (see VBAssassins comment), debuggability etc. in mind, it is not so simple anymore. So as a rule of thumb: Forget about it. When eval is the answer you're propably asking the wrong question! ;-)
When is eval evil in php?
[ "", "php", "eval", "" ]
I am trying to make a webpage that uses a moving div that slowly moves to the left. There is also another div that moves on top of it to the right that gives a 3D effect (but that's beside the point). What I am trying to do right now has made a 7000px wide div that slowly moves to the left (animating the "right" property of CSS with jQuery `animate()`), but after it's all moved by, the animation ends. Is there a way to make the div an infinite width or at least cause it to go back to the beginning (much like a grocery store checkout moving belt thing) so the animation never stops? I am thinking this requires a few seperate divs, each once it reaches its end, goes back, but I can't figure out how to do that as I am a beginner jQuery developer.
**UPDATE** Taking in account your example at <http://nth.brandonwang.org/stuhf2/simpleindex.html> you can fix it just by adding a callback at the end, your script must be like this: ``` $(document).ready(function() { animateRight (); animateLeft (); }); function animateRight () { $('#lightright').css ("left", "100%"); $('#lightright').animate({left:'0%'},1500, "", animateRight); } function animateLeft () { $('#lightleft').css ("right", "100%"); $('#lightleft').animate({right:'0%'},1600, animateLeft); } ``` Basically we just reset the animated css property and start de animation effect, the animation duration is faster in this code just to help to see the effect. Hope that it helps you
You could look into using the jQuery `marquee` plugin: <http://remysharp.com/demo/marquee.html> <http://remysharp.com/2008/09/10/the-silky-smooth-marquee/>
How to make infinite movement of a div?
[ "", "javascript", "jquery", "css", "html", "" ]
How to format the number which can be converted to Byte[] (array); I know how to convert the result value to byte[], but the problem is how to format the intermediate number. This is by data, ``` int packet = 10; int value = 20; long data = 02; // This will take 3 bytes [Last 3 Bytes] ``` i need the long value, through that i can shift and I'll fill the byte array like this ``` Byte[0] = 10; Byte[1] = 20; Byte[2] = 00; Byte[3] = 00; Byte[4] = 02; ``` Byte 2,3,4 are data but formatting the intermediate value is the problem. How to form this Here is the sample long data= 683990319104; ///I referred this as intermediate value. This is the number i receiving from built in application. ``` Byte[] by = new byte[5]; for (int i = 0; i < 5; i++) { by[i] = (byte)(data & 0xFF); data>>= 8; } Here Byte[0] = 00; Byte[1] = 00; //Byte 0,1,2 are Data (ie data = 0) Byte[2] = 00; Byte[3] = 65; //Byte 3 is value (ie Value = 65) Byte[4] = 159; // Byte 4 is packet (is Packet = 159); ``` This is one sample. Currently BitConverter.GetBytes(..) is ues to receive. Byte while sending, the parameter is long. So i want the format to generate the number `683990319104` from ``` packet = 159 value = 65 data = 0 ``` I think now its in understandable format :)
The use of 3 bytes to define the long seems unusual; if it is just the 3 bytes... why a long? why not an int? For example (note I've had to make assumptions about your byte-trimming based on your example - you won't have the full `int`/`long` range...): ``` static void Main() { int packet = 10; int value = 20; long data = 02; byte[] buffer = new byte[5]; WritePacket(buffer, 0, packet, value, data); for (int i = 0; i < buffer.Length; i++) { Console.Write(buffer[i].ToString("x2")); } Console.WriteLine(); ReadPacket(buffer, 0, out packet, out value, out data); Console.WriteLine(packet); Console.WriteLine(value); Console.WriteLine(data); } static void WritePacket(byte[] buffer, int offset, int packet, int value, long data) { // note I'm trimming as per the original question buffer[offset++] = (byte)packet; buffer[offset++] = (byte)value; int tmp = (int)(data); // more efficient to work with int, and // we're going to lose the MSB anyway... buffer[offset++] = (byte)(tmp>>2); buffer[offset++] = (byte)(tmp>>1); buffer[offset] = (byte)(tmp); } static void ReadPacket(byte[] buffer, int offset, out int packet, out int value, out long data) { // note I'm trimming as per the original question packet = buffer[offset++]; value = buffer[offset++]; data = ((int)buffer[offset++] << 2) | ((int)buffer[offset++] << 1) | (int)buffer[offset]; } ```
Not entirely sure what you are asking exactly, but I think you are looking for BitConverter.GetBytes(data).
number formation for byte conversion
[ "", "c#", "" ]
I want take a section of a picture, for example the middle of a picure, and repeat only that section in the background of a div. Is this even remotely possible? I suppose I could do this in javascript, but that would be messy. In theory the answer to my question should be able to take a single pixel from a picture and repeat it in a line, or as a solid background. Does anyone have any idea how I could do this in CSS?
You might be able to achieve this effect using the CSS3 [`border-image`](http://ejohn.org/blog/border-image-in-firefox/) property. Unfortunately, I am not aware of a way to do this sort of thing in CSS2. Also, I don't think that you can do this via CSS sprites, because sprites don't stretch parts of your image—they just allow you to show certain parts of the image. Steve
Contrary to what some here have stated, depending on the image, you CAN do this with CSS/Sprites. But that isn't always going to be the case. It comes down to the image you want to repeat, it's height/width in relation to the sprite it exists on, the direction you want to repeat it, and the size of the container you want it to repeat in. [![alt text](https://i.stack.imgur.com/n9hPx.gif)](https://i.stack.imgur.com/n9hPx.gif) (source: [sampsonresume.com](http://www.sampsonresume.com/labs/sprite.gif)) This sprite could be repeated on the left 100px for use in a sidebar, while the other portions could serve as buttons and roll-over states in a navigation. with a small change, you could make the repeatable portion horizontal.
Repeating a section of an image in CSS
[ "", "javascript", "html", "css", "background", "repeat", "" ]
## Input: The customer claims that the application (.NET) when querying for some data returns data different from when the customer looks into the data table directly. I understand there could be various reasons and in completely different places. My purpose is not to solve it here, but rather to ask experienced DBAs and DB developers if: ## Is it possible for a VIEW to show data that does not match the underlying TABLE(s)? * **What are possible causes/reasons for this?** * Can an UPDATE statement on a view cause future SELECTs to return 'updated' data, when the table really does not? ## Possible causes (please comment on those with question-marks): 1. the reason is that there are two separate transactions, which would explain the customers' confusion. 2. the underlying table was altered, but the view was not refreshed (using sp\_refreshview) 3. a different user is connecting and can see different data due to permissions ? 4. programmer error: wrong tables/columns, wrong filters (all-in-one here) 5. corruption occurs: DBCC CHECKDB should help 6. can `SELECT ... FOR UPDATE` cause this **???** 7. ? \_\_ ## What really happened (THE ANSWER): Column positions were altered in some tables: Apparently the customer gave full database access to a consultant for database usage analysis. That great guy changed the order of the columns to see the few *audit* fields at the beginning of the table when using `SELECT * ...` clauses. Using [dbGhost](http://www.innovartis.co.uk/products/products.aspx) the database schema was compared to the schema of the backup taken few days before the problem appeared, and the column position differences were discovered. What came next was nothing related to programming, but more an issue of politics. Therefore the `sp_refreshview` was the solution. I just took one step more to find who caused the problem. Thank you all.
Yes, sort of. Possible Causes: 1. The View needs to be refreshed or recompiled. Happens when source column definitions change and the View (or something it depends on) is using "\*", can be nasty. Call sp\_RefreshView. Can also happen because of views or functions (data sources) that it calls as well. 2. The View is looking at something different from what they/you think. They are looking at the wrong table or view. 3. The View is transforming the data in an unexpected way. It works right, just not like they expected. 4. The View is returning a different subset of the data than expected. Again, it works right, just not like they think. 5. They are looking at the wrong database/server or with a Logon/user identity that causes the View to alter what it shows. Particularly nefarious because unlike Management Studio, most client programs do not tell you what database/server they are pointed at.
it is possible if the underlying table has been changed and sp\_refreshview has not been ran against the view, so the view will have missing columns if those were added to the table. To see what I mean read [how to make sure that the view will have the underlying table changes by using sp\_refreshview](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/how-to-make-sure-that-the-view-will-have)
Database VIEW does not reflect the data in the underying TABLE
[ "", "sql", "sql-server", "schema", "" ]
while review a javascript coding, i saw that ``` var detailInf = { "hTitle":"Results", "hMark":"98" }; ``` What's the concept behind this js coding. While give alert for the variable its shows as "[object Object]". So this is an object, then how can we access the variable and reveal the data from this object.
That's an object in [JSON](http://www.json.org/) format. That's a [javascript object literal](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Literals#Object_Literals). Basically, the bits to the left of the `:`'s are the property names, and the bits to the right are the property values. So, what you have there is a variable called `detailInf`, that has two properties, `hTitle` and `hMark`. `hTitle`'s value is Results, `hMark`'s value is 98. ``` var detailInf = { "hTitle":"Results", "hMark":"98"}; alert(detailInf.hTitle); //should alert "Results" alert(detailInf.hMark); //should alert "98 ``` **Edit** Paolo's answer is better :-)
Try doing this: ``` alert(detailInf['hTitle']); alert(detailInf.hTitle); ``` Both will alert "Results" - this is a Javascript object that can be used as a dictionary of sorts. Required reading: [Objects as associative arrays](http://www.quirksmode.org/js/associative.html) As a footnote, you should really get [Firebug](http://www.getfirebug.com) when messing around with Javascript. You could then just `console.log(detailInf);` and you would get a nicely mapped out display of the object in the console.
How to access the properties of a JavaScript object?
[ "", "javascript", "scripting", "" ]
**EDIT: After feedback from my original post, I've change the text to clarify my problem.** I have the following query (pseudo code): ``` $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); mysql_query("SET NAMES 'utf8'; COLLATE='utf8_danish_ci';"); mysql_query("SELECT id FROM myTable WHERE name = 'Fióre`s måløye'", $conn); ``` This returns 0 rows. In my logfile, I see this: ``` 255 Connect root@localhost on 255 Query SET NAMES 'utf8'; COLLATE='utf8_danish_ci' 255 Init DB norwegianfashion 255 Query SELECT id FROM myTable WHERE name = 'Fióre`s måløye' 255 Quit ``` * If I run the query directly in phpMyAdmin, I get the result. * Table encoding: UTF-8 * HTML page encoding: UTF-8 * I can add records (from form input) where names uses accents (e.g. "Fióre`s Häßelberg") * I can read records with accents when using -> "name LIKE '$labelName%'" * The information in the DB looks fine I have no clue why I can't select any rows which name has accent characters. I really hope someone can help me. **UPDATE 1:** I've come to a compromise. I'll be converting accents with htmlentities when storing data, and html\_entity\_decode when retrieving data from the DB. That seems to work. The only drawback I see so far, is that I can't read the names in cleartext using phpMySQL.
As other answers indicate, this very much seems like an encoding problem. I suggest turning on query logging ( <http://dev.mysql.com/doc/refman/5.1/en/query-log.html> ) as it can show you what the database really receives. **UPDATE**: I finally found a page explaining the dirty details of PHP and UTF-8 (<http://www.phpwact.org/php/i18n/charsets>). Also, make sure you read this (<http://niwo.mnsys.org/saved/~flavell/charset/form-i18n.html>) to understand how you to get proper data returned from form posts.
I think you should rather return `$result` than `$this->query`. Additionally you should be aware of [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) and consider using [`mysql_real_escape_string`](http://docs.php.net/mysql_real_escape_string) or Prepared Statements to protect you against such attacks. `addslashes` is not a proper protection.
Encoding problems in PHP / MySQL
[ "", "php", "mysql", "encoding", "" ]
I found BigDecimal have setScale method, but doesn't have getScale method. How to getScale on BigDecimal?
You have the scale() (not getScale in this case) method in BigDecimal which returns the scale set by setScale(..). See: <http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#scale()>
[BigDecimal.scale()](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#scale()): > public int scale() > > Returns the scale of this BigDecimal. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. For example, a scale of -3 means the unscaled value is multiplied by 1000. > > Returns: > the scale of this BigDecimal.
How to getScale on BigDecimal?
[ "", "java", "bigdecimal", "" ]
I want to move through the pixels of an image, not by going line by line, column by column in the "normal" way. But begin at the center pixel and going outward in a spiral motion. But I'm not sure how to do this. Any suggestions on how this can be done?
You can do this by using parametric functions, function for radius is r(t) = R, and x(t) = Rcos(t) and y(t)=Rsin(t). Do you mean something like [this](http://www60.wolframalpha.com/input/?i=plot+t*cos%28t%29%2C+t*sin%28t%29)?
It would be helpful to think about this in reverse. For example, starting at the top left corner and moving in a clockwise direction you would move along the top row, then down the right hand side, along the bottom, and up the left edge to the pixel under the starting point. Then move along the second row, and continue in a spiral. Depending on the dimensions of the image you will end up with either a single column of pixels or a single row of pixels and will be moving either up/down or left/right. From this finishing point you can then follow your steps backwards and process all the pixels as you need to. To work out your starting position mathematically you would need to know the width/height of the image as well as which pixel you would like to end on and the direction you want to be travelling in when you get to the last pixel.
C# Moving through an image in a spiral motion?
[ "", "c#", ".net", "image-processing", "" ]
I am learning jQuery and have a created several plug ins. Unfortunately due to my company's coding practices they want all javascript code to be extract out to js files. This for me poses two challenges: 1. Can i extract the actual $(document).ready(..) call to a js file? So far with my limited knowledge I have not figured if this at all possible. If not, I welcome any suggestions to make this cleaner and more acceptable way to include this code. 2. There are too many javascript includes for each asp.net page header since I may be using several plugins. Is there a way to reduce the potential costly server trips that I would need to make each time I need these files? Any suggestions, corrections are greatly appreciated thanks
`1.` Absolutely. Just add a script reference to your html like this: ``` <script type='text/javascript' src='js/yourfile.js'></script> ``` Then just start your .js file with ``` jQuery(function() { foo; ... bar; }); ``` or any other shortcut ways of starting the jQuery code block. `2.` You should run your scripts through something like [Minify](http://code.google.com/p/minify/) before sending them off to the user. This will combine the files and pack them in nicely, so that they take up less space.
Using $(document).ready () in an external javascript file is fine - it will work exactly the same :) In fact - not only will it work, but it is good practice as it helps to seperate the content (HTML) from the behaviour (Javascript). In response to your section question - you can combine all of your plugins into a single javascript file and link to that one inside the <head>. You could also try minifying the scripts, although this is normally a bit overkill until the site goes live. When I use jQuery, I normally use this kind of structure: ``` <html> <head> <!-- html tags such as title, link, meta etc --> <script type="text/javascript" src="/path/to/jquery.js"></script> <script type="text/javascript" src="/path/to/plugin.js"></script> <!-- more plugins included if required --> </head> <body> <!-- html here --> <!-- script is the last thing before the ending body tag (increases performance) --> <script type="text/javascript" src="/path/to/your_jQuery_code.js"></script> </body> </html> ```
Keeping my jQuery code away from the html files
[ "", "javascript", "jquery", "" ]
I'm currently inserting a record into a SQL Server Table and then selecting the auto-increment ID as follows: ``` (@p0 int,@p1 nvarchar(8))INSERT INTO [dbo].[Tag]([Some_Int], [Tag]) VALUES (@p0, @p1) SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value] ``` (This was generated using Linq-to-SQL). For some reason when I run this code inside a transaction using the TransactionScope object with a Serializable isolation level, SQL Server throws a deadlock error. I analyzed the deadlock graph events and found that the two processes involved were each waiting on the other to perform the convert operation, as I understand the following information: ``` <resource-list> <keylock hobtid="72057594101170176" dbid="5" objectname="foo.dbo.Tag" indexname="PK_Tag_1" id="lockb77cdc0" mode="RangeS-S" associatedObjectId="72057594101170176"> <owner-list> <owner id="processc9be40" mode="RangeS-S"/> </owner-list> <waiter-list> <waiter id="processc9ae38" mode="RangeI-N" requestType="convert"/> </waiter-list> </keylock> <keylock hobtid="72057594101170176" dbid="5" objectname="foo.dbo.Tag" indexname="PK_Tag_1" id="lockb77cdc0" mode="RangeS-S" associatedObjectId="72057594101170176"> <owner-list> <owner id="processc9ae38" mode="RangeS-S"/> </owner-list> <waiter-list> <waiter id="processc9be40" mode="RangeI-N" requestType="convert"/> </waiter-list> </keylock> </resource-list> ``` My understanding was that the transaction scope would prevent the second process from performing the insert until the first had finished both inserting and selecting the identity. However this doesn't seem to be the case. Could anyone shed some light on the best approach to achieving what I require in a thread-safe way? --**Updated**-- Just to note; I'm 99% sure that a connection isn't being shared between the two processes as each creates a new DataContext to communicate with the database. --**Updated Again**-- Remus Rusanu pointed out that some omitted information was related to the problem, I tried to simplify the scenario based on the deadlock graph report, but I've extended the explanation here. Before I do the insert I perform an exists query on the table in question to determine if the tag already exists. If it does I end the transaction. If not the insert should go ahead and then I perform an update, not shown here, on a table that has `Some_Int` as the primary key, though the update is purely for a last modified value. It may also be of importance that the Tag table has a clustered index composed of both the auto inc ID and Some\_Int. I didn't think this last piece of information was of relevance as I have tried changing the table to only have the auto inc field as the primary key / clustered index to no avail. Thanks.
The 'convert' in question is a ['lock convert' from RangeS-S to RangeI-N](http://msdn.microsoft.com/en-us/library/ms191272.aspx), not related to the 'CONVERT' function in any way. The fact that you have RangeS-S locks already placed on the PK\_Tag\_1 index indicates that you're doing something more than just an INSERT. Does your transaction does, by any chance, a check first to see if the the new record 'exists' before attempting the insert?
Check the isolationLevel, which is used in your query. Note, that TransactionScope uses **Serializable** isolation level by default (<http://msdn.microsoft.com/en-us/library/ms172152.aspx>). Try change the isolation level of your transaction to Read Commited.
Why does the following SQL Server insert deadlock when run within a transaction?
[ "", "c#", "sql-server", "linq-to-sql", "deadlock", "transactionscope", "" ]
``` {"something":"1","mode":"true","number":"1234"} ``` Because I'm getting a 406 on expecting JSON. It's being generated via Jersey, which is told that a method @Produces JSON. It's being received by a Dojo xhrGet which has JSON set as its handleAs. EDIT - To clarify, I'm not interested in the code where I evaluate or anything like that. The question was very simple - is it valid JSON?
It is, but you've got both the boolean (`mode`) and numeric (`number`) elements as strings. Shouldn't it be: ``` {"something":"1","mode":true,"number":1234} ```
It is valid JSON if all values of the dictionary are Strings. This is also valid JSON: {"something": 1, "mode": true, "number": 1234} Usually, however, a 406 error happens when you ask for a response type (such as html or json) and the server cannot send it in that type. Why do you think the input is invalid?
Is this valid JSON?
[ "", "javascript", "json", "" ]
I have been trying to build a user control with some custom properties set in the designer. However the control involves some interop code and settings which shouldn't be adjusted at runtime. Is there a way to stop the values being changed after they have been initially set by the designer code?
Are you able to modify the property definition? One approach is, add a sentinel to the property setter, and allow only one set operation (which would usually be done by InitializeComponent()): ``` private int _myProperty; private bool _isMyPropertySet = false; public int MyProperty { set { if (!_isMyPropertySet) { _isMyPropertySet = true; _myProperty = value; } else { throw new NotSupportedException(); } } } ```
Michael provided a great answer, and it will solve your problem at runtime. However, at design time, if you need to be able to change that value more than once (it is design time, and the probability is likely high), then you will want to combine the DesignMode check with Michaels example: ``` private int _myProperty; private bool _isMyPropertySet = false; public int MyProperty { set { if (this.DesignMode || !_isMyPropertySet) { _isMyPropertySet = true; _myProperty = value; } else { throw new NotSupportedException(); } } } ``` Now you will be able to edit this value to your hearts content during design, without running into that NotSupportedException() and getting a botched designer on the second set.
C# stop property change at runtime
[ "", "c#", "properties", "user-controls", "" ]
I have a question regarding the std::sort algorithm. Here is my test code: ``` struct MyTest { int m_first; int m_second; MyTest(int first = 0, int second = 0) : m_first(first), m_second(second) { } }; int main(int argc,char *argv[]) { std::vector<MyTest> myVec; for(int i = 0; i < 10; ++i) { myVec.push_back(MyTest(i, i + 1)); } //Sort the vector in descending order on m_first without using stand alone function or functors return 0; } ``` Is it possible to sort the vector on the variable `m_first` without using any stand alone functions or functors? Also, please note that I am not using boost.
Yes, so long as the value type in the range to be sorted has an `operator <` that defines a "strict weak ordering", that is to say, it can be used to compare two `MyTest` instances correctly. You might do something like: ``` class MyTest { ... bool operator <(const MyTest &rhs) const { return m_first<rhs.m_first; } }; ```
Write an operator< for your struct. This is the default function used by sort and the easiest way to allow it to function on your custom data structures.
std::sort without functors
[ "", "c++", "stl", "sorting", "functor", "" ]
We are stuck with Java2SE v1.4 till the end of 2010. That's really nasty, but we can't help it. What options do we have to use some of the new features already now? I can think of several ways like * changing the bytecode, e.g. using [Retrotranslator](http://retrotranslator.sourceforge.net/) or [Retroweaver](http://retroweaver.sourceforge.net/). * backport of libraries, e.g. [Concurrent Backport](http://backport-jsr166.sourceforge.net/), but this does not help for generics. * emulation of Java 5 features, e.g. checked Collections, Varargs with helper methods, etc. * changing source code by precompilation, stripping all 1.5 stuff before final compilation, e.g. using [Declawer](http://sites.google.com/site/glazedlists/Home/declawer) can do this. I am most interested in very positive experience with it in production environments using Weblogic and "real" stuff.
Thanks for your answers. Here is the summary of all relevant answers and my own research. **Changing the bytecode: The Retros** This is done by the ["retro"-tools](http://en.wikipedia.org/wiki/Comparison_of_backporting_tools): [Retrotranslator](http://retrotranslator.sourceforge.net/), [Retroweaver](http://retroweaver.sourceforge.net/) and [JBossRetro](http://www.jboss.org/community/docs/DOC-10738). Retrotranslator seems to be the most mature and active of them tool. These tools scan all classes and change the bytecode to remove Java 5 and 6 features. Many Java5 features are supported, some by using 3rd party backport libraries. This option is most popular and there is some positive feedback from users. Experiments showed that it's working as expected. See a short overview on [developerworks](http://www.ibm.com/developerworks/java/library/j-jtp02277.html). Pro: You can develop entirely in Java 5, build modules and all kind of JARs. In the end you just transform all classes to Java 1.4 and package your EAR. This is easily done with Retrotranslator's Maven integration (`org.codehaus.mojo:retrotranslator-maven-plugin`). Con: Conservative environments do not allow changed bytecode to be deployed. The result of the retro-step is not visible to any coder and can't be approved. The second problem is fear: There might be some cryptic production problem and the retro-code is another step that might be blamed for that. App-server vendors might refuse help due to changed bytecode. So nobody wants to take responsibility to use it in production. As this is rather a policital than a technical problem, so I see no solution. It has happened to us, so I was looking for further options :-( **Compiling Java5 to Java 1.4: jsr14** There is an unsupported option, `javac -source 1.5 and -target jsr14` which compiles the Java5 source to valid Java 1.4 bytecode. Most features like varargs or extended for loop are translated by the compiler anyway. Generics and annotations are stripped. Enums are not supported and I don't know about autoboxing, as the `valueOf` methods were mostly introduced in Java5. Con: Only byte code is translated, library usage is not changed. So you have to be careful not to use Java5 specific APIs (but could use Backports). Further you have to build all modules at the same time, because for development time you propably want Java5 code with generic and annotation information. So you have to build the entire project from scratch for Java 1.4 production. **Changing Source back to Java 1.4: Declawer** As answered in a [related question](https://stackoverflow.com/questions/603828/java-5-to-java-1-4-source-code-backporting-tool), there is [Declawer](https://glazedlists.dev.java.net/servlets/ProjectDocumentList?folderID=4541&expandFolder=4541&folderID=4540), a compiler extension, that works for generics and varargs, but not for enhanced for loop or autoboxing. The generated source "is a little funky, but not too bad". Pro: The generated source is available and can be reviewed. In worst case fixes can be made in this source. There is no "magic", because the source is valid Java. Some people even use JAD (Java decompiler) to get the Java 1.4 source again. The output of Jad readable is readable if you compile with debug information and don't use inner classes. Con: Similar to `-target jsr14`, you need an extra step in the deployment. Same problems with libraries, too. **Changing Source back to Java 1.4: by hand** Several answers suggested doing it by hand. For an automatic, repeating build process this is of course not useful, but for one-time changes it's reasonable. Just automate what is possible. Maybe look at Antlr for creating a home-grown conversion tool. **Backported Libraries:** The problem is, that Java5 also ships new libraries, that are not available in older JREs, see [related question](https://stackoverflow.com/questions/547872/converting-java-1-5-source-into-1-1-source). Fortunately there are several backported libraries that give you some functionality of Java5, but can't simulate language features, like generics. * [Annotations](http://backport175.codehaus.org/), discussed at [TSS](http://www.theserverside.com/news/thread.tss?thread_id=31882) * [Concurrent](http://backport-jsr166.sourceforge.net/) * [com.sun.net.httpserver](http://javablog.co.uk/2007/10/27/http-server-api-backport-to-java-5/) (Java 6 to 5) * [Gif writing](http://www.jakobnielsen.net/java6-gif-backport/) (Java 6 to 5) * Start your own backport project ;-) * You might copy classes you need from the JDK or other libraries, but most likely they are related to other classes. **Emulating Java5 features in Java 1.4 code:** I was thinking about some things you might do to make your life easier and still staying with Java 1.4. The most important features are typesafe collections, here are some ideas: * Instead of using generics you can create your own typesafe containers with some template. * Add a typesafe Iterator (which is no Iterator any more). * Add `asList` methods that allows `1,2,...,n` arguments and an array of them (to simulate varargs). * Methods for varargs (converting `1,...,n` arguments to arrays) and `valueOf` can be put in some helper class.
> sourcecode precompilation, stripping > all 1.5 stuff before final compilation > and deployment. Are there any tools > which can do this? Yes. They're called Retrotranslator or Retroweaver. Apart from Generics (which only exist for the compiler's sake anyway), you cannot simply "strip 1.5 stuff". Enums (and maybe also some other features) have to be replaced with functionally equivalent code. Which is exactly what those tools do.
Backport Java 5/6 features to Java 1.4?
[ "", "java", "java1.4", "backport", "" ]
If you could help me with this dilemma I have. Now, I know C \ C++, I know asm, I know about dll injection, I know about virtual memory addressing, but I just can't figure out how software like CheatEngine, and others, manage to change a variable's value in another process. For those who don't know, 3rd party cheat engine tools can scan for values in the memory space of a program and identify the location of a variable with a given value and change it. My question is, how do they do it? Given an address, if I were to write C code, how could I change the value at that address belonging to another process without getting an invalid addressing error? Thanks.
I'm fairly certain those programs are pretending to be debuggers. On Windows, I would start with [DebugActiveProcess()](http://msdn.microsoft.com/en-us/library/ms679295(VS.85).aspx) and go from there. Oh, and the very useful looking [ReadProcessMemory()](http://msdn.microsoft.com/en-us/library/ms680553(VS.85).aspx) function (and WriteProcessMemory()).
On unix: ptrace()
How to change a value in memory space of another process
[ "", "c++", "c", "windows", "linux", "memory-management", "" ]
I have a question about iterate through the Alphabet. I would like to have a loop that begins with "a" and ends with "z". After that, the loop begins "aa" and count to "az". after that begins with "ba" up to "bz" and so on... Anybody know some solution? ## Thanks EDIT: I forgot that I give a char "a" to the function then the function must return b. if u give "bnc" then the function must return "bnd"
*Edit: Made it do exactly as the OP's latest edit wants* This is the simplest solution, and tested: ``` static void Main(string[] args) { Console.WriteLine(GetNextBase26("a")); Console.WriteLine(GetNextBase26("bnc")); } private static string GetNextBase26(string a) { return Base26Sequence().SkipWhile(x => x != a).Skip(1).First(); } private static IEnumerable<string> Base26Sequence() { long i = 0L; while (true) yield return Base26Encode(i++); } private static char[] base26Chars = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); private static string Base26Encode(Int64 value) { string returnValue = null; do { returnValue = base26Chars[value % 26] + returnValue; value /= 26; } while (value-- != 0); return returnValue; } ```
**First effort, with just a-z then aa-zz** ``` public static IEnumerable<string> GetExcelColumns() { for (char c = 'a'; c <= 'z'; c++) { yield return c.ToString(); } char[] chars = new char[2]; for (char high = 'a'; high <= 'z'; high++) { chars[0] = high; for (char low = 'a'; low <= 'z'; low++) { chars[1] = low; yield return new string(chars); } } } ``` Note that this will stop at 'zz'. Of course, there's some ugly duplication here in terms of the loops. Fortunately, that's easy to fix - and it can be even more flexible, too: **Second attempt: more flexible alphabet** ``` private const string Alphabet = "abcdefghijklmnopqrstuvwxyz"; public static IEnumerable<string> GetExcelColumns() { return GetExcelColumns(Alphabet); } public static IEnumerable<string> GetExcelColumns(string alphabet) { foreach(char c in alphabet) { yield return c.ToString(); } char[] chars = new char[2]; foreach(char high in alphabet) { chars[0] = high; foreach(char low in alphabet) { chars[1] = low; yield return new string(chars); } } } ``` Now if you want to generate just a, b, c, d, aa, ab, ac, ad, ba, ... you'd call `GetExcelColumns("abcd")`. **Third attempt (revised further) - infinite sequence** ``` public static IEnumerable<string> GetExcelColumns(string alphabet) { int length = 0; char[] chars = null; int[] indexes = null; while (true) { int position = length-1; // Try to increment the least significant // value. while (position >= 0) { indexes[position]++; if (indexes[position] == alphabet.Length) { for (int i=position; i < length; i++) { indexes[i] = 0; chars[i] = alphabet[0]; } position--; } else { chars[position] = alphabet[indexes[position]]; break; } } // If we got all the way to the start of the array, // we need an extra value if (position == -1) { length++; chars = new char[length]; indexes = new int[length]; for (int i=0; i < length; i++) { chars[i] = alphabet[0]; } } yield return new string(chars); } } ``` It's possible that it would be cleaner code using recursion, but it wouldn't be as efficient. Note that if you want to stop at a certain point, you can just use LINQ: ``` var query = GetExcelColumns().TakeWhile(x => x != "zzz"); ``` **"Restarting" the iterator** To restart the iterator from a given point, you could indeed use `SkipWhile` as suggested by thesoftwarejedi. That's fairly inefficient, of course. If you're able to keep any state between call, you can just keep the iterator (for either solution): ``` using (IEnumerator<string> iterator = GetExcelColumns()) { iterator.MoveNext(); string firstAttempt = iterator.Current; if (someCondition) { iterator.MoveNext(); string secondAttempt = iterator.Current; // etc } } ``` Alternatively, you may well be able to structure your code to use a `foreach` anyway, just breaking out on the first value you can actually use.
Iterating through the Alphabet - C# a-caz
[ "", "c#", "count", "loops", "iteration", "alphabet", "" ]
I am using quartz for schedulling. ``` TriggerUtils.getDateOf(0,40,18,09,06); ``` it accept 5 parameter. (seconds, minutes, hours, daysOfMonth, month). When i pass fourth parameter as "09". Eclipse give me error "The literal Octal 09 (digit 9) of type int is out of range ". **But when i pass the fourth parameter as "9" instead of "09", it works.** Can anyone explain me this error?
In java, if you are defining an integer, a leading '0' will denote that you are defining a number in octal ``` int i = 07; //integer defined as octal int i = 7; // integer defined as base 10 int i = 0x07; // integer defined as hex int i = 0b0111; // integer defined as binary (Java 7+) ```
There is no 9 in [Octal](http://en.wikipedia.org/wiki/Octal) (what you get with a preceding 0). 0-7, only.
09 is not recognized where as 9 is recognized
[ "", "java", "integer", "octal", "" ]
I'm wondering how I can open a file literally in C++ (like double clicking it)?
Provided you have the ".txt" extension registered (and text files should be associated with Notepad in a default installation, or something else if you've changed it from Explorer - you'd have to work pretty hard to disassociate them), Windows will open it for you without you having to specify the executable name: ``` ShellExecute (hwnd,"open","c:\\x.txt",NULL,NULL,SW_SHOW); ``` or, for a web page in your browser of choice: ``` ShellExecute (hwnd,"open","http://www.microsoft.com",NULL,NULL,SW_SHOW); ```
You mean like open explorer? How about using ``` system("explorer.exe file.to.open"); ```
how to open a file (ie. .txt file) in C++ (kinda like double clicking it in windows)?
[ "", "c++", "windows", "file", "io", "" ]
I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected. What would be a good way to get the filesize of a file that is changing in size. Ive done something like this... ``` import string import os f1 = open('VSERVICE.xml', 'r') f2 = open('split.xml', 'w') for line in f1: if str(line) == '</Service>\n': break else: f2.write(line) size = os.path.getsize('split.xml') print('size = ' + str(size)) ``` running this prints 0 as the filesize for about 80 iterations and then 4176. Does Python store the output in a buffer before actually outputting it?
Yes, Python is buffering your output. You'd be better off tracking the size yourself, something like this: ``` size = 0 for line in f1: if str(line) == '</Service>\n': break else: f2.write(line) size += len(line) print('size = ' + str(size)) ``` (That might not be 100% accurate, eg. on Windows each line will gain a byte because of the `\r\n` line separator, but it should be good enough for simple chunking.)
File size is different from file position. For example, ``` os.path.getsize('sample.txt') ``` It exactly returns file size in bytes. But ``` f = open('sample.txt') print f.readline() f.tell() ``` Here f.tell() returns the current position of the file handler - i.e. where the next write will put its data. Since it is aware of the buffering, it should be accurate as long as you are simply appending to the output file.
After writing to a file, why does os.path.getsize still return the previous size?
[ "", "python", "filesize", "" ]
Yes I read [Utility for downloading artifacts from maven repo without mvn/poms](https://stackoverflow.com/questions/884808/) and other related questions, but I don't want to install the file manually. Actually I want to have something like a *wget* for maven, which fetches an artifact (with dependencies) and puts it somewhere or installs it in the local repository. Is the maybe a plugin available which does this?
There is the `dependency:get` goal, as described at the [dependency plugin manual](http://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.html). This featured was requested at this [jira ticket](http://jira.codehaus.org/browse/MDEP-184). But I tried it with Maven 2.1.0 and it didn't work.
I'm not sure if there is a Maven plugin to handle this, but it is fairly simple to use the [Maven Ant tasks](http://maven.apache.org/ant-tasks/index.html "Maven Ant Tasks") for this purpose. You don't need to have Maven or a POM file, just Ant and this build file: ``` <?xml version="1.0" encoding="UTF-8"?> <project name="mvn-get" default="get" basedir="."> <property name="maven.ant.tasks.jar" value="${ant.home}/lib/maven-ant-tasks-2.011.jar" /> <property name="maven.ant.tasks.bootstrap.location" value="http://apache.inetbridge.net/maven/binaries/maven-ant-tasks-2.0.11.jar" /> <available property="maven.ant.tasks.jar.exists" file="${maven.ant.tasks.jar}" /> <!-- This will download the "latest version" of the maven-ant-tasks if needed --> <target name="bootstrap_maven" unless="maven.ant.tasks.jar.exists"> <get src="${maven.ant.tasks.bootstrap.location}" dest="${maven.ant.tasks.jar}" /> </target> <!-- This will initialize all the maven ant tasks and download the requested artifact and its dependencies --> <target name="get" depends="bootstrap_maven" xmlns:artifact="urn:maven-artifact-ant"> <path id="maven.ant.tasks.classpath" path="${maven.ant.tasks.jar}" /> <typedef resource="org/apache/maven/artifact/ant/antlib.xml" uri="urn:maven-artifact-ant" classpathref="maven.ant.tasks.classpath" /> <condition property="maven.repo.local" value="${maven.repo.local}" else="${user.home}/.m2/repository"> <isset property="maven.repo.local" /> </condition> <echo>maven.repo.local=${maven.repo.local}</echo> <artifact:localRepository id="local.repository" path="${maven.repo.local}" /> <artifact:dependencies pathId="build.classpath" sourcesFilesetId="sources.id"> <dependency groupId="${mvn.get.groupId}" artifactId="${mvn.get.artifactId}" version="${mvn.get.version}"/> <localRepository refid="local.repository" /> </artifact:dependencies> </target> </project> ``` Using a command line like the following will do what you want: ``` ant -Dmvn.get.groupId=commons-httpclient -Dmvn.get.artifactId=commons-httpclient -Dmvn.get.version=3.1 -Dmaven.repo.local=. ``` The inspiration for this came from this [excellent blog post.](http://ptrthomas.wordpress.com/2009/03/08/why-you-should-use-the-maven-ant-tasks-instead-of-maven-or-ivy/ "Why you should use the Maven Ant Tasks instead of Maven or Ivy")
Is it possible to explicity tell maven to download and install an artifact to the local repository?
[ "", "java", "maven-2", "build", "" ]
I have a query doing something like: ``` SELECT FieldX, FieldY FROM A WHERE FieldW IN (108, 109, 113, 138, 146, 160, 307, 314, 370, 371, 441, 454 ,457, 458, 479, 480, 485, 488, 490, 492, 519, 523, 525, 534, 539, 543, 546, 547, 550, 564, 573, 629, 642, 643, 649, 650, 651, 694, 698, 699, 761, 762, 768, 772, 773, 774, 775, 778, 784, 843, 844, 848, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 868, 869, 871, 872, 873, 891) ``` Having an IN clause with so many options, is it bad for query performance? I'm experiencing many timeouts in my application, and I believe it could be a source of this kind of problem. Can I optimize the query without removing the numbers, using any good SQL Hint? EDIT: @KM these are keys in a different table. This is a forum application, explaining briefly: c# gets all forums from database and stores it in app cache. Before C# calls a procedure that gets the threads for these forums and for this user, c# does some logic filtering the "all forums" collection, considering permissions and some business logic. The timeout happens on database and not on application itself. Doing all this logic on the query will require a lot of inner joins and I'm not 100% sure I can do all this inside the procedure. I'm using **SQL Server 2000**
There are several considerations when writing a query using the IN operator that can have an effect on performance. **First, IN clauses are generally internally rewritten by most databases to use the OR logical connective.** So `col IN ('a','b','c')` is rewritten to: `(COL = 'a') OR (COL = 'b') or (COL = 'c')`. The execution plan for both queries will *likely* be equivalent assuming that you have an index on `col`. **Second, when using either IN or OR with a variable number of arguments, you are causing the database to have to re-parse the query and rebuild an execution plan each time the arguments change.** Building the execution plan for a query can be an expensive step. Most databases cache the execution plans for the queries they run using the EXACT query text as a key. If you execute a similar query but with different argument values in the predicate - you will most likely cause the database to spend a significant amount of time parsing and building execution plans. This is why [bind variables are strongly recommended](http://decipherinfosys.wordpress.com/2007/08/29/bind-variables-usage-parameterized-queries-in-sql-server/) as a way to ensure optimal query performance. **Third, many database have a limit on the complexity of queries they can execute - one of those limits is the number of logical connectives that can be included in the predicate.** In your case, a few dozen values are unlikely to reach the built-in limit of the database, but if you expect to pass hundreds or thousands of value to an IN clause - it can definitely happen. In which case the database will simply cancel the query request. **Fourth, queries that include IN and OR in the predicate cannot always be optimally rewritten in a parallel environment.** There are various cases where parallel server optimization do not get applied - [MSDN has a decent introduction](http://msdn.microsoft.com/en-us/library/ms178065.aspx) to optimizing queries for parallelism. Generally though, queries that use the UNION ALL operator are trivially parrallelizable in most databases - and are preferred to logical connectives (like OR and IN) when possible.
You can try creating a temporary table, insert your values to it and use the table instead in the `IN` predicate. AFAIK, `SQL Server 2000` cannot build a hash table of the set of constants, which deprives the optimizer of possibility to use a `HASH SEMI JOIN`. This will help only if you don't have an index on `FieldW` (which you should have). You can also try to include your `FieldX` and `FieldY` columns into the index: ``` CREATE INDEX ix_a_wxy ON a (FieldW, FieldX, FieldY) ``` so that the query could be served only by using the index. `SQL Server 2000` lacks `INCLUDE` option for `CREATE INDEX` and this may degrade `DML` performance a little but improve the query performance. **Update:** From your execution plan I see than you need a composite index on `(SettingsID, SectionID)` `SQL Server 2000` indeed can built a hash table out of a constant list (and does it), but `Hash Semi Join` most probably will be less efficient than a `Nested Loop` for query query. And just a side note: if you need to know the count of rows satisfying the `WHERE` condition, don't use `COUNT(column)`, use `COUNT(*)` instead. A `COUNT(column)` does not count the rows for which the `column` value is `NULL`. This means that, first, you can get the results you didn't expect, and, second, the optimizer will need to do an extra `Key Lookup` / `Bookmark Lookup` if your column is not covered by an index that serves the `WHERE` condition. Since `ThreadId` seems to be a `CLUSTERED PRIMARY KEY`, it's all right for this very query, but try to avoid it in general.
Is SQL IN bad for performance?
[ "", "sql", "sql-server-2000", "" ]
I've been using the DateTime class in PHP, because date() has the downsides of the Unix timestamp. However, neither approach detects invalid dates for months which don't have 31 days, but attempt to use the 31st day. Example code: ``` try { $date = new DateTime('02/31/2018'); $formattedDate = $date->format('Y-m-d'); } catch (Exception $e) { } echo $formattedDate; ``` Example output: ``` 2018-03-03 ``` **Update 1:** To use checkdate() I need the component parts of the date. To get that, I will need to instantiate a DateTime object with the date string as the constructor. In the case of '02/31/2018', it will convert it to '03/03/2018' when instantiated. At that point it will be too late to run the component month, day, year through checkdate(). What is the solution? **Update 2:** Getting the component part of the dates is easy if I force a specific format (e.g. mm/dd/yyyy), but if I accept all formats accepted by strtotime(), I cannot perform a checkdate before running it through strtotime() -> date() or DateTime::\_\_construct -> DateTime::format(). I've been using the DateTime class in PHP, because date() has the downsides of the Unix timestamp. However, neither approach detects invalid dates for months which don't have 31 days, but attempt to use the 31st day. Example code: ``` try { $date = new DateTime('02/31/2018'); $formattedDate = $date->format('Y-m-d'); } catch (Exception $e) { } echo $formattedDate; ``` Example output: ``` 2018-03-03 ``` **Update 1:** To use checkdate() I need the component parts of the date. To get that, I will need to instantiate a DateTime object with the date string as the constructor. In the case of '02/31/2018', it will convert it to '03/03/2018' when instantiated. At that point it will be too late to run the component month, day, year through checkdate(). What is the solution? **Update 2:** Getting the component part of the dates is easy if I force a specific format (e.g. mm/dd/yyyy), but if I accept all formats accepted by strtotime(), I cannot perform a checkdate before running it through strtotime() -> date() or DateTime::\_\_construct -> DateTime::format().
To get the component parts of the date, you can just split the string... ``` $date = explode('/','02/18/2018'); ``` Then use checkdate(), now that you have the components.
Try the [`checkdate`](https://www.php.net/manual/en/function.checkdate.php) function. > Checks the validity of the date formed > by the arguments. A date is considered > valid if each parameter is properly > defined. > > **Parameters** > > *month* > > The month is between 1 and 12 inclusive. > > *day* > > The day is within the allowed number of days for the given month . > ***Leap years are taken into > consideration.*** > > *year* > > The year is between 1 and 32767 inclusive.
How can I catch '02/31/2010' as an invalid date using DateTime class?
[ "", "php", "datetime", "date", "" ]