Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
What kind of skills should a WPF developer know to create MVVM applications? Things like Attached Dependency Properties and DelegateCommands. Thanks!
There's a good intro video/screencast on WPF and MVVM on Ch9; <http://channel9.msdn.com/shows/Continuum/MVVM/>
DataTemplate for sure.
MVVM WPF Application Developer skill set
[ "", "c#", "wpf", "mvvm", "" ]
I cannot use AsEnumerable() on DataTable, I'm using C# 3 but I'm just targeting 2.0 framework (LINQ capability is courtesy of [LINQBridge](http://code.google.com/p/linqbridge/)). Is there any way I can make DataTable enumerable without using Select() ? ``` bool isExisting = (bdsAttachments.DataSource as DataTable).Select().Any(xxx => (string)dr["filename"] == filename); ``` Update: I wanted it to make it look like this: ``` bool isExisting = (bdsAttachments.DataSource as DataTable).AsEnumerable().Any(xxx => (string)dr["filename"] == filename); ``` I'm getting an inkling that the Select method of DataTable returns a copy, I'm thinking to just use AsEnumerable, the problem is I'm just targeting 2.0 framework, System.Data.DataSetExtensions is not available BTW, i tried this: <http://cs.rthand.com/blogs/blog_with_righthand/archive/2006/01/15/284.aspx>, but has compilation errors.
``` public static IEnumerable<DataRow> EnumerateRows(this DataTable table) { foreach (var row in table.Rows) { yield return row; } } ``` Allows you to call: ``` bool isExisting = (bdsAttachments.DataSource as DataTable).EnumerateRows().Any(dr => (string)dr["filename"] == filename); ```
1. `IEnumerable<DataRow> rows = dataTable.AsEnumerable();` (System.Data.DataSetExtensions.dll) 2. `IEnumerable<DataRow> rows = dataTable.Rows.OfType<DataRow>();` (System.Core.dll)
How can I make DataTable enumerable?
[ "", "c#", "ado.net", "datatable", ".net-2.0", "enumerable", "" ]
I am having a JavaScript namespace say ``` A={ CA: function() { this.B(); }, B: function() { var test='test'; var result='t1'; C: function() { this.test='test1'; ..... ..... return 'test1'; } result=this.C(); return result; } } ``` Now when I am executing such code it is giving that TypeError: this.C is not a function. Can somebody tell me why it is so. I know it is something related with lexical scoping but am unable to understand this.
I think the problem is that when `this.C()` is executed inside the function referred to by `B`, `this` refers to the object that contains `B`, that is, object `A`. (This assumes `B()` is called within the context of `A`) The problem is, `C` does not exist on the object `A`, since it's defined within `B`. If you want to call a local function `C()` within `B`, just use `C()`. EDIT: Also, I'm not sure what you've posted is valid JavaScript. Specifically, `B` should be defined this way, since you can't use the object:property syntax within a function. ``` B: function() { var test='test'; var result='t1'; var C = function() { this.test='test1'; return 'test1'; } result=C(); return result; } ```
You have to be careful when you use *this* to identify anything in Javascript because each time you change scope "this" changes. Assigning the 'this' reference to it's own variable helps get around this. ``` var a = new function() { var self = this; self.method = function() { alert('hiya'); }; var b = function() { this.method(); // this isn't 'a' anymore? self.method(); // but 'self' is still referring to 'a' }; }; ```
Calling method inside another method in javascript?
[ "", "javascript", "methods", "" ]
I need to explain myself why I do not use static methods/propertis. For example, ``` String s=String.Empty; ``` is this property (belongs to .Net framework) wrong? is should be like? ``` String s= new EmptySting(); ``` or ``` IEmptyStringFactory factory=new EmptyStringFactory(); String s= factory.Create(); ```
I think the worst thing about using statics is that you can end up with tight coupling between classes. See the ASP.NET before System.Web.Abstractions came out. This makes your classes harder to test and, possibly, more prone to bugs causing system-wide issues.
Why would you want to create a new object every time you want to use the empty string? Basically the empty string is a singleton object. As Will says, statics *can* certainly be problematic when it comes to testing, but that doesn't mean you should use statics *everywhere*. (Personally I prefer to use "" instead of `string.Empty`, but that's a discussion which has been done to death elsewhere.)
what is the inconveniences of using static property or method in OO approach?
[ "", "c#", "oop", "" ]
Can anyone help, i trying to figure what i need to do, i have been given the tasks of writing a server and a client in TCP (UDP). basically multiple clients will connect to the server.. and the server sends MESSSAGES to the client. I have no problem in creating the server and client but with tcp i am unsure whcih way to go. DOes the .net 3.5 support everything or do i need to go on the hunt for some component? I am looking for soome good examples with c# for TCP or UDP. THis is where i am not 100% sure .. as far as i know there is UDP and TCP ... 1 is connected and 1 is not.. So which way do i go and can c# support both?? Advantages /Disadvantages? Say if the server has to support multiple clients that i only need to open 1 port or do i need to open 2? Also if a client crashes i need for it not to effect the SERVER hence the server can either ignore it and close connection if one is open or timeout a connection... If in fact a connection is needed again going back to tcp udp Any ideas where i shoudl beging and choosing which protocol and amount of ports i am going to need to assign? thanks
Is there a requirement to do this at such a low level? Why not use WCF? It fully supports messaging over TCP/IP, using binary data transfer, but it's at a much higher level of abstraction than raw sockets.
UDP cons: * packet size restriction means you can only send small messages (less than about 1.5k bytes). * Lack of stream makes it hard to secure UDP: hard to do an authentication scheme that works on lossy exchange, and just as hard to protect the integrity and confidentiality of individual messages (no key state to rely on). * No delivery guarantee means your target must be prepared to deal with message loss. Now is easy to argue that if the target can handle a total loss of messages (which *is* possible) then why bother to send them in the first place? UDP Pros: * No need to store a system endpoint on the server for each client (ie. no socket). This is one major reason why MMO games connected to hundred of thousands of clients use UDP. * Speed: The fact that each message is routed individually means that you cannot hit a stream congestion like TCP can. * Broadcast: UDP can broadcast to all listeners on a network segment. You shouldn't even consider UDP if you're considering TCP too. If you're considering TCP means you are thinking in terms of a stream (**exactly once in order messages**) and using UDP will put the burden of fragmentation, retry and acknowledgment, duplicate detection and ordering in your app. You'll be in no time reinventing TCP in your application and it took all engineers in the word 20 years to get *that* right (or at least as right as it is in IPv4). If you're unfamiliar with these topics I recommend you go with the flow and use WCF, at least it gives you the advantage of switching in and out with relative ease various transports and protocols. Will be much harder to change your code base from TCP to UDP and vice versa if you made the wrong choice using raw .Net socket components.
TCP or UDP help with a server/client in c#?
[ "", "c#", ".net", "tcp", "udp", "client-server", "" ]
I've encountered a strange problem in Sql Server. I have a pocket PC application which connects to a web service, which in turn, connects to a database and inserts lots of data. The web service opens a transaction for each pocket PC which connects to it. Everyday at 12 P.M., 15 to 20 people with different pocket PCs get connected to the web service simultaneously and finish the transfer successfully. But after that, there remains one open transaction (visible in Activity Monitor) associated with 4000 exclusive locks. After a few hours, they vanish (probably something times out) and some of the transfered data is deleted. Is there a way I can prevent these locks from happening? Or recognize them programmatically and wait for an unlock? Thanks a lot.
Doing lots of tests, I found out a deadlock is happening. But I couldn't find the reason, as I'm just inserting so many records in some independent tables. These links helped a bit, but to no luck: <http://support.microsoft.com/kb/323630> <http://support.microsoft.com/kb/162361> I even broke my transactions to smaller ones, but I still got the deadlock. I finally removed the transactions and changed the code to not delete them from the source database, and didn't get the deadlocks anymore. As a lesson, now I know if you have some (more than one) large transactions getting executed on the same database at the same time, you'll sure have problems in SQL Server, I don't know about Oracle.
You could run `sp_lock` and check to see if there are any exclusive locks held on tables you're interested in. That will tell you the SPID of the offending connection, and you can use `sp_who` or `sp_who2` to find more information about that SPID. Alternatively, the Activity Monitor in Management Studio will give you graphical versions of this information, and will also allow you to kill any offending processes (the `kill` command will allow you to do the same in a query editor).
Transaction commit executes succesfully but not getting done
[ "", "c#", "sql-server-2005", "ado.net", "transactions", "" ]
I have some data formated like the following ``` 2009.07.02 02:20:14 40.3727 28.2330 6.4 2.6 -.- -.- BANDIRMA-BALIKESIR 2009.07.02 01:38:34 38.3353 38.8157 3.5 2.7 -.- -.- KALE (MALATYA) 2009.07.02 00:10:28 38.8838 26.9328 3.0 3.0 -.- -.- CANDARLI KÖRFEZI (EGE DENIZI) 2009.07.01 23:33:31 36.8027 34.0975 8.2 2.9 -.- -.- GÜZELOLUK-ERDEMLI (MERSIN) 2009.07.01 22:32:44 38.9260 27.0338 5.0 3.4 -.- -.- CANDARLI KÖRFEZI (EGE DENIZI) 2009.07.01 22:12:37 40.2120 41.0378 3.7 2.9 -.- -.- OVACIK-ILICA (ERZURUM) 2009.07.01 22:10:53 38.9208 26.9502 5.0 3.5 -.- -.- ÇANDARLI-DIKILI (IZMIR) 2009.07.01 21:44:29 38.8695 27.1268 6.9 2.9 -.- -.- YUNTDAG-BERGAMA (IZMIR) 2009.07.01 21:27:53 38.9073 26.9895 5.0 3.0 -.- -.- CANDARLI KÖRFEZI (EGE DENIZI) 2009.07.01 21:18:19 38.9212 26.9060 5.0 3.4 -.- -.- CANDARLI KÖRFEZI (EGE DENIZI) 2009.07.01 21:12:15 38.8657 26.9447 13.7 3.8 -.- -.- CANDARLI KÖRFEZI (EGE DENIZI) 2009.07.01 21:09:43 38.9260 27.0853 5.0 3.1 -.- -.- ZEYTINDAG-BERGAMA (IZMIR) 2009.07.01 21:05:40 38.9153 26.9710 5.0 3.4 -.- -.- ÇANDARLI-DIKILI (IZMIR) 2009.07.01 20:29:02 37.6888 38.7212 5.0 3.3 -.- -.- AKINCILAR-KAHTA (ADIYAMAN) 2009.07.01 18:17:12 41.2700 36.0502 2.7 2.7 -.- -.- TAFLAN- (SAMSUN) 2009.07.01 17:50:03 38.6312 35.7962 5.0 2.8 -.- -.- ELBASI-BÜNYAN (KAYSERI) ``` I would like to split this on white lines but i would like last column to not split when there are parenthesis? I would like each line to split in to 8 pieces. Is this possible?
Put this into a Regular Expression tool, such as [RegexBuddy](http://regexbuddy.com/). But for your purposes, it will be easy to split on `\s+` or `\s\s+` and set the [limit](http://www.j2ee.me/javase/6/docs/api/java/lang/String.html#split(java.lang.String,%20int)). It depends on which parts of the text you want, which is why you use the tool to help you write your regex. If you specifically want to avoid matching spaces preceded by "(" which doesn't actually solve your problem due to possible lines like "Words (word word)" you can use a [zero-width negative lookahead](http://www.j2ee.me/javase/6/docs/api/java/util/regex/Pattern.html) group. Something like `\s+(?!\()`.
Why are you using regex here? The data file is perfectly aligned, you can extract the data with ``` line.substring(0,12) line.substring(13,20) .. .. ``` It is much faster this way.
Java regex split
[ "", "java", "regex", "split", "" ]
In ASP.NET (hosted) I need a simple file IO operation to read data out of a file and then force a download. Its really that simple. I keep getting a `System.UnauthorizedAccessException` when executing the following code: ``` System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open); ``` Locally it works fine, but when i upload to the shared hosting account i get the above exception. Whats strange is that in the browser if i enter the full path to the file, i can see and use the file.
As everyone else has mentioned, this is most likely because the ASP process hasn't got security permissions to access the file directory. If you can access the file via your browser perhaps you could read the file by using a HttpWebRequest rather than File.Open. This would make sense if you don't have admin control over the server. Here's some sample code for using HttpWebRequest incase it'd help: ``` /// <summary> /// Submits a request to the specified url and returns the text response, or string.Empty if the request failed. /// </summary> /// <param name="uri">The url to submit the request to.</param> /// <returns>The text response from the specified url, or string.Empty if the request failed.</returns> protected string getPageResponse(string url) { //set the default result string responseText = string.Empty; //create a request targetting the url System.Net.WebRequest request = System.Net.HttpWebRequest.Create(url); //set the credentials of the request request.Credentials = System.Net.CredentialCache.DefaultCredentials; //get the response from the request System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); //get the response code (format it as a decimal) string statusCode = response.StatusCode.ToString("d"); //only continue if we had a succesful response (2XX or 3XX) if (statusCode.StartsWith("2") || statusCode.StartsWith("3")) { //get the response stream so we can read it Stream responseStream = response.GetResponseStream(); //create a stream reader to read the response StreamReader responseReader = new StreamReader(responseStream); //read the response text (this should be javascript) responseText = responseReader.ReadToEnd(); } //return the response text of the request return responseText; } ```
You should use IsolatedStorage for your file operations. **[What Is Isolated Storage?](http://www.velocityreviews.com/forums/t20811-article-what-is-isolated-storage-net-framework-tools-series.html)** Running code with limited privileges has many benefits given the presence of predators who are foisting viruses and spyware on your users. The .NET Framework has several mechanisms for dealing with running as least-privileged users. Because most applications have to deal with storing some of their state in a persistent way (without resorting to databases or other means), it would be nice to have a place to store information that was safe to use without having to test whether the application has enough rights to save data to the hard drive. That solution is what isolated storage is designed to provide. By using isolated storage to save your data, you will have access to a safe place to store information without needing to resort to having users grant access to specific files or folders in the file system. The main benefit of using isolated storage is that your application will run regardless of whether it is running under partial, limited, or full-trust. You can refer to [IsolatedStorageFileStream](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefilestream.aspx)
System.UnauthorizedAccessException on a simple ASP.Net File.IO operations
[ "", "c#", "asp.net", "" ]
I wrote a windows service in C# that does some functionality (a public method) after reading a file at regular intervals. Is it possible for me to use this functionality from another C# application ? If possible, please give a solution based on .net 2.0 as well as .net 3.0 Thanks
The cleanest option would be to write that functionality in a separate assembly (dll) that you use from both the service and the second .NET application. You **can** reference the service assembly (even if it is an exe, in VS2008 at least) - but it seems a little overkill. If you want to execute the method **in the context of the running service**, then you'll need some IPC (perhaps WCF or sockets).
Just expose it using WCF and call it from your other app. They are in different processes so you have to use IPC
Using windows services [written in C#] using C#
[ "", "c#", "windows-services", ".net-2.0", "communication", "" ]
What is the most elegant way (in C#) of determining how many pages of data you have given: a.) Total Records b.) Records Per page. Currently what I have is working, but it's using if/else to check if the value is than the total (1 page) or more, and then has to truncate the decimal place, perform a mod operation and add 1 more if there was a trailing decimal. I'm sure there's a Math function that does alot of this for me and isn't so ugly. Thanks.
``` int pages = ((totalRecords-1) / recordsPerPage)+1 ``` Assuming `totalRecords` and `recordsPerPage` are ints. If they're doubles (why are they doubles?) you'll need to convert them to ints or longs first, because this relies on integer division to work. Wrap it in a function so that you don't have to repeat the calculation everywhere in your code base. Just set it up once in a function like this: ``` public int countPages(int totalRecords, int recordsPerPage) { return ((totalRecords-1) / recordsPerPage)+1; } ``` If `totalRecords` can be zero, you can just add a special case for it in the function easily: ``` public int countPages(int totalRecords, int recordsPerPage) { if (totalRecords == 0) { return 1; } return ((totalRecords-1) / recordsPerPage)+1; } ```
``` int pages = 1 + (totalRecords + 1) / (recordsPerPage + 1) ```
Determine # of pages from Total and PerPage values
[ "", "c#", "pagination", "" ]
I look for a way how I can create a ddl for my jpa annotated entities. I prefer a pure java way for this. If possible it would be nice to have generate the drop statements too.
**Export data from a database as sql** Use the [liquibase](http://www.liquibase.org/) opensource project > LiquiBase is an open source (LGPL), database-independent library for tracking, managing and applying database changes. It is built on a simple premise: All database changes (structure and data) are stored in an XML-based descriptive manner and checked into source control. **Generate create and drop script for given JPA entities** We use this code to generate the drop and create statements: Just construct this class with all entity classes and call create/dropTableScript. If needed you can use a persitence.xml and persitance unit name instead. Just say something and I post the code too. ``` import java.util.Collection; import java.util.Properties; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.dialect.Dialect; import org.hibernate.ejb.Ejb3Configuration; /** * SQL Creator for Tables according to JPA/Hibernate annotations. * * Use: * * {@link #createTablesScript()} To create the table creationg script * * {@link #dropTablesScript()} to create the table destruction script * */ public class SqlTableCreator { private final AnnotationConfiguration hibernateConfiguration; private final Properties dialectProps; public SqlTableCreator(final Collection> entities) { final Ejb3Configuration ejb3Configuration = new Ejb3Configuration(); for (final Class entity : entities) { ejb3Configuration.addAnnotatedClass(entity); } dialectProps = new Properties(); dialectProps.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect"); hibernateConfiguration = ejb3Configuration.getHibernateConfiguration(); } /** * Create the SQL script to create all tables. * * @return A {@link String} representing the SQL script. */ public String createTablesScript() { final StringBuilder script = new StringBuilder(); final String[] creationScript = hibernateConfiguration.generateSchemaCreationScript(Dialect .getDialect(dialectProps)); for (final String string : creationScript) { script.append(string).append(";\n"); } script.append("\ngo\n\n"); return script.toString(); } /** * Create the SQL script to drop all tables. * * @return A {@link String} representing the SQL script. */ public String dropTablesScript() { final StringBuilder script = new StringBuilder(); final String[] creationScript = hibernateConfiguration.generateDropSchemaScript(Dialect .getDialect(dialectProps)); for (final String string : creationScript) { script.append(string).append(";\n"); } script.append("\ngo\n\n"); return script.toString(); } } ```
DataNucleus has SchemaTool that can be invoked from java, or from the command line. It does what you require --Andy ([DataNucleus](http://www.datanucleus.org))
How can I create a ddl for my jpa entities from java code?
[ "", "java", "hibernate", "jpa", "ddl", "" ]
VS 2008 I have this code snippet I found on a VB website. But for some reason I am having trouble converting it to C#. ``` My.Computer.Network.IsAvailable ``` Many thanks,
``` using System.Net.NetworkInformation; internal class Program { private static void Main() { NetworkInterface.GetIsNetworkAvailable(); } } ```
Yes, garethm is right, this class (Network) is from a VB.NET library - you need to reference the Microsoft.VisualBasic assembly if using in a C# project. ``` Microsoft.VisualBasic.Devices.Network n = new Microsoft.VisualBasic.Devices.Network(); if (n.IsAvailable) { // do stuff } ``` Works for me - my network is available :). As far as how Network relates to NetworkInterface class, it depends on what you want to do next. For instance, Network has such nice stuff as NetworkAvailabilityChanged event, and UploadFile method. On the other hand, NetworkInterface can give you a bunch of specific technical info such as speed or whether it supports multicast. BTW, there is nothing undocumented about using a class from Microsoft.VisualBasic namespace - it's the core idea behind .NET that you can use classes from assemblies regardless of the language they were written in.
convert code snippet to C#
[ "", "c#", "" ]
I have some pages that I don't want users to be able to access directly. I have this function I came up with which works: ``` function prevent_direct_access() { if($_SERVER['REQUEST_URI'] == $_SERVER['PHP_SELF']) { //include_once('404.php'); header("Location: 404.php"); } } ``` This does exactly what I want, the URL does not change but the content does. However I am wondering if there is something I need to add to tell search engines that this is a 404 and not to index it. keep in mind I do not want the URL to change though. Thanks!
Don’t redirect but send the 404 status code: ``` header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404); exit; ```
for the search engines, if you return HTTP status 404 they should not index I believe. But you could always redirect to somewhere covered by a robots.txt
PHP: prevent direct access to page
[ "", "php", "http-status-code-404", "" ]
I've written a small scraper that is meant to open up a connection to a PHP script on a remote server via HTTP and pump some XML it finds there into a local file. Not exactly rocket science, I know. The code below is the scraper in its entirety (cleaned up and anonymized). This code works fine except for one small detail, it seems that no matter the size of the XML file (1 MB or 7 MB) the resulting XML file is always missing a small section at the end (600-800 characters). **Notes:** * If I open the php page in Firefox - I get the whole doc no problem. * If I fire up wireshark and run the program below, I see the whole doc transferred across the wire, but not written down into the file. ``` using System; using System.IO; using System.Collections.Generic; using System.Text; namespace myNameSpace { class Program { static void Main(string[] args) { Console.Write("BEGIN TRANSMISSION\n"); writeXMLtoFile(); Console.Write("END TRANSMISSION\n"); } public static void writeXMLtoFile() { String url = "http://somevalidurl.com/dataPage.php?lotsofpars=true"; TextWriter tw = new StreamWriter("xml\\myFile.xml"); tw.Write(ScreenScrape(url)); Console.Write(" ... DONE\n"); tw.Close(); } public static string ScreenScrape(string url) { System.Net.WebRequest request = System.Net.WebRequest.Create(url); using (System.Net.WebResponse response = request.GetResponse()) { using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } } } ``` Should I be using a different Writer? I've tried both TextWriter and StreamWriter to the same effect. Kind regards from Iceland, Gzur
Try: ``` XmlDocument doc = new XmlDocument(); doc.Load(url); doc.Save(filename); ``` It really is that easy (with some error handling obviously). The .Net framework should do everything for you. I jumped through hoops a month or so ago trying to do the same thing and kicked myself when I read the help file on XmlDocument ;)
Additionally, if really all you want to do is download a page to the file system, investigate the [`WebClient.DownloadFile`](http://msdn.microsoft.com/en-us/library/ez801hhe.aspx) method :)
Problem with retrieving XML via HTTP and writing to file
[ "", "c#", ".net", "visual-studio", "" ]
I have a Class named "Constants" that contains all the "constant" variable in my application (mostly Strings). The Class is written like so: ``` public class Constants { public const string DATABASE="myDatabase"; public const string whatever="whatever"; public enum Colors { Red Blue Orange } public const string Time = "07/03/2009 9:14 PM"; } ``` The members of this Class can be accessed normally by other classes. The weird thing is, if I remove the "const", that variable can no longer be accessed on other classes. ``` public class Constants { public const string DATABASE="myDatabase"; public const string whatever="whatever"; public enum Colors { Red Blue Orange } public string Time = DateTime.Now.ToString(); //NO LONGER CONST } ``` I tried to CLEAN the solution and rebuilding. I also closed/re-run VS2005. Is this a known bug? Or am I missing something else? Thanks!
Once you remove the `const` modifier the variable becomes an instance variable. Instance variables can only be accessed through an instance of the class (not through the type). This is "By Design". You would need to use code like the following to access Time ``` var c = new Constants(); var t = c.Time; ``` If "const" doesn't suit your need for some reason, particularly if you are using a type which cannot be const, you may want to try static instead. It will have the same effect in terms of access semantics.
The *const* keyword implies both *static* and *readonly*. Without *const* it's not static anymore, so you need an instance of `Constants` to access that member: ``` var c = new Constants(); Console.WriteLine(c.Time); // should work now ```
CONST variable removed. Member can no longer be accessed outside class
[ "", "c#", "constants", "" ]
If a Java program is started, it get's in the system process-monitor the name java. Many Java-programs are that way hard to distinguish. So it would be nice, if a way exists, to set the name, that will be shown in the process-monitor. I'm aware that this may work different on different Operating Systems. A simple way would be, if the java-interpreter would support a switch to set the name, like this: ``` java -processname MyProgram -jar MyProgram ``` But I couldn't find such a switch, so it is probably non-existant. An API in Java to set the process-name would be also fine. So, so you have any suggestions?
I don't know if this is possible, but you could use a command line tool that comes with the JDK called 'jps'. It's like \*nix `ps`, but just Java programs instead. `jps -v` shows all the arguments you have passed to java. Also, I have seen people attach a "process name" to their java processes by adding an unused `-Dmyprocessname` to the args.
as @omerkudat said: ``` jps -v ``` prints out all java processes {processID, params list} If the params list is not enough to recognize the applications you need, try adding some dummy params when running them: ``` java -Dname=myApp -cp myApp.jar some.client.main.MainFrame ``` This will print like: ``` 7780 MainFrame -Dname=myApp ``` and you can use the process ID to kill / monitor it.
How can I set the process name for a Java-program?
[ "", "java", "process", "" ]
I have a Python regular expression that matches a set of filenames. How to change it so that I can use it in Mercurial's .hgignore file to ignore files that do *not* match the expression? Full story: I have a big source tree with `*.ml` files scattered everywhere. I want to put them into a new repository. There are other, less important files which are too heavy to be included in the repository. I'm trying to find the corresponding expression for `.hgignore` file. 1st observation: Python doesn't have regular language complement operator (AFAIK it can complement only a set of characters). (BTW, why?) 2nd observation: The following regex in Python: ``` re.compile("^.*(?<!\.ml)$") ``` works as expected: ``` abcabc - match abc.ml - no match x/abcabc - match x/abc.ml - no match ``` However, when I put exactly the same expression in the `.hgignore` file, I get this: ``` $ hg st --all ? abc.ml I .hgignore I abcabc I x/xabc I x/xabc.ml ``` According to `.hgignore` manpage, Mercurial uses just normal Python regular expressions. How is that I get different results then? How is it possible that Mercurial found a match for the `x/xabc.ml`? Does anybody know less ugly way around the lack of regular language complement operator?
The regexs are applied to each subdirectory component in turn as well as the file name, not the entire relative path at once. So if I have a/b/c/d in my repo, each regex will be applied to a, a/b, a/b/c as well as a/b/c/d. If any component matches, the file will be ignored. (You can tell that this is the behaviour by trying `^bar$` with bar/foo - you'll see that bar/foo is ignored.) `^.*(?<!\.ml)$` ignores x/xabc.ml because the pattern matches x (i.e. the subdirectory.) This means that there is no regex that will help you, because your patterns are bound to match the first subdirectory component.
Through some testing, found two solutions that appear to work. The first roots to a subdirectory, and apparently this is significant. The second is brittle, because it only allows one suffix to be used. I'm running these tests on Windows XP (customized to work a bit more unixy) with Mercurial 1.2.1. (Comments added with `# message` by me.) ``` $ hg --version Mercurial Distributed SCM (version 1.2.1) $ cat .hgignore syntax: regexp ^x/.+(?<!\.ml)$ # rooted to x/ subdir #^.+[^.][^m][^l]$ $ hg status --all ? .hgignore # not affected by x/ regex ? abc.ml # not affected by x/ regex ? abcabc # not affected by x/ regex ? x\saveme.ml # versioned, is *.ml I x\abcabc # ignored, is not *.ml I x\ignoreme.txt # ignored, is not *.ml ``` And the second: ``` $ cat .hgignore syntax: regexp #^x/.+(?<!\.ml)$ ^.+[^.][^m][^l]$ # brittle, can only use one suffix $ hg status --all ? abc.ml # versioned, is *.ml ? x\saveme.ml # versioned, is *.ml I .hgignore # ignored, is not *.ml I abcabc # ignored, is not *.ml I x\abcabc # ignored, is not *.ml I x\ignoreme.txt # ignored, is not *.ml ``` The second one has fully expected behavior as I understand the OP. The first only has expected behavior in the subdirectory, but is more flexible.
How to emulate language complement operator in .hgignore?
[ "", "python", "regex", "mercurial", "" ]
I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?
The answer by Ber - storing it in threadlocals - is a very bad idea. There's absolutely no reason to do it this way. A much better way is to override the form's `__init__` method to take an extra keyword argument, `request`. This stores the request in the *form*, where it's required, and from where you can access it in your clean method. ``` class MyForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MyForm, self).__init__(*args, **kwargs) def clean(self): ... access the request object via self.request ... ``` and in your view: ``` myform = MyForm(request.POST, request=request) ```
For what it's worth, if you're using **Class Based Views**, instead of function based views, override [`get_form_kwargs`](https://docs.djangoproject.com/en/1.7/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form_kwargs) in your editing view. Example code for a custom [CreateView](https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#django.views.generic.edit.CreateView): ``` from braces.views import LoginRequiredMixin class MyModelCreateView(LoginRequiredMixin, CreateView): template_name = 'example/create.html' model = MyModel form_class = MyModelForm success_message = "%(my_object)s added to your site." def get_form_kwargs(self): kw = super(MyModelCreateView, self).get_form_kwargs() kw['request'] = self.request # the trick! return kw def form_valid(self): # do something ``` The above view code will make `request` available as one of the keyword arguments to the form's `__init__` constructor function. Therefore in your `ModelForm` do: ``` class MyModelForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): # important to "pop" added kwarg before call to parent's constructor self.request = kwargs.pop('request') super(MyModelForm, self).__init__(*args, **kwargs) ```
How do I access the request object or any other variable in a form's clean() method?
[ "", "python", "django", "" ]
Is there a way to make this code work? LogonControl.java ``` @Audit(AuditType.LOGON) public void login(String username, String password) { // do login } ``` AuditHandler.java ``` public void audit(AuditType auditType) { // persist audit } ``` Endgame being, that each time login() is called, audit() is also called, with the appropriate audittype. I imagine AOP is probably the solution to this, but I would like it to be as simple as possible (the AspectJ tutorials I've looked at normally have very convoluted annotations). Note: I don't want to have to predefine the methods that will call audit, I'm writing this for an extensible framework, and others may need to use it.
Using reflection is easy just annotate a method with @Audit, just like test runners in JUnit: ``` public interface Login { void login(String name, String password); } public class LoginImpl implements Login { @Audit(handler = LoginHandler.class) public void login(String name, String password) { System.out.println("login"); } } ``` @Audit is defined as: ``` @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Audit { Class<? extends Handler> handler(); } ``` where Handler is: ``` interface Handler { void handle(); } class LoginHandler implements Handler { public void handle() { System.out.println("HANDLER CALLED!"); } } ``` and now the real code: ``` public class LoginFactory { private static class AuditInvocationHandler implements InvocationHandler { private final Login realLogin; public AuditInvocationHandler(Login realLogin) { this.realLogin = realLogin; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Method realMethod = realLogin.getClass().getMethod( method.getName(), method.getParameterTypes()); Audit audit = realMethod.getAnnotation(Audit.class); if (audit != null) { audit.handler().newInstance().handle(); } return method.invoke(realLogin, args); } } public static Login createLogin() { return (Login) Proxy.newProxyInstance( LoginFactory.class.getClassLoader(), new Class[]{Login.class}, new AuditInvocationHandler(new LoginImpl())); } } ``` @Test: ``` Login login = LoginFactory.createLogin(); login.login("user", "secret"); login.logout(); ``` output: ``` HANDLER CALLED! login logout ```
It's done - use [Spring](http://www.springsource.org/) or [Guice](http://code.google.com/p/google-guice/). Rolling your own makes sense if you want to [know how wheels work](http://www.codinghorror.com/blog/archives/001145.html), or if you think that you can do something that's significantly lighter. Just be sure that both are true before you undertake it.
Java: Simple technique for annotation-based code injection?
[ "", "java", "annotations", "aop", "" ]
Using the C# compilers query comprehension features, you can write code like: ``` var names = new string[] { "Dog", "Cat", "Giraffe", "Monkey", "Tortoise" }; var result = from animalName in names let nameLength = animalName.Length where nameLength > 3 orderby nameLength select animalName; ``` In the query expression above, the `let` keyword allows a value to be passed forward to the where and orderby operations without duplicate calls to `animalName.Length`. What is the equivalent set of LINQ extension method calls that achieves what the "let" keyword does here?
Let doesn't have its own operation; it piggy-backs off of `Select`. You can see this if you use "reflector" to pull apart an existing dll. it will be *something* like: ``` var result = names .Select(animalName => new { nameLength = animalName.Length, animalName}) .Where(x=>x.nameLength > 3) .OrderBy(x=>x.nameLength) .Select(x=>x.animalName); ```
There's a good article [here](https://web.archive.org/web/20091003125950/http://gregbeech.com/blogs/tech/archive/2008/04/21/translating-c-3-0-query-syntax-for-linq-to-objects-part-4-let.aspx) Essentially `let` creates an anonymous tuple. It's equivalent to: ``` var result = names.Select( animal => new { animal = animal, nameLength = animal.Length }) .Where(x => x.nameLength > 3) .OrderBy(y => y.nameLength) .Select(z => z.animal); ```
Code equivalent to the 'let' keyword in chained LINQ extension method calls
[ "", "c#", "linq", "extension-methods", "linq-to-objects", "" ]
Is there a more elegant solution to convert an '`Arraylist`' into a '`Arraylist<Type>`'? Current code: ``` ArrayList productsArrayList=getProductsList(); ArrayList<ProductListBean> productList = new ArrayList<ProductListBean>(); for (Object item : productsArrayList) { ProductListBean product = (ProductListBean)item; productList.add(product); } ```
``` ArrayList<ProductListBean> productList = (ArrayList<ProductListBean>)getProductsList(); ``` Note that this is inherently unsafe, so it should only be used if getProductsList can't be updated.
Look up *type erasure* with respect to Java. Typing a collection as containing `ProductListBean` is a compile-time annotation on the collection, and the compiler can use this to determine if you're doing the right thing (i.e. adding a `Fruit` class would not be valid). However once compiled the collection is simply an `ArrayList` since the type info has been erased. Hence, `ArrayList<ProductListBean>` and `ArrayList` are the same thing, and casting (as in Matthew's answers) will work.
Converting an untyped Arraylist to a typed Arraylist
[ "", "java", "arraylist", "" ]
After reading a bit on Javascript's [prototypical inheritance model](http://javascript.crockford.com/prototypal.html), I change my style of constructing a class from ``` var Some_Class = function() { this.public_method = function() { }; (function() { // constructor }).call(this) } ``` to ``` var Some_Class = function() { (function() { // constructor }).call(this) } Some_Class.prototype.public_method = function() { }; ``` Although I understand that this is a good practice, but I am not allowed to access private methods from the public method anymore ``` var Some_Class = function() { var private_member = 'whatever'; (function() { // constructor }).call(this) } Some_Class.prototype.public_method = function() { return private_member; // not possible }; ``` After reading through an article [here](http://robertnyman.com/2008/10/21/javascript-inheritance-experimenting-with-syntax-alternatives-and-private-variables/) (Closure-created constructor), then I came out with this ``` var Some_Class = function() { var private_member = 'whatever', private_method = function(_some_value) { // private method implementation }; if(!arguments.callee.prototype.public_method) { arguments.callee.prototype.public_method = function() { private_method.call(this, private_method); }; } (function() { // constructor }).call(this) } ``` However, what are the drawbacks of doing this?! or is there a better way of doing this if I want to access [private member](http://www.crockford.com/javascript/private.html) in the public method?
The use of function scope variables and closures to simulate private variables/functions is a well established idiom in the javascript community. If the variable is truly intended to be private, I see no drawback to this approach (although some claim that performant code on certain browsers/hosts has to pay attention to how many closures get created). In your example, the private\_method (and its environment) is shared across all objects - since your public\_method closure is created only the first time the object is constructed (and bound to the constructor's prototype property that sets the created object's internal prototype chain) - so the private\_method that is used is only the one that was created the first time. Here is some sample code that will help illustrate what is going on: ``` var global = 1; var Some_Class = function() { var private_method = 'whatever'; var now = ++global; print("outer now: " + now ); private_method = function(_some_value) { // private method implementation print("inner now: " + now); }; if(!arguments.callee.prototype.public_method) { arguments.callee.prototype.public_method = function() { private_method.call(this, private_method); }; } (function() { // constructor }).call(this) } new Some_Class().public_method(); // outer now: 2, inner now: 2 new Some_Class().public_method(); // outer now: 3, inner now: 2 new Some_Class().public_method(); // outer now: 4, inner now: 2 ``` Are you sure that is what you want? If your private\_method does not need to refer to the enclosing object's state, then I see little benefit in doing things the way you are doing. What I usually do (if i have to use 'new' to create my object) is the following: ``` function MyClass() { var private_var = 1; function private_func() { } this.public_func = function() { // do something private_func(); } this.public_var = 10; } var myObj = new MyClass(); ``` The downside to this approach is that each time you construct the object via 'new' you re-create all the closures. But unless my profiler tells me that this design choice needs to be optimized, i prefer its simplicity and clarity. Also I don't see the benefit in your code of doing the following either: ``` (function() { }).call(this); // call the constructor ``` Why are you creating a separate scope in your constructor?
My answer is a non-answer: there's no built-in `private` access in JavaScript but that's okay because [YAGNI](http://c2.com/xp/YouArentGonnaNeedIt.html). Here's how I make `private` members in my code: ``` function Some_Class() { this._private_member = 'whatever'; } Some_Class.prototype._private_method = function() { }; ``` That's good enough. It's not really worth it to jump through hoops when the only real purpose of `private` is to protect yourself from... yourself. (I say this having spent many hours myself playing around with every permutation of closures and prototyping, just as you are, and finally saying "screw it, it's not worth it".)
Better way to access private members in Javascript
[ "", "javascript", "prototype", "" ]
Let's say I have a date that I can represent in a culture-invariant format (ISO 8601). I'll pick July 6, 2009, 3:54 pm UTC time in Paris, a.k.a. 5:54 pm local time in Paris observing daylight savings. > 2009-07-06T15:54:12.000+02:00 OK... is there any hidden gem of markup that will tell the browser to convert that string into a localized version of it? The closest solution is using Javascript's Date.prototype.toLocaleString(). It certainly does a good job, but it can be slow to iterate over a lot of dates, and it relies on Javascript. Is there any HTML, CSS, XSLT, or otherwise semantic markup that a browser will recognize and automatically render the correct localized string? **Edit**: The method I am currently using is replacing the text of an HTML element with a localized string: Starting with: ``` <span class="date">2009/07/06 15:54:12 GMT</span> ``` Using Javascript (with jQuery): ``` var dates = $("span.date", context); // use for loop instead of .each() for speed for(var i=0,len=dates.length; i < len; i++) { // parse the date var d = new Date(dates.eq(i).text()); // set the text to the localized string dates.eq(i).text(d.toLocaleString()); } ``` From a practical point of view, it makes the text "flash" to the new value when the Javascript runs, and I don't like it. From a principles point of view, I don't get why we need to do this - the browser should be able to localize standard things like currency, dates, numbers, as long as we mark it up as such. --- A follow up question: Why do browsers/the Web not have such a simple feature - take a standard data item, and format it according to the client's settings?
I use toLocaleString() on my site, and I've never had a problem with the speed of it. How are you getting the server date into the Date object? Parsing? I add a comment node right before I display the date as the server sees it. Inside the comment node is the date/time of that post as the number of milliseconds since epoch. In Rails, for example: ``` <!--<%= post.created_at.to_i * 1000 %>--> ``` If they have JS enabled, I use jQuery to grab those nodes, get the value of the comment, then: ``` var date = new Date(); date.setTime(msFromEpoch); // output date.toLocaleString() ``` If they don't have JS enabled, they can feel free to do the conversion in their head. If you're trying to parse the ISO time, that may be the cause of your slowness. Also, how many dates are we talking?
Unfortunately, there is not. HTML & CSS are strictly used for presentation, as such, there is no "smarts" built in to change the way things are displayed. Your best bet would be to use a server side language (like .NET, Python, etc.) to emit the dates into the HTML in the format you want them shown to your user.
Localize dates on a browser?
[ "", "javascript", "html", "css", "xslt", "localization", "" ]
How do I make any wxPython widget (like wx.Panel or wx.Button) automatically expand to fill its parent window?
The short answer: use a sizer with a proportion of 1 and the wx.Expand tag. So here I am in the **init** of a panel ``` sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) self.SetSizer(sizer) ```
this shows how you can expand child panel with frame resize it also show how you can switch two panels, one containing cntrls and one containing help I think this solves all your problems ``` import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.panel = wx.Panel(self) # create controls self.cntrlPanel = wx.Panel(self.panel) stc1 = wx.StaticText(self.cntrlPanel, label="wow it works") stc2 = wx.StaticText(self.cntrlPanel, label="yes it works") btn = wx.Button(self.cntrlPanel, label="help?") btn.Bind(wx.EVT_BUTTON, self._onShowHelp) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(stc1) sizer.Add(stc2) sizer.Add(btn) self.cntrlPanel.SetSizer(sizer) # create help panel self.helpPanel = wx.Panel(self.panel) self.stcHelp = wx.StaticText(self.helpPanel, label="help help help\n"*8) btn = wx.Button(self.helpPanel, label="close[x]") btn.Bind(wx.EVT_BUTTON, self._onShowCntrls) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.stcHelp) sizer.Add(btn) self.helpPanel.SetSizer(sizer) self.helpPanel.Hide() self.helpPanel.Raise() self.helpPanel.SetBackgroundColour((240,250,240)) self.Bind(wx.EVT_SIZE, self._onSize) self._onShowCntrls(None) def _onShowHelp(self, event): self.helpPanel.SetPosition((0,0)) self.helpPanel.Show() self.cntrlPanel.Hide() def _onShowCntrls(self, event): self.cntrlPanel.SetPosition((0,0)) self.helpPanel.Hide() self.cntrlPanel.Show() def _onSize(self, event): event.Skip() self.helpPanel.SetSize(self.GetClientSizeTuple()) self.cntrlPanel.SetSize(self.GetClientSizeTuple()) app = wx.PySimpleApp() frame = MyFrame() frame.Show() app.SetTopWindow(frame) app.MainLoop() ```
wxPython: Making something expand
[ "", "python", "user-interface", "wxpython", "" ]
Is there such a structure in c++ standard library? I don't have access to anything else so unordered\_map in tr1 cant be used (and boost etc). What I have is a large number of custom class elements 100000+ which I need to store, and access them very fast O(1) on everage. I can't use arrays/vectors as the elements will be stored randomly and I don't know the position of the element. Is my only alternative to implements an own hashmap implementation with only the c++ standard library available?
The problem is that the O(1) lookup is not standard. I am unsure about what boost has, but some STL implementations (like sgi) have hash\_map. That's what you need. Here is the [documentation](http://www.sgi.com/tech/stl/hash_map.html). Just try out: ``` #include <hash_map> ``` Keep in mind if this works, it is not portable... but maybe for now that's ok, and later you can find workarounds.
If you are really restricted to `std::` and can't use anything else, **`std::map`** is your best bet. This only gives you logarithmic lookup time, not constant one, but compared with arrays/vectors it will be blazingly fast. Also I guess for just 100000 elements the logarithmic lookup will be by fast enough and you won't win much by using a hash table. That being said, chances are that your implementation already includes some hash table implementation. So if `std::map` really isn't fast enough, try ``` #include <tr1/unordered_map> std::tr1::unordered_map<int,int> test; ``` or ``` #include <hash_map> stdext::hash_map<int,int> test; ``` or even ``` #include <boost/tr1/unordered_map.hpp> std::tr1::unordered_map<int,int> test; ```
C++ data structure with lookuptime O(1), like java's hashmap in stl?
[ "", "c++", "performance", "data-structures", "" ]
I would like to learn how to build a web-based email client in PHP (similar to yahoo and gmail). Does anyone know how I can get started with this? I would like my system to be able to send and receive email.
Most obvious answer would be "*don't*": there are already lots of webmail software, some of which are PHP-based *(if you depend on using PHP, because you already have a server based on a LAMP stack, for instance)*. To quote only a few names, all PHP-based, you could have a look at these ones: * [SquirrelMail](http://www.squirrelmail.org/): a quite old-one, and not really sexy... But has been doing the job for years * [Horde IMP](http://www.horde.org/imp/): well-know too, and quite powerful * [roundcube](http://roundcube.net/): maybe the most "sexy" and "web 2.0" of the list of those I tried * [AtMail](http://atmail.org/): I've never used this one, so I can't say much more... I've used the three firsts of the list for quite some time ; roundcube was definitely the most "*user-friendly*", I'd say... *(Googling a bit, you might find many more -- but I think I spoke about the ones that are the most used)* --- Now, if you **have to** set up a Webmail, say, for you company: definitely **use some already existing software**: * an existing software would be quite "*good*" already: + many people using it, which means many people who said "*this could be done better*", or "*that is not user-friendly*", or... you get the point ; all this made the existing software better **:-)** + many people will have tried to break such an application -- which means lots of security-fixes, which means an application probably more secure than you'll write in a long time... * an existing open-source application will represent **hundreds of days of work** + are you really ready to spend that kind of amount of time working on something that already exists? + if you're working for a company: is your company ready to pay your for one year? *or even probably more ?* working on something that already exists? + you don't believe me? Read this blog-post: [Code: It's Trivial](http://www.codinghorror.com/blog/archives/001284.html) ; it's about Stack Overflow, but it would be exactly the same for a webmail software (except that Stack Overflow is more recent -- *and probably had less code-contributors ; but that's just a wild guess ^^* ) As a sidenote: if your company wants you to build a clone of gmail, you won't *(same thing: how many people worked on gmail? How many programmers does your company have? How much can your company spend on this? )*... And for just a couple dollars each year, your company could have a "*professionnal*" Google account for each one of it's employes, BTW... --- After all this, if you still want to / have to write a custom hand-made webmail using a LA\*(M)\*P stack, you will need to know at least the following: * How to programm in PHP * The basics of IMAP *(even if you use a library / framework, such a big application will require you to know some stuff about the underlying protocols, or won't ever understand "why" or "how" something went wrong)* * HTML / CSS / JavaScript *(with some knowledge of AJAX -- come on, it's 2009 !)* * So your application is easier to maintain *(and adding/reworking/modifying stuff and correcting bugs is possible)*, you will probably want to use some Framework, and follow some design patterns and best practices + As an example, you can take a look at Frameworks like [symfony](http://www.symfony-project.org/), or [Zend Framework](http://framework.zend.com/) + Yes, you can develop and application without a Framework, and/or without MVC... But.. *ergh*... Considering all this is not a problem *(If you are not quite good at all this already, and/or don't have much experience, it could take at least a couple of years to acquire that... Considering programming and web-developping is your full-time activity)*, you can start tkinking about accessing a mail server using, for instance, IMAP. There are several possibilities here. I would have a look, at least, before choosing, at these two: * [PHP IMAP extension](http://php.net/imap) * [`Zend_Mail`](http://framework.zend.com/manual/en/zend.mail.read.html) ; maybe it can be used outside of the Zend Framework, BTW --- Once your application is quite done, you will *(hopefully !)* start getting users, which means at least three things: * Bug-reports ; those are almost always **urgent** for users -- like "*OMG I don't understand nothing works anymore, I gotta get my mail RIGHT NOW!*" * Requests for evolutions: users always want more stuff like "*I saw that in gmail on my personnal account ; how is it we don't have that too with our corporate account? It's the tool we use to work !*" * "*This is too slow, I can't work !*" ; then, pray you thought about scalability and optimization when you designed/developped the application! Here, again, are you ready to deal with that? --- Well, I think I said enough ; now, it's your time to think: do you really want/need to develop such an application from scratch? If you have a bit of free time, **maybe you could participate in an already existing, open-source, project ?** That could be profitable to every one ;-) Finally, one last thing: \*\*if you want to work on such a project just for fun, to know what it's like, and to learn more about web-development, then DO !\*\* \*(It's, in my opinion, probably the only reason that would justify working on this, BTW)\*
1. Learn the web stack: HTML, javascript, php, mysql... 2. Write a few small projects 3. Get hired somewhere to learn from more experienced people 4. Learn OOP, design patterns, best practices etc 5. Apply what you learned for a few years If you pass point 5, you'll know how to build one.
How do you build a web based email client using PHP?
[ "", "php", "email-client", "" ]
I have a site with a SELECT statement like this: ``` SELECT * FROM MyTable WHERE MyDate >= GETDATE() ``` I have a record with the value 6/24/2009 9:00:00 AM to MyDate field. When the user visit this page in 6/24/2009 before 9:00:00 AM, this record is shown. But when the user visit this page in 6/24/2009, but after 9:00:00 AM, the SELECT don't get this record. How can I build this SELECT statement disconsidering time, to this record appers until 6/24/2009 12:00:00 PM? Thank you.
Do you really mean 12:00 PM? That's noon, not midnight. Sounds like you really want somthing more like this: ``` SELECT * FROM MyTable WHERE cast(floor(cast(MyDate as float))+1 as datetime) > getdate() ``` See this: [How can I truncate a datetime in SQL Server?](https://stackoverflow.com/questions/923295/how-to-truncate-a-datetime-in-sql-server) The
MCardinale, you already have an answer but I wanted to give one extra piece of advice. Be very sure that you want to do it that way. Per-row functions in SELECT statements never scale very well as the database tables become bigger (not just the one in the accepted answer, I mean *any* per-row function). That's because they tend to break the ability of the DBMS to choose the correct execution plan for maximum speed. If you want a solution to scale well, you need to store information in the DB in such a way as the extraction speed is blindingly fast (based on the maxim, some would say truism, that table rows are almost always read far more often than they're written). To that end, a workable solution is often to add an entire new column which just contains the date portion of the given datetime column and use insert/update triggers to ensure it's set correctly. Then, by having an index on that new column, queries on the date of each row can be done without having to worry about the performance of per-row functions. The impact of the trigger on performance shouldn't matter since inserts and updates happen far less than selects. What this solution does is to shift the cost of converting datetimes to dates off to the insert/update rather than the select, greatly reducing the cumulative cost. This becomes apparent in a database table that never changes once set up - the cost in your current situation happens (unnecessarily) every time you read the data. In the situation described in this answer, the cost disappears totally. Of course it will need more disk space for the table but rarely have I ever seen disk space as the bottleneck in a DBMS - it's almost always raw CPU grunt. Now I realize that this may break 3NF (since that new column may not be dependent on the key) but often that comes in handy for performance. The general rule I follow is to implement in 3NF and drop back to other normalized forms if performance becomes an issue. Just some food for thought - enjoy. Post Scriptum: If you are really storing a datetime in your field, you probably should steer clear of calling it `MyDate`. If it is really intended to be a date, the column type is wrong (and my advice here becomes moot). Otherwise, it should be renamed to something more descriptive. The DBAs and code-cutters that follow you will be eternally grateful :-)
How build a SELECT statement with dates disconsidering time?
[ "", "sql", "sql-server-2005", "" ]
This is a security best practice and I'm wondering if I should even be wasting my time with this. In the same vein of an initial crack of the Blu-ray movie format, hackers just inspected the memory of a player to snoop out a key value. It seems like it's feasible to do the same thing with browser memory, and to look at values that the javascript interpreter has set - so should I be encrypting data that is in memory? Thinking this through - it's eventually insane, b/c if my browser is displaying sensitive data on the screen, conceivable that piece of data is in memory and could be snooped. So it wouldnt matter if I had encrypting that same data in javascript somewhere. I'm having a tough time explaining to my superiors of why we shouldnt go to this level of security...
Really, if you are concerned with some data being in the browser, then it shouldn't be there. When data goes to the client, you can consider it compromised as you have no way of ensuring it is secure. Others have brought up a good point, you send encrypted information to the client, but you won't be able to do anything with it, because you'll have to decrypt it to show it to the end user. This is why if you look at regulations for banks, they never display any personal information (SSN etc.) on the browser, unless it was specifically typed in by the user (typed in and then posted back).
Adam, It's a client issue. When programming for web, browser are clients, you don't and haven't to address security issues on client side if isn't the scope of your project.
Should I be encrypting contents of browser / javascript memory?
[ "", "javascript", "security", "" ]
I'm having problems binding on a form with multiple models being submitted. I have a complaint form which includes complaint info as well as one-to-many complainants. I'm trying to submit the form but I'm getting errors on the bind. ModelState.IsValid always returns false. If I debug and view the ModelState Errors, I get one saying: "The EntityCollection has already been initialized. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph". Also, when debugging, I can see that the the Complaint Model does get populated with Complainants from the form submission, so it seems that part is working. I'm not sure if what I'm doing is not possible with the default ModelBinder, or if I'm simply not going about it the right way. I can't seem to find any concrete examples or documentation on this. A very similar problem can be found on stackoverflow [here](https://stackoverflow.com/questions/711184/asp-net-mvc-example-of-editing-multiple-child-records) but it doesn't seem to deal with strongly typed views. Controller Code: ``` public ActionResult Edit(int id) { var complaint = (from c in _entities.ComplaintSet.Include("Complainants") where c.Id == id select c).FirstOrDefault(); return View(complaint); } // // POST: /Home/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Complaint complaint) { if (!ModelState.IsValid) { return View(); } try { var originalComplaint = (from c in _entities.ComplaintSet.Include("Complainants") where c.Id == complaint.Id select c).FirstOrDefault(); _entities.ApplyPropertyChanges(originalComplaint.EntityKey.EntitySetName, complaint); _entities.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } ``` View Code (This is a partial view that gets called by Create/Edit Views, which are also strongly typed with Complaint): ``` <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ProStand.Models.Complaint>" %> <%= Html.ValidationSummary() %> <% using (Html.BeginForm()) {%> <table cellpadding="0" cellspacing="0" class="table"> <tr> <td> <label for="DateReceived">Date Received:</label> <%= Html.TextBox("DateReceived") %> <%= Html.ValidationMessage("DateReceived", "*") %> </td> <td> <label for="DateEntered">Date Entered:</label> <%= Html.TextBox("DateEntered")%> <%= Html.ValidationMessage("DateEntered", "*") %> </td> </tr> <tr> <td> <label for="Concluded">Concluded:</label> <%= Html.CheckBox("Concluded")%> <%= Html.ValidationMessage("Concluded", "*") %> </td> <td> <label for="IncidentDate">Incident Date:</label> <%= Html.TextBox("IncidentDate")%> <%= Html.ValidationMessage("IncidentDate", "*") %></td> </tr> </table> <hr /> <table> <% if (Model != null) { int i = 0; foreach (var complainant in Model.Complainants){ %> <%= Html.Hidden("Complainants[" + i + "].Id", complainant.Id)%> <tr> <td> <label for="Surname">Surname:</label> <%= Html.TextBox("Complainants[" + i + "].Surname", complainant.Surname)%> <%= Html.ValidationMessage("Surname", "*")%> </td> <td> <label for="GivenName1">GivenName1:</label> <%= Html.TextBox("Complainants[" + i + "].GivenName1", complainant.GivenName1)%> <%= Html.ValidationMessage("GivenName1", "*")%> </td> </tr> <% i++; %> <% }} %> <tr> <td colspan=2> <input type="submit" value="Submit" /> </td> </tr> </table> <% } %> <div> <%=Html.ActionLink("Back to List", "Index") %> </div> ```
Blind guess: change: ``` <%= Html.TextBox("Complainants[" + i + "].Surname", complainant.Surname)%> ``` with: ``` <%= Html.TextBox("Complaint.Complainants[" + i + "].Surname", complainant.Surname)%> ``` Respectively - add "Complaint." before "Complainants[..." **EDIT**: This is NOT a right answer. Left it undeleted just because that might add some value until proper answer pops up. **EDIT2:** I might be wrong, but for me it seems there's problem with entity framework (or - with the way you use it). I mean - asp.net mvc manages to read values from request but can't initialize complainants collection. [Here](http://msdn.microsoft.com/en-us/library/cc679591.aspx) it's written: > The InitializeRelatedCollection(TTargetEntity) method initializes an existing EntityCollection(TEntity) that was created by using the default constructor. The EntityCollection(TEntity) is initialized by using the provided relationship and target role names. > > The InitializeRelatedCollection(TTargetEntity) method is used during deserialization only. Some more info: > Exception: > > * InvalidOperationException > > Conditions: > > * When the provided EntityCollection(TEntity) is already initialized. > * When the relationship manager is already attached to an ObjectContext. > * When the relationship manager already contains a relationship with this name and target role. Somewhy InitializeRelatedCollection gets fired twice. Unluckily - i got no bright ideas why exactly. Maybe this little investigation will help for someone else - more experienced with EF. :) **EDIT3:** This isn't a solution for this particular problem, more like a workaround, a proper way to handle model part of mvc. Create a viewmodel for presentation purposes only. Create a new domain model from pure POCOs too (because EF will support them in next version only). Use [AutoMapper](http://automapper.codeplex.com/) to map EFDataContext<=>Model<=>ViewModel. That would take some effort, but that's how it should be handled. This approach removes presentation responsibility from your model, cleans your domain model (removes EF stuff from your model) and would solve your problem with binding.
``` public ActionResult Edit([Bind(Exclude = "Complainants")]Complaint model) { TryUpdateModel(model.Complainants, "Complainants"); if (!ModelState.IsValid) { // return the pre populated model return View(model); } } ``` **This works for me!** I think that when Complaint object gets created then its 'Complainants' collection gets initialized (because of entity framework auto logic) and then model binder tries to create the collection itself as well, which causes the error. But when we try to update the model manually then collection is already initialized but model binder is not asked to initialize it again.
Model Binding on Multiple Model Form Submission from Strongly-Typed View
[ "", "c#", "asp.net-mvc", "html-helper", "model-binding", "" ]
This looks simple but I can't find a simple answer. I want to open a connection to a remote JMS broker (IP and port are known), open a session to the a specific queue (name known) and post a message to this queue. Is there any simple Java API (standard if possible) to do that ? --- **EDIT** Ok I understand now that JMS is a driver spec just like JDBC and not a communication protocol as I thought. Given I am running in JBoss, I still don't understand how to create a [JBossConnectionFactory](http://www.jboss.org/file-access/default/members/jbossmessaging/freezone/docs/javadoc/api-1.4.0.SP1/org/jboss/jms/client/JBossConnectionFactory.html). --- **EDIT** I actually gave the problem some thoughts (hmmm) and if JMS needs to be treated the same as JDBC, then I need to use a client provided by my MQ implementation. Since we are using SonicMQ for our broker, I decided to embed the sonic\_Client.jar library provided with SonicMQ. This is working in a standalone Java application and in our JBoss service. Thanks for the help
You'll need to use JMS, create a `QueueConnectionFactory` and go from there. Exactly how you create the `QueueConnectionFactory` will be vendor specific (JMS is basically a driver spec for message queues just as JDBC is for databases) but on IBM MQ it something like this: ``` MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory(); connectionFactory.setHostName(<hostname>); connectionFactory.setPort(<port>); connectionFactory.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP); connectionFactory.setQueueManager(<queue manager>); connectionFactory.setChannel("SYSTEM.DEF.SVRCONN"); QueueConnection queueConnection = connectionFactory.createQueueConnection(); QueueSession queueSession = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = queueSession.createQueue(<queue name>); QueueSender queueSender = session.createSender(queue); QueueReceiver queueReceiver = session.createReceiver(queue); ``` **EDIT (following question edit)** The best way to access a remote queue, or any queue for that matter, is to add a `Queue` instance to the JNDI registry. For remote queues this is achieved using MBeans that add the `Queue` instance when the server starts. Take a look at <http://www.jboss.org/community/wiki/UsingWebSphereMQSeriesWithJBossASPart4>, which while it's an example with IBM MQ, is essentially what you have to do to connect to any remote queue. If you look at `jbossmq-destinations-service.xml` and `org.jboss.mq.server.jmx` you'll see the MBeans you need to create in relation to a JBoss queue.
Here is the code we used to connect to the SonicMQ broker using the `sonic_Client.jar` library: ``` import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; public class JmsClient { public static void main(String[] args) throws JMSException { ConnectionFactory factory = new progress.message.jclient.ConnectionFactory("tcp://<host>:<port>", "<user>", "<password>"); Connection connection = factory.createConnection(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { MessageProducer producer = session.createProducer(session.createQueue("<queue>")); try { producer.send(session.createTextMessage("<message body>")); } finally { producer.close(); } } finally { session.close(); } } finally { connection.close(); } } } ```
Post a message to a remote JMS queue using JBoss
[ "", "java", "post", "connection", "jms", "message", "" ]
At the moment I am developing an annotation-based binding-framework for Java Swing that uses [JGoodies Binding](http://www.jgoodies.com) under the hood. Unfortunately I am stuck with an annotation for a JRadioButton-binding. What I want to do is specify a property-name of a model which holds a special value (enum). The radio-button shall be selected if this property has a specific value. Now I want to specify the value in the annotation like this: ``` @RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.FIRST) JRadioButton firstButton @RadioButtonBinding(property = "selectedItem", selectedValue = MyEnum.SECOND) JRadioButton secondButton ``` However, I do not know how to declare the annotation to allow the above and **any** other enum, too. My first guess was this, but I learned that annotation attributes cannot be generic: ``` @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface RadioButtonBinding { /** The model-property to which the selected value is bound */ String property(); // Idea 1: Specifying the enum class and the enum constant as String - works but is not typesafe Class<? extends Enum<?>> enumClass(); String enumConstantName(); // Idea 2: Directly specifying the enum constant - gives a compile-time error <T extends Enum<T>> T enumValue(); } ``` Any ideas how to solve this?
It's not going to work the way you want it to. As you've found out, you can only use really plain return types in annotations. Additionally, trying to get around these restrictions by doing stuff like abusing String isn't going to work because you need to be using a constant expression for initialising your annotation's values. I think the closest you're going to get is to initialise with a String and then use code to compare with the enum's name(). But there goes your type safety...
If your enums can implement all the same interface, you may find useful this question "[Coding tip - intersection types and java enums](https://stackoverflow.com/questions/574529/coding-tip-intersection-types-and-java-enums)"
Is there a way to declare an annotation attribute for *any* enum?
[ "", "java", "enums", "annotations", "" ]
After updating to php 5.3 one of our systems has developed an interesting bug. It parses csv files and the first step is to show the user what they have uploaded to check it over before confirming. However we have run into a bug where some files upload, but aren't read. The weird thing is if we take the data from those files, copy and paste it into notepad and save as a .csv file it will upload fine. My first thought was maybe something to do with people creating csv files from a specific program? I noticed that the one that doesn't work (even though it contains the same data) is a little smaller than the one we copy and paste from it. Any help greatly appreciated.
Sounds like one has Carriage Return + LineFeeds and the other has only Line feeds (or is it carriage returns?) Either that or it has a different encoding: ASCII versus UTF-16
Are the CSV files in the same encoding? Perhaps some have the UTF-8 BOM at the start, or others are in something like UTF-16. Or, there could be a difference in the line ending characters - the **evil** one could use just LF, and the **good** CR+LF.
Two seemingly identical CSV files, only one works
[ "", "php", "csv", "" ]
**Edit: When I say "SQL Server", I'm really talking about the Management Studio. Sorry if that was confusing.** Oh I hate when things like this happen. I was working with SQL Server yesterday and trying out the PIVOT command to try to figure out how it worked. So I created a new table with four columns, and the first column was going to have the same value for the first few rows. I added the "value1" to the first row, first column, and hit enter - sine no keys or constraints were added yet, it allowed me to enter down to the next row with NULLs for the other columns on the first row (which is fine). To my surprise, it also allowed me to enter "value1" on the second row and enter down - this should be impossible since now there are two identical rows. However, since I was just messing around, this didn't bother me. So I proceed to create four rows as such: **Table 1** ``` Col1 Col2 Col3 Col4 --------------------------------- Value1 NULL NULL NULL Value1 NULL NULL NULL Value1 NULL NULL NULL Value1 NULL NULL NULL ``` Obviously this is strange and breaks relational theory, but I didn't really care since this is just a table I created to mess around with. However, I just about pulled my hair out at what happened next. After I had this data in, I could not do *anything* to the table. If I tried to fill in col2, col3, or col4 on any of the rows, SQL Server would scream at me for having duplicate rows: "No row was updated. The data in row 1 was not committed.... The row value(s) updated or deleted either do not make the row unique or they alter multiple rows(4 rows)." So in other words, SQL Server allowed me to enter in duplicate rows, but when I tried to update the rows to make them unique, it wouldn't allow me, citing that there are duplicate rows as its reason. The worst part is I couldn't even delete any rows either (I get the same error message). The only solution I found once in this scenario was to delete the table and start over - which is ridiculous. My question is, how can this sort of behavior exist in a well known program that has evolved over a decade? Am I the one being brainless and I should accept SQL Server's behavior? To me this is unacceptable and SQL Server should either never have allowed me to enter duplicate rows in the first place, or it should have allowed me to update the duplicate rows until they were all unique and and then try to save. This is by no means meant to be some sort of SQL Server hating post. It's relatively rare I run into behavior like this, but when I do, it can really set me behind and drive me crazy. I just don't understand why the program has behavior built in like this. Like why in the world did it let me enter the duplicate rows in the first place if it didn't plan to let me fix it? I remember working with MS Access back in the day and I would run into the same sort of strange, archaic behavior. A few times I had to copy out huge amounts of data, re-create the table, and copy it back in just because Access had allowed me to do something it shouldn't have, and is now blocking me from any changes to fix it - effectively producing a deadlock. So what's going on here? Do I need some sort of paradigm change when approaching SQL Server? Is it me or SQL Server that's the problem? (You can say it's me, I can take it.)
All management studio ever does is provides a UI to create some SQL for you and runs it against the DB. In your case, every time you added a row, it produced an INSERT statement. This is perfectly valid. When you then tried to use the UI to DELETE or UPDATE a single record out of all these duplicate records it was unable to produce the SQL to do that. The reason being, as there was no key on the table, there is no way of producing a WHERE clause that would represent the record you were trying to UPDATE or DELETE. It's "error" messages sound perfectly clear and valid to me. As for your comments: > To my surprise, it also allowed me to > enter "value1" on the second row and > enter down - this should be impossible > since now there are two identical > rows. However, since I was just > messing around, this didn't bother me. > > Obviously this is strange and breaks > relational theory, but I didn't really > care since this is just a table I > created to mess around with. There is nothing wrong with having a database table that allows duplicates, it is a perfectly valid thing to do if it's what you need. As for not "caring" or being "bothered" that you had allowed duplicates. That is where the mistake lies. It is then that you should've realised you forgot to add a primary key.
The record editor in Sql Server Management Studio is a small (and relatively unimportant) part of the SQL Server product offering. I think you can safely accept the quirks of the editor without being concerned about the relative quality of the server itself. Behind the scenes, the Management Studio is executing SQL statements to perform your actions, just as if you typed that SQL yourself. So if you break a rule, you pay the fine.
SSMS permits duplicate records in a table, but not subsequent updates
[ "", "sql", "sql-server-2008", "ssms", "" ]
I have a C# Windows Form application that contains a menu with this event: ``` private void createMenuItem_Click(object sender, EventArgs e) { canvas.Layer.RemoveAllChildren(); canvas.Controls.Clear(); createDock(); } ``` I would like to provide the user with the opportunity to fire this event through another menu option that pulls up a timer. My timer looks like this: ``` private void transfer_timer() { System.Timers.Timer Clock = new System.Timers.Timer(); Clock.Elapsed += new ElapsedEventHandler(createMenuItem_Click); Clock.Interval = timer_interval; Clock.Start(); } ``` When I do this the resulting error message is: createDock - Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. What am I doing wrong?
Don't do that. :) Factor it out more like this ... ``` private void createMenuItem_Click(object sender, EventArgs e) { DoCanvasWork(); // pick a good name :) } private void transfer_timer() { System.Timers.Timer Clock = new System.Timers.Timer(); Clock.Elapsed += new ElapsedEventHandler(Clock_Tick); Clock.Interval = timer_interval; Clock.Start(); } private void Clock_Tick( object sender, EventArgs e ) { BeginInvoke( new MethodInvoker(DoCanvasWork) ); } private void DoCanvasWork() { canvas.Layer.RemoveAllChildren(); canvas.Controls.Clear(); createDock(); } ``` That will give you much more clear and much more maintainable code. Your timer is not selecting a menu, it's doing the work that's the same as if the menu had been selected. Per comment: You're welcome. Glad to help! Here's a [good primer](http://weblogs.asp.net/justin_rogers/pages/126345.aspx) on cross thread marshaling (short read, good examples). But, basically [BeginInvoke](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx) is taking a delegate (the [MethodInvoker](http://msdn.microsoft.com/en-us/library/system.windows.forms.methodinvoker.aspx)) and executing it asynchronously on the thread that the control was created on. In this case, it's a non-blocking, fire and forget message across threads (i.e. I don't wait for a return and I don't call EndInvoke to get a return). If you really want to get in-depth with this, [Chris Sells book on Winforms](https://rads.stackoverflow.com/amzn/click/com/0321116208) is a great resource.
UI elements have thread affinity. In general, their methods can only be called from the thread that created. You can use the [Invoke](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx) method on a control to do a cross-thread call. Invoke will marshal the call and execute it on the UI thread.
C# - Can a timer call a menu event?
[ "", "c#", "winforms", "" ]
I am trying to write a program that supports speech recognition via a custom (specialised) grammar. However, the SpeechRecognized event never fires, and the speech recognition applet acts as if the grammar didn't exist. Here are my precise steps. Please tell me where I am going wrong. 1. Open Control Panel, search for "speech", then click on "Start speech recognition". 2. Open Visual C#, create a new Windows Forms project 3. Copy and paste the code from [the first answer on this Stack Overflow question](https://stackoverflow.com/questions/227140/c-speech-recognition-is-this-what-the-user-said) into the project. 4. Add the necessary reference to System.Speech. 5. Run the program, with the speech recognition applet still running. 6. Say "Start listening". 7. Say a number between 1 and 100. The label's text never changes from its default value ("label1"), so it seems that rec\_SpeechRecognized() is never called, i.e. the SpeechRecognized event never fires. If I say a number that sounds somewhat similar to the name of an open window or a program in my start menu, it'll ask me if that is what I meant. It appears to be completely agnostic of the custom grammar I just defined. I tried lots of examples I found on the web, which are all pretty much equivalent to the example in that answer I linked to, only with different grammar. I get the same result for all of them, so I assume I must be doing something else wrong. What am I doing wrong?
From the lack of answers I suspect it works for everyone else but not for me. Thus, looks like the answer is "it's not possible".
I think you haven't linked the Form1 load event to the `Form1_Load` routine in the designer. I followed your steps exactly, and had the same results; see if you can get a breakpoint anywhere in `Form1_Load`. Once I edited the designer to make sure that `Form1_Load` actually got called, it ran fine.
Use speech recognition from C#
[ "", "c#", "speech-recognition", "" ]
I have a few pages on my asp.net website that I would like to turn off a control on the master page. Is there a way to communicate with the master page from a child page?
Easiest way is to setup a property on your master page that handles the on/off functionality when called. Then in your child page set the [MasterType directive](http://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx) to get a strongly typed reference to your master page to bypass the need to cast. Your child page would have: ``` <%@ MasterType VirtualPath="~/Site1.Master" %> ``` And to call the property of the master page: ``` Master.MyLabel = false; // or true ``` So on your master you could have: ``` public bool MyLabel { get { return masterLabel.Enabled; } set { masterLabel.Enabled = value; } } ```
You need to use a MasterType directive in your page markup ``` <%@ MasterType TypeName="Namespace.Etc.MyMasterPage" %> ``` Then you will be able to access any public properties of the page's master page using ``` this.Master.PropertyIWantToIntefereWith... ``` Hope this helps
How to control elements on a asp.net master page from child page
[ "", "c#", "asp.net", "master-pages", "" ]
Consider me a novice to Windows environment and COM programming. I have to automate an application (CANoe) access. CANoe exposes itself as a COM server and provides CANoe.h , CANoe\_i.c and CANoe.tlb files. How can I write a C++ client, for accessing the object, functions of the application? Also, please specify how to access the code present in tlb file from C++.
Visual Studio has a lot of built-in support for importing type libraries into your C++ project and using the objects thus defined. For example, you can use the `#import` directive: ``` #import "CANoe.tlb" ``` This will import the type library, and convert it to header files and implementation files - also it will cause the implementation files to be built with your project and the header files to be included, so this is lots of magic stuff right there. Then, you get a whole lot of typedefs for smart pointer wrappers for the types and objects defined in the type library. For example, if there was a CoClass called `Application` which implemented the interface `IApplication`, you could do this: ``` ApplicationPtr app(__uuidof(Application)); ``` This would cause at run time, the coclass application to be created and bound to the variable `app`, and you can call on it like so: ``` app->DoSomeCoolStuff(); ``` Error handling is done by checking the result of COM calls, and throwing the appropriate \_com\_error exception as necessary so this implies you need to write exception safely.
Use `import` directive to import the .tlb file - this will give you a C++ equivalent of the interfaces exposed by the COM component. You will also need to register the COM component to the registry (run regsvr32 on the .dll file of the component). After that you can call CoCreateInstance() (or \_com\_ptr\_t::CreateInstance() as it is usually more convenient) to create an instance of the class that implements the interface. You can then call methods of the interface - it will work almost the same way as if it was a plain C++ interface and class.
COM automation using tlb file
[ "", "c++", "com", "automation", "typelib", "" ]
I am an intern and was asked to do some research on SQL 2008 data compression. We want to store several parts of outlook emails in a table. The problem is that we want to store the entire email body in a field, but then want to compress it. Using Char() will not store the whole body, but will allow compression... using varchar() will store the entire body but not allow compression. Any ideas on how to store the whole body AND compress it? Thank You for your replies!
[Types of data compression in SQL Server 2008](http://blogs.msdn.com/sqlserverstorageengine/archive/2007/11/12/types-of-data-compression-in-sql-server-2008.aspx) [Creating Compressed Tables and Indexes](http://technet.microsoft.com/en-us/library/cc280449.aspx) [Whitepaper: Data Compression: Strategy, Capacity Planning and Best Practices](http://sqlcat.com/whitepapers/comments/850.aspx)
SQL 2008 can do this for you, see [Creating Compressed Tables and Indexes](http://msdn.microsoft.com/en-us/library/cc280449.aspx)
SQL 2008 Compression
[ "", "sql", "sql-server-2008", "compression", "char", "varchar", "" ]
I'm building my c++ program with cmake on a Mac. The compiler gives me following Error: ``` error: boost/filesystem.hpp: No such file or directory ``` The line that triggers the error is the following: ``` #include "boost/filesystem.hpp" ``` or ``` #include <boost/filesystem.hpp> ``` Which of the above I use doesn't changed the Error But in my CMakeLists.txt I include the boost headers in the following way: ``` FIND_PACKAGE(Boost) MESSAGE("Boost information:") MESSAGE(" Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}") MESSAGE(" Boost_LIBRARIES: ${Boost_LIBRARIES}") MESSAGE(" Boost_LIBRARY_DIRS: ${Boost_LIBRARY_DIRS}") INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) LINK_DIRECTORIES(${Boost_LIBRARY_DIRS}) ``` Boost include dirs is filled with "/opt/local/include/" during the cmake process and this folder contains a folder boost which contains the filesystem.hpp Boost gives the following messages while generating the Makefile, I only copied the boost part: ``` -- Boost version: 1.38.0 -- Found the following Boost libraries: Boost information: Boost_INCLUDE_DIRS: /opt/local/include Boost_LIBRARIES: Boost_LIBRARY_DIRS: /opt/local/lib -- Configuring done ``` While running make VERBOSE=1 This line contains the error: ``` cd /Users/janusz/Documents/workspace/ImageMarker/Debug/src && /usr/bin/c++ -O3 -Wall -Wno-deprecated -g -verbose -I/Users/janusz/Documents/workspace/ImageMarker/src/. -o CMakeFiles/ImageMarker.dir/FaceRecognizer.cpp.o -c /Users/janusz/Documents/workspace/ImageMarker/src/FaceRecognizer.cpp /Users/janusz/Documents/workspace/ImageMarker/src/FaceRecognizer.cpp:8:32: error: boost/filesystem.hpp: No such file or directory make[2]: *** [src/CMakeFiles/ImageMarker.dir/FaceRecognizer.cpp.o] Error 1 ``` Do you understand why the compiler isn't picking the /opt/local/include directory? If you need more information I'm happy to provide it
First of all use ``` FIND_PACKAGE(Boost REQUIRED) ``` rather than ``` FIND_PACKAGE(Boost) ``` This way cmake will give you a nice error message if it doesn't find it, long before any compilations are started. If it fails set the environment variable BOOST\_ROOT to /opt/local (which is the install prefix). Additionally you will have to link in the filesystem library, so you want ``` FIND_PACKAGE(Boost COMPONENTS filesystem REQUIRED) ``` for later use of ``` target_link_libraries(mytarget ${Boost_FILESYSTEM_LIBRARY}) ``` Enter ``` cmake --help-module FindBoost ``` at the shell to get the docs for the Boost find module in your cmake installation. PS: An example The CMakeLists.txt ``` cmake_minimum_required(VERSION 2.6) project(Foo) find_package(Boost COMPONENTS filesystem REQUIRED) include_directories(${Boost_INCLUDE_DIRS}) add_executable(foo main.cpp) target_link_libraries(foo ${Boost_FILESYSTEM_LIBRARY} ) ``` main.cpp ``` #include <boost/filesystem.hpp> #include <vector> #include <string> #include <cstdio> #include <cstddef> namespace fs = boost::filesystem; using namespace std; int main(int argc, char** argv) { vector<string> args(argv+1, argv+argc); if(args.empty()) { printf("usage: ./foo SOME_PATH\n"); return EXIT_FAILURE; } fs::path path(args.front()); if(fs::exists(path)) printf("%s exists\n", path.string().c_str()); else printf("%s doesn't exist\n", path.string().c_str()); return EXIT_SUCCESS; } ```
I solved a similar problem by adding some lines in my CMakeLists.txt. ``` cmake_minimum_required(VERSION 3.5) project(MyResource) function(myresources out_var) set(RESULT) foreach(in_f ${ARGN}) file(RELATIVE_PATH src_f ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${in_f}) set(out_f "${PROJECT_BINARY_DIR}/${in_f}.c") add_custom_command(OUTPUT ${out_f} COMMAND myresource ${out_f} ${src_f} DEPENDS ${in_f} WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMENT "Building binary file for ${out_f}" VERBATIM) list(APPEND result ${out_f}) endforeach() set(${out_var} "${result}" PARENT_SCOPE) endfunction() find_package(Boost COMPONENTS filesystem REQUIRED) find_path(BOOST_FILESYSTEM_INCLUDE_DIRS boost/filesystem.hpp) add_executable(myresource myresource.cpp) target_link_libraries(myresource ${Boost_FILESYSTEM_LIBRARY} ${Boost_SYSTEM_LIBRARY}) target_include_directories(myresource PUBLIC ${BOOST_FILESYSTEM_INCLUDE_DIRS}) ```
Why is this boost header file not included
[ "", "c++", "boost", "cmake", "compilation", "" ]
I have a very large set of permissions in my application that I represent with a Flags enumeration. It is quickly approaching the practical upper bound of the long data type. And I am forced to come up with a strategy to transition to a different structure soon. Now, I could break this list down into smaller pieces, however, this is already just a subset of the overall permissions for our application, based on our applications layout. We use this distinction extensively for display purposes when managing permissions and I would rather not have to revisit that code at this time if I can avoid it. Has anybody else run into this issue? How did you get past it? General examples are fine, but I am most interested in a c# specific example if there are any language specific tricks that I can employ to get the job done. May not be neccessary, but here is the list of Permissions currently defined for the portion of the app I am dealing with. ``` //Subgroup WebAgent [Flags] public enum WebAgentPermission : long { [DescriptionAttribute("View Rule Group")] ViewRuleGroup = 1, [DescriptionAttribute("Add Rule Group")] AddRuleGroup = 2, [DescriptionAttribute("Edit Rule Group")] EditRuleGroup = 4, [DescriptionAttribute("Delete Rule Group")] DeleteRuleGroup = 8, [DescriptionAttribute("View Rule")] ViewRule = 16, [DescriptionAttribute("Add Rule")] AddRule = 32, [DescriptionAttribute("Edit Rule")] EditRule = 64, [DescriptionAttribute("Delete Rule")] DeleteRule = 128, [DescriptionAttribute("View Location")] ViewLocation = 256, [DescriptionAttribute("Add Location")] AddLocation = 512, [DescriptionAttribute("Edit Location")] EditLocation = 1024, [DescriptionAttribute("Delete Location")] DeleteLocation = 2048, [DescriptionAttribute("View Volume Statistics")] ViewVolumeStatistics = 4096, [DescriptionAttribute("Edit Volume Statistics")] EditVolumeStatistics = 8192, [DescriptionAttribute("Upload Volume Statistics")] UploadVolumeStatistics = 16384, [DescriptionAttribute("View Role")] ViewRole = 32768, [DescriptionAttribute("Add Role")] AddRole = 65536, [DescriptionAttribute("Edit Role")] EditRole = 131072, [DescriptionAttribute("Delete Role")] DeleteRole = 262144, [DescriptionAttribute("View User")] ViewUser = 524288, [DescriptionAttribute("Add User")] AddUser = 1048576, [DescriptionAttribute("Edit User")] EditUser = 2097152, [DescriptionAttribute("Delete User")] DeleteUser = 4194304, [DescriptionAttribute("Assign Permissions To User")] AssignPermissionsToUser = 8388608, [DescriptionAttribute("Change User Password")] ChangeUserPassword = 16777216, [DescriptionAttribute("View Audit Logs")] ViewAuditLogs = 33554432, [DescriptionAttribute("View Team")] ViewTeam = 67108864, [DescriptionAttribute("Add Team")] AddTeam = 134217728, [DescriptionAttribute("Edit Team")] EditTeam = 268435456, [DescriptionAttribute("Delete Team")] DeleteTeam = 536870912, [DescriptionAttribute("View Web Agent Reports")] ViewWebAgentReports = 1073741824, [DescriptionAttribute("View All Locations")] ViewAllLocations = 2147483648, [DescriptionAttribute("Access to My Search")] AccessToMySearch = 4294967296, [DescriptionAttribute("Access to Pespective Search")] AccessToPespectiveSearch = 8589934592, [DescriptionAttribute("Add Pespective Search")] AddPespectiveSearch = 17179869184, [DescriptionAttribute("Edit Pespective Search")] EditPespectiveSearch = 34359738368, [DescriptionAttribute("Delete Pespective Search")] DeletePespectiveSearch = 68719476736, [DescriptionAttribute("Access to Search")] AccessToSearch = 137438953472, [DescriptionAttribute("View Form Roles")] ViewFormRole = 274877906944, [DescriptionAttribute("Add / Edit Form Roles")] AddFormRole = 549755813888, [DescriptionAttribute("Delete UserFormRolesDifferenceMasks")] DeleteFormRole = 1099511627776, [DescriptionAttribute("Export Locations")] ExportLocations = 2199023255552, [DescriptionAttribute("Import Locations")] ImportLocations = 4398046511104, [DescriptionAttribute("Manage Location Levels")] ManageLocationLevels = 8796093022208, [DescriptionAttribute("View Job Title")] ViewJobTitle = 17592186044416, [DescriptionAttribute("Add Job Title")] AddJobTitle = 35184372088832, [DescriptionAttribute("Edit Job Title")] EditJobTitle = 70368744177664, [DescriptionAttribute("Delete Job Title")] DeleteJobTitle = 140737488355328, [DescriptionAttribute("View Dictionary Manager")] ViewDictionaryManager = 281474976710656, [DescriptionAttribute("Add Dictionary Manager")] AddDictionaryManager = 562949953421312, [DescriptionAttribute("Edit Dictionary Manager")] EditDictionaryManager = 1125899906842624, [DescriptionAttribute("Delete Dictionary Manager")] DeleteDictionaryManager = 2251799813685248, [DescriptionAttribute("View Choice Manager")] ViewChoiceManager = 4503599627370496, [DescriptionAttribute("Add Choice Manager")] AddChoiceManager = 9007199254740992, [DescriptionAttribute("Edit Chioce Manager")] EditChoiceManager = 18014398509481984, [DescriptionAttribute("Delete Choice Manager")] DeleteChoiceManager = 36028797018963968, [DescriptionAttribute("Import Export Choices")] //57 ImportExportChoices = 72057594037927936 } ```
I see values from at least a handful of different enumerations in there... My first thought was to approach the problem by splitting the permissions up in logical groups (`RuleGroupPermissions`, `RulePermissions`, `LocationPermissions`, ...), and then having a class (`WebAgentPermissions`) exposing a property for each permission enum type. Since the permission values seem repetitive, you could probably get away with a single enum in the end: ``` [Flags] public enum Permissions { View = 1, Add = 2, Edit = 4, Delete = 8 } ``` And then have the `WebAgentPermissions` class expose a property for each area where permissions are to be set; ``` class WebAgentPermissions { public Permissions RuleGroup { get; set; } public Permissions Rule { get; set; } public Permissions Location { get; set; } // and so on... } ```
Language documentation says: <http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx> "The underlying type is Int32 and so the maximum single bit flag is 1073741824 and obviously there are a total of 32 flags for each enum." However... UPDATED: Commenter is correct. Check out this: <http://msdn.microsoft.com/en-us/library/ms182147(VS.80).aspx> Int32 is only the DEFAULT datatype! In fact you can specify Int64. ``` public enum MyEnumType : Int64 ``` ...allowing up to 64 values. But that certainly seems to be the maximum, after that you're going to be looking at re-engineering. Without knowing too much about the rest of your solution, I can't say exactly what might suit. But an array (or hash-map) of privilege identifiers is probably the most natural approach.
What to do when bit mask (flags) enum gets too large
[ "", "c#", "permissions", "enums", "types", "bitmask", "" ]
In other words, given a base class `shape` and a derived class `rectangle`: ``` class shape { public: enum shapeType {LINE, RECTANGLE}; shape(shapeType type); shape(const shape &shp); } class rectangle : public shape { public: rectangle(); rectangle(const rectangle &rec); } ``` I'd like to know if I could create an instance of `rectangle` by calling: ``` shape *pRectangle = new shape(RECTANGLE); ``` and how could I implement the copy constructor, in order to get a new `rectangle` by calling: ``` shape *pNewRectangle = new shape(pRectangle); ```
Short Answer: No Long Answer: You need a factory object/method. You can add a static factory method to the base class the creates the appropriate object type. ``` class Shape { static Shape* createShape(shapeType type) { switch (type) { case RECTANGLE:return new rectangle(); ... } } }; ``` ### Personal preference: I would go with a completely different class to be the factory rather than using a static method on the base class. The reason for this is that every time you create a new Shape class the above style forces you to re-build the Shape class each time. So I would separator out the factory into a ShapeFactory class.
You can't do this directly from within the constructor. Instead, you'll need to use another approach, such as a [Factory method](http://en.wikipedia.org/wiki/Factory_method_pattern). The problem is, when you do new shape(...), you'll always return an instance of shape - not rectangle. If you want a "rectangle", at some point, it will need to call new rectangle(..). A method could handle this logic for you, but not the default construction in C++.
Can I create an object from a derived class by constructing the base object with a parameter?
[ "", "c++", "constructor", "polymorphism", "copy-constructor", "" ]
What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script. I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure the Skype4Py package is installed, and if not I'll install it. My ideas for accomplishing the check * check for a directory in the typical install path * try to import the package and if an exception is throw, then install package
If you mean a python script, just do something like this: ### Python 3.3+ use sys.modules and [find\_spec](https://docs.python.org/3/library/importlib.html#importlib.util.find_spec): ``` import importlib.util import sys # For illustrative purposes. name = 'itertools' if name in sys.modules: print(f"{name!r} already in sys.modules") elif (spec := importlib.util.find_spec(name)) is not None: # If you choose to perform the actual import ... module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) print(f"{name!r} has been imported") else: print(f"can't find the {name!r} module") ``` ### Python 3: ``` try: import mymodule except ImportError as e: pass # module doesn't exist, deal with it. ``` ### Python 2: ``` try: import mymodule except ImportError, e: pass # module doesn't exist, deal with it. ```
As of Python 3.3, you can use the [find\_spec()](https://docs.python.org/3/library/importlib.html#importlib.util.find_spec) method ``` import importlib.util # For illustrative purposes. package_name = 'pandas' spec = importlib.util.find_spec(package_name) if spec is None: print(package_name +" is not installed") ```
Check if Python Package is installed
[ "", "python", "package", "skype", "python-import", "" ]
In C#.net, I have the following DataSource setup that I am trying to dynamically assign a WHERE clause to in the code behind... ``` <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="MyNameSpace.DataClasses1DataContext" TableName="MyTableWithADateTimeColumn" > </asp:LinqDataSource> ``` The code behind looks something like this... ``` LinqDataSource1.Where = "MyDateColumn == DateTime(" + DateTime.Now + ")"; ``` This gives me an error of `')' or ',' expected`. I've also tried casting it inside quotation marks, as well, as without casting it as DateTime and with quotation marks... ``` LinqDataSource1.Where = @"MyDateColumn == """ + DateTime.Now + @""" "; ``` This gives me `Operator '==' incompatible with operand types 'DateTime' and 'String'`. I've tried several other ways, but I am obviously missing something here. Similar code is working fine for strings.
is it this? What about this then... ``` LinqDataSource1.Where = "MyDateColumn == DateTime.Parse(" + DateTime.Now + ")"; //can't create a date from string in constructor use .Parse()... ```
I believe you need to include double quotes around the string being converted to a DateTime. ``` LinqDataSource1.Where = "MyDateColumn == DateTime(\"" + DateTime.Now.ToString() + "\")"; ```
Setting the LinqDataSource Where Clause using DateTime Column
[ "", "c#", ".net", "linq-to-sql", "" ]
I've read that it is possible to automate monthly reports in Crystal Reports with COM/ActiveX. I'm not that advanced to understand what this is or what you can even do with it. I also do a lot of work with Excel and it looks like you also use COM/ActiveX to interface with it. Can someone explain how this works and maybe provide a brief example?
First you have to install the wonderful [pywin32](https://github.com/mhammond/pywin32) module. It provides COM support. You need to run the `makepy` utility. It is located at `C:\...\Python26\Lib\site-packages\win32com\client`. On Vista, it must be ran with admin rights. This utility will show all available COM objects. You can find yours and it will generate a python wrapper for this object. The wrapper is a python module generated in the `C:\...\Python26\Lib\site-packages\win32com\gen_py` folder. The module contains the interface of the COM objects. The name of the file is the COM unique id. If you have many files, it is sometimes difficult to find the right one. After that you just have to call the right interface. It is magical :) A short example with excel ``` import win32com.client xlApp = win32com.client.Dispatch("Excel.Application") xlApp.Visible=1 workBook = xlApp.Workbooks.Open(r"C:\MyTest.xls") print str(workBook.ActiveSheet.Cells(i,1)) workBook.ActiveSheet.Cells(1, 1).Value = "hello" workBook.Close(SaveChanges=0) xlApp.Quit() ```
You can basically do the equivalent of late binding. So whatever is exposed through IDispatch is able to be consumed. Here's some code I wrote this weekend to get an image from a twain device via Windows Image Acquisition 2.0 and put the data into something I can shove in a gtk based UI. ``` WIA_COM = "WIA.CommonDialog" WIA_DEVICE_UNSPECIFIED = 0 WIA_INTENT_UNSPECIFIED = 0 WIA_BIAS_MIN_SIZE = 65536 WIA_IMG_FORMAT_PNG = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}" def acquire_image_wia(): wia = win32com.client.Dispatch(WIA_COM) img = wia.ShowAcquireImage(WIA_DEVICE_UNSPECIFIED, WIA_INTENT_UNSPECIFIED, WIA_BIAS_MIN_SIZE, WIA_IMG_FORMAT_PNG, False, True) fname = str(time.time()) img.SaveFile(fname) buff = gtk.gdk.pixbuf_new_from_file(fname) os.remove(fname) return buff ``` It's not pretty but it works. I would assert it's equivalent to what you would have to write in VB.
What can you do with COM/ActiveX in Python?
[ "", "python", "com", "crystal-reports", "activex", "pywin32", "" ]
in Excel, `=ROUNDUP(474.872126666666, 2)` -> 474.88 in .NET, ``` Math.Round(474.87212666666666666666666666667, 2, MidpointRounding.ToEven) // 474.87 Math.Round(474.87212666666666666666666666667, 2, MidpointRounding.AwayFromZero) // 474.87 ``` My client want Excel rounding result, is there any way I can get 474.88 in .NET? Thanks a lot
``` double ROUNDUP( double number, int digits ) { return Math.Ceiling(number * Math.Pow(10, digits)) / Math.Pow(10, digits); } ```
Here's my try on a solution that behaves like Excel ROUNDUP function. I tried to cover cases such as: negative decimal numbers, negative digits (yep Excel supports that), large decimal values ``` public static decimal RoundUp(decimal number, int digits) { if (digits > 0) { // numbers will have a format like +/-1.23, where the fractional part is optional if numbers are integral // Excel RoundUp rounds negative numbers as if they were positive. // To simulate this behavior we will use the absolute value of the number // E.g. |1.23| = |-1.23| = 1.23 var absNumber = Math.Abs(number); // Now take the integral part (E.g. for 1.23 is 1) var absNumberIntegralPart = Decimal.Floor(absNumber); // Now take the fractional part (E.g. for 1.23 is 0.23) var fraction = (absNumber - absNumberIntegralPart); // Multiply fractional part by the 10 ^ number of digits we're rounding to // E.g. For 1.23 with rounded to 1 digit it will be 0.23 * 10^1 = 2.3 // Then we round that value UP using Decimal.Ceiling and we transform it back to a fractional part by dividing it by 10^number of digits // E.g. Decimal.Ceiling(0.23 * 10) / 10 = Decimal.Ceiling(2.3) / 10 = 3 / 10 = 0.3 var tenPower = (decimal)Math.Pow(10, digits); var fractionRoundedUp = Decimal.Ceiling(fraction * tenPower) / tenPower; // Now we add up the absolute part with the rounded up fractional part and we put back the negative sign if needed // E.g. 1 + 0.3 = 1.3 return Math.Sign(number) * (absNumberIntegralPart + fractionRoundedUp); } else if (digits == 0) { return Math.Sign(number) * Decimal.Ceiling(Math.Abs(number)); } else if (digits < 0) { // negative digit rounding means that for RoundUp(149.12, -2) we will discard the fractional part, shift the decimal point on the left part 2 places before rounding up // then replace all digits on the right of the decimal point with zeroes // E.g. RoundUp(149.12, -2). Shift decimal point 2 places => 1.49. Now roundup(1.49) = 2 and we put 00 instead of 49 => 200 var absNumber = Math.Abs(number); var absNumberIntegralPart = Decimal.Floor(absNumber); var tenPower = (decimal)Math.Pow(10, -digits); var absNumberIntegraPartRoundedUp = Decimal.Ceiling(absNumberIntegralPart / tenPower) * tenPower; return Math.Sign(number)*absNumberIntegraPartRoundedUp; } return number; } [TestMethod] public void Can_RoundUp_Correctly() { Assert.AreEqual(1.466m, MathExtensions.RoundUp(1.4655m, 3)); Assert.AreEqual(-1.466m, MathExtensions.RoundUp(-1.4655m, 3)); Assert.AreEqual(150m, MathExtensions.RoundUp(149.001m, 0)); Assert.AreEqual(-150m, MathExtensions.RoundUp(-149.001m, 0)); Assert.AreEqual(149.2m, MathExtensions.RoundUp(149.12m, 1)); Assert.AreEqual(149.12m, MathExtensions.RoundUp(149.12m, 2)); Assert.AreEqual(1232m, MathExtensions.RoundUp(1232, 2)); Assert.AreEqual(200m, MathExtensions.RoundUp(149.123m, -2)); Assert.AreEqual(-200m, MathExtensions.RoundUp(-149.123m, -2)); Assert.AreEqual(-20m, MathExtensions.RoundUp(-12.4655m, -1)); Assert.AreEqual(1.67m, MathExtensions.RoundUp(1.666666666666666666666666666m, 2)); Assert.AreEqual(1000000000000000000000000000m, MathExtensions.RoundUp(999999999999999999999999999m, -2)); Assert.AreEqual(10000000000000m, MathExtensions.RoundUp(9999999999999.999m, 2)); } ```
Excel RoundUp vs .NET Math.Round
[ "", "c#", "excel", "math", "rounding", "" ]
I'm working on sorting a list of objects, and unfortunately, I'm not quite getting the information from the debugging to see where I'm going wrong. I have a custom class that I implemented a CompareTo method in, and I call .Sort() on a List of items of that class. Unfortunately, my program never actually gets to the compareTo() method...it errors out and shutdowns down immediately on the call to the .Sort(). What generally should I be on the look out for? Here's my class definition, interface listing for the class. ``` /// <summary> /// Summary description for ClientWorkspace. /// </summary> public class ClientWorkspace : IStorable { } ``` I didn't list the compareTo method since it never even gets to that code.
I believe the exception message would be something like this: "Failed to compare two elements in the array" with an innerexception of "At least one object must implement the IComparable interface". This gives you what you need to know: **You haven't declared your class to implement the `IComparable` interface.** It is not enough to just implement the `CompareTo` method, since the sorting algorithms will look for the `IComparable` interface before attempting to call `CompareTo` through that interface. ...and that is why your method isn't getting called.
Try making your class implement the IComparable interface. > If a custom class or structure does > not implement IComparable, its members > cannot be ordered and the sort > operation can throw an > InvalidOperationException. [Source: MSDN](http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx)
Basic Sorting Question - C# - (Java Programmer Learning C#)
[ "", "c#", "sorting", "collections", "" ]
This question is related to [a previous question of mine](https://stackoverflow.com/questions/1034266) That's my current code ``` IEnumerable<Shape> Get() { while(//get implementation yield return new Shape(//... } void Insert() { var actual = Get(); using (var db = new DataClassesDataContext()) { db.Shapes.InsertAllOnSubmit(actual); db.SubmitChanges(); } } ``` I'm getting a memory overflow, since the IEnumerable is too big. How do I prevent it?
Try using [InsertOnSubmit](http://msdn.microsoft.com/en-us/library/bb763516(VS.100).aspx) rather than [InsertAllOnSubmit](http://msdn.microsoft.com/en-us/library/bb763476(VS.100).aspx). And then commit at appropriate intervals, like Erich said. Or, if you want to do it in batches of e.g. 5, try [Handcraftsman's](https://stackoverflow.com/questions/1034429/how-to-prevent-memory-overflow-when-using-an-ienumerablet-and-linq-to-sql/1034476#answer-1035039) or [dtb's](https://stackoverflow.com/questions/1008785#answer-1008855) solutions for getting IEnumerable's of IEnumerable. E.g., with dtb's Chunk: ``` var actual = Get(); using (var db = new DataClassesDataContext()) { foreach(var batch in actual.Chunk(5)) { db.Shapes.InsertAllOnSubmit(batch); db.SubmitChanges(); } } ```
One option is to break it up into multiple batches. Create a temporary buffer of `Shape` objects, iterate until you fill it or run out from the enumerator, then do a `InsertBatchOnSubmit`.
How to prevent memory overflow when using an IEnumerable<T> and Linq-To-Sql?
[ "", "c#", ".net", "linq-to-sql", "ienumerable", "yield", "" ]
Having the following class (.Net 3.5): ``` public class Something { public string Text {get; private set;} private Something() { Text = string.Empty; } public Something(string text) { Text = text; } } ``` This serializes without error but the resulting XML does not include the Text property since it does not have a public setter. Is there a way (the simpler, the better) to have the XmlSerializer include those properties?
`XmlSerializer` only cares about public read/write members. One option is to implement `IXmlSerializable`, but that is a **lot** of work. A more practical option (if available and suitable) may be to use `DataContractSerializer`: ``` [DataContract] public class Something { [DataMember] public string Text {get; private set;} private Something() { Text = string.Empty; } public Something(string text) { Text = text; } } ``` This works on both public and private members, but the xml produced is not quite the same, and you can't specify xml attributes.
No. XML Serialization will only serialized public read/write fields and properties of objects.
XmlSerializer with parameterless constructor with no public properties or fields... Is it possible?
[ "", "c#", ".net", "xml-serialization", "" ]
I am writing an install script that installs all tables, stored procedures, views, full text indexs, users ect. It all works fine if the user has all the correct permissions and the script runs from start to finish. However if the script dies somewhere midway through then it cannot just be run again. To accomplish this I want to basically return the database to a "brand new" state where it has nothing. I realize how to drop each table/sp/view.. on their own but I am looking for a more general way to reset the database. I also need to be able to delete Fulltext Catalogs and users. Thanks for any help. *Running SQL Server 2005*
Sounds like a job for [Drop Database](http://msdn.microsoft.com/en-us/library/ms178613.aspx): Warning: It doesn't EMPTY the database as the question asks, but it DELETES it, so be sure you have permissions to create a new one. ``` -- SQL Server Syntax DROP DATABASE [ IF EXISTS ] { database_name | database_snapshot_name } [ ,...n ] [;] ```
Can you run the entire script within a transaction and then call a rollback if it fails? A CREATE TABLE can be rolled back just as easily as an INSERT/UPDATE.
SQL Completely Empty Database
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I've been looking for a way to hash a given string in C# that uses a predetermined key. On my adventures through the internet trying to find an example i have seen lots of MD5CryptoServiceProvider examples which seem to use a default key for the machine, but none of them that apply a specific key. I need to have a specific key to encode data as to synchronize it to someone else's server. I hand them a hashed string and an ID number and they use that analyze the data and return a similar set to me. So is there anyway to get md5 to hash via a specific key that would be consistent to both. I would prefer this to be done in C#, but if its not possible with the libraries can you do so with some web languages like php or asp? Edit: Misunderstood the scenario I was thrown into and after a little sitting and thinking about why they would have me use a key it appears they want a key appended to the end of the string and hashed. That way the server can appended the key it has along with the data passed to ensure its a valid accessing computer. Anyways... thanks all ^\_^ Edit2: As my comment below says, it was the term 'salting' I was oblivious to. Oh the joys of getting thrown into something new with no directions.
MD5 is not encryption - it's a hash. It doesn't allow a string to be decrypted. You're looking for a symmetric encryption algorithm. It uses the same key to encrypt and decrypt. Trying to use encryption functions [without understanding them is dangerous](http://www.codinghorror.com/blog/archives/001267.html). Even if you think you understand them, you can make a mistake. If you're transferring data to another person's server, you may be better off using something like [gpg](http://gnupg.org/) to encrypt the file using a symmetric key you both agree on over the phone, *or* perhaps some public-key crypto. This way, you don't write any crypto code, and it's safer (not completely secure, mind you, but safer). --- **Edit:** I'm still trying to decipher your requirements. MD5 is an unkeyed hash function - there is not key in use at all. So let's say the server sends you a giant string, or a file, and a hash of it. You would then MD5 the string or file, and compare the hash you computed with the hash they sent. If they match - the data was **not corrupted in transit**. That *doesn't* mean no one tampered with what they sent you in transit, because MD5 has no "secret sauce" to it. I can md5 anything I want and send it to you. A HMAC is a *keyed hash function*. It has a secret ingredient that only you and the group you're communicating with should know - the secret key. If they send you a long string or file, and a HMAC, you can compute the HMAC yourself, compare your HMAC and theirs, and if they match, **the data was not corrupted in transit, nor was the data tampered with**.
[MD5](http://en.wikipedia.org/wiki/MD5) is a hash function and, strictly speaking, is not used to "encrypt" a string. It produces a 128-bit "Message Digest" (hence the MD in the name) that is used as a kind of fingerprint for the input string.
MD5 Hashing Given a Key in C#
[ "", "c#", "md5", "hash", "" ]
I would like to use Runtime.exec() to initiate another process in a directory with spaces. (It sounds stupid but I really want to satisfy my curiosity) Details of the problem(simplified version) I have a myprogram.exe locates in C:/Program Files/MyProgram. What I observe: 1). when I call Runtime.exec("C://Program Files//MyProgram//myprogram.exe"), IOException indicates: can't find file C:/Program, with error code = 2. I think it must a result of the space 2). I tried: Runtime.exec("/"C://Program Files//MyProgram//myprogram.exe/""), IOException indicates: can't find the file: "C:/Program Files/MyProgram/myprogram.exe" 3). I learnt my lesson and try an overloaded version of Runtime.exec(): File dir = new File("C://Program Files//MyProgram//"); And run: Runtime.exec("myprogram.exe", null, dir), and it says: can't find file myprogram.exe in C:/Program Files/MyProgram/ 4). I tried 1), instead of "Program Files", I rename it to Program\_Files, everything works I know I can also use ProcessBuilder to do similar thing, but I can't let it go in my heart...(Maybe it's my weakness). Can anyone tell me why 2) and 3) does not work? Thanks.
I saw there was another answer several minutes ago, in the comment region, I finally find the way to solve it. I am sorry that I don't know how that answer was deleted... or who gave the answer by commenting the answer... UPDATE: through some further investigation, I found out it's *Matt Kane* that gave the right answer by commenting. Please allow me to express my deep gratitude for your kind help. ;-) Here is how I tackle it according to Matt's comment, and tested working: ``` String[] cmdArray = new String[]{"C://Program Files//MyProgram//myprogram.exe", arg1, arg2}; Runtime.exec(cmdArray); ``` where arg1 and arg2 are two parameters passing to myprogram.exe Use the overloaded version of exec(): 1)Process exec(String[] cmdarray) 2)Process exec(String[] cmdarray, String[] envp) 3)Process exec(String[] cmdarray, String[] envp, File dir) Either one will work. Here I would like to mention the difference between dir in 3) and the absolute path in cmdarray, which could be ""C://Program Files//MyProgram//" in my case. In dir in 3), you can specify the directory you run the .exe, all relative directory you specify will be appended after this dir. Example: if your dir is C:/Hello World, and in your .exe you gonna store a file in /folder1, finally you will find the file locates in C:/Hello World/folder1 However, dir does not work for the executable.(In my case, it's myprogram.exe). For example, if your .exe locates in C:/Program Files/MyProgram/, and you have already set dir to C:/Program Files/MyProgram. You can't successfully run the program without specifying the absolute path of the executable file. In my case, you can only succeed through: cmdarray[0] = "C://Program Files//MyProgram//myprogram.exe" If you make it wrong, the error will look like this: java.io.exception: Cannot run program "myprogram.exe" (in directory "C:/Program Files/MyProgram/"): CreateProcess error=2, The system cannot find the file specified. Note that it only say, "can't run in \*\* directory" instead of saying "can't find file in \*\*\* directory". I thought it's quite ridiculous, but anyway, that's the way how it works.
Try putting a backslash before the space... "C:/Program\ and\ Files/MyProgram/myprogram.exe" you have to use double backslash so that it gets passed to the OS. If that doesn't work, try "C:/\"Program and Files\"/MyProgram/myprogram.exe"
Runtime.exec() with absolute directory
[ "", "java", "executable", "spaces", "runtime.exec", "" ]
I’m using C# and WinForms to try and put just the date from a dateTimePicker into a variable. But I keep getting the date and the time. In the example below textBox1 shows what I’m looking for. But I can’t figure out how to do the same for textBox2. Where it gives the date and time. This isn’t the exact code I’m using in my app, but a simplified example of it for use as an example. How can I modify it to do what I need? Thanks. ``` private void dateTimePicker1_CloseUp(object sender, EventArgs e) { DateTime varDate; textBox1.Text = dateTimePicker1.Value.ToShortDateString(); varDate = dateTimePicker1.Value; textBox2.Text = Convert.ToString(varDate); } ```
``` varDate = dateTimePicker1.Value.Date; ``` This will return the DateTimePicker's value with the time set to 00:00:00
Try this ``` textBox2.Text = varDate.ToShortDateString(); ``` or ``` varDate = DateTimePicker1.Value.Date; textBox2.Text = varDate.ToShortDateString() // varDate.ToString("MM/dd/yy") this would also work ```
How can i put just the date from a dateTimePicker into a variable?
[ "", "c#", "winforms", "datetime", "" ]
I have a Control I want to create. Here's a simple example of what I was to accomplish. I want the control to contain a button. ``` Button b = new Button(); b.Text = "Test"; b.Click += new EventHandler(b_Click); this.Controls.Add(b); ``` Now, the control renders fine, the button shows up on the page. The heart of the problem I'm having is that the b\_Click Event Handler is never triggered. ``` protected void b_Click(object sender, EventArgs e) { throw new NotImplementedException(); } ``` Any help here would be much appreciated. I don't want to use a User Control here for purely selfish reasons and would like to totally encapsulate this in a single DLL. Thanks In Advance. EDIT\*\* ``` namespace ClassLibrary1 { [DefaultProperty("Text")] [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")] public class WebCustomControl1 : WebControl { protected override void CreateChildControls() { Button b = new Button(); b.ID = "button"; b.Text = "Click Me"; b.Click += new EventHandler(b_Click); this.Controls.Add(b); base.CreateChildControls(); } protected void b_Click(object sender, EventArgs e) { this.Controls.Add(new LiteralControl("<p>Click!</p>")); } } } ``` So from the comments I've tried this. The simplest of exampes, still no go. Is there something I'm fundamentally missing?
``` public class WebCustomControl1 : WebControl ``` needed to be ``` public class WebCustomControl1 : WebControl, INamingContainer ``` that's it. that's all that was needed to make this postback issue work.
Override the CreateChildControls method and create/add the button (and register the handler) in that method. Using OnInit/OnLoad to create controls like this is incorrect and will lead to inconsistent behavior (such as what you're experiencing). Edit: You might also try setting button.ID so that it's the same on every postback, it's possible the raised event isn't seeing it for that reason.
Asp.NET Server Control Postback
[ "", "c#", "asp.net", "events", "user-controls", "postback", "" ]
Why aren't many commercial, 3D video games (not random open source 2D ones) written in Java? In theory, it makes a lot of sense: you get a productivity boost and a cross-platform application almost for free, among other things, such as the vast amount of Java libraries, and built-in garbage collection (although I admit I'm not sure if the latter is a good thing). So why is it rarely used? I can only think of a couple popular commercial games written for the Java platform. Is it because of performance? If so, wouldn't most of the heavy lifting be done by the GPU anyway?
The game development world is a funny one: On one hand, they're often quick to accept new ideas, on the other hand, they're still in the stone age. The truth is, there's rarely that much incentive in switching to .NET/Java/anything other than C/C++. Most game companies license parts of the game engine from other companies. These parts are written in C++, and although you might have access to the source so you could port it, that takes a lot of effort (and of course, the license needs to allow it). Also, a lot of legacy code already exists in C++. If code from previous projects can be reused (say, if you're writing a sequel), that counts even more in favor of sticking with the same language, instead of rewriting it in a new language (more so since you'll likely reintroduce a ton of bugs which you'll need to spend time ironing out. Finally, it's rare for games to be written in 100% C++ anyway - a lot is done using scripting languages, whether they're custom or just integrating an existing languages (Lua being one of the more popular ones these days). As far as garbage collection is concerned, that can be a bit of a problem. The problem is not so much that it exists, it's more how it works - the garbage collector MUST be non-blocking (or at least be guaranteed to only block very briefly), since it's simply unacceptable to have the game freeze for 10 seconds while it scans all the allocated memory to see what can be freed. I know Java tends to choke quite a bit in GC'ing when it's close to running out of memory (and for some games out there, it will). You're also a bit more restricted in what you can do: you can't fully exploit the hardware due to the overhead of the runtime. Imagine Crysis being written in Java... even if that's the only visible difference, it just wouldn't be the same (I'm also pretty sure you'd need a Core i7 to run it.). This doesn't mean these languages don't have their place in game development - and no, I'm not just referring to tool programming. For most games, you don't need that extra bit of performance you get from C++, including 3D games, and if you're writing it all from scratch, it can make perfect sense to use something like XNA - in fact, there's a good chance it will. As far as commercial games are concerned - does [RuneScape](http://runescape.com) count? That may well be the most succesful Java game out there.
I think John Carmack said it best with: > The biggest problem is that Java is really slow. On a pure cpu / memory / display / communications level, most modern cell phones should be considerably better gaming platforms than a Game Boy Advanced. With Java, on most phones you are left with about the CPU power of an original 4.77 mhz IBM PC, and lousy control over everything. > [...snip...] > Write-once-run-anywhere. Ha. Hahahahaha. We are only testing on four platforms right now, and not a single pair has the exact same quirks. All the commercial games are tweaked and compiled individually for each (often 100+) platform. Portability is not a justification for the awful performance. ([source](http://www.armadilloaerospace.com/n.x/johnc/recent%20updates/archive?news_id=295)) Granted, he was talking about mobile platforms, but I've found similar problems with Java as a whole coming from a C++ background. I miss being able to allocate memory on the Stack/Heap on my own terms.
Why are only a few video games written in Java?
[ "", "java", "" ]
Would it be correct to say that whenever casting is used, the resulting object is a const object? ...And therefore can only be used as an argument to a function if that function accepts it as a const object? e.g. ``` class C1 { public: C1(int i=7, double d = 2.5){}; }; void f(C1& c) {}; int main(){ f(8); return 1; } //won't compile ``` (Of course if f(....) receives the argument by value then it gets a non-const version which it can work with)
Usually when an object of a certain type is converted to an object of another type (a non-reference type), a temporary object is created (not a const object). A temporary object (invisible, nameless, rvalue) can only bind (in C++98/03) to references that are const (except for the temporary known as the 'exception object'). Therefore, the result of a conversion that creates a temporary can only be used as an argument to a function that either accepts it as a const reference, or as a type that it can be copied/converted into. So for e.g. ``` void f(double); // 1 void f(const int&); // 2 void f(int&); // 3 struct B { B(int) { } }; struct C { C(int) { } }; void f(B b); // 4 void f(B& b); // 5 void f(const C& c); //6 void f(C& c); // 7 // D inherits from B struct D : B { D(int) : B(0) { } }; void f(D& d); // 8 int main() { f( (int) 3.0 ); // calls 2, NOT 3 f( (float) 3 ); // calls 1 - const reference requires the same type f( 1 ); // calls 2, NOT 3 f( (B) 1 ); // calls 4, not 5 - can accept it by non-const value f( (C) 1 ); // calls 6, not 7 - can accept it by const-reference f( (D) 1 ); // calls 4, not 8 - since a 'D' temporary object can be converted to a 'B' object - but will not bind to a non-const reference } ``` Hope that helps.
It's a little off to call this 'casting'. You are doing 'implicit construction'. Implicit construction always creates a temporary object, which in turn is always const. Note you can mark the constructor 'explicit' and this would block the implicit construction call you're seeing here. But that only means you would need f(C(8)) instead of f(8); the C instance would still be const because it is temporary, however note no cast is being done. See also const\_cast for dirty workarounds if you really, really need to. The other workaround would be to do a two liner: C c(8); f(c);
casting producing const objects in c++
[ "", "c++", "casting", "" ]
I have a stored procedure that logs some data, how can I call this with NHibernate? So far I have: ``` ISession session = .... IQuery query = session.CreateQuery("exec LogData @Time=:time @Data=:data"); query.SetDateTime("time", time); query.SetString("data", data); query.?????; ``` What should the method `?????` be? Or am doing something more fundamentally wrong?
This seems to be a limitation of NHibernate, from [NHibernate Documentation](http://nhibernate.info/doc/nhibernate-reference/querysql.html#querysql-limits-storedprocedures): > The procedure must return a result set. NHibernate will use IDbCommand.ExecuteReader() to obtain the results.
ExecuteUpdate on SQL Query should help you. **Sample:** ``` ISession session = .... IQuery query = session.CreateSQLQuery("exec LogData @Time=:time, @Data=:data"); query.SetDateTime("time", time); query.SetString("data", data); query.ExecuteUpdate(); ```
How do I call a stored procedure from NHibernate that has no result?
[ "", "c#", "nhibernate", "stored-procedures", "" ]
I am a LINQ newbie trying to use it to acheive the following: I have a list of ints:- ``` List<int> intList = new List<int>(new int[]{1,2,3,3,2,1}); ``` Now, I want to compare the sum of the first three elements [index range 0-2] with the last three [index range 3-5] using LINQ. I tried the LINQ Select and Take extension methods as well as the SelectMany method, but I cannot figure out how to say something like ``` (from p in intList where p in Take contiguous elements of intList from index x to x+n select p).sum() ``` I looked at the Contains extension method too, but that doesn't see to get me what I want. Any suggestions? Thanks.
Use [Skip](http://msdn.microsoft.com/en-us/library/bb358985.aspx) then Take. ``` yourEnumerable.Skip(4).Take(3).Select( x=>x ) (from p in intList.Skip(x).Take(n) select p).sum() ```
You can use GetRange() ``` list.GetRange(index, count); ```
How to select values within a provided index range from a List using LINQ
[ "", "c#", "linq", "list", "range", "" ]
I need to retrieve SuperClass name of a java file (which extends a class, i need that class name). In order to do this, I began to use ASTParser but I'm newbie so any example or illustration can be helpful. I use ASTView to comprehend which ways that AST keeps a java file structure but I'm stuck while trying visit(), endvisit() functions. I could not find any detailed example. Thanks in advance...
You didn't say much of how far you had got already. In the visitor, override `visit(TypeDeclaration node)` and then, on the node, call `getSuperclassType()`. If you return `true` the parsing will continue inside the type declaration, otherwise it stops.
Could you use the getSuperClass() method of the Class class in your code instead? [getSuperClass()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getSuperclass())
How Can a SuperClass name be retrieved from a java file using ASTParser?
[ "", "java", "eclipse-plugin", "" ]
I have the following problem. I have three classes, A, B and C. A contains a OneToMany relationed list of B:s. B contains a ManyToOne relation to C. C contains a field called "name" and B also contains a field called "name". What I'd like to accomplish is to have the items in A's list sorted primarily by C's name and secondarily by B's name - the problem is that I do not know how to do this. Is it even possible? I'm using EclipseLink as my JPA provider. ``` class A { @OneToMany @OrderBy("b.c.name, b.name") <---- this is the problem List<B> b; } class B { @ManyToOne C c; String name; } class C { String name; } ``` EDIT Yes, I've tried different variations, for example @OrderBy("c.name") doesn't work, I just get an error message telling me that the entity class b does not contain a field called "c.name".
It's NOT possible. @OrderBy only accepts direct property / field names, not nested properties. Which makes sense, really, because "c" table - depending on your fetching strategy may not even be part of a select issued to retrieve your "b"s.
ChssPly76 is right. What you could do is to create a named query like this one: ``` SELECT b FROM B b WHERE b.a = :mya ORDER BY b.c.name ```
Defining the order of a list
[ "", "java", "jpa", "" ]
I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists. I remember I did something like this: ``` def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp ``` Now that I've learnt a little bit more since then, I'd use a list comprehension like this: ``` [m[i] for i in row_indices] ``` But I'm still wondering if there's an even more pythonic way to do it. Any ideas? I would like to know also alternatives with numpy o any other array libraries.
It's worth looking at [NumPy](https://numpy.org/devdocs/user/quickstart.html) for its slicing syntax. Scroll down in the linked page until you get to "Indexing, Slicing and Iterating".
It's the clean an obvious way. So, I'd say it doesn't get more Pythonic than that.
Pythonic way to get some rows of a matrix
[ "", "list", "coding-style", "filtering", "python", "" ]
Why doesn't Python allow modules to have a [`__call__`](https://docs.python.org/reference/datamodel.html#object.__call__) method? (Beyond the obvious that it wouldn't be easy to import directly.) Specifically, why doesn't using `a(b)` syntax find the `__call__` attribute like it does for functions, classes, and objects? (Is lookup just incompatibly different for modules?) ``` >>> print(open("mod_call.py").read()) def __call__(): return 42 >>> import mod_call >>> mod_call() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable >>> mod_call.__call__() 42 ```
Special methods are only guaranteed to be called implicitly when they are defined on the type, not on the instance. (`__call__` is an attribute of the module instance `mod_call`, not of `<type 'module'>`.) You can't add methods to built-in types. <https://docs.python.org/reference/datamodel.html#special-lookup>
Python doesn't allow modules to override or add *any* magic method, because keeping module objects simple, regular and lightweight is just too advantageous considering how rarely strong use cases appear where you could use magic methods there. When such use cases *do* appear, the solution is to make a class instance masquerade as a module. Specifically, code your `mod_call.py` as follows: ``` import sys class mod_call: def __call__(self): return 42 sys.modules[__name__] = mod_call() ``` Now your code importing and calling `mod_call` works fine.
Callable modules
[ "", "python", "module", "python-import", "" ]
How does one convert from an int or a decimal to a float in C#? I need to use a float for a third-party control, but I don't use them in my code, and I'm not sure how to end up with a float.
You can just do a cast ``` int val1 = 1; float val2 = (float)val1; ``` or ``` decimal val3 = 3; float val4 = (float)val3; ```
The same as an int: ``` float f = 6; ``` Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float: ``` int i = 8; float f = Convert.ToSingle(i); ``` Or you can just cast an int to a float: ``` float f = (float)i; ```
How do I convert Int/Decimal to float in C#?
[ "", "c#", "casting", "floating-point", "" ]
Here's my extension method for invoke on a control: ``` public static void Invoke<T>(this T c, Action<System.Windows.Forms.Control> DoWhat) where T:System.Windows.Forms.Control { if (c.InvokeRequired) c.Invoke(o=> DoWhat(c) ); else DoWhat(c); } ``` `ds` is a strongly typed dataset. This works: ``` Action<DataGridView> a = row => row.DataSource = ds.bLog; this.dataGridView1.Invoke(a); ``` this doesn't compile: ``` this.dataGridView1.Invoke<DataGridView>(o => o.DataSource = ds.bLog); ``` and says System.Windows.Forms.Control does not contain a definition for 'DataSource'... do I really have to break this into 2 lines? For clarity/safety should I call the generic extension method InvokeSafe? **Edit:**Extension method revised (works, but I'd like to remove the named delegate requirement): ``` private delegate void myDel(); public static void InvokeSafe<T>(this T c, Action<T> DoWhat) where T : Control { myDel d = delegate() { DoWhat(c); }; if (c.InvokeRequired) c.Invoke(d); else DoWhat(c); } ``` I can't seem to figure out how to make factor out `myDel` into an anonymous delegate in the block?
Try changing your method signature to: ``` public static void Invoke<T>(this T c, Action<T> DoWhat) ``` This will let your `Action` use the desired type that you specify.
The problem is that your action is only declared (in the method) to act on `Control`. Change it to this: ``` public static void Invoke<T>(this T c, Action<T> DoWhat) where T:System.Windows.Forms.Control { if (c.InvokeRequired) c.Invoke((EventHandler) delegate { DoWhat(c) } ); else DoWhat(c); } ``` That way the compiler will infer that you want an `Action<DataGridView>` so the lambda expression in the caller will be able to use `DataSource`.
Threadsafe Generic Extension method usage syntax issue
[ "", "c#", "multithreading", "generics", "user-interface", "extension-methods", "" ]
Hi there I got this query string I have to run so I can update a distinct row in a sql server table: ``` servidorSql.ConnectionString = conexao Dim insert As String = "UPDATE [Equipamentos] SET [ID_Cliente]=@ID_Cliente, [Identificacao] = @Identificacao, [Fabricante] = @Fabricante, [Modelo] = @Modelo, [Versao_Software] = @Versao_Software, [Localizacao] = @Localizacao WHERE [ID_Equipamento]=@ID_Equipamento" Dim sqlquery As SqlCommand = New SqlCommand(insert, servidorSql) Try servidorSql.Open() sqlquery.Parameters.AddWithValue("@ID_Cliente", ID_Cliente) sqlquery.Parameters.AddWithValue("@ID_Equipamento", ID_Equipamento) sqlquery.Parameters.AddWithValue("@Identificacao", Identificacao) sqlquery.Parameters.AddWithValue("@Fabricante", Fabricante) sqlquery.Parameters.AddWithValue("@modelo", modelo) sqlquery.Parameters.AddWithValue("@versao_Software", versao_Software) sqlquery.Parameters.AddWithValue("@localizacao", localizacao) sqlquery.ExecuteNonQuery() servidorSql.Close() Catch e As SqlClient.SqlException MsgBox(e.ToString()) End Try ``` The problem is that it doens't do anything, it doesn't update the table and it doesn't give me any exception. "ID\_Equipamento" is key and identity of the table and I've tried to run the query with the field being update or not, and it's the same. Any suggestion?
The problem it's in the query it self! Couldn't figure ou very well why, but doens't matter. The problem is solved.... Thanks anyway for your help. Aprecciated
Capture an SQL Profiler trace to confirm that the parameter that the ID your passing in is definitely the ID that you think it is. If you also select the RowCounts column you can see the number of rows updated.
Why Doesn't My SQL Query do anything?
[ "", "vb.net", "sql", "" ]
Is if almost always required to have thread syncing (i.e. use of mutex, semaphores, critical sections, etc.) when there is cross-thread data accessing, even if it's not required after going through a requirements analysis?
I would always recommended going with the simplest, most straightforward synchronization scheme until analysis shows you should do otherwise - this usually means a few large locks versus many fine-grained locks or lockfree. The issue is that determining if lock-free code is correct is much more difficult than determining if the corresponding code with locks is correct. This creates a large burden on maintainers of your code, and there is a good chance they will get it wrong and introduce bugs. Even if you know that lock-free is safe with how your code is currently used, this could change in the future by people who aren't as aware. Secondly, in many cases, the difference in performance between code with locks and lock-free code is neglible - until you know there is an issue with lock contention, you should not consider lock-free. Even if there are contention problems, lock-free is not necessarily the best solution.
Even if you don't need a mutex, semaphore, critical section, etc. for their normal locking semantics, you may still need a [memory barrier](http://en.wikipedia.org/wiki/Memory_barrier). The former constructs usually imply a memory barrier, which is why removing them can change the program. In addition, these problems can be extremely hard to debug, as a different scheduling of the involved threads can make the problem vanish and appear. In the simplest case, this means the mere act of running a completely separate program changes the behavior of yours.
Best practices: syncing between threads
[ "", "c++", "multithreading", "" ]
I am working with an extension of the DefaultTableModel as follows: This is the NEW AchievementTableModel after updating it to reflect input from some answers. ``` public AchievementTableModel(Object[][] c, Object[] co) { super(c,co); } public boolean isCellEditable(int r, int c) {return false;} public void replace(Object[][] c, Object[] co) { setDataVector(convertToVector(c), convertToVector(co)); fireTableDataChanged(); } ``` My GUI is a JTable that has the following properties: ``` if(table==null) table = new JTable(model); else table.setModel(model); table.setFillsViewportHeight(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); table.getTableHeader().setReorderingAllowed(false); table.getTableHeader().setResizingAllowed(false); table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); table.getColumnModel().setColumnSelectionAllowed(false); ``` I have a JComboBox that selects which data to display. The TableModel is updated with a call to model.replace(cells) and then runs through the above table creation code again. When selecting a row in the GUI JTable, and printing the table.getSelectedRow() value, I ALWAYS get -1 after changing the table data with a model.replace(cells) call from the first selection, even if I reselect the first JComboBox option. Is there a reason for this that I'm missing? Should I change some code? EDIT: The code has changed a lot over trying to answer this question so here is the updated code. The new AchievementTableModel is above. This sets up the model and table to be viewed correctly and displayed in a ScrollPane ``` if(model==null) model = new AchievementTableModel(cells, columns); else model.replace(cells, columns); if(table==null) { table = new JTable(model); table.setFillsViewportHeight(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getTableHeader().setReorderingAllowed(false); table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); table.getColumnModel().setColumnSelectionAllowed(false); table.getTableHeader().setResizingAllowed(false); } else table.setModel(model); column = table.getColumn(columns[0]); column.setPreferredWidth(25); column = table.getColumn(columns[1]); column.setPreferredWidth(225); column = table.getColumn(columns[2]); column.setPreferredWidth(40); table.doLayout(); add(new JScrollPane(table), BorderLayout.CENTER); ```
you shouldnt reinitialize your table with a new JTable after you call replace. the fireTableDataChanged() method will alert your existing table that it should repaint. what is happening is that you are looking at the table that you put into the panel, but you are changing the variable to a different instance of JTable. When you query that new, but not visible table, it will give you -1 for the selected row count. it might be helpful if you edit your post to display what is going on in that area of the code. **2nd edit:** instead of this: ``` if(model==null) model = new AchievementTableModel(cells, columns); else model.replace(cells, columns); if(table==null) { table = new JTable(model); table.setFillsViewportHeight(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getTableHeader().setReorderingAllowed(false); table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); table.getColumnModel().setColumnSelectionAllowed(false); table.getTableHeader().setResizingAllowed(false); } else table.setModel(model); column = table.getColumn(columns[0]); column.setPreferredWidth(25); column = table.getColumn(columns[1]); column.setPreferredWidth(225); column = table.getColumn(columns[2]); column.setPreferredWidth(40); table.doLayout(); add(new JScrollPane(table), BorderLayout.CENTER); ``` do this instead: ``` if(model==null) { model = new AchievementTableModel(cells, columns); } else { model.setDataVector(cells, columns); } if(table==null) { table = new JTable(model); table.setFillsViewportHeight(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getTableHeader().setReorderingAllowed(false); table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); table.getColumnModel().setColumnSelectionAllowed(false); table.getTableHeader().setResizingAllowed(false); column = table.getColumn(columns[0]); column.setPreferredWidth(25); column = table.getColumn(columns[1]); column.setPreferredWidth(225); column = table.getColumn(columns[2]); column.setPreferredWidth(40); table.doLayout(); add(new JScrollPane(table), BorderLayout.CENTER); } else { table.setModel(model); } ``` you dont need to add the table to a new scrollpane and re-add it to the panel on each model change.
Ok, now I'm interested It looks like you have to really really clean up your code because there are a lot of reference all around. The reason you are not seeing the table with a selected index is because each time you create a new `JTable` the method where you print the selected record still points to the original. Since you're displaying now a "newly" created table the old one prints `-1`. The reason you get empty table when using the `DefaultTableModel` is because the vectors are `null` ( perhaps obtained from the combo ) and thus both the data and the headers disappear from the table. You don't need a subclass if you're using `Object[][]` as data anyway. So here is a somehow simpler test class that you can see to correct yours. I test it with both, your custom **`TableModel`** and the **`DefaultTableModel`** This has nothing to do with your custom table model but the way you're using your references. I hope this helps. ``` import javax.swing.*; import java.awt.*; import javax.swing.table.*; import java.util.*; import java.awt.event.*; public class Test { private DefaultTableModel tableModel = null; //private AchievementTableModel tableModel = null; private Object [] headers = new Object[]{"Name", "Last Name"}; private Object [][] data; private Object [][] dataA = new Object[][]{{"Oscar","Reyes"},{"John","Doe"}}; private Object [][] dataB = new Object[][]{{"Color","Green"},{"Thing","Car"}}; private JTable table; public static void main( String [] args ) { Test test = new Test(); test.main(); } public void main() { // Create the frame JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Create the unique table. table = new JTable(); frame.add(new JScrollPane( table )); // Add two buttons frame.add( new JPanel(){{ // swap table model button ( simulates combo ) add(new JButton("Change Table model"){{ addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { if( tableModel == null ) { data = dataA; tableModel = new DefaultTableModel( data, headers ); //tableModel = new AchievementTableModel( data, headers ); table.setModel( tableModel ); } else { data = data == dataA ? dataB : dataA; tableModel.setDataVector( data, headers ); //tableModel.replace( data ); // not needed DefaultTableModel already has it. } } }); }}); // and print selectedRow button add( new JButton("Print selected row"){{ addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { System.out.println(table.getSelectedRow()); } }); }}); }}, BorderLayout.SOUTH); // show the frame frame.pack(); frame.setVisible( true ); } } ``` Your subclass unchanged. ``` class AchievementTableModel extends DefaultTableModel { public AchievementTableModel(Object[][] c, Object[] co) { super.dataVector = super.convertToVector(c); super.columnIdentifiers = super.convertToVector(co); } public int getColumnCount() {return super.columnIdentifiers.size();} public int getRowCount() {return super.dataVector.size();} public String getColumnName(int c) {return (String)super.columnIdentifiers.get(c);} @SuppressWarnings("unchecked") public Object getValueAt(int r, int c) {return ((Vector<Object>)super.dataVector.get(r)).get(c);} public boolean isCellEditable(int r, int c) {return false;} public void replace(Object[][] c) { super.dataVector = super.convertToVector(c); super.fireTableDataChanged(); } } ``` Try it and see how it doesn't lose the table reference and always print the correct `selectedRow`. ![alt text](https://i.stack.imgur.com/gNQPQ.png) Compare it with your code and fix it from there.
JTable not returning selected row correctly
[ "", "java", "user-interface", "jtable", "selection", "" ]
Is there a way to make a java.awt.Font strike through?
So i found this, which works. ``` Font font = new Font("helvetica", Font.PLAIN, 12); Map attributes = font.getAttributes(); attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); Font newFont = new Font(attributes); ```
underline and strikethrough examples in awt. <http://www.java2s.com/Code/Java/2D-Graphics-GUI/TextAttributeUnderlineandstrikethrough.htm> Basically, create a new AttributedString out of your string, add a STRIKETHROUGH attribute, and draw. NOTE: This will NOT make the FONT strikethrough, but you can set the text to that font and then strikethrough on the text. This is simply another way of doing it. Rich's answer actually makes the font strikethrough.
Strike through java.awt.Font
[ "", "java", "swing", "" ]
I just spent *way* too long trying to diagnose why, in the following snippet of code, the `ProcessEvent()` method seemed to be ignoring the `false` value I passed in for `aInvokeEventHandler`: ``` HRESULT CEventManager:: Process(Event anEvent) { return (m_pPool->GetFsm()->ProcessEvent(anEvent), false); } // Definition of ProcessEvent() HRESULT ProcessEvent(const Event& anEvent, bool aInvokeEventHandler = true); ``` Whenever I broke in the `ProcessEvent()` method, `aInvokeEventHandler` would always be `true`, regardless of whether I passed in `false`. It took a workmate to point out to me that the `false` value should be inside the *inner* parentheses on the `return` line, like so: ``` return m_pPool->GetFsm()->ProcessEvent(anEvent, false); // Corrected code ``` As soon as I saw this, I kicked myself. Spotting this was obviously made harder because the original coder used redundant *outer* parentheses on the `return` line. My question is, why didn't the compiler pick this up for me? My method is returning a `HRESULT`, yet in the original code above, I am clearly returning a composite set of values in parentheses, i.e: ``` (HRESULT, bool) ``` Is notation like this acceptable in the C/C++ standards, and if so, what purpose would there be in allowing this? Or is this a bug in the compiler?
You are suffering from the comma operator, which evaluates and discards the value of its left-hand operand, and then evaluates its right-hand operand as the value of the expression. Also, the default value for the argument to ProcessEvent is why your one-argument call was acceptable.
What you wrote: ``` return (m_pPool->GetFsm()->ProcessEvent(anEvent), false); ``` What it means (roughly): ``` bool temp = false; m_pPool->GetFsm()->ProcessEvent(anEvent); return temp; ```
Compiler not flagging incorrect return value for HRESULT
[ "", "c++", "c", "compiler-construction", "hresult", "" ]
I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (<http://www.fileformat.info/info/unicode/char/2028/index.htm>). I don't want it to be treated as a line break when I read lines from the file. Is there a way to exclude it from separators when I iterate over the file or use readlines()? (Besides reading the entire file into a string and then splitting by \n.) Thank you!
I can't duplicate this behaviour in python 2.5, 2.6 or 3.0 on mac os x - U+2028 is always treated as non-endline. Could you go into more detail about where you see this error? That said, here is a subclass of the "file" class that might do what you want: ``` #/usr/bin/python # -*- coding: utf-8 -*- class MyFile (file): def __init__(self, *arg, **kwarg): file.__init__(self, *arg, **kwarg) self.EOF = False def next(self, catchEOF = False): if self.EOF: raise StopIteration("End of file") try: nextLine= file.next(self) except StopIteration: self.EOF = True if not catchEOF: raise return "" if nextLine.decode("utf8")[-1] == u'\u2028': return nextLine+self.next(catchEOF = True) else: return nextLine A = MyFile("someUnicode.txt") for line in A: print line.strip("\n").decode("utf8") ```
I couldn't reproduce that behavior but here's a naive solution that just merges readline results until they don't end with U+2028. ``` #!/usr/bin/env python from __future__ import with_statement def my_readlines(f): buf = u"" for line in f.readlines(): uline = line.decode('utf8') buf += uline if uline[-1] != u'\u2028': yield buf buf = u"" if buf: yield buf with open("in.txt", "rb") as fin: for l in my_readlines(fin): print l ```
How to exclude U+2028 from line separators in Python when reading file?
[ "", "python", "utf-8", "readline", "separator", "" ]
I have a method which I would like to invoke asynchronously: ``` void Foo() { } ``` I can indeed invoke this asynchronously by the following: ``` delegate void DVoidMethod(); DVoidMethod FooDelegate = new DVoidMethod(Foo); FooDelegate.BeginInvoke(null,null); ``` Has anyone got any alternatives? I think three lines of code is too much?
## Disclaimer: **Don't use this in real code. This is just an attempt to shorten the code OP mentioned. To do real async calls without getting results back, use:** ``` ThreadPool.QueueUserWorkItem(stateObject => Foo()); ``` --- Use `Action` and `Func` delegates in the framework: ``` new Action(Foo).BeginInvoke(null, null); ``` `Action<T>` has been around since 2.0. Other variants are added in 3.5. On 2.0, you can, however, declare a bunch of them somewhere manually for further use; or even better, use [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx).
How about: ``` ThreadPool.QueueUserWorkItem(new WaitCallback((o) => Foo())); ``` --- **Update to account for the TPL APIs available in newer versions of .net:** In **.Net 4** and above you can do: ``` Task.Factory.StartNew(() => Foo()); ``` In **.Net 4.5** and above you can also do: ``` Task.Run(() => Foo()); ``` The difference between [Task.Factory.StartNew](http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.startnew.aspx) and [Task.Run](http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.run.aspx) is that the 'StartNew' method has some additional parameters that let you pass state, task creation options and a scheduler to give you some extra control if you need it.
Most Concise way to Invoke a void Method Asynchronously
[ "", "c#", "asynchronous", "delegates", "code-golf", "" ]
I have a strange problem that is only happening in a single location. I am using jQuery and my page is working fine in my machine as well as in other locations. In a single location the page isn't working. I shamelessly asked the client to use Firefox and install Firebug and I am surprised to find that a "jQuery is not a function" error is reported. It seems that jQuery fails to load. This only happens in the client's office. The client can successfully run the web application from home. What could have caused such a thing to happen? Can a javascript policy be defined in a LAN to block scripts from specific locations? Could it be something wrong with my code? I have used both local jquery and google references (not both at the same time): ``` <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> ```
1) They could be blocking external scripts or certain types of scripts. Are they a Government client per chance? 2) Are you actually loading both scripts in that way? That can cause a conflict.
You also need to note the order in which the scripts are executed ... if you have scripts that are trying to run **before** the jquery libs are included, then you will get this error.
jQuery doesn't get loaded in client's office
[ "", "javascript", "jquery", "" ]
I am trying to develop a class that reads the standard output of an external program(using an instance of Process, Runtime.getRuntime().exec(cmdLine, env, dir)). The program takes user inputs during the process, and would not proceed until a valid input is given; this seems to be causing a problem in the way I am trying to read its output: ``` egm.execute(); // run external the program with specified arguments BufferedInputStream stdout = new BufferedInputStream(egm.getInputStream()); BufferedInputStream stderr = new BufferedInputStream(egm.getErrorStream()); BufferedOutputStream stdin = new BufferedOutputStream(egm.getOutputStream()); int c; //standard output input stream int e; //standadr error input stream while((c=stdout.read()) != -1) //<-- the Java class stops here, waiting for input? { egm.processStdOutStream((char)c); } while((e=stderr.read()) != -1) { egm.processStdErrStream((char)e); } //... ``` How can I fix this so that the program takes in a valid input and proceed? Any help resolving this problem will be great!
You *have* to consume both the program's stdout and stderr concurrently to avoid blocking scenarios. See [this article](http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4) for more info, and in particular note the `StreamGobbler` mechanism that captures stdout/err in separate threads. This is essential to prevent blocking and is the source of numerous errors if you don't do it properly!
In this situation you should have separate Threads reading InputStream and ErrStream. Also you may want to do something like: ``` public void run() { while( iShouldStillBeRunning ) { int c; while( stdout.available() > 0 && ((c=stdout.read()) != -1)) { egm.processStdOutStream((char)c); } Thread.sleep(100); } } ``` Because you will get blocked on `stdout.read()` until there is input.
Java reading standard output from an external program using inputstream
[ "", "java", "io", "" ]
I don't know if this is true, but when I was reading FAQ on one of the problem providing sites, I found something, that poke my attention: > Check your input/output methods. In C++, using cin and cout is too slow. Use these, and you will guarantee not being able to solve any problem with a decent amount of input or output. Use printf and scanf instead. Can someone please clarify this? Is really using *scanf()* in C++ programs faster than using *cin >> something* ? If yes, that is it a good practice to use it in C++ programs? I thought that it was C specific, though I am just learning C++...
Here's a quick test of a simple case: a program to read a list of numbers from standard input and XOR all of the numbers. **iostream version:** ``` #include <iostream> int main(int argc, char **argv) { int parity = 0; int x; while (std::cin >> x) parity ^= x; std::cout << parity << std::endl; return 0; } ``` **scanf version:** ``` #include <stdio.h> int main(int argc, char **argv) { int parity = 0; int x; while (1 == scanf("%d", &x)) parity ^= x; printf("%d\n", parity); return 0; } ``` **Results** Using a third program, I generated a text file containing 33,280,276 random numbers. The execution times are: ``` iostream version: 24.3 seconds scanf version: 6.4 seconds ``` Changing the compiler's optimization settings didn't seem to change the results much at all. Thus: there really is a speed difference. --- *EDIT:* User clyfish [points out below](https://stackoverflow.com/a/15939289/462335) that the speed difference is largely due to the iostream I/O functions maintaining synchronization with the C I/O functions. We can turn this off with a call to `std::ios::sync_with_stdio(false);`: ``` #include <iostream> int main(int argc, char **argv) { int parity = 0; int x; std::ios::sync_with_stdio(false); while (std::cin >> x) parity ^= x; std::cout << parity << std::endl; return 0; } ``` **New results:** ``` iostream version: 21.9 seconds scanf version: 6.8 seconds iostream with sync_with_stdio(false): 5.5 seconds ``` **C++ iostream wins!** It turns out that this internal syncing / flushing is what normally slows down iostream i/o. If we're not mixing stdio and iostream, we can turn it off, and then iostream is fastest. The code: <https://gist.github.com/3845568>
<http://www.quora.com/Is-cin-cout-slower-than-scanf-printf/answer/Aditya-Vishwakarma> Performance of `cin`/`cout` can be slow because they need to keep themselves in sync with the underlying C library. This is essential if both C IO and C++ IO is going to be used. However, if you only going to use C++ IO, then simply use the below line before any IO operations. ``` std::ios::sync_with_stdio(false); ``` For more info on this, look at the corresponding [libstdc++ docs](http://gcc.gnu.org/onlinedocs/libstdc++/manual/io_and_c.html).
Using scanf() in C++ programs is faster than using cin?
[ "", "c++", "performance", "io", "" ]
How can i iterate bits in a byte array?
You'd have to write your own implementation of `Iterable<Boolean>` which took an array of bytes, and then created `Iterator<Boolean>` values which remembered the current index into the byte array *and* the current index within the current byte. Then a utility method like this would come in handy: ``` private static Boolean isBitSet(byte b, int bit) { return (b & (1 << bit)) != 0; } ``` (where `bit` ranges from 0 to 7). Each time `next()` was called you'd have to increment your bit index within the current byte, and increment the byte index within byte array if you reached "the 9th bit". It's not really *hard* - but a bit of a pain. Let me know if you'd like a sample implementation...
``` public class ByteArrayBitIterable implements Iterable<Boolean> { private final byte[] array; public ByteArrayBitIterable(byte[] array) { this.array = array; } public Iterator<Boolean> iterator() { return new Iterator<Boolean>() { private int bitIndex = 0; private int arrayIndex = 0; public boolean hasNext() { return (arrayIndex < array.length) && (bitIndex < 8); } public Boolean next() { Boolean val = (array[arrayIndex] >> (7 - bitIndex) & 1) == 1; bitIndex++; if (bitIndex == 8) { bitIndex = 0; arrayIndex++; } return val; } public void remove() { throw new UnsupportedOperationException(); } }; } public static void main(String[] a) { ByteArrayBitIterable test = new ByteArrayBitIterable( new byte[]{(byte)0xAA, (byte)0xAA}); for (boolean b : test) System.out.println(b); } } ```
Java Iterate Bits in Byte Array
[ "", "java", "arrays", "byte", "bit", "loops", "" ]
Has anyone integrated Hamcrest with TestNG so that its matchers can easily be used in TestNG assertions?
In short, to answer your question: You don't need to integrate TestNG with Hamcrest. Just call `org.hamcrest.MatcherAssert.assertThat(...)` directly which throws `java.lang.AssertionError`. **Background** I found your question via Google, wondering exactly the same issue. After further Googling, I didn't find any satisfying answers, so I read the source code for JUnit's integration with Hamcrest. With JUnit, Hamcrest integration is normally used by calling: ``` org.junit.Assert.assertThat( T actual, org.hamcrest.Matcher<? super T> matcher) ``` When I read the source code, I discovered it just a small wrapper to call: ``` org.hamcrest.MatcherAssert.assertThat( String reason, T actual, org.hamcest.Matcher<? super T> matcher) ``` This function throws `java.lang.AssertionError`.
If you are facing problem with empty method then I would suggest to add `hamcrest` first in dependency list. or import first `hamcrest`, it will solve the problem. I was using TestNJ with rexsl(internally using Hamcrest) and it fails to find empty method. then I added rexsl first in dependency list, if you are adding library in class path you can try to add first the Hamcrest one. hope it will help someone like me.
Mixing Hamcrest and TestNG
[ "", "java", "testng", "hamcrest", "" ]
I am using [Sphinx](https://www.sphinx-doc.org). I want to template it. So after reading the docs, what I am trying is, in my conf.py, I put a line like, ``` templates_path = ['_templates'] ``` and I created a file ``` _templates/page.html ``` But this does not override the default template provided by sphinx. What more should I do, and where does this template need to go? --- **EDIT:** Directory structure from the comments: ``` conf.py abc.txt def.txt makefile _templates\ page.html ```
Be sure you are using the theme name as an explicit directory in your template. e.g.: `{% extends "basic/layout.html" %}` see: [HTML Theming Support](https://www.sphinx-doc.org/en/master/theming.html#templating)
The documentation <https://www.sphinx-doc.org/en/master/templating.html#working-with-the-builtin-templates> says that the template it's looking for is `layout.html`. Perhaps you should use that name.
Sphinx templating
[ "", "python", "templates", "python-sphinx", "" ]
I need to check if a database is totally empty (no tables) using an SQL query. How can this be done? Thanks for the help!
``` SELECT COUNT(DISTINCT `table_name`) FROM `information_schema`.`columns` WHERE `table_schema` = 'your_db_name' ``` will return the actual number of tables (or views) in your DB. If that number is 0, then there are no tables.
``` select count(*) from information_schema.tables where table_type = 'BASE TABLE' and table_schema = 'your_database_name_here' ```
SQL to check if database is empty (no tables)
[ "", "sql", "mysql", "" ]
1)Is there any difference between these two keywords for the elements of collections??(**Copy** those elements to the other collection and **addAll** those elements to the other collection)
Yes, there is a difference. From the [java docs](http://java.sun.com/javase/6/docs/api/java/util/Collections.html): **`Copy`:** Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected. **Example:** `Copy` `[1,2,3]` to `[4,5,6,7,8]` => `[1,2,3,7,8]` **`AddAll`:** Adds all of the specified elements to the specified collection **Example:** `AddAll` of `[1,2,3]` to `[4,5,6,7,8]` => `[4,5,6,7,8,1,2,3]`
According to JavaDoc, [copy()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#copy(java.util.List,%20java.util.List)) copies only from one List to another and only to the specific indices on one List to the other. [addAll()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#addAll(java.util.Collection)) just adds all items from one Collection to the other, regardless of index, and regardless the type of Collection.
Is there any difference between the **copy** and ** addAll**?
[ "", "java", "collections", "" ]
I am still having trouble understanding what interfaces are good for. I read a few tutorials and I still don't know what they really are for other then "they make your classes keep promises" and "they help with multiple inheritance". Thats about it. I still don't know when I would even use an interface in a real work example or even when to identify when to use it. From my limited knowledge of interfaces they can help because if something implements it then you can just pass the interface in allowing to pass in like different classes without worrying about it not being the right parameter. But I never know what the real point of this since they usually stop short at this point from showing what the code would do after it passes the interface and if they sort of do it it seems like they don't do anything useful that I could look at and go "wow they would help in a real world example". So what I guess I am saying is I am trying to find a real world example where I can see interfaces in action. I also don't understand that you can do like a reference to an object like this: ``` ICalculator myInterface = new JustSomeClass(); ``` So now if I would go myInterface dot and intellisense would pull up I would only see the interface methods and not the other methods in JustSomeClass. So I don't see a point to this yet. Also I started to do unit testing where they seem to love to use interfaces but I still don't understand why. Like for instance this example: ``` public AuthenticationController(IFormsAuthentication formsAuth) { FormsAuth = formsAuth ?? new FormsAuthenticationWrapper(); } public class FormsAuthenticationWrapper : IFormsAuthentication { public void SetAuthCookie(string userName, bool createPersistentCookie) { FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } public void SignOut() { FormsAuthentication.SignOut(); } } public IFormsAuthentication FormsAuth { get; set; } ``` Like why bother making this interface? Why not just make FormsAuthenticationWrapper with the methods in it and call it a day? Why First make an interface then have the Wrapper implement the interface and then finally write the methods? Then I don't get what the statement is really saying. Like I now know that the statement is saying this ``` FormsAuth = formsAuth ?? new FormsAuthenticationWrapper(); ``` if formsAuth is null then make a new FormsAuthenticationWrapper and then assign it to the property that is an Interface. I guess it goes back to the whole point of why the reference thing. Especially in this case since all the methods are exactly the same. The Wrapper does not have any new methods that the interface does not have and I am not sure but when you do this the methods are filled right(ie they have a body) they don't get converted to stubs because that would really seem pointless to me(it it would be converted back to an interface). Then in the testing file they have: ``` var formsAuthenticationMock = new Mock<AuthenticationController.IFormsAuthentication>(); ``` So they just pass in the FormsAuthentication what I am guessing makes all the fake stubs. I am guessing the wrapper class is used when the program is actually running since it has real methods that do something(like sign a person out). But looking at new Mock(from moq) it accepts a class or an interface. Why not just again made the wrapper class put those methods in and then in the new Mock call that? Would that not just make the stubs for you?
Interfaces define *contracts*. In the example you provide, the `??` operator just provides a default value if you pass `null` to the constructor and doesn't really have anything to do with interfaces. What is more relevant is that you might use an actual `FormsAuthenticationWrapper` object, but you can also implement your own `IFormsAuthentication` type that has nothing to do with the wrapper class at all. The interface tells you what methods and properties you need to implement to fulfill the contract, and allows the compiler to verify that your object really does honor that contract (to some extent - it's simple to honor a contract in name, but not in spirit), and so you don't have to use the pre-built `FormsAuthenticationWrapper` if you don't want to. You can build a different class that works completely differently but still honors the required contract. In this respect interfaces are much like normal inheritance, with one important difference. In C# a class can only inherit from one type but can implement many interfaces. So interfaces allow you to fulfill multiple contracts in one class. An object can *be* an IFormsAuthentication object and *also be* something else, like IEnumerable. Interfaces are even more useful when you look at it from the other direction: they allow you to treat many different types as if they were all the same. A good example of this is with the various collections classes. Take this code sample: ``` void OutputValues(string[] values) { foreach (string value in values) { Console.Writeline(value); } } ``` This accepts an array and outputs it to the console. Now apply this simple change to use an interface: ``` void OutputValues(IEnumerable<string> values) { foreach (string value in values) { Console.Writeline(value); } } ``` This code *still* takes an array and outputs it to the console. But it also takes a `List<string>` or anything else you care to give it that implements `IEnumerable<string>`. So we've taken an interface and used it to make a simple block of code *much* more powerful. Another good example is the ASP.Net membership provider. You tell ASP.Net that you honor the membership contract by implementing the required interfaces. Now you can easily customize the built-in ASP.Net authentication to use any source, and all thanks to interfaces. The data providers in the System.Data namespace work in a similar fashion. One final note: when I see an interface with a "default" wrapper implementation like that, I consider it a bit of an anit-pattern, or at least a code smell. It indicates to me that maybe the interface is too complicated, and you either need to split it apart or consider using some combination of composition + events + delegates rather than derivation to accomplish the same thing.
Ok, I had a hard time understanding too at first, so don't worry about it. Think about this, if you have a class, that lets say is a video game character. ``` public class Character { } ``` Now say I want to have the Character have a weapon. I could use an interface to determin the methods required by a weapon: ``` interface IWeapon { public Use(); } ``` So lets give the Character a weapon: ``` public class Character { IWeapon weapon; public void GiveWeapon(IWeapon weapon) { this.weapon = weapon; } public void UseWeapon() { weapon.Use(); } } ``` Now we can create weapons that use the IWeapon interface and we can give them to any character class and that class can use the item. ``` public class Gun : IWeapon { public void Use() { Console.Writeline("Weapon Fired"); } } ``` Then you can stick it together: ``` Character bob = new character(); Gun pistol = new Gun(); bob.GiveWeapon(pistol); bob.UseWeapon(); ``` Now this is a general example, but it gives a lot of power. You can read about this more if you look up the Strategy Pattern.
Understanding Interfaces
[ "", "c#", ".net", "asp.net-mvc", "interface", "" ]
I have a solution I'm trying to get to build on TFS. I want to update the versions of all appropriate files, and I've been stuck trying to get this done. There are plenty of links on how to do it, but none of them work for me, due to one little issue... Scope. ``` <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="DesktopBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <Target Name="DesktopBuild"> <CallTarget Targets="GetFiles" /> <Message Text="CSFiles: '@(CSFiles)'" /> </Target> <Target Name="GetFiles"> <ItemGroup> <CSFiles Include="**\AssemblyInfo.cs" /> </ItemGroup> <Message Text="CSFiles: '@(CSFiles)'" /> </Target> </Project> ``` My tree looks like this: * test.proj * application.sln * application (Folder) + main.cs + Properties (Folder) - AssemblyInfo.cs When I run "c:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe test.proj" from the solution folder... I get the following output: ``` Microsoft (R) Build Engine Version 3.5.30729.1 [Microsoft .NET Framework, Version 2.0.50727.3074] Copyright (C) Microsoft Corporation 2007. All rights reserved. Build started 7/6/2009 3:54:10 PM. Project "D:\src\test.proj" on node 0 (default targets). CSFiles: 'application\Properties\AssemblyInfo.cs' DesktopBuild: CSFiles: '' Done Building Project "D:\src\test.proj" (default targets). Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:00.04 ``` So, how can I make my ItemGroup have global scope? All the Targets files used by the compiler and TeamBuild do this same thing, and theirs all seem to be global... I don't understand why this isn't working for me. Any help?
Have you tried using DependsOnTarget rather than CallTarget? It could be that CallTarget is causing the scope issue.
The previous commenter was correct, you should change this to use DependsOnTargets instead of using the CallTarget task. What you are seeing is a [bug](http://sedodream.com/2005/12/28/MSBuildCreatePropertyItemAndCallTargetBug.aspx) not a scoping inssue. The [way to avoid](http://sedodream.com/2006/01/08/MSBuildCreatePropertyBugWorkaround.aspx) this bug is to use DependsOnTargets (which is a much better approach anywayz). Sayed Ibrahim Hashimi My Book: [Inside the Microsoft Build Engine : Using MSBuild and Team Foundation Build](https://rads.stackoverflow.com/amzn/click/com/0735626286)
ItemGroup Item scope, alternatively "Why does MSBuild hate me?"
[ "", "c#", "tfs", "msbuild", "scope", "tfsbuild", "" ]
Say this is my string ``` $string = 'product[0][1][0]'; ``` How could I use that string alone to actually get the value from an array as if I had used this: ``` echo $array['product'][0][1][0] ``` I've messed around with preg\_match\_all with this regex (`/\[([0-9]+)\]/`), but I am unable to come up with something satisfactory. Any ideas? Thanks in advance.
You could use `preg_split` to get the individual array indices, then a loop to apply those indices one by one. Here's an example using a crude `/[][]+/` regex to split the string up wherever it finds one or more square brackets. (Read the `[][]` construct as `[\]\[]`, i.e. a character class that matches right or left square brackets. The backslashes are optional.) ``` function getvalue($array, $string) { $indices = preg_split('/[][]+/', $string, -1, PREG_SPLIT_NO_EMPTY); foreach ($indices as $index) $array = $array[$index]; return $array; } ```
This is prettttty hacky, but this will work. Don't know how much your array structure is going to change, either, this won't work if you get too dynamic. ``` $array = array(); $array['product'][0][1][0] = "lol"; $string = 'product[0][1][0]'; $firstBrace = strpos( $string, "[" ); $arrayExp = substr($string, $firstBrace ); $key = substr( $string, 0, $firstBrace ); echo $arrayExp, "<br>"; echo $key, "<br>"; $exec = "\$val = \$array['".$key."']".$arrayExp.";"; eval($exec); echo $val; ```
How can I use a string to get a value from a multi dimensional array?
[ "", "php", "arrays", "multidimensional-array", "" ]
I am looking for a regular expression that can get me src (case insensitive) tag from following HTML snippets in java. ``` <html><img src="kk.gif" alt="text"/></html> <html><img src='kk.gif' alt="text"/></html> <html><img src = "kk.gif" alt="text"/></html> ```
One possibility: ``` String imgRegex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"; ``` is a possibility (if matched case-insensitively). It's a bit of a mess, and deliberately ignores the case where quotes aren't used. To represent it without worrying about string escapes: ``` <img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*> ``` This matches: * `<img` * one or more characters that aren't `>` (i.e. possible other attributes) * `src` * optional whitespace * `=` * optional whitespace * starting delimiter of `'` or `"` * **image source** (which may not include a single or double quote) * ending delimiter * *although the expression can stop here, I then added:* + zero or more characters that are not `>` (more possible attributes) + `>` to close the tag **Things to note:** * If you want to include the `src=` as well, move the open bracket further left :-) * This does not care about delimiter balancing or attribute values without delimiters, and it can also choke on badly-formed attributes (such as attributes that include `>` or image sources that include `'` or `"`). * Parsing HTML with regular expressions like this is non-trivial, and at best a quick hack that works in the majority of cases.
This question comes up a lot here. Regular expressions are a **bad** way of handling this problem. Do yourself a favour and use an HTML parser of some kind. Regexes are flaky for parsing HTML. You'll end up with a complicated expression that'll behave unexpectedly in some corner cases that *will* happen otherwise. **Edit:** *If* your HTML is that simple then: ``` Pattern p = Pattern.compile("src\\s*=\\s*([\\"'])?([^ \\"']*)"); Matcher m = p.matcher(str); if (m.find()) { String src = m.group(2); } ``` And there are [any number of Java HTML parsers](http://java-source.net/open-source/html-parsers) out there.
Regular expression to get an attribute from HTML tag
[ "", "java", "regex", "" ]
I want to add an additional roadblock in my application to prevent automating it via javascript, specifically when the automated requests are being done via XMLHttpRequest from any of the popular browsers. Is there a reliable tell-tale sign of a XMLHttpRequest that I can use in ASP.NET? And I guess the other related question is, is it hard for XMLHttpRequest to appear to be an ordinary human driven request? Because if it is, then I guess I'm on fools errand. UPDATE: I might be phrasing the question too narrowly. The goal is to detect : code written by someone else, not submitted by a ordinary browser, might be a bot, might not be from a my intranet customers, etc. So far XHR and .NET WebRequest requests come to mind.
You could always use a CAPTCHA to ensure that a human is responsible for submitting the request. recaptcha.net is free and helps to digitize books. **Edit:** If you know what type of malicious behavior you are trying to prevent, you could develop simple algorithms for detecting that behavior. When that behavior is detected you could challenge the client with a CAPTCHA to ensure that a human is responsible. This approach is starting to become common practice. Take a look at this [post](http://www.codinghorror.com/blog/archives/001228.html) on this topic.
no, there is no way of doing this. a lot of the popular libraries like jquery put a special header ("x-requested-with" for jquery) to indicate it's an ajax call, but that's obviously voluntary on the part of the client. you *must* assume that any request you receive may be malicious unfortunately
Reliable way to sniff XMLHttpRequest (browser sniffing for AJAX requests) in ASP.NET?
[ "", "asp.net", "javascript", "xmlhttprequest", "browser-detection", "" ]
I would like to lookup an enum from its string value (or possibly any other value). I've tried the following code but it doesn't allow static in initialisers. Is there a simple way? ``` public enum Verbosity { BRIEF, NORMAL, FULL; private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>(); private Verbosity() { stringMap.put(this.toString(), this); } public static Verbosity getVerbosity(String key) { return stringMap.get(key); } }; ```
Use the `valueOf` method which is automatically created for each Enum. ``` Verbosity.valueOf("BRIEF") == Verbosity.BRIEF ``` For arbitrary values start with: ``` public static Verbosity findByAbbr(String abbr){ for(Verbosity v : values()){ if( v.abbr().equals(abbr)){ return v; } } return null; } ``` Only move on later to Map implementation if your profiler tells you to. I know it's iterating over all the values, but with only 3 enum values it's hardly worth any other effort, in fact unless you have a lot of values I wouldn't bother with a Map it'll be fast enough.
You're close. For arbitrary values, try something like the following: ``` public enum Day { MONDAY("M"), TUESDAY("T"), WEDNESDAY("W"), THURSDAY("R"), FRIDAY("F"), SATURDAY("Sa"), SUNDAY("Su"), ; private final String abbreviation; // Reverse-lookup map for getting a day from an abbreviation private static final Map<String, Day> lookup = new HashMap<String, Day>(); static { for (Day d : Day.values()) { lookup.put(d.getAbbreviation(), d); } } private Day(String abbreviation) { this.abbreviation = abbreviation; } public String getAbbreviation() { return abbreviation; } public static Day get(String abbreviation) { return lookup.get(abbreviation); } } ```
How can I lookup a Java enum from its String value?
[ "", "java", "enums", "lookup", "" ]
I have recently started seeing user agents like Java/1.6.0\_14 (and variations) on my site What does this mean. Is it a browser or bot or what
This likely means someone is crawling your website using Java. This isn't much of anything to be concerned about unless you notice the crawler using large amounts of your bandwidth or not respecting your robots.txt file. Usually legitimate crawlers will take the time to create custom user agent to make it easy to contact the crawler if you have a problem, but even if they're using the default user agent, it's more than likely perfectly benign. However, if you do notice a spike in 404 hits or *lots* of hits from the Java client, you're likely under attack by spammers looking for security holes in your website. If your site is built well, there's not a whole lot they can do other than burn some of your bandwidth, but if they find a security hole, they'll be sure to exploit it. Dealing with spammers properly is beyond the scope of this answer, but a scorched earth solution (which will work as a short term fix at the very least) would be to block all user agents that contain the string 'java'.
It means your site is being accessed through the JVM on someones machine. It could be a crawler or simply someone scraping data. You can replicate the user-agent string using the [HttpURLConnection](http://java.sun.com/j2se/1.4.2/docs/api/java/net/HttpURLConnection.html) class. Here is a sample: ``` import java.net.*; public class Request { public static void main(String[] args) { try { URL url=new URL("http://google.ca"); HttpURLConnection con=(HttpURLConnection)url.openConnection(); con.connect(); System.out.println(con.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } } ```
Java User Agent
[ "", "java", "user-agent", "" ]
I'm using XSLT 1.0 an want to transform an XML file. It works fine with *IE 6.0* and *Firefox 3.0.11*. However, the *PHP 5.2.6 XSLTProcessor* (providing XSLT 1.0) and *Qt C++ QXmlQuery* (providing only XSLT 2.0) generates blank output. I think of two options: 1. Convert it to XSLT 2.0 (preferred) 2. Extract Firefox part to parse. The *W3C* specs seem to long for me to digest and the documents to transform are not that large.
XSLT should be pretty much backward compatibly, although obviously there are things you can use in XSLT 2.0 that make life much easier. It sounds like you have something wrong in your XSLT, but as you don't provide anything for us to look at it is hard to say. I would recommend getting hold of Kernow-for-Saxon - it is a great UI for testing XSLT (much better than trying to use Firefox or IE) and if you have errors in your XSLT then Saxon is one of the better XSLT processors for giving good errors to try to identify the cause. <http://kernowforsaxon.sourceforge.net/> I don't know anything about either the PHP or Qt processors, but it is possible there are errors in them that are not handling your XSLT correctly.
If the whole spec is too long (???), start with the [Changes](http://www.w3.org/TR/xslt20/#changes) section. Also, XSLTProcessor is just a wrapper round libxslt, and unlikely to break on a valid XSLT 1.0 transform. I wonder if there is something funky about your transformation that you can fix without going to 2.0, or if there's something wrong with your XSLTProcessor deployment. Can you successfully apply other transformations?
Converting XSLT 1.0 to XSLT 2.0
[ "", "php", "xml", "qt", "xslt", "" ]
Many times I needed a set of pointers. Every time that happens, I end up writing a less<> implementation for a pointer type - cast two pointers to size\_t and compare the results. My question is - is that available in the standard? I could not find anything like that. Seems like common enough case... Update: it seems that the upcoming standard fixes all of the problems with less<> provided for pointer types and unordered\_set included, too. In a few years this question will be moot. In the mean time, the current standard has no "legal" solution to this, but size\_t cast works. Update for update: well, I'll be gobsmacked! Not only ``` std::map<void *, int, std::less<void*> > myMap; ``` works, but even ``` std::map<void *, int > myMap; ``` as well. And that's in gcc 3.4.1 . I've been doing all the these casts for nothing, and litb is perfectly right. Even the section number he cites is exactly the same in the current standard. Hurray!
Two pointers can be compared with using the comparison function objects `less`, `greater` etc. Otherwise, using blanket `operator<` etc, this is only possible if the pointers point to elements of the same array object or one past the end. Otherwise, results are unspecified. `20.3.3/8` in C++03 > For templates `greater`, `less`, `greater_equal`, and `less_equal`, the specializations for any > pointer type yield a total order, even if the built-in operators `<`, `>`, `<=`, `>=` do not. No need to explicitly specialize and manually casting to `size_t`: That would lower the portability even, since the mapping of `reinterpret_cast` from pointers to integers is implementation defined and is not required to yield any order. --- **Edit**: For a more detailed answer, see [this one](https://stackoverflow.com/questions/1418068/what-are-the-operations-supported-by-raw-pointer-and-function-pointer-in-c-c/1418152#1418152).
~~No, it's not available.~~ The standard says that pointers are only comparable with the built-in operators when they point to the same array or other memory block. That is, the block needs to have been allocated all at once, as opposed to two separate allocations that might happen to be adjacent to each other. This is OK: ``` int x[2]; bool b = &x[0] < &x[1]; ``` This is undefined: ``` int x0; int x1; bool b = &x0 < &x1; ``` This is OK: ``` struct foo { int x0; int x1; }; foo f; bool b = &f.x0 < &f.x1; ``` Both values are members of the same struct, so they belong to the same block of memory (namely, `f`'s). Practically speaking, though, there's nothing wrong with your custom-defined comparison. However, your custom specialization is unnecessary, since the `std::less` template *is* defined for pointers, evidently. So this is OK: ``` int x0; int x1; std::less<int*> compare; bool b = compare(&x0, &x1); ``` There's still no indication of what the result must be, but you're at least promised to have *some* result, as opposed to undefined behavior. You get a total order, but you don't know *what* order until you run it.
Do you have to write a custom less<> for use in std::map with pointers, or can you use std::less?
[ "", "c++", "" ]
I have a list of check boxes. For the check boxes that are selected, I change it's name before submitting. In FF the function works. In IE I get: > A script on this page is causing Internet Explorer to run slowly. If it > continues to run, your computer may > become unresponsive. > > Do you want to abort the script? YES/NO Not sure why this loop is causing problems in IE and not FF? ``` function sub() { var x=document.getElementsByName("user"); for (i = 0; i < x.length; i++) //for all check boxes { if (x[i].checked == true) { x[i].name="id"; //change name of data so we know it is for an id //By renaming the first element of the list, we have reduced the length of the list by one //and deleted the first element. This is why we need to keep i at it's current position after a name change. i=i-1; } }//end for document.checks.submit(); } ```
This should work with a both a live and a non-live list. Personally, though, I'd try to find some way to output the original page so that the server can figure out which elements to use, instead of relying on javascript to do it. ``` function sub() { var x=document.getElementsByName("user"); var nodesToChangeIndex=0; var nodesToChange=new Array(); for (i = 0; i < x.length; i++) //for all check boxes { if (x[i].checked == true) { nodesToChange[nodesToChangeIndex++] = x[i]; } }//end for for(i=0; i < nodesToChangeIndex; i++) { nodesToChange[i].name="id"; } document.checks.submit(); } ```
I would avoid writing a script like that - it is like having an for/i++ loop calling a function that changes the index as a side effect - unpredictable. You run an iterator through NodeList while modifying the list from inside the loop. You cannot be sure it works until you happen to know exactly the way NodeList is implemented. It's unpleasant, but I would first copy the list into "real" array, and then do the renaming.
Remaning checkbox name from JS cause IE to run slow, not FF?
[ "", "javascript", "html", "internet-explorer", "firefox", "dom", "" ]
I am writing unit tests with C#, NUnit and Rhino Mocks. Here are the relevant parts of a class I am testing: ``` public class ClassToBeTested { private IList<object> insertItems = new List<object>(); public bool OnSave(object entity, object id) { var auditable = entity as IAuditable; if (auditable != null) insertItems.Add(entity); return false; } } ``` I want to test the values in insertItems after a call to OnSave: ``` [Test] public void OnSave_Adds_Object_To_InsertItems_Array() { Setup(); myClassToBeTested.OnSave(auditableObject, null); // Check auditableObject has been added to insertItems array } ``` What is the best practice for this? I have considered adding insertItems as a Property with a public get, or injecting a List into ClassToBeTested, but not sure I should be modifying the code for purposes of testing. I have read many posts on testing private methods and refactoring, but this is such a simple class I wondered what is the best option.
The quick answer is that you should never, ever access non-public members from your unit tests. It totally defies the purpose of having a test suite, since it locks you into internal implementation details that you may not want to keep that way. The longer answer relates to what to do then? In this case, it is important to understand why the implementation is as it is (this is why TDD is so powerful, because we use the tests to *specify* the expected behavior, but I get the feeling that you are not using TDD). In your case, the first question that comes to mind is: "Why are the IAuditable objects added to the internal list?" or, put differently, "What is the expected *externally visible* outcome of this implementation?" Depending on the answer to those questions, *that's* what you need to test. If you add the IAuditable objects to your internal list because you later want to write them to an audit log (just a wild guess), then invoke the method that writes the log and verify that the expected data was written. If you add the IAuditable object to your internal list because you want to amass evidence against some kind of later Constraint, then try to test that. If you added the code for no measurable reason, then delete it again :) The important part is that it is very beneficial to test *behavior* instead of *implementation*. It is also a more robust and maintainable form of testing. Don't be afraid to modify your System Under Test (SUT) to be more testable. As long as your additions make sense in your domain and follow object-oriented best practices, there are no problems - [you would just be following the Open/Closed Principle](http://blog.ploeh.dk/2009/06/05/TestabilityIsReallyTheOpenClosedPrinciple.aspx).
You shouldn't be checking the list where the item was added. If you do that, you'll be writing a unit test for the Add method on the list, and not a test for *your* code. Just check the return value of OnSave; that's really all you want to test. If you're really concerned about the Add, mock it out of the equation. Edit: @TonE: After reading your comments I'd say you may want to change your current OnSave method to let you know about failures. You may choose to throw an exception if the cast fails, etc. You could then write a unit test that expects and exception, and one that doesn't.
Unit testing and checking private variable value
[ "", "c#", "unit-testing", "nunit", "" ]
I have an Excel spreadsheet provided as a report, when really its more of a database, with the row number acting as primary key. I need to compare some columns in this set with a different set of records from an Access 2007 database. To make matters more complicated, this needs to be done automatically, without user input, on a regular schedule. What is the best way to get the data out of the spreadsheet, and what is the best way to run the comparison. As for getting data out of the spreadsheet, ACEDAO seems the best option, since this is Excel 2007, but MSDN has no information I could find on how to query Excel using DAO/ACEDAO, only to export to Excel using DAO/ACEDAO. As for running the comparison, beyond comparing each column of each entry, I can't figure out a better way to do it.
If memory serves, you can create a linked table to an Excel spreadsheet. Once it is linked into Access, you can treat it like any other table. The query to do the comparison looks something like this (see picture below). It will return rows from the Excel spreadsheet that do not match (right-click on the picture and save it to your computer for a clearer view). As far as the automation goes, if you're willing to leave a copy of Access running you can [set up a Timer in a form](http://msdn.microsoft.com/en-us/library/bb214858.aspx). If not, you will have to use [Office Automation](http://msdn.microsoft.com/en-us/library/bb256372.aspx). See here for a "hello world" example in C#: <http://rnarayana.blogspot.com/2008/02/access-2007-office-automation-using-c.html> [![alt text](https://i.stack.imgur.com/Sc1HC.jpg)](https://i.stack.imgur.com/Sc1HC.jpg)
Using ACE you can query the workbook directly e.g. ``` SELECT S1.seq AS seq_ACE, S2.seq AS seq_Excel FROM Sequence AS S1 LEFT OUTER JOIN [Excel 12.0;Database=C:\Test.xlsx;].Sequence AS S2 ON S1.seq = S2.seq; ```
Compare rows in a spreadsheet with records in a database
[ "", "sql", "excel", "ms-access", "vba", "" ]
Here's what I have: ``` decimal sum = _myDB.Products.Sum(p => p.Price).GetValueOrDefault(); ``` I also have two dates: `DateTime start`, `DateTime end` I want to retrieve the sum of all of the product prices between start and end, but I can't figure out how to incorporate the variables into the lambda equation. How do you incorporate variables into a lambda equation to give it some specification?
Use [Enumerable.Where](http://msdn.microsoft.com/en-us/library/bb534803.aspx) ``` decimal sum = _myDB.Products .Where(p => (p.Date >= start) && (p.Date <= end) ) .Sum(p => p.Price) .GetValueOrDefault(); ```
``` decimal sum = _myDB.Products .Where(p => p.Start >= mystartDate && p.End <= myenddate) .Sum(p => p.Price) ``` Pardon my syntax. But, I hope you get the idea. EDIT: Corrected after Reed's suggestion. Old code (incorrect) ``` decimal sum = _myDB.Products .Sum(p => p.Price) .Where(p => p.Start >= mystartDate && p.End <= myenddate) ```
What's the equivalence of an SQL WHERE in Lambda expressions?
[ "", "c#", "asp.net-mvc", "entity-framework", "lambda", "" ]
I am attempting to parse (in Java) Wikimedia markup as found on Wikipedia. There are a number of existing packages out there for this task, but I have not found any to fit my needs particularly well. The best package I have worked with is the [Mathclipse Bliki parser](http://www.matheclipse.org/en/Java_Wikipedia_API), which does a decent job on most pages. This parser is incomplete, however, and fails to parse certain pages or parses incorrectly on others. Sadly the code is rather messy and thus fixing the problems in this parsing engine is very time consuming and error prone. In attempting to find a better parsing engine I have investigated using an EBNF-based parser for this task (specifically ANTLR). After some attempts however it seems that this approach isn't particularly well suited for this task, as the Wikimedia markup is relatively relaxed and thus cannot be easily fit into a structured grammar. My experience with ANTLR and similar parsers is very limited however, so it may be my inexperience that is causing problems rather than such parsers being inherently poorly suited for this task. Can anyone with more experience on these topics weigh in here? @Stobor: I've mentioned that I've looked at various parsing engines, including the ones returned by the google query. The best I've found so far is the Bliki engine. The problem is that fixing problems with such parsers becomes incredibly tedious, because they are all essentially long chains of conditionals and regular expressions, resulting in spaghetti code. I am looking for something more akin to the EBNF method of parsing, as that method is much clearer and more concise, and thus easier to understand and evolve. I've seen the mediawiki link you posted, and it seems to confirm my suspicions that EBNF out of the box is poorly suited for this task. Thus I am looking for a parsing engine that is clear and understandable like EBNF, but also capable of handling the messy syntax of wiki markup.
Parsing mediawiki content in any generic sense is pretty much impossible short using mediawiki itself. In order to parse it you need to be able fully parse HTML and CSS (since they can be embedded), and handle full template instantiation and expansion, as well as any parser addition the relevent content may have been using. That template instantiation is equivalent to a preprocessor. It is in some senses similiar to parsing C++ except the parser also handle malformed input and arbitrary syntax additions made by parser extensions. The actual mediawiki implementation is a lot like Perl 5, the original implementation was not so bad because all the edge cases just fall out however things are linked together, but actually getting any subsequent implementation to do the same thing is really complicated, especially since the behaviors are often emergent and undocumented, not designed. If you do not need 100% of pages to work or to be able to extract all content you might be able to cobble something together that works for you, and as you have noted there are some packages that do that. Short of knowing your actual precise needs I doubt anyone can give you a substantially better answer on how to parse it. If you need to be able to work on every page and correctly parse everything you better have a fairly large team and several years to work, and even then you still have lots of small edge cases. So in short, no an EBNF grammer is not well suited to parsing mediawiki markup, but nothing really is...
You are correct Wikimedia does not lend itself to EBNF well defined grammers. You will have to look at tools that will backtrack to be able to parse Wiki btyacc which is a backtracking yacc. [http://www.siber.com/btyacc/](http://accent.compilertools.net/) You could look at Accent. Better than Yacc <http://accent.compilertools.net/> Or you may have to breakdown and learn some flavour of prolog and roll you own. Whatever you do you have a interesting learning period ahead of you. Good luck
Parsing wikimedia markup - are EBNF-based parsers poorly suited?
[ "", "java", "parsing", "antlr", "ebnf", "wikitext", "" ]
I'm working in C#/.NET and I'm parsing a file to check if one line matches a particular regex. Actually, I want to find the **last** line that matches. To get the lines of my file, I'm currently using the System.IO.StreamReader.ReadLine() method but as my files are very huge, I would like to optimize a bit the code and start from the end of the file. Does anyone know if there is in C#/.NET a similar function to ReadLine() starting from the end of the stream? And if not, what would be, to your mind, the easiest and most optimized way to do the job described above?
Funny you should mention it - yes I have. I wrote a `ReverseLineReader` a while ago, and put it in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil). It was in answer to [this question](https://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c) on Stack Overflow - the answer contains the code, although it uses other bits of MiscUtil too. It will only cope with some encodings, but hopefully all the ones you need. Note that this will be less efficient than reading from the start of the file, if you ever have to read the whole file - all kinds of things may assume a forward motion through the file, so they're optimised for that. But if you're actually just reading lines near the end of the file, this could be a big win :) (Not sure whether this should have just been a close vote or not...)
Since you are using a regular expression I think your best option is going to be to read the entire line into memory and then attempt to match it. Perhaps if you provide us with the regular expression and a sample of the file contents we could find a better way to solve your problem.
StreamReader.ReadLine() starting from the end of the stream
[ "", "c#", "parsing", "" ]
I would like to create a table to store device settings. The table has three rows: id, parameter\_name and parameter\_value. The table was created by executing the following query statement: ``` DATABASE_CREATE = "create table DATABASE_TABLE (KEY_ID INTEGER PRIMARY KEY AUTOINCREMENT, KEY_NAME INTEGER not null, VALUE TEXT not null); ``` and then the rows are stored by executing the following method: ``` private long insertRow(int rowParameter, String rowValue, SQLiteDatabase db){ long res = -1; ContentValues settingsParameterValues = new ContentValues(); settingsParameterValues.put(KEY_NAME, rowParameter); settingsParameterValues.put(VALUE, rowValue); if(db != null){ res = db.insert(DATABASE_TABLE, null, settingsParameterValues); } return res; } ``` When the database is created the default values are stored: ``` @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); insertRow(PRIVACY_LEVEL_ROW_INDEX, "0", db); insertRow(STREAM_TITLE_ROW_INDEX, "untitled", db); insertRow(STREAM_TAGS_ROW_INDEX, "", db); } ``` The problem with method insertRow() however is that it can't prevent duplicating the entries. Does anyone know how to prevent duplicate entries in this case?
[You can use the column constraint `UNIQUE`.](http://www.sqlite.org/lang_createtable.html) > The UNIQUE constraint causes an unique index to be created on the specified columns.
I would create a UNIQUE CONSTRAINT in the database table definition. That will automatically prevent duplicate entries and it's pretty much the only concurrency-safe way to do it! Also, don't forget about CHECK CONSTRAINT which may be more helpful if you need to define more complex rules for the data in you tables.
SQLite: prevent duplicates
[ "", "sql", "database", "android", "sqlite", "" ]
6.7 is out, and although going to the web and finding some .nbm-s and copying over a few update center URL-s isn't the biggest chore...it's still a chore. Any tips for this? Is there maybe a hidden directory somewhere that I can just copy into the new 6.7 install? Edit: for people like me who use both, I've asked this question in Eclipse-land as well: [A new version of Eclipse just came out. Is there anything I can do to avoid having to manually hunt down my plugins again?](https://stackoverflow.com/questions/1059732/a-new-version-of-eclipse-just-came-out-is-there-anything-i-can-do-to-avoid-havi)
Netbeans 6.7 **does** has this feature: [Importing Plugins From Previous Release Into The New One](http://wiki.netbeans.org/NewAndNoteWorthyNB67#section-NewAndNoteWorthyNB67-ImportingPluginsFromPreviousReleaseIntoTheNewOne), but it seems a bit shy about it. When the new version of Netbeans is launched you'll be asked if you want to import settings from a previous version. Click yes and Netbeans will look for compatible plugins in the background. **Note that you won't be prompted again.** Instead, after a few minutes, an icon should appear in the bottom-right corner: <http://lh6.ggpht.com/_BEizchvf9zs/Sk83UjMwZBI/AAAAAAAAABQ/hlX5DT-k0fg/s800/netbeans-screenshot.png> Not exactly in your face, right? Click on that and you'll get the option of installing any compatible plugins. Also note that if you exit this process at any point then the icon will disappear - restarting Netbeans will bring it back (though you might have to wait for it to do another background scan). **Finally**, you can also trigger this process (and choose an arbitrary [userdir location](http://wiki.netbeans.org/FaqWhatIsUserdir) to import from) with the command line option [`-J-Dplugin.manager.import.from=/path/to/userdir`](http://blogs.oracle.com/rechtacek/entry/new_feature_in_netbeans_7) e.g. in Vista: ``` C:\Users\JDoe>"c:\Program Files (x86)\NetBeans 6.7\bin\netbeans" -J-Dplugin.manager.import.from="C:\Users\JDoe\.netbeans\6.5" ``` or in Ubuntu: ``` /bin/sh ~/netbeans-6.7/bin/netbeans -J-Dplugin.manager.import.from="/homes/YOURHOMEDIR/.netbeans/6.5" ``` This might be useful if you want to import from a beta install.
In the 'modules' sub-directory of the < install\_dir >/< nb *version* >/, you will see the JARs of the modules you installed. But, there is no metadata information apparently there. And, I don't think only copying the JARs will help. Even if it does, couple of things: you will not be able to update the modules, when there are recent versions available and the old modules may simply not be compatible with the new release. So, the best thing, even though repeated work, is to install them from the Plugin manager. PS: You may consider asking this on the 'nbusers' mailing list.
A new version of Netbeans just came out. Is there anything I can do to avoid having to manually hunt down my plugins again?
[ "", "java", "netbeans", "plugins", "netbeans6.7", "netbeans6.5", "" ]
My code is ``` function getID( swfID ){ if(navigator.appName.indexOf("Microsoft") != -1){ me = window[swfID]; }else{ me = document[swfID]; } } function js_to_as( str ){ me.onChange(str); } ``` However, sometimes my `onChange` does not load. Firebug errors with > me.onChange is not a function I want to degrade gracefully because this is not the most important feature in my program. `typeof` gives the same error. Any suggestions on how to make sure that it exists and then only execute `onChange`? (None of the methods below except try catch one work)
Try something like this: ``` if (typeof me.onChange !== "undefined") { // safe to use the function } ``` or better yet (as per UpTheCreek upvoted comment) ``` if (typeof me.onChange === "function") { // safe to use the function } ```
## Modern JavaScript to the rescue! ``` me.onChange?.(str) ``` The [Optional Chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#Optional_chaining_with_function_calls) syntax (`?.`) solves this * in **JavaScript** since [ES2020](https://262.ecma-international.org/11.0/#sec-optional-chains) * in **Typescript** since [version 3.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html) In the example above, if a `me.onChange` property exists and is a function, it is called. If no `me.onChange` property exists, nothing happens: the expression just returns `undefined`. ***Note*** - if a `me.onChange` property exists but is *not* a function, a `TypeError` will be thrown just like when you call any non-function as a function in JavaScript. Optional Chaining doesn't do any magic to make this go away.
How to check if function exists in JavaScript?
[ "", "javascript", "" ]
I have a class `A` and a class `B` that inherits class `A` and extends it with some more fields. Having an object `a` of type `A`, how can I create an object `b` of type `B` that contains all data that object `a` contained? I have tried `a.MemberwiseClone()` but that only gives me another type `A` object. And I cannot cast `A` into `B` since the inheritance relationship only allows the opposite cast. What is the right way to do this?
There is no means of doing this automatically built into the language... One option is to add a constructor to class B that takes a class A as an argument. Then you could do: ``` B newB = new B(myA); ``` The constructor can just copy the relevant data across as needed, in that case.
I would add a copy constructor to A, and then add a new constructor to B that takes an instance of A and passes it to the base's copy constructor.
How to "clone" an object into a subclass object?
[ "", "c#", "object", "copy", "subclass", "" ]
I am trying to paint cell on a html page, where each cell is a DIV, I need to be able to capture right click event on any of these cells, How can I do that? ``` <script> function fn(event) { alert('hello'+event.button); } </script> <div id="cell01" class="" onclick="fn(event);" style="left: 1471px; width: 24px; height: 14px; top: 64px; text-align: center; position: absolute; background-color: rgb(128, 128, 0);">1</div> ```
Take a look at this: [Javascript - event properties](http://www.quirksmode.org/js/events_properties.html). Value for right mouse button is `2`, although also note that it recommends using `mousedown` or `mouseup` events rather than click. Here is a sample from the page showing right click detection: ``` function doSomething(e) { var rightclick; if (!e) var e = window.event; if (e.which) rightclick = (e.which == 3); else if (e.button) rightclick = (e.button == 2); alert('Rightclick: ' + rightclick); // true or false } ```
the easiest way ``` <div style="height: 100px; background-color: red;" oncontextmenu="window.alert('test');return false;"></div> ```
Capture Right Click on HTML DIV
[ "", "javascript", "html", "events", "" ]
Having this code: ``` using (BinaryWriter writer = new BinaryWriter(File.Open(ProjectPath, FileMode.Create))) { //save something here } ``` Do we need to close the BinaryWriter? If not, why?
So long as it's all wrapped up in a `using` block then you don't need to explicitly call `Close`. The `using` block will ensure that the object is disposed, and the `Close` and `Dispose` methods are interchangeable on `BinaryWriter`. (The `Close` method just calls `Dispose` behind the scenes.)
With the code you have there it will close the file once it exits the using block, so you do not need to call close explcitly. The only reason not to use the using statement would be if you want the file to still be open after you are done with your BinaryWriter, in which case you should hold on to a reference of it instead of passing it into the constructor like that.
Do we need to close a C# BinaryWriter or BinaryReader in a using block?
[ "", "c#", "idisposable", "using", "" ]
Let's create WinForms Application (I have Visual Studio 2008 running on Windows Vista, but it seems that described situation takes place almost everywhere from Win98 to Vista, on native or managed code). Write such code: ``` using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public class Form1 : Form { private readonly Button button1 = new Button(); private readonly ComboBox comboBox1 = new ComboBox(); private readonly TextBox textBox1 = new TextBox(); public Form1() { SuspendLayout(); textBox1.Location = new Point(21, 51); button1.Location = new Point(146, 49); button1.Text = "button1"; button1.Click += button1_Click; comboBox1.Items.AddRange(new[] {"1", "2", "3", "4", "5", "6"}); comboBox1.Location = new Point(21, 93); AcceptButton = button1; Controls.AddRange(new Control[] {textBox1, comboBox1, button1}); Text = "Form1"; ResumeLayout(false); PerformLayout(); } private void button1_Click(object sender, EventArgs e) { comboBox1.DroppedDown = true; } } } ``` Then, run app. Place mouse cursor on the form and don't touch mouse anymore. Start to type something in TextBox - cursor will hide because of it. When you press Enter key - event throws and ComboBox will be dropped down. But now cursor won't appear even if you move it! And appears only when you click somewhere. [There](http://www.asmcommunity.net/board/index.php?action=printpage%3Btopic=4867.0) I've found discussion of this problem. But there's no good solution... Any thoughts? :)
I was able to work around the problem like this: ``` comboBox1.DroppedDown = true; Cursor.Current = Cursors.Default; ```
I got this issue on a Delphi application. As suggested [here](https://social.msdn.microsoft.com/Forums/windows/en-US/9ae5a29b-9515-4165-a41c-45b383359594/combobox-hides-mouse-cursor-when-typing-in-text-area?forum=winforms) I just added `SendMessage(ComboBox1.Handle, WM_SETCURSOR, 0, 0)` after any DropDown event and it worked.
Why ComboBox hides cursor when DroppedDown is set?
[ "", "c#", "winforms", "combobox", "" ]