Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is it completely against the Java way to create struct like objects? ``` class SomeData1 { public int x; public int y; } ``` I can see a class with accessors and mutators being more Java like. ``` class SomeData2 { int getX(); void setX(int x); int getY(); void setY(int y); private int x; private int y; } ``` The class from the first example is notationally convenient. ``` // a function in a class public int f(SomeData1 d) { return (3 * d.x) / d.y; } ``` This is not as convenient. ``` // a function in a class public int f(SomeData2 d) { return (3 * d.getX()) / d.getY(); } ```
This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful. In practice, most fields have simple getters and setters. A possible solution would look like this: ``` public property String foo; a->Foo = b->Foo; ``` *Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller*
It appears that many Java people are not familiar with the Sun Java Coding Guidelines which say it is quite appropriate to use public instance variable when the class is essentially a "Struct", if Java supported "struct" (when there is no behavior). People tend to think getters and setters are the Java way, as if they are at the heart of Java. This is not so. If you follow the Sun Java Coding Guidelines, using public instance variables in appropriate situations, you are actually writing better code than cluttering it with needless getters and setters. **Java Code Conventions from 1999** and still unchanged. 10.1 Providing Access to Instance and Class Variables Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten-often that happens as a side effect of method calls. **One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. *In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public***. <http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177> <http://en.wikipedia.org/wiki/Plain_old_data_structure> <http://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28>
Struct like objects in Java
[ "", "java", "oop", "struct", "" ]
Does anyone know tools which look at a MySQL database, show you all the tables graphically and allow you to create complicated JOIN statements via drag-and-drop?
Before you buy anything, see if the free, official [MySQL's GUI tools](http://dev.mysql.com/downloads/gui-tools/) (specifically the **MySQL Query Browser**) will work for you. Personally, I'm fairly comfortable interacting with MySQL's command line interface and haven't used their GUI tools very much, but I just downloaded Query Browser and it seems like it does exactly what you're looking for. Also, check out ["Building Queries Visually in MySQL Query Browser"](http://www.packtpub.com/article/building-queries-visually-in-mysql-query-browser) for a nice tour of MySQL Query Browser.
As an update, the MySQL Tools collection is no longer supported, and has been replaced by MySQL Workbench. The documentation can be found here: <http://dev.mysql.com/doc/workbench/en/index.html> and you can download it here: <http://dev.mysql.com/downloads/workbench/> Edit: stumbled across this today too, a good beginner tutorial for mysql workbench -> <http://net.tutsplus.com/tutorials/databases/visual-database-creation-with-mysql-workbench/>
MySQL tools which ease creation of SQL JOIN statements?
[ "", "sql", "mysql", "" ]
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
``` >>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' ```
Just a little addition, if you want a float number as output from the unpack method instead of a tuple just write ``` >>> import struct >>> [x] = struct.unpack('f', b'\xdb\x0fI@') >>> x 3.1415927410125732 ``` If you have more floats then just write ``` >>> import struct >>> [x,y] = struct.unpack('ff', b'\xdb\x0fI@\x0b\x01I4') >>> x 3.1415927410125732 >>> y 1.8719963179592014e-07 >>> ```
Convert Bytes to Floating Point Numbers?
[ "", "python", "floating-point", "" ]
Knowing an exception code, is there a way to find out more about what the actual exception that was thrown means? My exception in question: 0x64487347 Exception address: 0x1 The call stack shows no information. I'm reviewing a .dmp of a crash and not actually debugging in Visual Studio.
Because you're reviewing a crash dump I'll assume it came in from a customer and you cannot easily reproduce the fault with more instrumentation. I don't have much help to offer save to note that the exception code 0x64487347 is ASCII "dShG", and developers often use the initials of the routine or fault condition when making up magic numbers like this. A little Googling turned up one hit for dHsg in the proper context, the name of a function in a Google Book search for "Using Visual C++ 6" By Kate Gregory. Unfortunately that alone was not helpful.
A true C++ exception thrown from Microsoft's runtime will have an SEH code of 0xe06d7363 (E0 + 'msc'). You have some other exception. .NET generates SEH exceptions with the code 0xe0434f4d (E0 + 'COM'). NT's status codes are documented in ntstatus.h, and generally start 0x80 (warnings) or 0xC0 (errors). The most famous is 0xC0000005, STATUS\_ACCESS\_VIOLATION.
C++ Exception code lookup
[ "", "c++", "exception", "visual-c++", "crash", "memory-dump", "" ]
I have a old website that generate its own RSS everytime a new post is created. Everything worked when I was on a server with PHP 4 but now that the host change to PHP 5, I always have a "bad formed XML". I was using xml\_parser\_create() and xml\_parse(...) and fwrite(..) to save everything. Here is the example when saving (I read before save to append old RSS line of course). ``` function SaveXml() { if (!is_file($this->getFileName())) { //Création du fichier $file_handler = fopen($this->getFileName(),"w"); fwrite($file_handler,""); fclose($file_handler); }//Fin du if //Header xml version="1.0" encoding="utf-8" $strFileData = '<?xml version="1.0" encoding="iso-8859-1" ?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>'.$this->getProjectName().'</title><link>http://www.mywebsite.com</link><description>My description</description><lastBuildDate>' . date("r"). '</lastBuildDate>'; //Data reset($this->arrData); foreach($this->arrData as $i => $value) { $strFileData .= '<item>'; $strFileData .= '<title>'. $this->GetNews($i,0) . '</title>'; $strFileData .= '<pubDate>'. $this->GetNews($i,1) . '</pubDate>'; $strFileData .= '<dc:creator>'. $this->GetNews($i,2) . '</dc:creator>'; $strFileData .= '<description><![CDATA['. $this->GetNews($i,3) . ']]> </description>'; $strFileData .= '<link><![CDATA['. $this->GetNews($i,4) . ']]></link>'; $strFileData .= '<guid>'. $this->GetNews($i,4) . '</guid>'; //$strFileData .= '<category>'. $this->GetNews($i,5) . '</category>'; $strFileData .= '<category>Mycategory</category>'; $strFileData .= '</item>'; }//Fin du for i $strFileData .= '</channel></rss>'; if (file_exists($this->getFileName()))//Détruit le fichier unlink($this->getFileName()); $file_handler = fopen($this->getFileName(),"w"); fwrite($file_handler,$strFileData); fclose($file_handler); }//Fin de SaveXml ``` My question is : how do you create and fill up your RSS in PHP?
At swcombine.com we use [Feedcreator](http://feedcreator.org/). Use that one and your problem will be gone. :) Here is the PHP code to use it once installed: ``` function feed_simnews() { $objRSS = new UniversalFeedCreator(); $objRSS->title = 'My News'; $objRSS->link = 'http://link.to/news.php'; $objRSS->description = 'daily news from me'; $objRSS->xsl = 'http://link.to/feeds/feedxsl.xsl'; $objRSS->language = 'en'; $objRSS->copyright = 'Copyright: Mine!'; $objRSS->webmaster = 'webmaster@somewhere.com'; $objRSS->syndicationURL = 'http://link.to/news/simnews.php'; $objRSS->ttl = 180; $objImage = new FeedImage(); $objImage->title = 'my logo'; $objImage->url = 'http://link.to/feeds/logo.jpg'; $objImage->link = 'http://link.to'; $objImage->description = 'Feed provided by link.to. Click to visit.'; $objImage->width = 120; $objImage->height = 60; $objRSS->image = $objImage; //Function retrieving an array of your news from date start to last week $colNews = getYourNews(array('start_date' => 'Last week')); foreach($colNews as $p) { $objItem = new FeedItem(); $objItem->title = $p->title; $objItem->description = $p->body; $objItem->link = $p->link; $objItem->date = $p->date; $objItem->author = $p->author; $objItem->guid = $p->guid; $objRSS->addItem($objItem); } $objRSS->saveFeed('RSS2.0', 'http://link.to/feeds/news.xml', false); }; ``` Quite KISS. :)
I would use [simpleXML](http://www.php.net/simplexml) to create the required structure and export the XML. Then I'd cache it to disk with file\_put\_contents().
PHP - RSS builder
[ "", "php", "rss", "" ]
What SQL can be used to list the tables, and the rows within those tables in an SQLite database file – once I have attached it with the `ATTACH` command on the `sqlite3` command line tool?
The `.tables`, and `.schema` "helper" functions don't look into ATTACHed databases: they just query the `SQLITE_MASTER` table for the "main" database. Consequently, if you used ``` ATTACH some_file.db AS my_db; ``` then you need to do ``` SELECT name FROM my_db.sqlite_master WHERE type='table'; ``` Note that temporary tables don't show up with `.tables` either: you have to list `sqlite_temp_master` for that: ``` SELECT name FROM sqlite_temp_master WHERE type='table'; ```
There are a few steps to see the tables in an SQLite database: 1. List the tables in your database: ``` .tables ``` 2. List how the table looks: ``` .schema tablename ``` 3. Print the entire table: ``` SELECT * FROM tablename; ``` 4. List all of the available SQLite prompt commands: ``` .help ```
How can I list the tables in a SQLite database file that was opened with ATTACH?
[ "", "sql", "sqlite", "database-schema", "" ]
Lets say I have a Dictionary object: ``` Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>(); ``` Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A *foreach* is easy: ``` foreach (SomeObject object in myDictionary.Values) { // Do stuff to object } ``` But how can I perform this in reverse?
I'd use a SortedList instead of a dictionary. You can still access it by Key, but you can access it by index as well. ``` SortedList sCol = new SortedList(); sCol.Add("bee", "Some extended string matching bee"); sCol.Add("ay", "value matching ay"); sCol.Add("cee", "Just a standard cee"); // Go through it backwards. for (int i = sCol.Count - 1; i >=0 ; i--) Console.WriteLine("sCol[" + i.ToString() + "] = " + sCol.GetByIndex(i)); // Reference By Key foreach (string i in sCol.Keys) Console.WriteLine("sCol[" + i + "] = " + sCol[i]); // Enumerate all values foreach (string i in sCol.Values) Console.WriteLine(i); ``` It's worth noting that a sorted list stores key/value pairs sorted by key only.
A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :)
In C# .NET 2.0, what's an easy way to do a foreach in reverse?
[ "", "c#", ".net", "collections", "iteration", "" ]
Which is better? Or use and OR mapper with SP's? If you have a system with SP's already, is an OR mapper worth it?
I like ORM's because you don't have to reinvent the wheel. That being said, it completely depends on your application needs, development style and that of the team. This question has already been covered [Why is parameterized SQL generated by NHibernate just as fast as a stored procedure?](https://stackoverflow.com/questions/50346/why-is-parameterized-sql-generated-by-nhibernate-just-as-fast-as-a-stored-proce)
There is nothing good to be said about stored procedures. There were a necessity 10 years ago but every single benefit of using sprocs is no longer valid. The two most common arguments are regarding security and performance. The "sending stuff over the wire" crap doesn't hold either, I can certainly create a query dynamically to do everything on the server too. One thing the sproc proponents won't tell you is that it makes updates impossible if you are using column conflict resolution on a merge publication. Only DBAs who think they are the database overlord insist on sprocs because it makes their job look more impressive than it really is.
Stored procedures or OR mappers?
[ "", "sql", "stored-procedures", "" ]
The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says: **The node to be removed is not a child of this node.** Does anyone know the proper way to do this? ``` public void DeleteProject (string projectName) { string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"]; XmlDocument configDoc = new XmlDocument(); configDoc.Load(ccConfigPath); XmlNodeList projectNodes = configDoc.GetElementsByTagName("project"); for (int i = 0; i < projectNodes.Count; i++) { if (projectNodes[i].Attributes["name"] != null) { if (projectName == projectNodes[i].Attributes["name"].InnerText) { configDoc.RemoveChild(projectNodes[i]); configDoc.Save(ccConfigPath); } } } } ``` **UPDATE** Fixed. I did two things: ``` XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']"); ``` Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach. The actual fix was: ``` project.ParentNode.RemoveChild(project); ``` Thanks Pat and Chuck for this suggestion.
Instead of ``` configDoc.RemoveChild(projectNodes[i]); ``` try ``` projectNodes[i].parentNode.RemoveChild(projectNodes[i]); ```
try ``` configDoc.DocumentElement.RemoveChild(projectNodes[i]); ```
Removing nodes from an XmlDocument
[ "", "c#", ".net", "xml", "xmldocument", "" ]
I like to use static functions in C++ as a way to categorize them, like C# does. ``` Console::WriteLine("hello") ``` Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory? What about `static const`?
> but is it good or bad The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class? The use of static methods in uninstantiable classes in C# and Java *is a workaround* because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
I'm all for using static **functions**. These just make sense especially when organized into modules (`static class` in C#). However, *the moment* those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class. In a nutshell: static functions ok, static data bad.
Is using too much static bad or good?
[ "", "c++", "static", "" ]
Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS.
Have you taken a look at this: <http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/> MySQL should be pretty straight forward. Let us know what problems you're encountering...
I've been given a PHP / MySQL web site that I'm to host with IIS 7.0 on 64-bit Windows Server 2008. I'm a .NET / MSSQL developer, and am unfamiliar with either PHP or MySQL. > **[Kev](https://stackoverflow.com/users/419/kev)** wrote: > > Have you taken a look at this… I don't know if any one implementation of Win64 PHP is more authoratative or popular than another. I'm going to try following the steps in Kev's [Enable FastCGI support in IIS7.0](http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis-70/) article with file *php-5.2.5-x64-2007-11-12.zip* from [fusion-x lan](http://www.fusionxlan.com/PHPx64.php). It's "PHP Version 5.2.5 (x64)", but according to [php.net](http://www.php.net/downloads.php), the latest version is PHP 5.2.6. Oh, well. --- 1. Make sure "ISAPI Extensions" are installed in IIS (mine were). 2. Download and then unzip *php-5.2.5-x64-2007-11-12.zip* 3. Copy contents of folder *php-5.2.5 (x64)* into \*C:\php\* 4. Copy file *C:\php\php.ini-dist* into folder \*C:\Windows\* 5. Rename file *C:\Windows\php.ini-dist* as *php.ini* 6. Edit *php.ini* in Notepad. Remove leading semi-colon (;) from line: ``` ;extension=php_mysql.dll ``` 7. Save and close 8. Copy file *C:\php\ext\php\_mysql.dll* into folder \*C:\Windows\System32\* 9. Within IIS Manager's "Handler Mappings", choose "Add Script Map…" ``` Request path: *.php Executable: C:\php\php5isapi.dll Name: PHP ``` 10. Install MySQL (someone had already installed [MySQL 5.0](http://dev.mysql.com/downloads/mysql/5.0.html) for me). 11. Create file *C:\inetpub\wwwroot\test.php* as ``` <html> <head> <title>PHP Information</title> </head> <body> <?php phpInfo(); ?> </body> </html> ``` 12. Navigate to *<http://localhost/test.php>* in your web browser. You will see a page of information about PHP. --- Roadblock: [How do I get PHP to work with ADOdb and MySQL?](https://stackoverflow.com/questions/155308/how-do-i-get-php-to-work-with-adodb-and-mysql)
How do I get PHP and MySQL working on IIS 7.0?
[ "", "php", "mysql", "iis-7", "" ]
I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host. I found [bpgsql](http://barryp.org/software/bpgsql/) really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?
MySQLdb is what I have used before. If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it. Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.
I don't have any experience with <http://www.SiteGround.com> as a web host personally. This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this). Try the following CGI script to see if MySQLdb is installed. ``` #!/usr/bin/python module_name = 'MySQLdb' head = '''Content-Type: text/html %s is ''' % module_name try: __import__(module_name) print head + 'installed' except ImportError: print head + 'not installed' ```
Python and MySQL
[ "", "python", "mysql", "postgresql", "bpgsql", "" ]
I have one table "orders" with a foreing key "ProductID". I want to show the orders in a grid with the **product name**, without **LazyLoad** for better performance, but I if use **DataLoadOptions** it retrieves **all** Product fields, which seams like a **overkill**. Is there a way to retrieve **only** the Product name in the first query? Can I set some attribute in the DBML? In this [table](http://visualstudiomagazine.com/listings/list.aspx?id=566) says that "Foreign-key values" are "Visible" in Linq To SQL, but don't know what this means. **Edit**: Changed the title, because I'm not really sure the there is no solution. Can't believe no one has the same problem, it is a very common scenario.
I get the solution in this other question [Which .net ORM can deal with this scenario](https://stackoverflow.com/questions/381049/which-net-orm-can-deal-with-this-scenario#381084), that is related to the **liammclennan** answer but more clear (maybe the question was more clear too)
What you are asking for is a level of optimisation the linq-to-sql does not provide. I think your best bet is to create a query that returns exactly the data you want, possibly as an anonymous type: ``` from order in DB.GetTable<Orders>() join product in DB.GetTable<Products>() on order.ProductID = product.ID select new { ID = order.ID, Name = order.Name, ProductName = product.Name }; ```
Linq To SQL: Can I eager load only one field in a joined table?
[ "", ".net", "sql", "performance", "linq-to-sql", "" ]
When I try to `print` a string in a Windows console, sometimes I get an error that says `UnicodeEncodeError: 'charmap' codec can't encode character ....`. I assume this is because the Windows console cannot handle all Unicode characters. How can I work around this? For example, how can I make the program display a replacement character (such as `?`) instead of failing?
**Note:** This answer is sort of outdated (from 2008). Please use the solution below with care!! --- Here is a page that details the problem and a solution (search the page for the text *Wrapping sys.stdout into an instance*): [PrintFails - Python Wiki](http://wiki.python.org/moin/PrintFails) Here's a code excerpt from that page: ``` $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 <type 'unicode'> 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None <type 'unicode'> 2 Б Б ``` There's some more information on that page, well worth a read.
**Update:** [Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html#pep-528-change-windows-console-encoding-to-utf-8) implements [PEP 528: Change Windows console encoding to UTF-8](https://www.python.org/dev/peps/pep-0528/): *the default console on Windows will now accept all Unicode characters.* Internally, it uses the same Unicode API as [the `win-unicode-console` package mentioned below](https://github.com/Drekin/win-unicode-console). `print(unicode_string)` should just work now. --- > I get a `UnicodeEncodeError: 'charmap' codec can't encode character...` error. The error means that Unicode characters that you are trying to print can't be represented using the current (`chcp`) console character encoding. The codepage is often 8-bit encoding such as `cp437` that can represent only ~0x100 characters from ~1M Unicode characters: ``` >>> u"\N{EURO SIGN}".encode('cp437') Traceback (most recent call last): ... UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in position 0: character maps to ``` > I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Windows console does accept Unicode characters and it can even display them (BMP only) **if the corresponding font is configured**. `WriteConsoleW()` API should be used as suggested in [@Daira Hopwood's answer](https://stackoverflow.com/a/4637795/4279). It can be called transparently i.e., you don't need to and should not modify your scripts if you use [`win-unicode-console` package](https://github.com/Drekin/win-unicode-console): ``` T:\> py -m pip install win-unicode-console T:\> py -m run your_script.py ``` See [What's the deal with Python 3.4, Unicode, different languages and Windows?](https://stackoverflow.com/a/30551552/4279) > Is there any way I can make Python > automatically print a `?` instead of failing in this situation? If it is enough to replace all unencodable characters with `?` in your case then you could set [`PYTHONIOENCODING` envvar](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONIOENCODING): ``` T:\> set PYTHONIOENCODING=:replace T:\> python3 -c "print(u'[\N{EURO SIGN}]')" [?] ``` In Python 3.6+, the encoding specified by `PYTHONIOENCODING` envvar is ignored for interactive console buffers unless `PYTHONLEGACYWINDOWSIOENCODING` envvar is set to a non-empty string.
Python, Unicode, and the Windows console
[ "", "python", "unicode", "" ]
I'm new to MVC (and ASP.Net routing). I'm trying to map `*.aspx` to a controller called `PageController`. ``` routes.MapRoute( "Page", "{name}.aspx", new { controller = "Page", action = "Index", id = "" } ); ``` Wouldn't the code above map \*.aspx to `PageController`? When I run this and type in any .aspx page I get the following error: > The controller for path '/Page.aspx' could not be found or it does not implement the IController interface. > Parameter name: controllerType Is there something I'm not doing here?
> I just answered my own question. I had > the routes backwards (Default was > above page). Yeah, you have to put all custom routes above the Default route. > So this brings up the next question... > how does the "Default" route match (I > assume they use regular expressions > here) the "Page" route? The Default route matches based on what we call Convention over Configuration. Scott Guthrie explains it well in his first blog post on ASP.NET MVC. I recommend that you read through it and also his other posts. Keep in mind that these were posted based on the first CTP and the framework has changed. You can also find web cast on ASP.NET MVC on the asp.net site by Scott Hanselman. * <http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx> * <http://www.asp.net/MVC/>
I just answered my own question. I had the routes backwards (Default was above page). Below is the correct order. So this brings up the next question... how does the "Default" route match (I assume they use regular expressions here) the "Page" route? ``` routes.MapRoute( "Page", "{Name}.aspx", new { controller = "Page", action = "Display", id = "" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); ```
ASP.Net MVC route mapping
[ "", "c#", "asp.net", "asp.net-mvc", "routes", "" ]
How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP? This is somewhat easy in .NET if you know your way around. But how do you do it in Java?
Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did: ``` import java.io.*; import java.util.*; public class ExecTest { public static void main(String[] args) throws IOException { Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com"); BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream())); String thisLine = output.readLine(); StringTokenizer st = new StringTokenizer(thisLine); st.nextToken(); String gateway = st.nextToken(); System.out.printf("The gateway is %s\n", gateway); } } ``` This presumes that the gateway is the second token and not the third. If it is, you need to add an extra `st.nextToken();` to advance the tokenizer one more spot.
On Windows, OSX, Linux, etc then Chris Bunch's answer can be much improved by using ``` netstat -rn ``` in place of a `traceroute` command. Your gateway's IP address will appear in the second field of the line that starts either `default` or `0.0.0.0`. This gets around a number of problems with trying to use `traceroute`: 1. on Windows `traceroute` is actually `tracert.exe`, so there's no need for O/S dependencies in the code 2. it's a quick command to run - it gets information from the O/S, not from the network 3. `traceroute` is sometimes blocked by the network The only downside is that it will be necessary to keep reading lines from the `netstat` output until the right line is found, since there'll be more than one line of output. **EDIT:** The Default Gateway's IP Address is in the second field of the line that starts with 'default' if you are on a MAC (tested on Lion), or in the **third field** of the line that starts with '0.0.0.0' (tested on Windows 7) Windows: > > Network Destination Netmask Gateway Interface Metric > > > > 0.0.0.0 0.0.0.0 **192.168.2.254** 192.168.2.46 10 Mac: > > Destination Gateway Flags Refs Use Netif Expire > > > > default **192.168.2.254** UGSc 104 4 en1
How can I determine the IP of my router/gateway in Java?
[ "", "java", "sockets", "ip", "router", "" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these groups separately. I've reviewed [the documentation](https://docs.python.org/3/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
**IMPORTANT NOTE:** You *may* have to **sort your data** first. --- The part I didn't get is that in the example construction ``` groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) ``` `k` is the current grouping key, and `g` is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the `groupby` iterator itself returns iterators. Here's an example of that, using clearer variable names: ``` from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print("A %s is a %s." % (thing[1], key)) print("") ``` This will give you the output: > A bear is a animal. > A duck is a animal. > > A cactus is a plant. > > A speed boat is a vehicle. > A school bus is a vehicle. In this example, `things` is a list of tuples where the first item in each tuple is the group the second item belongs to. The `groupby()` function takes two arguments: (1) the data to group and (2) the function to group it with. Here, `lambda x: x[0]` tells `groupby()` to use the first item in each tuple as the grouping key. In the above `for` statement, `groupby` returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group. Here's a slightly different example with the same data, using a list comprehension: ``` for key, group in groupby(things, lambda x: x[0]): listOfThings = " and ".join([thing[1] for thing in group]) print(key + "s: " + listOfThings + ".") ``` This will give you the output: > animals: bear and duck. > plants: cactus. > vehicles: speed boat and school bus.
`itertools.groupby` is a tool for grouping items. From [the docs](https://docs.python.org/3/library/itertools.html#itertools.groupby), we glean further what it might do: > `# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B` > > `# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D` `groupby` objects yield key-group pairs where the group is a generator. Features * A. Group consecutive items together * B. Group all occurrences of an item, given a sorted iterable * C. Specify how to group items with a *key function* \* Comparisons ``` # Define a printer for comparing outputs >>> def print_groupby(iterable, keyfunc=None): ... for k, g in it.groupby(iterable, keyfunc): ... print("key: '{}'--> group: {}".format(k, list(g))) ``` ``` # Feature A: group consecutive occurrences >>> print_groupby("BCAACACAADBBB") key: 'B'--> group: ['B'] key: 'C'--> group: ['C'] key: 'A'--> group: ['A', 'A'] key: 'C'--> group: ['C'] key: 'A'--> group: ['A'] key: 'C'--> group: ['C'] key: 'A'--> group: ['A', 'A'] key: 'D'--> group: ['D'] key: 'B'--> group: ['B', 'B', 'B'] # Feature B: group all occurrences >>> print_groupby(sorted("BCAACACAADBBB")) key: 'A'--> group: ['A', 'A', 'A', 'A', 'A'] key: 'B'--> group: ['B', 'B', 'B', 'B'] key: 'C'--> group: ['C', 'C', 'C'] key: 'D'--> group: ['D'] # Feature C: group by a key function >>> # islower = lambda s: s.islower() # equivalent >>> def islower(s): ... """Return True if a string is lowercase, else False.""" ... return s.islower() >>> print_groupby(sorted("bCAaCacAADBbB"), keyfunc=islower) key: 'False'--> group: ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'] key: 'True'--> group: ['a', 'a', 'b', 'b', 'c'] ``` Uses * [Anagrams](https://stackoverflow.com/questions/8181513/finding-and-grouping-anagrams-by-python) ([see notebook](https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb)) * [Binning](https://stackoverflow.com/a/45991797/4531270) * [Group odd and even numbers](https://naiquevin.github.io/a-look-at-some-of-pythons-useful-itertools.html) * [Group a list by values](https://stackoverflow.com/questions/5695208/group-list-by-values) * [Remove duplicate elements](https://stackoverflow.com/questions/56796328/how-to-delete-repeat-elements-in-this-list) * [Find indices of repeated elements in an array](https://stackoverflow.com/a/44792205/4531270) * [Split an array into n-sized chunks](https://stackoverflow.com/a/42677465/4531270) * [Find corresponding elements between two lists](https://stackoverflow.com/a/41993784/4531270) * [Compression algorithm](https://youtu.be/iCrOGS1QlB8?t=27m27s) ([see notebook](https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb))/[Run Length Encoding](https://stackoverflow.com/questions/25537028/run-length-encoding-in-python-with-list-comprehension/25537050#25537050) * [Grouping letters by length, key function](https://youtu.be/iCrOGS1QlB8?t=29m11s) ([see notebook](https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb)) * [Consecutive values over a threshold](https://youtu.be/iCrOGS1QlB8?t=30m19s) ([see notebook](https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb)) * [Find ranges of numbers in a list](https://stackoverflow.com/questions/4628333/converting-a-list-of-integers-into-range-in-python) or [continuous items](https://stackoverflow.com/questions/2154249/identify-groups-of-continuous-numbers-in-a-list) (see [docs](https://docs.python.org/release/2.4.4/lib/itertools-example.html)) * [Find all related longest sequences](https://stackoverflow.com/questions/46928922/pythonic-way-to-find-all-potential-longest-sequence) * [Take consecutive sequences that meet a condition](https://stackoverflow.com/a/46752214/4531270) ([see related post](https://stackoverflow.com/a/46432991/4531270)) *Note: Several of the latter examples derive from Víctor Terrón's PyCon [(talk)](https://www.youtube.com/watch?v=iCrOGS1QlB8) [(Spanish)](https://www.youtube.com/watch?v=4ZIxcdREYVc), "Kung Fu at Dawn with Itertools". See also the `groupby` [source code](https://github.com/python/cpython/blob/6cca5c8459cc439cb050010ffa762a03859d3051/Modules/itertoolsmodule.c#L11-L375) written in C.* \* A function where all items are passed through and compared, influencing the result. Other objects with key functions include `sorted()`, `max()` and `min()`. --- Response ``` # OP: Yes, you can use `groupby`, e.g. [do_something(list(g)) for _, g in groupby(lxml_elements, criteria_func)] ```
How do I use itertools.groupby()?
[ "", "python", "python-itertools", "" ]
I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about." Example: Consider the following example... ``` Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. ``` I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. ### Update: Just got home. Here is some info to answer your questions: 1. Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out. 2. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation). 3. I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. 4. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube). Thanks everyone for your imput.
This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid. I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python, ``` def iter_arr(array): sum = 0 for i in array: if type(i) == type(list()): sum = sum + iter_arr(i) else: sum = sum + i return sum ``` 1. Iterate over each element in array 2. If element is another array, call the function again 3. If element is not array, add it to the sum 4. Return sum You would then apply this to each element in the 'cared about' dimension. This is easier in python due to duck-typing though ...
@Jeff I actually think this is an interesting question. I'm not sure how useful it is, but it is a valid question. @Ed Can you provide a little more info on this question? You said the dimension of the array is dynamic, but is the number of elements dynamic as well? EDIT: I'm going to try and answer the question anyways. I can't give you the code off the top of my head (it would take a while to get it right without any compiler here on this PC), but I can point you in the right direction ... Let's use 8 dimensions (0-7) with indexes 0 to 3 as an example. You care about only 1,2 and 6. This means you have two arrays. First, `array_care[4][4][4]` for 1,2, and 6. The `array_care[4][4][4]` will hold the end result. Next, we want to iterate in a very specific way. We have the array `input[4][4][4][4][4][4][4][4]` to parse through, and we care about dimensions 1, 2, and 6. We need to define some temporary indexes: ``` int dim[8] = {0,0,0,0,0,0,0,0}; ``` We also need to store the order in which we want to increase the indexes: ``` int increase_index_order[8] = {7,5,4,3,0,6,2,1}; int i = 0; ``` This order is important for doing what you requested. Define a termination flag: ``` bool terminate=false; ``` Now we can create our loop: ``` while (terminate) { array_care[dim[1]][dim[2]][dim[6]] += input[dim[0]][dim[1]][dim[2]][dim[3]][dim[4]][dim[5]][dim[6]][dim[7]]; while ((dim[increase_index_order[i]] = 3) && (i < 8)) { dim[increase_index_order[i]]=0; i++; } if (i < 8) { dim[increase_index_order[i]]++; i=0; } else { terminate=true; } } ``` That should work for 8 dimensions, caring about 3 dimensions. It would take a bit more time to make it dynamic, and I don't have the time. Hope this helps. I apologize, but I haven't learned the code markups yet. :(
How Does One Sum Dimensions of an Array Specified at Run-Time?
[ "", "c++", "c", "arrays", "microsoft-dynamics", "" ]
I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is: ``` cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl -DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:\src\include" -I"C:\Program Files\Microsoft Visual Studio 9.0\VC\include" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c ``` The code compiles cleanly. The link command is: ``` link -debug -nologo -machine:IX86 -verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib msvcrt.lib oldnames.lib kernel32.lib winmm.lib [snip large list of dependencies] D:\src\lib\app_main.obj -out:mymain.exe ``` The errors that I'm getting are: ``` app_main.obj : error LNK2019: unresolved external symbol "_\_declspec(dllimport) public: void __thiscall std::locale::facet::_Register(void)" (__imp_?_Register@facet@locale@std@@QAEXXZ) referenced in function "class std::ctype<char> const & __cdecl std::use_facet<class std::ctype<char> (class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype<char>::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype<char> const & __cdecl std::use_facet<class std::ctype<char> (class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype<unsigned short>::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype<unsigned short> const & __cdecl std::use_facet<class std::ctype<unsigned short> >(class std::locale const &)" (??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z) mymain.exe : fatal error LNK1120: 3 unresolved externals ``` Notice that these errors are coming from the legacy code, not my code - app\_main.obj is part of the legacy code, while mymain.c is my source. I've done some searching around, and what that I've read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I'm linking to. Since I'm dealing with legacy code, a solution has to come from my environment. It's been a long time since I've done C++ work, and even longer since I've used Visual Studio, so I'm hoping that this is just some ignorance on my part. Any ideas on how to get these resolved?
After trying to get this stuff to compile under VS 2008, I tried earlier versions of VS - 2005 worked with warnings, and 2003 just worked. I double checked the linkages and couldn't find any problems, so either I just couldn't find it, or that wasn't the problem. So to reiterate, downgrading to VS 2003 fixed it.
These are standard library references. Make sure that all libraries (including the standard library) are using the *same* linkage. E.g. you can't link statically while linking the standard lib dynamically. The same goes for the threading model used. Take special care that you and the 3rd party library use the same linkage options. This can be a real pain in the \*ss.
C++ linker unresolved external symbols
[ "", "c++", "" ]
I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the `javascript:` prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: ``` onchange="javascript: myFunction(this)" ``` and ``` onchange="myFunction(this)" ``` ?
Probably nothing in your example. My understanding is that `javascript:` is for anchor tags (in place of an actual `href`). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank `href` coupled with an `onclick` will do). For example: ``` <a href="javascript:someFunction();">Blah</a> ``` Rather than: ``` <a href="" onclick="someFunction();">Blah</a> ```
It should not be used in event handlers (though most browsers work defensively, and will not punish you). I would also argue that it should not be used in the href attribute of an anchor. If a browser supports javascript, it will use the properly defined event handler. If a browser does not, a javascript: link will appear broken. IMO, it is better to point them to a page explaining that they need to enable javascript to use that functionality, or better yet a non-javascript required version of the functionality. So, something like: ``` <a href="non-ajax.html" onclick="niftyAjax(); return false;">Ajax me</a> ``` Edit: Thought of a good reason to use javascript:. Bookmarklets. For instance, this one sends you to google reader to view the rss feeds for a page: ``` var b=document.body; if(b&&!document.xmlVersion){ void(z=document.createElement('script')); void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js'); void(b.appendChild(z)); }else{ location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href) } ``` To have a user easily add this Bookmarklet, you would format it like so: ``` <a href="javascript:var%20b=document.body;if(b&&!document.xmlVersion){void(z=document.createElement('script'));void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js');void(b.appendChild(z));}else{location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href)}">Drag this to your bookmarks, or right click and bookmark it!</a> ```
What's the purpose (if any) of "javascript:" in event handler tags?
[ "", "javascript", "" ]
I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically. For example, here's the options if sorted alphabetically: ``` Calgary Edmonton Halifax Montreal Toronto ``` What I would like the list to be is more like this: ``` **Montreal** Calgary Edmonton Halifax Toronto ``` Is there a way that I can do this using a single query? Or am I stuck running the query twice and appending the results?
``` SELECT name FROM locations ORDER BY CASE WHEN name = 'Montreal' THEN 0 ELSE 1 END, name ```
``` SELECT name FROM options ORDER BY name = "Montreal", name; ``` Note: This works with MySQL, not SQL 2000 like the OP requested.
Sort with one option forced to top of list
[ "", "sql", "sorting", "" ]
I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match. How I can replace all the URL? I guess I should be using the *exec* command, but I did not really figure how to do it. ``` function replaceURLWithHTMLLinks(text) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i; return text.replace(exp,"<a href='$1'>$1</a>"); } ```
First off, rolling your own regexp to parse URLs is a *terrible idea*. You must imagine this is a common enough problem that someone has written, debugged and [tested](http://benalman.com/code/test/js-linkify/) a library for it, according to [the RFCs](https://metacpan.org/pod/Regexp::Common::URI#REFERENCES). **URIs are complex** - check out the [code for URL parsing in Node.js](https://github.com/joyent/node/blob/master/lib/url.js) and the Wikipedia page on [URI schemes](http://en.wikipedia.org/wiki/URI_scheme). There are a ton of edge cases when it comes to parsing URLs: [international domain names](http://en.wikipedia.org/wiki/Top-level_domain#IDN_test_domains), actual (`.museum`) vs. nonexistent (`.etc`) TLDs, weird punctuation including [parentheses](http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html), punctuation at the end of the URL, IPV6 hostnames etc. I've looked at [a ton](https://github.com/search?l=JavaScript&q=linkify&ref=cmdform&search_target=global&type=Repositories) of [libraries](https://github.com/search?l=JavaScript&q=autolink&ref=cmdform&search_target=global&type=Repositories), and there are a few worth using despite some downsides: * Soapbox's [linkify](http://soapbox.github.io/jQuery-linkify/) has seen some serious effort put into it, and [a major refactor in June 2015](https://github.com/SoapBox/jQuery-linkify/pull/51) [removed the jQuery dependency](https://github.com/SoapBox/jQuery-linkify/issues/56). It still has [issues with IDNs](https://github.com/SoapBox/linkifyjs/issues/92). * [AnchorMe](http://alexcorvi.github.io/anchorme.js/) is a newcomer that [claims to be faster](https://github.com/ali-saleem/anchorme.js/issues/2) and leaner. Some [IDN issues](https://github.com/ali-saleem/anchorme.js/issues/1) as well. * [Autolinker.js](https://github.com/gregjacobs/Autolinker.js) lists features very specifically (e.g. *"Will properly handle HTML input. The utility will not change the `href` attribute inside anchor () tags"*). I'll thrown some tests at it when a [demo becomes available](https://github.com/gregjacobs/Autolinker.js/issues/138). Libraries that I've disqualified quickly for this task: * Django's urlize [didn't handle certain TLDs properly](https://github.com/ljosa/urlize.js/pull/18) (here is the official [list of valid TLDs](http://data.iana.org/TLD/tlds-alpha-by-domain.txt). [No demo](https://github.com/ljosa/urlize.js/issues/21). * [autolink-js](https://github.com/bryanwoods/autolink-js/issues/12) wouldn't detect "www.google.com" without http://, so it's not quite suitable for autolinking "casual URLs" (without a scheme/protocol) found in plain text. * [Ben Alman's linkify](https://github.com/cowboy/javascript-linkify) hasn't been maintained since 2009. If you insist on a regular expression, the most comprehensive is the [URL regexp from Component](https://github.com/component/regexps/blob/master/index.js#L3), though it will falsely detect some non-existent two-letter TLDs by looking at it.
### Replacing URLs with links (Answer to the General Problem) The regular expression in the question misses *a lot* of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like `.museum`, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood's blog post *[The Problem With URLs](http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html)* for an explanation of some of the other issues. > The **best summary of URL matching libraries** is in **[Dan Dascalescu's Answer ![+100](https://i.stack.imgur.com/AhNsx.png)](https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links#21925491)** > (as of Feb 2014) --- ### "Make a regular expression replace more than one match" (Answer to the specific problem) Add a "g" to the end of the regular expression to enable global matching: ``` /ig; ``` But that only fixes the problem in the question where the regular expression was only replacing the first match. *Do not use that code.*
How to replace plain URLs with links?
[ "", "javascript", "regex", "" ]
I build up an array of strings with ``` string[] parts = string.spilt(" "); ``` And get an array with X parts in it, I would like to get a copy of the array of strings starting at element ``` parts[x-2] ``` Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?
How about Array.Copy? <http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx> > Array.Copy Method (Array, Int32, Array, Int32, Int32) > > Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.
I remembered answering this question and just learned about a new object that may provide a high performance method of doing what you want. Take a look at [`ArraySegment<T>`](http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx). It will let you do something like. ``` string[] parts = myString.spilt(" "); int idx = parts.Length - 2; var stringView = new ArraySegment<string>(parts, idx, parts.Length - idx); ```
Pass reference to element in C# Array
[ "", "c#", "arrays", "" ]
What's the best way to allow a user to browse for a file in C#?
``` using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Select a file"; if (dlg.ShowDialog()== DialogResult.OK) { //do something with dlg.FileName } } ```
I would say use the standard "Open File" dialog box ([OpenFileDialog](http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx)), this makes it less intimidating for new users and helps with a consistant UI.
What's the best way to allow a user to browse for a file in C#?
[ "", "c#", "" ]
SQL: ``` SELECT u.id, u.name, isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault FROM universe u LEFT JOIN history h ON u.id=h.id AND h.dateCol<GETDATE()-1 GROUP BY u.Id, u.name ```
A solution, albeit one that defers handling of the null value to the code, could be: > DateTime yesterday = DateTime.Now.Date.AddDays(-1); ``` var collection= from u in db.Universe select new { u.id, u.name, MaxDate =(DateTime?) ( from h in db.History where u.Id == h.Id && h.dateCol < yesterday select h.dateCol ).Max() }; ``` This does not produce exactly the same SQL, but does provide the same logical result. Translating "complex" SQL queries to LINQ is not always straightforward.
``` var collection= from u in db.Universe select new { u.id, u.name, MaxDate =(DateTime?) ( from h in db.History where u.Id == h.Id && h.dateCol < yesterday select h.dateCol ).Max() }; ``` Just youse the above code and this should work fine!
How do I most elegantly express left join with aggregate SQL as LINQ query
[ "", "c#", "linq", "left-join", "" ]
I was curious about how other people use the **this** keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples: In a constructor: ``` public Light(Vector v) { this.dir = new Vector(v); } ``` Elsewhere ``` public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); } ```
There are several usages of [this](http://msdn.microsoft.com/en-us/library/dk1507sz.aspx) keyword in C#. 1. [To qualify members hidden by similar name](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx) 2. [To have an object pass itself as a parameter to other methods](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx) 3. To have an object return itself from a method 4. [To declare indexers](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx) 5. [To declare extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx) 6. [To pass parameters between constructors](http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C%29) 7. [To internally reassign value type (struct) value](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/1800162#1800162). 8. To invoke an extension method on the current instance 9. To cast itself to another type 10. [To chain constructors defined in the same class](https://stackoverflow.com/questions/1814953/c-sharp-constructor-chaining-how-to-do-it) You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using [auto-implemented properties](https://msdn.microsoft.com/en-us/library/bb384054.aspx).
I don't mean this to sound snarky, but it doesn't matter. Seriously. Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office. It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something. I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.
When do you use the "this" keyword?
[ "", "c#", "coding-style", "this", "" ]
Suppose I have the following CSS rule in my page: ``` body { font-family: Calibri, Trebuchet MS, Helvetica, sans-serif; } ``` How could I detect which one of the defined fonts were used in the user's browser? For people wondering why I want to do this is because the font I'm detecting contains glyphs that are *not* available in other fonts. If the user does *not* have the font, then I want it to display a link asking the user to download that font (so they can use my web application with the correct font). Currently, I am displaying the download font link for all users. I want to only display this for people who do *not* have the correct font installed.
I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present. This won't work for monospaced fonts. Here's where it came from: [Javascript/CSS Font Detector (ajaxian.com; 12 Mar 2007)](https://web.archive.org/web/20090303050802/http://ajaxian.com/archives/javascriptcss-font-detector)
I wrote a simple JavaScript tool that you can use it to check if a font is installed or not. It uses simple technique and should be correct most of the time. **[jFont Checker](https://github.com/derek1906/jFont-Checker/)** on github
How to detect which one of the defined font was used in a web page?
[ "", "javascript", "html", "css", "fonts", "" ]
Are PHP variables passed by value or by reference?
It's by value according to the [PHP Documentation](http://php.net/manual/en/functions.arguments.php). > By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. > > To have an argument to a function always passed by reference, prepend an ampersand (**&**) to the argument name in the function definition. ``` <?php function add_some_extra(&$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.' ?> ```
In PHP, by default, objects are passed as reference to a new object. See this example: ``` class X { var $abc = 10; } class Y { var $abc = 20; function changeValue($obj) { $obj->abc = 30; } } $x = new X(); $y = new Y(); echo $x->abc; //outputs 10 $y->changeValue($x); echo $x->abc; //outputs 30 ``` Now see this: ``` class X { var $abc = 10; } class Y { var $abc = 20; function changeValue($obj) { $obj = new Y(); } } $x = new X(); $y = new Y(); echo $x->abc; //outputs 10 $y->changeValue($x); echo $x->abc; //outputs 10 not 20 same as java does. ``` Now see this: ``` class X { var $abc = 10; } class Y { var $abc = 20; function changeValue(&$obj) { $obj = new Y(); } } $x = new X(); $y = new Y(); echo $x->abc; //outputs 10 $y->changeValue($x); echo $x->abc; //outputs 20 not possible in java. ``` I hope you can understand this.
Are PHP Variables passed by value or by reference?
[ "", "php", "variables", "pass-by-reference", "pass-by-value", "" ]
How do you debug **PHP** scripts? I am aware of basic debugging such as using the Error Reporting. The breakpoint debugging in **PHPEclipse** is also quite useful. What is the **best** (in terms of fast and easy) way to debug in phpStorm or any other IDE?
Try [Eclipse PDT](https://eclipse.org/pdt/) to setup an Eclipse environment that has debugging features like you mentioned. The ability to step into the code is a much better way to debug then the old method of var\_dump and print at various points to see where your flow goes wrong. When all else fails though and all I have is SSH and vim I still `var_dump()`/`die()` to find where the code goes south.
You can use Firephp an add-on to firebug to debug php in the same environment as javascript. I also use [Xdebug](http://xdebug.org/) mentioned earlier for profiling php.
How do you debug PHP scripts?
[ "", "php", "eclipse", "debugging", "phpstorm", "xdebug", "" ]
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: ``` >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } ``` **NOTE:** It should not include methods. Only fields.
Note that best practice in Python 2.7 is to use *[new-style](https://www.python.org/doc/newstyle/)* classes (not needed with Python 3), i.e. ``` class Foo(object): ... ``` Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary *object*, it's sufficient to use `__dict__`. Usually, you'll declare your methods at class level and your attributes at instance level, so `__dict__` should be fine. For example: ``` >>> class A(object): ... def __init__(self): ... self.b = 1 ... self.c = 2 ... def do_nothing(self): ... pass ... >>> a = A() >>> a.__dict__ {'c': 2, 'b': 1} ``` A better approach (suggested by [robert](https://stackoverflow.com/users/409638/robert) in comments) is the builtin [`vars`](https://docs.python.org/3/library/functions.html#vars) function: ``` >>> vars(a) {'c': 2, 'b': 1} ``` Alternatively, depending on what you want to do, it might be nice to inherit from `dict`. Then your class is *already* a dictionary, and if you want you can override `getattr` and/or `setattr` to call through and set the dict. For example: ``` class Foo(dict): def __init__(self): pass def __getattr__(self, attr): return self[attr] # etc... ```
Instead of `x.__dict__`, it's actually more pythonic to use `vars(x)`.
Python dictionary from an object's fields
[ "", "python", "dictionary", "attributes", "object", "metaprogramming", "" ]
Is it possible in c# to initialize an array in, for example, subindex 1? I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes. As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done. But, I was wondering if it was possible to create a new non-zero based array
You can use [`Array.CreateInstance`](http://msdn.microsoft.com/en-us/library/system.array.createinstance%28v=vs.110%29.aspx). See [Array Types in .NET](http://msdn.microsoft.com/en-us/magazine/cc301755.aspx)
It is possible to do as you request see the code below. ``` // Construct an array containing ints that has a length of 10 and a lower bound of 1 Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 }); // insert 1 into position 1 lowerBoundArray.SetValue(1, 1); //insert 2 into position 2 lowerBoundArray.SetValue(2, 2); // IndexOutOfRangeException the lower bound of the array // is 1 and we are attempting to write into 0 lowerBoundArray.SetValue(1, 0); ```
Initializing an array on arbitrary starting index in c#
[ "", "c#", "arrays", "interop", "ms-office", "initialization", "" ]
I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address. Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed. Here's a screenshot of it currently. ![ISO Address](https://i.stack.imgur.com/XK48E.png) Any ideas? --- @Chris A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space. I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no. I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot). It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it. Though if someone comes up with another way to approach the problem I'm open to that too. --- I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed. ``` resizeIt = function() { var str = $('iso_address').value; var cols = $('iso_address').cols; var linecount = 0; $A(str.split("\n")).each(function(l) { linecount += 1 + Math.floor(l.length / cols); // Take into account long lines }) $('iso_address').rows = linecount; }; ```
Facebook does it, when you write on people's walls, but only resizes vertically. Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice. None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'. Some JavaScript code to do it, using [Prototype](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) (because that's what I'm familiar with): ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.google.com/jsapi"></script> <script language="javascript"> google.load('prototype', '1.6.0.2'); </script> </head> <body> <textarea id="text-area" rows="1" cols="50"></textarea> <script type="text/javascript" language="javascript"> resizeIt = function() { var str = $('text-area').value; var cols = $('text-area').cols; var linecount = 0; $A(str.split("\n")).each( function(l) { linecount += Math.ceil( l.length / cols ); // Take into account long lines }) $('text-area').rows = linecount + 1; }; // You could attach to keyUp, etc. if keydown doesn't work Event.observe('text-area', 'keydown', resizeIt ); resizeIt(); //Initial on load </script> </body> </html> ``` PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea.
One refinement to some of these answers is to let CSS do more of the work. The basic route seems to be: 1. Create a container element to hold the `textarea` and a hidden `div` 2. Using Javascript, keep the `textarea`’s contents synced with the `div`’s 3. Let the browser do the work of calculating the height of that div 4. Because the browser handles rendering / sizing the hidden `div`, we avoid explicitly setting the `textarea`’s height. ``` document.addEventListener('DOMContentLoaded', () => { textArea.addEventListener('change', autosize, false) textArea.addEventListener('keydown', autosize, false) textArea.addEventListener('keyup', autosize, false) autosize() }, false) function autosize() { // Copy textarea contents to div browser will calculate correct height // of copy, which will make overall container taller, which will make // textarea taller. textCopy.innerHTML = textArea.value.replace(/\n/g, '<br/>') } ``` ``` html, body, textarea { font-family: sans-serif; font-size: 14px; } .textarea-container { position: relative; } .textarea-container > div, .textarea-container > textarea { word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */ box-sizing: border-box; padding: 2px; width: 100%; } .textarea-container > textarea { overflow: hidden; position: absolute; height: 100%; } .textarea-container > div { padding-bottom: 1.5em; /* A bit more than one additional line of text. */ visibility: hidden; } ``` ``` <div class="textarea-container"> <textarea id="textArea"></textarea> <div id="textCopy"></div> </div> ```
How to autosize a textarea using Prototype?
[ "", "javascript", "html", "css", "textarea", "prototypejs", "" ]
[Resharper](http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html) certainly thinks so, and out of the box it will nag you to convert ``` Dooberry dooberry = new Dooberry(); ``` to ``` var dooberry = new Dooberry(); ``` Is that really considered the best style?
It's of course a matter of style, but I agree with Dare: [C# 3.0 Implicit Type Declarations: To var or not to var?](http://www.25hoursaday.com/weblog/2008/05/21/C30ImplicitTypeDeclarationsToVarOrNotToVar.aspx). I think using var instead of an explicit type makes your code less readable.In the following code: ``` var result = GetUserID(); ``` What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples. Jeff wrote a post on this, saying [he favors var](http://blog.codinghorror.com/department-of-declaration-redundancy-department/). But that guy's crazy! I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.
I use it only when it's clearly obvious what var is. clear to me: ``` XmlNodeList itemList = rssNode.SelectNodes("item"); var rssItems = new RssItem[itemList.Count]; ``` not clear to me: ``` var itemList = rssNode.SelectNodes("item"); var rssItems = new RssItem[itemList.Count]; ```
Should I *always* favour implictly typed local variables in C# 3.0?
[ "", "c#", "styles", "resharper", "" ]
I have defined a Java function: ``` static <T> List<T> createEmptyList() { return new ArrayList<T>(); } ``` One way to call it is like so: ``` List<Integer> myList = createEmptyList(); // Compiles ``` Why can't I call it by explicitly passing the generic type argument? : ``` Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why? ``` I get the error `Illegal start of expression` from the compiler.
When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method(); ``` Object list = Collections.<String> emptyList(); ```
You can, if you pass in the type as a method parameter. ``` static <T> List<T> createEmptyList( Class<T> type ) { return new ArrayList<T>(); } @Test public void createStringList() { List<String> stringList = createEmptyList( String.class ); } ``` Methods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument. For a truly excellent FAQ on Java generics, [see Angelika Langer's generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html). . . **Follow-up:** It wouldn't make sense in this context to use the array argument as in `Collection.toArray( T[] )`. The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time. However, for the purposes of education, if you did want to use the array typing, the syntax is very similar: ``` static <T> List<T> createEmptyList( T[] array ) { return new ArrayList<T>(); } @Test public void testThing() { List<Integer> integerList = createEmptyList( new Integer[ 1 ] ); } ```
Why can't I explicitly pass the type argument to a generic Java method?
[ "", "java", "generics", "syntax", "" ]
I get a URL from a user. I need to know: a) is the URL a valid RSS feed? b) if not is there a valid feed associated with that URL using PHP/Javascript or something similar (Ex. <http://techcrunch.com> fails a), but b) would return their RSS feed)
Found something that I wanted: Google's [AJAX Feed API](http://code.google.com/apis/ajaxfeeds/) has a load feed and lookup feed function (Docs [here](http://code.google.com/apis/ajaxfeeds/documentation/reference.html#_intro_fonje)). a) [Load feed](http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www.digg.com/rss/index.xml) provides the feed (and feed status) in JSON b) [Lookup feed](http://ajax.googleapis.com/ajax/services/feed/lookup?v=1.0&q=http://www.techcrunch.com) provides the RSS feed for a given URL Theres also a find feed function that searches for RSS feeds based on a keyword. Planning to use this with JQuery's $.getJSON
The [Zend Feed class](http://framework.zend.com/manual/en/zend.feed.findFeeds.html) of the **Zend-framework** can automatically parse a webpage and list the available feeds. Example: ``` $feedArray = Zend_Feed::findFeeds('http://www.example.com/news.html'); ```
How To Discover RSS Feeds for a given URL
[ "", "php", "rss", "feed", "atom-feed", "" ]
How much less libraries are there for Mono than for Java? I lack the overview over both alternatives but I have pretty much freedom of choice for my next project. I'm looking for hard technical facts in the areas of * performance (for example, I'm told Java is good for threading, and I hear the runtime code optimization has become very good recently for .NET) * *real world* portability (it's both meant to be portable, what's Catch-22 for each?) * tool availability ([CI](http://en.wikipedia.org/wiki/Continuous_integration), build automation, debugging, IDE) I am especially looking for what you actually experienced in your own work rather than the things I could google. My application would be a back-end service processing large amounts of data from time series. My main target platform would be Linux. **Edit:** *To phrase my question more adequately, I am interested in the whole package (3rd party libraries etc.), not just the language. For libraries, that probably boils down to the question "how much less libraries are there for Mono than for Java"?* --- FYI, I have since chosen Java for this project, because it seemed just more battle-worn on the portability side and it's been around for a while on older systems, too. I'm a tiny little bit sad about it, because I'm very curious about C# and I'd love to have done some large project in it, but maybe next time. Thanks for all the advice.
Well....Java is actually more portable. Mono isn't implemented everywhere, and it lags behind the Microsoft implementation significantly. The Java SDK seems to stay in better sync across platforms (and it works on more platforms). I'd also say Java has more tool availability across all those platforms, although there are plenty of tools available for .NET on Windows platforms. **Update for 2014** I still hold this opinion in 2014. However, I'll qualify this by saying I'm just now starting to pay some attention to Mono after a long while of not really caring, so there may be improvements in the Mono runtime (or ecosystem) that I haven't been made aware of. AFAIK, there is still no support for WPF, WCF, WF, of WIF. Mono can run on iOS, but to my knowledge, the Java runtime still runs on far more platforms than Mono. Also, Mono is starting to see some much improved tooling (Xamarin), and Microsoft seems to have a much more cross-platform kind of attitude and willingness to work with partners to make them complimentary, rather than competitive (for example, Mono will be a pretty important part of the upcoming OWIN/Helios ASP.NET landscape). I suspect that in the coming years the differences in portability will lessen rapidly, especially after .NET being open-sourced. **Update for 2018** My view on this is starting to go the other way. I think .NET, broadly, particularly with .NET Core, has started to achieve "portability parity" with Java. There are efforts underway to bring WPF to .NET Core for some platforms, and .NET Core itself runs on a great many platforms now. Mono (owned by Xamarin, which is now owned by Microsoft) is a more mature and polished product than ever, and writing applications that work on multiple platforms is no longer the domain of deep gnosis of .NET hackery, but is a relatively straightforward endeavor. There are, of course, libraries and services and applications that are Windows-only or can only target specific platforms - but the same can be said of Java (broadly). If I were in the OP's shoes at this point, I can think of no reason inherent in the languages or tech stacks themselves that would prevent me from choosing .NET for any application going forward from this point.
Mono does a better job at targeting the platforms I want to support. Other than that, it is all subjective. I share C# code across the following platforms: * iOS (iPhone/iPad) * Android * The Web (HTML5) * Mac (OS X) * Linux * Windows I could share it even more places: * Windows Phone 7 * Wii * XBox * PS3 * etc. The biggie is iOS since [MonoTouch](https://en.wikipedia.org/wiki/Mono_(software)#Xamarin.iOS) works fantastically. I do not know of any good way to target iOS with Java. You cannot target Windows Phone 7 with Java, so I would say that the days of Java being better for mobile are behind us. The biggest factor for me though is personal productivity (and happiness). C# as a language is years ahead of Java IMHO and the .NET framework is a joy to use. Most of what is being added in Java 7 and Java 8 has been in C# for years. JVM languages like Scala and Clojure (both available on the CLR) are pretty nice though. I see Mono as a platform in it's own right (a great one) and treat .NET as the Microsoft implementation of Mono on Windows. This means that I develop and test on Mono first. This works wonderfully. If both Java and .NET (Mono let's say) were Open Source projects without any corporate backing, I would choose Mono over Java every time. I believe it is just a better platform. Both .NET/Mono and the JVM are great choices, although I would personally use some other language than Java on the JVM. # My take on some of the other comments: **Issue: Performance.** \*\*Answer: Both the JVM and the CLR perform better than detractors say they do. I would say that the JVM performs better. Mono is generally slower than .NET (though not always). I personally would take ASP.NET MVC over J2EE any day both as a developer and an end-user. Support for [Google Native Client](https://www.mono-project.com/docs/about-mono/releases/2.10.0/#google-native-client-support) is pretty cool too. Also, I know that poor GUI performance for desktop Java apps is supposed to be a thing of the past but I keep finding slow ones. Then again, I could say the same for WPF. GTK# is plenty fast though so there is no reason they have to be slow. **Issue: Java has a larger ecosystem of libraries available.** **Answer: Probably true, but it is a non-issue in practice.** Practically every Java library (including the JDK) runs just dandy on .NET/Mono thanks to [IKVM.NET](https://github.com/ikvmnet/ikvm). This piece of technology is a true marvel. The integration is amazing; you can use a Java library just like it was native. I have only had to use Java libraries in one .NET app though. The .NET/Mono ecosystem generally offers more than I need. **Issue: Java has better (broader) tools support** **Answer: Not on Windows. Otherwise I agree. MonoDevelop is nice though.** I want to give a shout-out to [MonoDevelop](http://monodevelop.com/); it is a jewel. MonoDevelop integrates most of the tools I want use including code completion (intellisense), Git/Subversion integration, support for unit tests, SQL integration, debugging, easy refactoring, and assembly browsing with on-the-fly decompilation. It is wonderful to use the same environment for everything from server-side web to mobile apps. **Issue: Compatibility across platforms.** **Answer: Mono is a single code-base across all platforms, including Windows.** Develop for Mono first and deploy to .NET on Windows if you like. If you compare .NET from MS to Java though then Java has the edge in terms of consistency across platforms. See next answer... **Issue: Mono lags .NET.** **Answer: No it does not.** IMHO, this is an often stated but incorrect statement. The Mono distribution from Xamarin ships with C#, VB.NET, F#, IronPython, IronRuby, and I think maybe Boo out of the box. The Mono C# compiler is completely up to date with MS. The Mono VB.NET compiler does lag the MS version. The other compilers are the same on both platforms (as are other .NET languages like Nemerle, Boo, and Phalanger (PHP) ). Mono ships with a lot of the actual Microsoft written code including the Dynamic Language Runtime (DLR), Managed Extensibility Framework (MEF), F#, and ASP.NET MVC. Because Razor is not Open Source, Mono currently ships with MVC2 but MVC3 works on Mono just fine. The core Mono platform has kept pace with .NET or many years and the compatibility is impressive. You can use the full C# 4.0 language and even some C# 5.0 features today. In fact, Mono often leads .NET in many ways. Mono implements parts of the CLR spec that even Microsoft does not support (like 64 bit arrays). One of the most exciting new pieces of technology in the .NET world is [Roslyn](http://en.wikipedia.org/wiki/Microsoft_Roslyn). Mono has offered the C# compiler as a service for many years. Some of what Roslyn offers is available via [NRefactory](https://github.com/icsharpcode/NRefactory) as well. An example of were Mono is still ahead would be the SIMD instructions to accelerate gaming performance. Microsoft does offer a number of products on top of .NET that are not available in Mono which is were the misconception about Mono lagging comes from. Windows Presentation Foundation (WPF), Entity Framework (EF), WCF (Windows Communication Foundation) are examples of products which do not work, or are poorly supported, on Mono. The obvious solution is to use cross-platform alternatives like GTK#, NHibernate, and ServiceStack instead. **Issue: Microsoft is evil.** **Answer: True. So what.** Many people offer the following reasons to avoid using Mono: 1. You should not use Mono because Microsoft tech should be avoided 2. Mono sucks because it does not let you use every technology that Microsoft offers To me, it is clear that these statements are incompatible. I reject the first statement but will skip that argument here. The second statement is true of all .NET alternatives. The JVM is a great platform and the explosion of JVM languages is awesome. Use what makes you happy. For now, that is often .NET/Mono for me.
Is .NET/Mono or Java the better choice for cross-platform development?
[ "", "java", ".net", "linux", "mono", "cross-platform", "" ]
How can I check the existence of an element in jQuery? The current code that I have is this: ``` if ($(selector).length > 0) { // Do something } ``` Is there a more elegant way to approach this? Perhaps a plugin or a function?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers `0` means `false`, everything else `true`. So you could write: ``` if ($(selector).length) ``` You don't need that `>0` part.
Yes! ``` jQuery.fn.exists = function(){ return this.length > 0; } if ($(selector).exists()) { // Do something } ``` This is in response to: [Herding Code podcast with Jeff Atwood](http://herdingcode.com/?p=36)
Is there an "exists" function for jQuery?
[ "", "javascript", "jquery", "" ]
We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++. What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available.
We used the following: Store files in the directory returned by GetBurnPath, then write using Burn. GetCDRecordableInfo is used to check when the CD is ready. ``` #include <stdio.h> #include <imapi.h> #include <windows.h> struct MEDIAINFO { BYTE nSessions; BYTE nLastTrack; ULONG nStartAddress; ULONG nNextWritable; ULONG nFreeBlocks; }; //============================================================================== // Description: CD burning on Windows XP //============================================================================== #define CSIDL_CDBURN_AREA 0x003b SHSTDAPI_(BOOL) SHGetSpecialFolderPathA(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate); SHSTDAPI_(BOOL) SHGetSpecialFolderPathW(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate); #ifdef UNICODE #define SHGetSpecialFolderPath SHGetSpecialFolderPathW #else #define SHGetSpecialFolderPath SHGetSpecialFolderPathA #endif //============================================================================== // Interface IDiscMaster const IID IID_IDiscMaster = {0x520CCA62,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}}; const CLSID CLSID_MSDiscMasterObj = {0x520CCA63,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}}; typedef interface ICDBurn ICDBurn; // Interface ICDBurn const IID IID_ICDBurn = {0x3d73a659,0xe5d0,0x4d42,{0xaf,0xc0,0x51,0x21,0xba,0x42,0x5c,0x8d}}; const CLSID CLSID_CDBurn = {0xfbeb8a05,0xbeee,0x4442,{0x80,0x4e,0x40,0x9d,0x6c,0x45,0x15,0xe9}}; MIDL_INTERFACE("3d73a659-e5d0-4d42-afc0-5121ba425c8d") ICDBurn : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetRecorderDriveLetter( /* [size_is][out] */ LPWSTR pszDrive, /* [in] */ UINT cch) = 0; virtual HRESULT STDMETHODCALLTYPE Burn( /* [in] */ HWND hwnd) = 0; virtual HRESULT STDMETHODCALLTYPE HasRecordableDrive( /* [out] */ BOOL *pfHasRecorder) = 0; }; //============================================================================== // Description: Get burn pathname // Parameters: pathname - must be at least MAX_PATH in size // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int GetBurnPath(char *path) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { BOOL flag; if (pICDBurn->HasRecordableDrive(&flag) == S_OK) { if (SHGetSpecialFolderPath(0, path, CSIDL_CDBURN_AREA, 0)) { strcat(path, "\\"); } else { ret = 1; } } else { ret = 2; } pICDBurn->Release(); } else { ret = 3; } return ret; } //============================================================================== // Description: Get CD pathname // Parameters: pathname - must be at least 5 bytes in size // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int GetCDPath(char *path) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { BOOL flag; WCHAR drive[5]; if (pICDBurn->GetRecorderDriveLetter(drive, 4) == S_OK) { sprintf(path, "%S", drive); } else { ret = 1; } pICDBurn->Release(); } else { ret = 3; } return ret; } //============================================================================== // Description: Burn CD // Parameters: None // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int Burn(void) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { if (pICDBurn->Burn(NULL) != S_OK) { ret = 1; } pICDBurn->Release(); } else { ret = 2; } return ret; } //============================================================================== bool GetCDRecordableInfo(long *FreeSpaceSize) { bool Result = false; IDiscMaster *idm = NULL; IDiscRecorder *idr = NULL; IEnumDiscRecorders *pEnumDiscRecorders = NULL; ULONG cnt; long type; long mtype; long mflags; MEDIAINFO mi; try { CoCreateInstance(CLSID_MSDiscMasterObj, 0, CLSCTX_ALL, IID_IDiscMaster, (void**)&idm); idm->Open(); idm->EnumDiscRecorders(&pEnumDiscRecorders); pEnumDiscRecorders->Next(1, &idr, &cnt); pEnumDiscRecorders->Release(); idr->OpenExclusive(); idr->GetRecorderType(&type); idr->QueryMediaType(&mtype, &mflags); idr->QueryMediaInfo(&mi.nSessions, &mi.nLastTrack, &mi.nStartAddress, &mi.nNextWritable, &mi.nFreeBlocks); idr->Release(); idm->Close(); idm->Release(); Result = true; } catch (...) { Result = false; } if (Result == true) { Result = false; if (mtype == 0) { // No Media inserted Result = false; } else { if ((mflags & 0x04) == 0x04) { // Writable Media Result = true; } else { Result = false; } if (Result == true) { *FreeSpaceSize = (mi.nFreeBlocks * 2048); } else { *FreeSpaceSize = 0; } } } return Result; } ```
To complement the accepted answer, we added this helper function to programatically change the burn directory on the fly as this was a requirement of ours. ``` typedef HMODULE (WINAPI * SHSETFOLDERPATHA)( int , HANDLE , DWORD , LPCTSTR ); int SetBurnPath( char * cpPath ) { SHSETFOLDERPATHA pSHSetFolderPath; HANDLE hShell = LoadLibraryA( "shell32.dll" ); if( hShell == NULL ) return -2; DWORD dwOrdinal = 0x00000000 + 231; pSHSetFolderPath = (SHSETFOLDERPATHA)GetProcAddress( hShell, (LPCSTR)dwOrdinal ); if( pSHSetFolderPath == NULL ) return -3; if( pSHSetFolderPath( CSIDL_CDBURN_AREA, NULL, 0, cpPath ) == S_OK ) return 0; return -1; } ```
Windows CD Burning API
[ "", "c++", "c", "windows", "cd-burning", "" ]
My path to a 'fulltime'- developer stated as a analyst using VBA with Excel, Access, and then onto C#. I went to college part time once I discovered I had a passion for coding not business. I do about most of my coding in C#, but being an ASP.NET developer I also write in HTML, JavaScript, SQL etc. . . the usual suspects. I like to keep moving forward find the edge that will get me to the next level, the next job, and of course more money. Most importantly I just want to learning something new and challenge me. I have spent time recently learning LINQ, but was wondering what should I learn next? Something on the .NET Framework or a new language technology?
If you want to be one of the best you need to specialise. If you become very good in many skills then you may never become truly excellent in one. I know because I have taken this route myself and have found it difficult to get employment at times. After all, who wants someone who is capable at many languages when there is someone who excels at the specific thing they need. If a company develops in C# then who would want someone who is OK at C# but also is good at C, Visual Basic, Perl and Cobol, when all they really want is the best possible C# developer for the money they can afford. After all, you will only ever be employed for one, maybe two of your skills. There are very few jobs for people who are good in 10 or 15 skills. If you are looking to a new skill then maybe check out the job boards and find which skills are particularly in need, but be aware that what is the flavour of the month this year may not even be on the scene next year, which will make all of that effort to learn the skill futile and wasted. What I would say is: 1. do one thing, and do it well. This may include supporting skills (C#, ASP.Net, SQL, LINQ etc). 2. If you want to choose something else, then choose something complementary. 3. Possibly most importantly, choose something you will enjoy. Maybe Ruby on Rails is the current flavour of the month, but if you don't enjoy doing it, then don't do it. Really, it's not worth it. You will never wish, on your death bed, that you had worked more in something you didn't enjoy. Another direction you could look at is maybe not for a particular development skill, but look for something else, maybe soft skills like people management, better business understanding or even look to something like literary skills to help improve your communications skills. All of these will help to allow you to do what you want to do more, and cut down on the stuff you really don't enjoy, thus helping to make your job more enjoyable. Apologies for the waffling here. Hope you are still awake :)
Yeah, the more I get into software, I start to see myself focusing less on the language and more on the design.. Yeah there are framework bits we need to get our head around but most of the time ( *most* not all ) you can look those up as-and-when you need them.. But a good design head? That takes years of experience to start getting it working right.. And that is what the companies really pay for.. "Build it and they will come" and all that...
What should I learn to increase my skills?
[ "", "c#", ".net", "" ]
In python, you can have a function return multiple values. Here's a contrived example: ``` def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) ``` This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also"). When should you draw the line and define a different method?
Absolutely (for the example you provided). ### Tuples are first class citizens in Python There is a builtin function [`divmod()`](https://docs.python.org/3/library/functions.html#divmod) that does exactly that. ``` q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x ``` There are other examples: `zip`, `enumerate`, `dict.items`. ``` for i, e in enumerate([1, 3, 3]): print "index=%d, element=%s" % (i, e) # reverse keys and values in a dictionary d = dict((v, k) for k, v in adict.items()) # or d = dict(zip(adict.values(), adict.keys())) ``` BTW, parentheses are not necessary most of the time. Citation from [Python Library Reference](https://docs.python.org/3/library/stdtypes.html?highlight=type%20seq#tuple): > Tuples may be constructed in a number of ways: > > * Using a pair of parentheses to denote the empty tuple: () > * Using a trailing comma for a singleton tuple: a, or (a,) > * Separating items with commas: a, b, c or (a, b, c) > * Using the tuple() built-in: tuple() or tuple(iterable) ### Functions should serve single purpose Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp). Sometimes it is sufficient to return `(x, y)` instead of `Point(x, y)`. ### Named tuples With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples. ``` >>> import collections >>> Point = collections.namedtuple('Point', 'x y') >>> x, y = Point(0, 1) >>> p = Point(x, y) >>> x, y, p (0, 1, Point(x=0, y=1)) >>> p.x, p.y, p[0], p[1] (0, 1, 0, 1) >>> for i in p: ... print(i) ... 0 1 ```
Firstly, note that Python allows for the following (no need for the parenthesis): ``` q, r = divide(22, 7) ``` Regarding your question, there's no hard and fast rule either way. For simple (and usually contrived) examples, it may seem that it's always possible for a given function to have a single purpose, resulting in a single value. However, when using Python for real-world applications, you quickly run into many cases where returning multiple values is necessary, and results in cleaner code. So, I'd say do whatever makes sense, and don't try to conform to an artificial convention. Python supports multiple return values, so use it when appropriate.
Is it pythonic for a function to return multiple values?
[ "", "python", "function", "return-value", "multiple-return-values", "" ]
How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#? I know to do it using plan `String.Replace`, like: ``` myStr.Replace("\n", "\r\n"); myStr.Replace("\r\r\n", "\r\n"); ``` However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).
Will this do? ``` [^\r]\n ``` Basically it matches a '\n' that is preceded with a character that is not '\r'. If you want it to detect lines that start with just a single '\n' as well, then try ``` ([^\r]|$)\n ``` Which says that it should match a '\n' but only those that is the first character of a line or those that are *not* preceded with '\r' There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea. **EDIT:** credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes: ``` myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n"); ```
It might be faster if you use this. ``` (?<!\r)\n ``` It basically looks for any \n that is not preceded by a \r. This would most likely be faster, because in the other case, almost every letter matches [^\r], so it would capture that, and then look for the \n after that. In the example I gave, it would only stop when it found a \n, and them look before that to see if it found \r
Regex (C#): Replace \n with \r\n
[ "", "c#", "regex", "" ]
I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
I found the answer here: <http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/> You just concatenate the string and insert a `CHAR(13)` where you want your line break. Example: ``` DECLARE @text NVARCHAR(100) SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.' SELECT @text ``` This prints out the following: > This is line 1. > This is line 2.
`char(13)` is `CR`. For DOS-/Windows-style `CRLF` linebreaks, you want `char(13)+char(10)`, like: ``` 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.' ```
How to insert a line break in a SQL Server VARCHAR/NVARCHAR string
[ "", "sql", "sql-server", "line-breaks", "" ]
How do I connect to a remote Oracle database instance from PHP? I need to query (read only) the remote Oracle database for some information; do I need to have an Oracle Instant Client installed? Is the OCI extension for PHP enough?
From [PHP Manual](http://php.net/manual/en/oci8.setup.php) * You will need the Oracle client libraries to use this extension. * The most convenient way to install all the required files is to use Oracle Instant Client, which is available from [Oracle's site](http://www.oracle.com/technology/software/tech/oci/instantclient/)
The best manual for using PHP with Oracle is [Underground PHP Oracle Manual](http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf). Periodically updated. For example last update describe new cool OCI (Oracle Call Interface) features. I found it by accident and since then has never regretted. Start from that good manual.
Connecting to Oracle using PHP
[ "", "php", "oracle", "" ]
What's the simplest way to connect and query a database for a set of records in C#?
@Goyuix -- that's excellent for something written from memory. tested it here -- found the connection wasn't opened. Otherwise very nice. ``` using System.Data.OleDb; ... using (OleDbConnection conn = new OleDbConnection()) { conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;"; using (OleDbCommand cmd = new OleDbCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandText = "Select * from yourTable"; using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Console.WriteLine(dr["columnName"]); } } } } ```
Very roughly and from memory since I don't have code on this laptop: ``` using (OleDBConnection conn = new OleDbConnection()) { conn.ConnectionString = "Whatever connection string"; using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = conn; cmd.CommandText = "Select * from CoolTable"; using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { // do something like Console.WriteLine(dr["column name"] as String); } } } } ```
How do I connect to a database and loop over a recordset in C#?
[ "", "c#", "database", "loops", "connection", "" ]
The ASP.NET AJAX **ModalPopupExtender** has `OnCancelScript` and `OnOkScript` properties, but it doesn't seem to have an `OnShowScript` property. I'd like to specify a javascript function to run each time the popup is shown. In past situations, I set the `TargetControlID` to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code. Anyone know of a way to do this? BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown
hmmm... I'm *pretty sure* that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page\_load ``` function pageLoad() { var popup = $find('ModalPopupClientID'); popup.add_shown(SetFocus); } function SetFocus() { $get('TriggerClientId').focus(); } ``` i'm not sure tho if this will help you with calling it from the server side tho
Here's a simple way to do it in markup: ``` <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="lnk_OpenGame" PopupControlID="Panel1" BehaviorID="SilverPracticeBehaviorID" > <Animations> <OnShown> <ScriptAction Script="InitializeGame();" /> </OnShown> </Animations> </ajaxToolkit:ModalPopupExtender> ```
How to specify javascript to run when ModalPopupExtender is shown
[ "", "asp.net", "javascript", "asp.net-ajax", "" ]
I've found syntax highlighters that highlight pre-existing code, but I'd like to do it as you type with a WYSIWYG-style editor. I don't need auto-completed functions, just the highlighting. As a follow-up question, what is the WYSIWYG editor that stackoverflow uses? Edit: Thanks to the answer below, I found two that look like they might suit my needs: [EditArea](http://www.cdolivet.net/editarea/) and [CodePress](http://codepress.sourceforge.net/) EDIT: See this question also: <https://stackoverflow.com/questions/379185/free-syntax-highlighting-editor-control-in-javascript>
Here is a really interesting article about how to write one: (Even better, he gives the full source to a JavaScript formatter and colorizer.) [Implementing a syntax-higlighting JavaScript editor in JavaScript](http://marijn.haverbeke.nl/codemirror/story.html) or A brutal odyssey to the dark side of the DOM tree > How does one do decent syntax > highlighting? A very simple scanning > can tell the difference between > strings, comments, keywords, and other > code. But this time I wanted to > actually be able to recognize regular > expressions, so that I didn't have any > blatant incorrect behaviour anymore. Importantly, it handles regex correctly. Also of interest is that he used a continuation passing style lexer/parser instead of the more typical lex (or regex) based lexers that you'll see in the wild. As a bonus he discusses a lot of real-world issues you'll run into when working with JavaScript in the browser.
The question might be better stated as "What syntax-highlighting editor do you recommended to replace an html textarea in my web app?" (Some of the other answers here deal with desktop apps or pure-syntax highlighters, not client-side editors) I also recommend [CodeMirror](http://marijn.haverbeke.nl/codemirror/), it's written in Javascript and supports lots of browsers. It uses a real parser (rather than regexps) so it can deal with complex problems like correctly highlighting escaped strings. The developer is also very responsive on the [discussion group](http://groups.google.com/group/codemirror).
Are there any JavaScript live syntax highlighters?
[ "", "javascript", "syntax-highlighting", "wysiwyg", "" ]
How do I use the profiler in Visual Studio 2008? I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Profile to bring up the profile dialog box, yet in 2008 there is no such menu item). Is this because Visual Studio 2008 does not include a profiler, and if it does where is it and where is the documentation for it?
The profiler is only available in the Team System editions of Visual Studio 2008. The last version that I used that included a profiler was Visual C++ 6.0. For Visual Studio 2005, you could try [Compuware DevPartner Performance Analysis Community Edition](http://www.compuware.com/media.asp?cid=701000000004ej0).
Microsoft has released stand-alone Profiler for VS 2008 [here](http://www.microsoft.com/downloads/details.aspx?familyid=fd02c7d6-5306-41f2-a1be-b7dcb74c9c0b&displaylang=en)
Profiling in Visual Studio 2008 PRO
[ "", "c++", "visual-studio", "visual-studio-2008", "profiling", "" ]
How are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control? ``` private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e) { bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled = !isControl && !isNumeric && !isNumPadNumeric; } ```
How about: ``` protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { e.Handled = !AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e); } private bool AreAllValidNumericChars(string str) { foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true; } ```
This is how I do it. It uses a regular expression to check if the text that will be in the box is numeric or not. ``` Regex NumEx = new Regex(@"^-?\d*\.?\d*$"); private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (sender is TextBox) { string text = (sender as TextBox).Text + e.Text; e.Handled = !NumEx.IsMatch(text); } else throw new NotImplementedException("TextBox_PreviewTextInput Can only Handle TextBoxes"); } ``` There is now a much better way to do this in WPF and Silverlight. If your control is bound to a property, all you have to do is change your binding statement a bit. Use the following for your binding: ``` <TextBox Text="{Binding Number, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> ``` Note that you can use this on custom properties too, all you have to do is throw an exception if the value in the box is invalid and the control will get highlighted with a red border. If you click on the upper right of the red border then the exception message will pop up.
Numeric Data Entry in WPF
[ "", "c#", "wpf", "" ]
I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha). I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class? Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800). Thanks!
You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See [C++ FAQ Lite](https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays) for an example of using a "2D" heap array. ``` int *array = new int[800*800]; ``` (Don't forget to `delete[]` it when you're done.)
Every post so far leaves the memory management for the programmer. This can and should be avoided. ReaperUnreal is darn close to what I'd do, except I'd use a vector rather than an array and also make the dimensions template parameters and change the access functions -- and oh just IMNSHO clean things up a bit: ``` template <class T, size_t W, size_t H> class Array2D { public: const int width = W; const int height = H; typedef typename T type; Array2D() : buffer(width*height) { } inline type& at(unsigned int x, unsigned int y) { return buffer[y*width + x]; } inline const type& at(unsigned int x, unsigned int y) const { return buffer[y*width + x]; } private: std::vector<T> buffer; }; ``` Now you can allocate this 2-D array on the stack just fine: ``` void foo() { Array2D<int, 800, 800> zbuffer; // Do something with zbuffer... } ``` I hope this helps! EDIT: Removed array specification from `Array2D::buffer`. Thanks to Andreas for catching that!
How to work around a very large 2d array in C++
[ "", "c++", "arrays", "graphics", "2d", "zbuffer", "" ]
I just saw a [comment of suggesting J#](https://stackoverflow.com/questions/5516/what-happened-to-all-of-the-java-developers-how-can-i-get-started-in-net#5522), and it made me wonder... is there a real, beneficial use of J# over Java? So, my feeling is that the only reason you would even consider using J# is that management has decreed that the company should jump on the Java bandwagon... and the .NET bandwagon. If you use J#, you are effectively losing the biggest benefit of picking Java... rich cross platform support. Sure there is Mono, but it's not as richly supported or as full featured right? I remember hearing Forms are not fully (perhaps at all) supported. I'm not trying to bash .NET here, I'm just saying, if you are going to go the Microsoft route, why not just use C#? If you are going to go the Java route, why would J# enter the picture? I'm hoping to find some real world cases here, so please especially respond if you've ACTUALLY used J# in a REAL project, and why.
J# is no longer included in VS2008. Unless you already have J# code, you should probably stay away. From [j# product page:](http://msdn.microsoft.com/en-us/vjsharp/default.aspx) > Since customers have told us that the > existing J# feature set largely meets > their needs and usage of J# is > declining, Microsoft is retiring the > Visual J# product and Java Language > Conversion Assistant tool to better > allocate resources for other customer > requirements. The J# language and JLCA > tool will not be available in future > versions of Visual Studio. To preserve > existing customer investments in J#, > Microsoft will continue to support the > J# and JLCA technology that shipped > with Visual Studio 2005 through to > 2015 as per our product life-cycle > strategy. For more information, see > Expanded Microsoft Support Lifecycle > Policy for Business & Development > Products.
The whole purpose of J# is to ease the transition of Java developers to the .NET environment which didn't work so well (I guessing here) so Microsoft dropped J# from Visual Studio 2008. For your question, "Is there a real benefit of using J#?".. in a nutshell... No..
Is there a real benefit of using J#?
[ "", "java", "j#", "" ]
I am confronted with a new kind of problem which I haven't encountered yet in my very young programming "career" and would like to know your opinion about how to tackle it best. **The situation** A research application (php/mysql) gathers stress related health data from users. User gets a an analyses after filling in the questionnaire. Value for each parameter is transformed into a percentile value using a benchmark (mean and standard devitation of existing data set). **The task** Since more and more ppl are filling in the questionnaire, there is the potential to make the benchmark values (mean/SD) more accurate by recalculating them using the new user data. I would like the database to regularly run a script that updates the benchmark values. **The question** I've never used stored precedures so far and I only have a slight notion of what they are but somehow I have a feeling they could maybe help me with this? Or should I write the script as php and then set up a cron job? [edit]After the first couple of answers it looks like cron is clearly the way to go.[/edit]
What you're considering could be done in a number of ways. 1. You could setup a trigger in your DB to recalculate the values whenever a new record is updated. You could store the code needed to update the values in a sproc if necessary. 2. You could write a PHP script and run it regularly via cron. #1 will slow down inserts to your database but will make sure your data is *always* up to date. #2 may lock the tables while it updates the new values, and your data will only be accurate until the next update. #2 is much easier to back up, as the script can easily be stored in your versioning system, whereas you'd need to store the trigger and sproc creation scripts in whatever backup you'd make. Obviously you'll have to weigh up your requirements before you pick a method.
PHP set up as a cron job lets you keep it in your source code management system, and if you're using a database abstraction layer it'll be portable to other databases if you ever decide to switch. For those reasons, I tend to go with scripts over stored procedures.
PHP/mySQL - regular recalculation of benchmark values as new users submit their data
[ "", "php", "mysql", "stored-procedures", "cron", "" ]
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. **Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?** I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. *Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: **How is Windows aware of my service? Can I manage it with the native Windows utilities?** **What is the equivalent of putting a start/stop script in /etc/init.d?***
Yes you can. I do it using the pythoncom libraries that come included with [ActivePython](http://www.activestate.com/Products/activepython/index.mhtml) or can be installed with [pywin32](https://sourceforge.net/projects/pywin32/) (Python for Windows extensions). This is a basic skeleton for a simple service: ``` import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) ``` Your code would go in the `main()` method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the `SvcStop` method
The simplest way is to use the: **NSSM - the Non-Sucking Service Manager.** Just download and unzip to a location of your choosing. It's a self-contained utility, around 300KB (much less than installing the entire pywin32 suite just for this purpose) and no "installation" is needed. The zip contains a 64-bit and a 32-bit version of the utility. Either should work well on current systems (you can use the 32-bit version to manage services on 64-bit systems). ### GUI approach **1 - install the python program as a service. Open a Win prompt as admin** ``` c:\>nssm.exe install WinService ``` **2 - On NSSM´s GUI console:** path: C:\Python27\Python27.exe Startup directory: C:\Python27 Arguments: c:\WinService.py **3 - check the created services on services.msc** ### Scripting approach (no GUI) This is handy if your service should be part of an automated, non-interactive procedure, that may be beyond your control, such as a batch or installer script. It is assumed that the commands are executed with administrative privileges. For convenience the commands are described here by simply referring to the utility as `nssm.exe`. It is advisable, however, to refer to it more explicitly in scripting with its full path `c:\path\to\nssm.exe`, since it's a self-contained executable that may be located in a private path that the system is not aware of. **1. Install the service** You must specify a name for the service, the path to the proper Python executable, and the path to the script: ``` nssm.exe install ProjectService "c:\path\to\python.exe" "c:\path\to\project\app\main.py" ``` More explicitly: ``` nssm.exe install ProjectService nssm.exe set ProjectService Application "c:\path\to\python.exe" nssm.exe set ProjectService AppParameters "c:\path\to\project\app\main.py" ``` Alternatively you may want your Python app to be started as a Python module. One easy approach is to tell nssm that it needs to change to the proper starting directory, as you would do yourself when launching from a command shell: ``` nssm.exe install ProjectService "c:\path\to\python.exe" "-m app.main" nssm.exe set ProjectService AppDirectory "c:\path\to\project" ``` This approach works well with virtual environments and self-contained (embedded) Python installs. Just make sure to have properly resolved any path issues in those environments with the usual methods. nssm has a way to set environment variables (e.g. PYTHONPATH) if needed, and can also launch batch scripts. **2. To start the service** ``` nssm.exe start ProjectService ``` **3. To stop the service** ``` nssm.exe stop ProjectService ``` **4. To remove the service**, specify the `confirm` parameter to skip the interactive confirmation. ``` nssm.exe remove ProjectService confirm ```
How do you run a Python script as a service in Windows?
[ "", "python", "windows", "cross-platform", "" ]
I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it. I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?
The previously mentioned JNI approach will likely work. You can use JNA which is basically a wrapper around JNI to make it easier to use. An added bonus is that it (in my opinion at least) generally is faster and more maintainable than raw JNI. You can find JNA at <https://jna.dev.java.net/> If you're just starting the application in the start menu because you're trying to make it behave like a service in windows, you can use the java service wrapper which is found here: <http://wrapper.tanukisoftware.org/doc/english/download.jsp>
As far as I know you need to start using JNI to set up a message handler for the Windows [WM\_QUERYENDSESSION](http://msdn.microsoft.com/en-us/library/aa376890.aspx) message. To do this (if you're new to Windows programming like me) you'll need to create a new class of window with a new message handling function (as described [here](http://www.angelcode.com/dev/window/window.asp)) and handle the WM\_QUERYENDSESSION from the message handler. NB: You'll need to use the JNIEnv::GetJavaVM(...) and then JavaVM::AttachCurrentThread(...) on the message handling thread before you can call any Java methods from your native message handling code.
How do I get my Java application to shutdown nicely in windows?
[ "", "java", "windows", "shutdown", "" ]
What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%? I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much. Based on Marius and Andy's answers I'm using the following solution: ``` double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12; double green = (percent > 50) ? 255 : percent * 5.12; var color = Color.FromArgb(255, (byte)red, (byte)green, 0); ``` Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) \* 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...
I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language: ``` function setColor(p){ var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12); var green = p>50 ? 255 : Math.round((p)*5.12); return "rgb(" + red + "," + green + ",0)"; } ```
What you probably want to do is to assign your 0% to 100% some points in a HSV or HSL color-space. From there you can interpolate colors (and yellow just happens to be between red and green :) and [convert them to RGB](http://en.wikipedia.org/wiki/HSL_color_space). That will give you a nice looking gradient between the two. Assuming that you will use the color as a status indicator and from a user-interface perspective, however, that is probably not such a good idea, since we're quite bad at seeing small changes in color. So dividing the value into, for example, three to seven buckets would give you more noticeable differences when things change, at the cost of some precision (which you most likely would not be able to appreciate anyway). So, all the math aside, in the end I'd recommend a lookup table with the following colors with v being the input value: ``` #e7241d for v <= 12% #ef832c for v > 12% and v <= 36% #fffd46 for v > 36% and v <= 60% #9cfa40 for v > 60% and v <= 84% #60f83d for v > 84% ``` These have been very naïvely converted from HSL values (0.0, 1.0, 1.0), (30.0, 1.0, 1.0), (60.0, 1.0, 1.0), (90.0, 1.0, 1.0), (120.0, 1.0, 1.0), and you might want to adjust the colors somewhat to suit your purposes (some don't like that red and green aren't 'pure'). Please see: * [Using HSL Color (Hue, Saturation, Luminosity) To Create Better-Looking GUIs](http://richnewman.wordpress.com/2007/04/29/using-hsl-color-hue-saturation-luminosity-to-create-better-looking-guis-part-1/) for some discussion and * [RGB and HSL Colour Space Conversions](https://web.archive.org/web/20141023005253/http://bobpowell.net/RGBHSB.aspx) for sample C# source-code.
Conditional formatting -- percentage to color conversion
[ "", "c#", "colors", "rgb", "" ]
I'm trying to set up an inheritance hierarchy similar to the following: ``` abstract class Vehicle { public string Name; public List<Axle> Axles; } class Motorcycle : Vehicle { } class Car : Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) { ... } } class MotorcycleAxle : Axle { public bool WheelAttached; } class CarAxle : Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } ``` I would like to only store MotorcycleAxle objects in a Motorcycle object's Axles array, and CarAxle objects in a Car object's Axles array. The problem is there is no way to override the array in the subclass to force one or the other. Ideally something like the following would be valid for the Motorcycle class: ``` class Motorcycle : Vehicle { public override List<MotorcycleAxle> Axles; } ``` but the types have to match when overriding. How can I support this architecture? Will I just have to do a lot of run-time type checking and casting wherever the Axles member is accessed? I don't like adding run-time type checks because you start to lose the benefits of strong typing and polymorphism. There have to be at least some run-time checks in this scenario since the WheelAttached and Left/RightWheelAttached properties depend on the type, but I would like to minimize them.
Use more generics ``` abstract class Vehicle<T> where T : Axle { public string Name; public List<T> Axles; } class Motorcycle : Vehicle<MotorcycleAxle> { } class Car : Vehicle<CarAxle> { } abstract class Axle { public int Length; public void Turn(int numTurns) { ... } } class MotorcycleAxle : Axle { public bool WheelAttached; } class CarAxle : Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } ```
2 options spring to mind. 1 is using generics: ``` abstract class Vehicle<TAxle> where TAxle : Axle { public List<TAxle> Axles; } ``` The second uses shadowing - and this assumes you have properties: ``` abstract class Vehicle { public IList<Axle> Axles { get; set; } } class Motorcyle : Vehicle { public new IList<MotorcycleAxle> Axles { get; set; } } class Car : Vehicle { public new IList<CarAxle> Axles { get; set; } } void Main() { Vehicle v = new Car(); // v.Axles is IList<Axle> Car c = (Car) v; // c.Axles is IList<CarAxle> // ((Vehicle)c).Axles is IList<Axle> ``` The problem with shadowing is that you have a generic List. Unfortunately, you can't constrain the list to only contain CarAxle. Also, you can't cast a List<Axle> into List<CarAxle> - even though there's an inheritance chain there. You have to cast each object into a new List (though that becomes much easier with LINQ). I'd go for generics myself.
What is the best way to inherit an array that needs to store subclass specific data?
[ "", "c#", "oop", "inheritance", "covariance", "contravariance", "" ]
I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment. When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well: ``` [DataContract] public DataTable GetTbl() { DataTable tbl = new DataTable("testTbl"); for(int i=0;i<100;i++) { tbl.Columns.Add(i); tbl.Rows.Add(new string[]{"testValue"}); } return tbl; } ``` However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly." ``` [DataContract] public DataTable GetTbl() { DataTable tbl = new DataTable("testTbl"); //Populate table with SQL query return tbl; } ``` The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used. Why would the way that the table is being populated have any bearing on the table returning successfully?
For anyone having similar problems, I have solved my issue. It was several-fold. * As Darren suggested and Paul backed up, the Max..Size properties in the configuration needed to be enlarged. The SvcTraceViewer utility helped in determining this, but it still does not always give the most helpful error messages. * It also appears that when the Service Reference is updated on the client side, the configuration will sometimes not update properly (e.g. Changing config values on the server will not always properly update on the client. I had to go in and change the Max..Size properties multiple times on both the client and server sides in the course of my debugging) * For a DataTable to be serializable, it needs to be given a name. The default constructor does not give the table a name, so: ``` return new DataTable(); ``` will not be serializable, while: ``` return new DataTable("someName"); ``` will name the table whatever is passed as the parameter. Note that a table can be given a name at any time by assigning a string to the `TableName` property of the DataTable. ``` var table = new DataTable(); table.TableName = "someName"; ``` Hopefully that will help someone.
The best way to diagnose these kinds of WCF errors (the ones that really don't tell you much) is to enable tracing. In your web.config file, add the following: ``` <system.diagnostics> <sources> <source name="System.ServiceModel" switchValue="Information" propagateActivity="true"> <listeners> <add name="ServiceModelTraceListener" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="wcf-traces.svclog"/> </listeners> </source> </sources> </system.diagnostics> ``` You can then open the resulting file in the SvcTraceViewer.exe utility which comes in the .NET Framework SDK (or with Visual Studio). On my machine, it can be found at %PROGRAMFILES%\Microsoft SDKs\Windows\v6.0A\Bin\SvcTraceViewer.exe. Just look for an error message (in bold red) and that will tell you specifically what your problem is.
Returning DataTables in WCF/.NET
[ "", "c#", ".net", "wcf", "web-services", "datatable", "" ]
Do you know if I can use Visio to forward-engineer a sequence diagram into code (c#)? Can it be done with Visio alone or do I need a plugin? What about other diagrams?
You have to get the Visio that for users of Visual Studio. See this link: [Visio for Enterprise Architects](http://msdn.microsoft.com/en-us/library/ms182014.aspx) for more details. The code generation capabilities are fairly weak and you might end up getting Visio into an inconsistent state. I know that Visio will let you forward and reverse engineer both code and databases, but both capabilities are very limited and I don't recommend doing it. In my opinion, Visio is a diagramming tool and it should be treated as such.
Looks like the latest version of Sparx Systems Enterprise Architect can forward engineer sequence diagrams [Sparx Systems Enterprise Architect](http://sparxsystems.com/products/index.html)
Visio and Forward-Engineering
[ "", "c#", "visio", "forward-engineer", "" ]
Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.
``` public static void DownloadFile(string remoteFilename, string localFilename) { WebClient client = new WebClient(); client.DownloadFile(remoteFilename, localFilename); } ```
[System.Net.WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient%28VS.80%29.aspx) From MSDN: ``` using System; using System.Net; using System.IO; public class Test { public static void Main (string[] args) { if (args == null || args.Length == 0) { throw new ApplicationException ("Specify the URI of the resource to retrieve."); } WebClient client = new WebClient (); // Add a user agent header in case the // requested URI contains a query. client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); Stream data = client.OpenRead (args[0]); StreamReader reader = new StreamReader (data); string s = reader.ReadToEnd (); Console.WriteLine (s); data.Close (); reader.Close (); } } ```
Fastest C# Code to Download a Web Page
[ "", "c#", "" ]
I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers. I'm using a simple Allow or Deny option for each 'Resource' or screen. We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group. I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance. **Option A** The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied. I think this will mean a smaller table, but would queries search the whole table to determine there is no match? **Option B** A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table. Thoughts?
If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access. ``` UserResources ------------- UserId FK->Users ResourceId FK->Resources ``` and the sql would be something like ``` if exists (select 1 from UserResources where UserId = @uid and ResourceId=@rid) set @allow=1; ``` With a clustered index on (UserId and ResourceId), the query would be blindingly fast even with millions of records.
I would vote for Option B. If you go with Option A and the assumption that if a user exists, they can get in, then you'll eventually run into the problem that you'll want to deny access to a user, without removing the user record. There will be lots of cases where you'll want to lock a user out, but won't want to completely destroy their account. One such instance (not necessarily linked to your use case), is when you fail to pay, and they cut off your account until you start paying again. They don't want to delete the record, because they still want to enable it when you pay up again, instead of recreating the account from scratch, and losing all user history.
Is it better to structure an SQL table to have a match, or return no result
[ "", "sql", "sql-server", "optimization", "" ]
Anything thats as good and as stable and as feature-rich as gigaspaces?
Gigaspaces is top notch as far as a Javaspaces implementation goes for scalability and performance. Are you restricted to a Javaspaces implementation? Blitz Javaspaces is top notch for a free product.
As the first answer says, what are your criteria? There's a number of commercial and open-source tools in the same space (but not Javaspaces-based): * [Oracle Coherence](http://coherence.oracle.com/display/COH34UG/Coherence+3.4+Home) * [Gemstone's Gemfire](http://www.gemstone.com/products/gemfire/) * [Terracotta](http://www.terracotta.org) (a degree of overlap, but not quite in the same space) * [GridGain](http://www.gridgain.com) (does the grid bit, but not the distributed cache bit)
Are there any alternatives to Gigaspaces?
[ "", "java", "jakarta-ee", "gigaspaces", "" ]
I've been doing c# for a long time, and have never come across an easy way to just new up a hash. I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls. ``` { "whatever" => {i => 1}; "and then something else" => {j => 2}}; ```
If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement. This example is based on the [MSDN Example](http://msdn.microsoft.com/en-us/library/bb531208.aspx) ``` var students = new Dictionary<int, StudentName>() { { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}}, { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }}, { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }} }; ```
When I'm not able to use C# 3.0, I use a helper function that translates a set of parameters into a dictionary. ``` public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data) { Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length / 2)); if (data == null || data.Length == 0) return dict; KeyType key = default(KeyType); ValueType value = default(ValueType); for (int i = 0; i < data.Length; i++) { if (i % 2 == 0) key = (KeyType) data[i]; else { value = (ValueType) data[i]; dict.Add(key, value); } } return dict; } ``` Use like this: ``` IDictionary<string,object> myDictionary = Dict<string,object>( "foo", 50, "bar", 100 ); ```
Literal hashes in c#?
[ "", "c#", "ruby", "hashtable", "literals", "" ]
I'm working on a cross platform application in Java which currently works nicely on Windows, Linux and MacOS X. I'm trying to work out a nice way to do detection (and handling) of 'crashes'. Is there an easy, cross-platform way to detect 'crashes' in Java and to do something in response? I guess by 'crashes' I mean uncaught exceptions. However the code does use some JNI so it'd be nice to be able to catch crashes from bad JNI code, but I have a feeling that's JVM specific.
For simple catch-all handling, you can use the following static method in [Thread](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html). From the Javadoc: > static void [**setDefaultUncaughtExceptionHandler**](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler))([Thread.UncaughtExceptionHandler](http://java.sun.com/javase/6/docs/api/java/lang/Thread.UncaughtExceptionHandler.html) eh) >           Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread. This is a very broad way to deal with errors or unchecked exceptions that may not be caught anywhere else. **Side-note:** It's better if the code can catch, log and/or recover from exceptions closer to the source of the problem. I would reserve this kind of generalized crash handling for totally unrecoverable situations (i.e. subclasses of [java.lang.Error](http://java.sun.com/javase/6/docs/api/java/lang/Error.html)). Try to avoid the possibility of a [RuntimeException](http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html) ever going completely uncaught, since it might be possible--and preferable--for the software to survive that.
For handling uncaught exceptions you can provide a new ThreadGroup which provides an implementation of ThreadGroup.uncaughtException(...). You can then catch any uncaught exceptions and handle them appropriately (e.g. send a crash log home). I can't help you on the JNI front, there's probably a way using a native wrapper executable before calling the JVM, but that executable is going to need to know about all the possible JVMs it could be calling and how the indicate crashes and where crash logs are placed etc.
How to capture crash logs in Java
[ "", "java", "error-handling", "crash", "" ]
Which of the following is better code in c# and why? ``` ((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString() ``` or ``` DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString() ``` Ultimately, is it better to cast or to parse?
If g[0]["MyUntypedDateField"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast)
Casting is the **only** good answer. You have to remember, that ToString and Parse results are not always exact - there are cases, when you cannot safely roundtrip between those two functions. The documentation of ToString says, it uses current thread culture settings. The documentation of Parse says, it also uses current thread culture settings (so far so good - they are using the same culture), but there is an explicit remark, that: > Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. **One reason the Parse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value.** So depending on the users settings, the ToString/Parse code can and will unexpectedly fail...
C# Casting vs. Parse
[ "", "c#", "datetime", "parsing", "string", "casting", "" ]
I am using a rich text editor on a web page. .NET has feature that prevent one from posting HTML tags, so I added a JavaScript snippet to change the angle brackets to and alias pair of characters before the post. The alias is replaced on the server with the necessary angle bracket and then stored in the database. With XSS aside, what are common ways of fixing this problem. (i.e. Is there a better way?) If you have comments on XSS(cross-site scripting), I'm sure that will help someone.
There's actually a way to turn that "feature" off. This will allow the user to post whichever characters they want, and there will be no need to convert characters to an alias using Javascript. See this article for [disabling request validation](http://mdid.org/mdidwiki/index.php?title=Disabling_Request_Validation). It means that you'll have to do your own validation, but from the sounds of your post, it seems that is what you are looking to do anyway. You can also disable it per page by following [the instructions here](http://www.asp.net/learn/whitepapers/request-validation/).
I think the safest way to go is to NOT allow the user to create tags with your WISYWIG. Maybe using something like a markdown editor like on this site or [available here.](http://wmd-editor.com/) would be another approach. Also keep the Page directive ValidateRequest=true which should stop markup from being sent in the request, you'll of course need to handle this error when it comes up. People will always be able to inject tags into the request either way using firefox extensions like [Tamper data](https://addons.mozilla.org/en-US/firefox/addon/966), but the ValidateRequest=true should at least stop ASP.NET from accepting them. A straight forward post on XSS attacks was recently made by Jeff here. It also speaks to making your cookies HttpOnly, which is a semi-defense against cookie theft. Good luck!
Browser WYSIWYG best practices
[ "", "asp.net", "javascript", "wysiwyg", "" ]
I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?
Here what i am using. I think this is actually generated by the MVC project template in VS: ``` public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName) { string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"]; string currentActionName = (string)helper.ViewContext.RouteData.Values["action"]; if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)) return true; return false; } ```
My current solution is with extension methods: ``` public static class UrlHelperExtensions { /// <summary> /// Determines if the current view equals the specified action /// </summary> /// <typeparam name="TController">The type of the controller.</typeparam> /// <param name="helper">Url Helper</param> /// <param name="action">The action to check.</param> /// <returns> /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>. /// </returns> public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller { MethodCallExpression call = action.Body as MethodCallExpression; if (call == null) { throw new ArgumentException("Expression must be a method call", "action"); } return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) && typeof(TController) == helper.ViewContext.Controller.GetType()); } /// <summary> /// Determines if the current view equals the specified action /// </summary> /// <param name="helper">Url Helper</param> /// <param name="actionName">Name of the action.</param> /// <returns> /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>. /// </returns> public static bool IsAction(this UrlHelper helper, string actionName) { if (String.IsNullOrEmpty(actionName)) { throw new ArgumentException("Please specify the name of the action", "actionName"); } string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller"); return IsAction(helper, actionName, controllerName); } /// <summary> /// Determines if the current view equals the specified action /// </summary> /// <param name="helper">Url Helper</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <returns> /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>. /// </returns> public static bool IsAction(this UrlHelper helper, string actionName, string controllerName) { if (String.IsNullOrEmpty(actionName)) { throw new ArgumentException("Please specify the name of the action", "actionName"); } if (String.IsNullOrEmpty(controllerName)) { throw new ArgumentException("Please specify the name of the controller", "controllerName"); } if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) { controllerName = controllerName + "Controller"; } bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase); return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase); } } ```
Asp.Net MVC: How to determine if you're currently on a specific view
[ "", "c#", "asp.net-mvc", "" ]
I'm maintaining a .NET 1.1 application and one of the things I've been tasked with is making sure the user doesn't see any unfriendly error notifications. I've added handlers to `Application.ThreadException` and `AppDomain.CurrentDomain.UnhandledException`, which do get called. My problem is that the standard CLR error dialog is still displayed (before the exception handler is called). Jeff talks about this problem on his blog [here](https://blog.codinghorror.com/console-apps-and-appdomain-currentdomain-unhandledexception/) and [here](https://blog.codinghorror.com/improved-unhandled-exception-behavior-in-net-20/). But there's no solution. So what is the standard way in .NET 1.1 to handle uncaught exceptions and display a friendly dialog box? Jeff's response was marked as the correct answer because the link he provided has the most complete information on how to do what's required.
Oh, in Windows Forms you definitely should be able to get it to work. The only thing you have to watch out for is things happening on different threads. I have an old Code Project article here which should help: *[User Friendly Exception Handling](http://www.codeproject.com/KB/exception/ExceptionHandling.aspx)*
**AppDomain.UnhandledException** is an **event**, not a global exception handler. This means, by the time it is raised, your application is already on its way down the drain, and there is nothing you can do about it, except for doing cleanup and error logging. What happened behind the scenes is this: The framework detected the exception, walked up the call stack to the very top, found no handlers that would recover from the error, so was unable to determine if it was safe to continue execution. So, it started the shutdown sequence and fired up this event as a courtesy to you so you can pay your respects to your already-doomed process. This happens when an exception is left unhandled in the main thread. There is no single-point solution to this kind of error. You need to put a real exception handler (a catch block) upstream of all places where this error occurs and forward it to (for example) a global handler method/class that will determine if it is safe to simply report and continue, based on exception type and/or content. Edit: It is possible to disable (=hack) the error-reporting mechanism built into Windows so the mandatory "crash and burn" dialog does not get displayed when your app goes down. However, this becomes effective for *all* the applications in the system, not just your own.
Unhandled Exception Handler in .NET 1.1
[ "", "c#", ".net", "exception", "" ]
What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development. Our JavaScript code is roughly "namespaced" as: ``` var Client = { var1: '', var2: '', accounts: { /* 100's of functions and variables */ }, orders: { /* 100's of functions and variables and subsections */ } /* etc, etc for a couple hundred kb */ } ``` At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes *forever* to find anything in the JavaScript code and the browser still has a dozen files to download. Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?
The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate. If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a `<script src='/path/to/js/$file.js' type='text/javascript'>` in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files. When deploying to production, you should have a script that combines them all into one JS file and "minifies" it to keep the size down.
Also, I suggest you to use Google's [AJAX Libraries API](http://code.google.com/apis/ajaxlibs/documentation/) in order to load external libraries. It's a Google developer tool which bundle majors JavaScript libraries and make it easier to deploy, upgrade and make them lighter by always using compressed versions. Also, it make your project simpler and lighter because you don't need to download, copy and maintain theses libraries files in your project. Use it this way : ``` google.load("jquery", "1.2.3"); google.load("jqueryui", "1.5.2"); google.load("prototype", "1.6"); google.load("scriptaculous", "1.8.1"); google.load("mootools", "1.11"); google.load("dojo", "1.1.1"); ```
Best practices for managing and deploying large JavaScript apps
[ "", "javascript", "web-applications", "deployment", "" ]
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.
**There's no easy way to find out the memory size of a python object**. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries). There is a [big chunk of code](http://code.activestate.com/recipes/544288/) (and an [updated big chunk of code](http://code.activestate.com/recipes/546530/)) out there to try to best approximate the size of a python object in memory. You may also want to check some [old description about PyObject](http://mail.python.org/pipermail/python-list/2002-March/135223.html) (the internal C struct that represents virtually all python objects).
Try this: ``` sys.getsizeof(object) ``` [getsizeof()](https://docs.python.org/3/library/sys.html#sys.getsizeof) Return the size of an object in bytes. It calls the object’s `__sizeof__` method and adds an additional garbage collector overhead **if** the object is managed by the garbage collector. [A recursive recipe](http://code.activestate.com/recipes/577504/)
Find out how much memory is being used by an object in Python
[ "", "python", "performance", "memory-profiling", "" ]
I have a layered application in Java which has a multi thread data access layer which is invoked from different points. A single call to this layer is likely to spawn several threads to parallelize requests to the DB. What I'm looking for is a logging tool that would allow me to define "activities" that are composed by various threads. Therefore, the same method in the data access layer should log different outputs depending on its caller. The ability to group different outputs to summarize the total cost of an operation is also important. Although the application is in Java, language is not a restriction; what I need are the design guidelines so to eventually implement it. We are currently using log4j, but can't get this behaviour from it.
You should also have a look at the [nested diagnostic context](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html) feature of log4j. Pushing different contexts to the logger for different callers might do the trick for you.
You should be able to pass a logger around, so you create a logger based on some "common" for the task data - i.e. username, etc. Then, pass this logger as parameter to all methods you need. That way, you'll be able to set different filters and/or rules in your log4j config file. Or to scrape the output file based on the logger name. EDIT: Also check MDC and NDC classes in log4j. You can add there context data.
Logging activities in multithreaded applications
[ "", "java", "logging", "log4j", "" ]
I'm just curious if any project exists that attempts to group all (or most) of PHP's built-in functions into a more object-oriented class hierarchy. For example, grouping all the string functions into a single String class, etc. I realize this won't actually solve any problems (unless the modifications took place at the PHP source code level), since all the built-in functions would still be accessible in the global namespace, but it would certainly make usability much easier.
To Answer your question, Yes there exists several of libraries that do exactly what you are talking about. As far as which one you want to use is an entirely different question. PHPClasses and pear.org are good places to start looking for such libraries. Update: As the others have suggested SPL is a good library and wraps many of built in php functions. However there still are lots of php functions that it does not wrap. Leaving us still without a silver bullet. In using frameworks such as Cakephp and Zend (others too), I have noticed that they attempt to solve some of these problems by including their own libraries and building basics such as DB connectivity into the frame work. So frameworks may be another solution
Way too many times. As soon as someone discovers that PHP has OO features they want to wrap everything in classes. The point to the OO stuff in PHP is so that you can architect your solutions in whichever way you want. But wrapping the existing functions in Objects doesn't yield much payoff. That being said PHP's core is quite object oriented already. Take a look at [SPL](http://www.php.net/~helly/php/ext/spl/).
Has anyone attempted to make PHP's system functions more Object-Oriented?
[ "", "php", "oop", "wrapper", "" ]
How do I add a method to an existing object (i.e., not in the class definition) in Python? I understand that it's not generally considered good practice to do so, except in some cases.
In Python, there is a difference between functions and bound methods. ``` >>> def foo(): ... print "foo" ... >>> class A: ... def bar( self ): ... print "bar" ... >>> a = A() >>> foo <function foo at 0x00A98D70> >>> a.bar <bound method A.bar of <__main__.A instance at 0x00A9BC88>> >>> ``` Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called. Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want: ``` >>> def fooFighters( self ): ... print "fooFighters" ... >>> A.fooFighters = fooFighters >>> a2 = A() >>> a2.fooFighters <bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>> >>> a2.fooFighters() fooFighters ``` Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves): ``` >>> a.fooFighters() fooFighters ``` The problem comes when you want to attach a method to a single instance: ``` >>> def barFighters( self ): ... print "barFighters" ... >>> a.barFighters = barFighters >>> a.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: barFighters() takes exactly 1 argument (0 given) ``` The function is not automatically bound when it's attached directly to an instance: ``` >>> a.barFighters <function barFighters at 0x00A98EF0> ``` To bind it, we can use the [MethodType function in the types module](https://docs.python.org/3/library/types.html#types.MethodType): ``` >>> import types >>> a.barFighters = types.MethodType( barFighters, a ) >>> a.barFighters <bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>> >>> a.barFighters() barFighters ``` This time other instances of the class have not been affected: ``` >>> a2.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: A instance has no attribute 'barFighters' ``` More information can be found by reading about [descriptors](https://docs.python.org/3/howto/descriptor.html) and [metaclass](https://web.archive.org/web/20090124004817/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html) [programming](http://www.gnosis.cx/publish/programming/metaclass_2.html).
Preface - a note on compatibility: other answers may only work in Python 2 - this answer should work perfectly well in Python 2 and 3. If writing Python 3 only, you might leave out explicitly inheriting from `object`, but otherwise the code should remain the same. > # Adding a Method to an Existing Object Instance > > I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python. > > I understand that it's not always a good decision to do so. **But, how might one do this?** ## Yes, it is possible - But not recommended I don't recommend this. This is a bad idea. Don't do it. Here's a couple of reasons: * You'll add a bound object to every instance you do this to. If you do this a lot, you'll probably waste a lot of memory. Bound methods are typically only created for the short duration of their call, and they then cease to exist when automatically garbage collected. If you do this manually, you'll have a name binding referencing the bound method - which will prevent its garbage collection on usage. * Object instances of a given type generally have its methods on all objects of that type. If you add methods elsewhere, some instances will have those methods and others will not. Programmers will not expect this, and you risk violating the [rule of least surprise](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). * Since there are other really good reasons not to do this, you'll additionally give yourself a poor reputation if you do it. Thus, I suggest that you not do this unless you have a really good reason. **It is far better to define the correct method in the class definition** or *less* preferably to monkey-patch the class directly, like this: ``` Foo.sample_method = sample_method ``` Since it's instructive, however, I'm going to show you some ways of doing this. ## How it can be done Here's some setup code. We need a class definition. It could be imported, but it really doesn't matter. ``` class Foo(object): '''An empty class to demonstrate adding a method to an instance''' ``` Create an instance: ``` foo = Foo() ``` Create a method to add to it: ``` def sample_method(self, bar, baz): print(bar + baz) ``` ### Method nought (0) - use the descriptor method, `__get__` Dotted lookups on functions call the `__get__` method of the function with the instance, binding the object to the method and thus creating a "bound method." ``` foo.sample_method = sample_method.__get__(foo) ``` and now: ``` >>> foo.sample_method(1,2) 3 ``` ### Method one - types.MethodType First, import types, from which we'll get the method constructor: ``` import types ``` Now we add the method to the instance. To do this, we require the MethodType constructor from the `types` module (which we imported above). The argument signature for types.MethodType (in Python 3) is `(function, instance)`: ``` foo.sample_method = types.MethodType(sample_method, foo) ``` and usage: ``` >>> foo.sample_method(1,2) 3 ``` Parenthetically, in Python 2 the signature was `(function, instance, class)`: ``` foo.sample_method = types.MethodType(sample_method, foo, Foo) ``` ### Method two: lexical binding First, we create a wrapper function that binds the method to the instance: ``` def bind(instance, method): def binding_scope_fn(*args, **kwargs): return method(instance, *args, **kwargs) return binding_scope_fn ``` usage: ``` >>> foo.sample_method = bind(foo, sample_method) >>> foo.sample_method(1,2) 3 ``` ### Method three: functools.partial A partial function applies the first argument(s) to a function (and optionally keyword arguments), and can later be called with the remaining arguments (and overriding keyword arguments). Thus: ``` >>> from functools import partial >>> foo.sample_method = partial(sample_method, foo) >>> foo.sample_method(1,2) 3 ``` This makes sense when you consider that bound methods are partial functions of the instance. ## Unbound function as an object attribute - why this doesn't work: If we try to add the sample\_method in the same way as we might add it to the class, it is unbound from the instance, and doesn't take the implicit self as the first argument. ``` >>> foo.sample_method = sample_method >>> foo.sample_method(1,2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sample_method() takes exactly 3 arguments (2 given) ``` We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn't actually use the `self` argument variable), but it would not be consistent with the expected signature of other instances (if we're monkey-patching this instance): ``` >>> foo.sample_method(foo, 1, 2) 3 ``` ## Conclusion You now know several ways you *could* do this, but in all seriousness - don't do this.
Adding a method to an existing object instance in Python
[ "", "python", "oop", "methods", "monkeypatching", "" ]
Example: ``` select ename from emp where hiredate = todate('01/05/81','dd/mm/yy') ``` and ``` select ename from emp where hiredate = todate('01/05/81','dd/mm/rr') ``` return different results
<http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525> > YY allows you to retrieve just two digits of a year, for example, the 99 in > 1999. The other digits (19) are automatically assigned to the current > century. RR converts two-digit years into four-digit years by rounding. > > 50-99 are stored as 1950-1999, and dates ending in 00-49 are stored as > 2000-2049. RRRR accepts a four-digit input (although not required), and > converts two-digit dates as RR does. YYYY accepts 4-digit inputs butdoesn't > do any date converting Essentially, your first example will assume that 81 is 2081 whereas the RR one assumes 1981. So the first example should not return any rows as you most likely did not hire any guys after May 1 2081 yet :-)
y2k compatibility. rr assumes 01 to be 2001, yy assumes 01 to be 1901 see: <http://www.oradev.com/oracle_date_format.jsp> edit: damn! [michael "quickfingers" stum](https://stackoverflow.com/users/91/michael-stum) [beat me to it](https://stackoverflow.com/questions/19058/what-is-the-difference-between-oracles-yy-and-rr-date-mask#19061)! /mp
What is the difference between oracle's 'yy' and 'rr' date mask?
[ "", "sql", "oracle", "" ]
I'm looking for a Java profiler that works well with the JVM coming with WebSphere 6.0.2 (IBM JVM 1.4.2). I use yourkit for my usual profiling needs, but it specifically refuses to work with this old jvm (I'm sure the authors had their reasons...). Can anybody point to a decent profiler that can do the job? Not interested in a generic list of profilers, BTW, I've seen the other stackoverflow theread, but I'd rather not try them one by one. I would prefer a free version, if possible, since this is a one-off need (I hope!) and I would rather not pay for another profiler just for this.
Update: I found out that [JProfiler](http://www.ej-technologies.com/products/jprofiler/overview.html) integrates smoothly with WAS 6.0.2 (IBM JDK 1.4).
Old post, but this may help someone. You can use [IBM Health Center](http://www.ibm.com/developerworks/java/jdk/tools/healthcenter/) which is free. It can be downloaded standalone or as part of the [IBM Support Assistant](http://www-01.ibm.com/software/support/isa/). I suggest downloading ISA since it has a ton of other useful tools such as [Garbage Collection and Memory Visualizer](http://www.ibm.com/developerworks/java/jdk/tools/gcmv/) and [Memory Analyzer](https://www-304.ibm.com/support/docview.wss?uid=swg21394814).
Java profiler for IBM JVM 1.4.2 (WebSphere 6.0.2)
[ "", "java", "websphere", "profiler", "" ]
I'm trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes). I'm using: ``` Process.GetCurrentProcess().PrivateMemorySize64 ``` However, the Process object has several different properties that let me read the memory space used: Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet and then the "peaks": which i'm guessing just store the maximum values these last ones ever took. Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited. So my question is obviously "which one should I use?", and I know the answer is "it depends". This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside. So... Which one should I use and why?
If you want to know how much the GC uses try: ``` GC.GetTotalMemory(true) ``` If you want to know what your process uses from Windows (VM Size column in TaskManager) try: ``` Process.GetCurrentProcess().PrivateMemorySize64 ``` If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usage column in TaskManager) try: ``` Process.GetCurrentProcess().WorkingSet64 ``` See [here](http://web.archive.org/web/20051030010819/http://shsc.info/WindowsMemoryManagement) for more explanation on the different sorts of memory.
OK, I found through Google the same page that Lars mentioned, and I believe it's a great explanation for people that don't quite know how memory works (like me). <http://shsc.info/WindowsMemoryManagement> My short conclusion was: * Private Bytes = The Memory my process has requested to store data. Some of it may be paged to disk or not. This is the information I was looking for. * Virtual Bytes = The Private Bytes, plus the space shared with other processes for loaded DLLs, etc. * Working Set = The portion of ALL the memory of my process that has not been paged to disk. So the amount paged to disk should be (Virtual - Working Set). Thanks all for your help!
Process Memory Size - Different Counters
[ "", "c#", ".net", "memory", "process", "diagnostics", "" ]
Visual Basic code does not render correctly with [prettify.js](https://code.google.com/archive/p/google-code-prettify) from Google. on Stack Overflow: ``` Partial Public Class WebForm1 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set page title Page.Title = "Something" End Sub End Class ``` in Visual Studio... ![Visual Basic in Visual Studio](https://i.stack.imgur.com/Fl1CM.jpg) I found this in the [README](https://web.archive.org/web/20160428230325/http://google-code-prettify.googlecode.com:80/svn/trunk/README.html) document: > How do I specify which language my > code is in? > > You don't need to specify the language > since prettyprint() will guess. You > can specify a language by specifying > the language extension along with the > prettyprint class like so: > > ``` > <pre class="prettyprint lang-html"> > The lang-* class specifies the language file extensions. > Supported file extensions include > "c", "cc", "cpp", "cs", "cyc", "java", "bsh", "csh", "sh", > "cv", "py", "perl", "pl", "pm", "rb", "js", > "html", "html", "xhtml", "xml", "xsl". > </pre> > ``` I see no *lang-vb* or *lang-basic* option. Does anyone know if one exists as an add-in? --- Note: This is related to the [VB.NET code blocks](https://web.archive.org/web/20080914043525/http://stackoverflow.uservoice.com:80/pages/general/suggestions/18775) suggestion for Stack Overflow.
/EDIT: I've rewritten the whole posting. Below is a pretty complete solution to the VB highlighting problem. If SO has got nothing better, *please* use it. VB syntax highlighting is definitely wanted. I've also added a code example with some complex code literals that gets highlighted correctly. However, I haven't even tried to get XLinq right. Might still work, though. The [keywords list](http://msdn.microsoft.com/en-us/library/ksh7h19t.aspx) is taken from the MSDN. Contextual keywords are not included. Did you know the `GetXmlNamespace` operator? The algorithm knows literal type characters. It should also be able to handle identifier type characters but I haven't tested these. Note that the code works on **HTML**. As a consequence, &, < and > are required to be read as named (!) entities, not single characters. Sorry for the long regex. ``` var highlightVB = function(code) { var regex = /("(?:""|[^"])+"c?)|('.*$)|#.+?#|(&amp;[HO])?\d+(\.\d*)?(e[+-]?\d+)?U?([SILDFR%@!#]|&amp;)?|\.\d+[FR!#]?|\s+|\w+|&amp;|&lt;|&gt;|([-+*/\\^$@!#%&<>()\[\]{}.,:=]+)/gi; var lines = code.split("\n"); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var tokens; var result = ""; while (tokens = regex.exec(line)) { var tok = getToken(tokens); switch (tok.charAt(0)) { case '"': if (tok.charAt(tok.length - 1) == "c") result += span("char", tok); else result += span("string", tok); break; case "'": result += span("comment", tok); break; case '#': result += span("date", tok); break; default: var c1 = tok.charAt(0); if (isDigit(c1) || tok.length > 1 && c1 == '.' && isDigit(tok.charAt(1)) || tok.length > 5 && (tok.indexOf("&amp;") == 0 && tok.charAt(5) == 'H' || tok.charAt(5) == 'O') ) result += span("number", tok); else if (isKeyword(tok)) result += span("keyword", tok); else result += tok; break; } } lines[i] = result; } return lines.join("\n"); } var keywords = [ "addhandler", "addressof", "alias", "and", "andalso", "as", "boolean", "byref", "byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate", "cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "continue", "csbyte", "cshort", "csng", "cstr", "ctype", "cuint", "culng", "cushort", "date", "decimal", "declare", "default", "delegate", "dim", "directcast", "do", "double", "each", "else", "elseif", "end", "endif", "enum", "erase", "error", "event", "exit", "false", "finally", "for", "friend", "function", "get", "gettype", "getxmlnamespace", "global", "gosub", "goto", "handles", "if", "if", "implements", "imports", "in", "inherits", "integer", "interface", "is", "isnot", "let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit", "mustoverride", "mybase", "myclass", "namespace", "narrowing", "new", "next", "not", "nothing", "notinheritable", "notoverridable", "object", "of", "on", "operator", "option", "optional", "or", "orelse", "overloads", "overridable", "overrides", "paramarray", "partial", "private", "property", "protected", "public", "raiseevent", "readonly", "redim", "rem", "removehandler", "resume", "return", "sbyte", "select", "set", "shadows", "shared", "short", "single", "static", "step", "stop", "string", "structure", "sub", "synclock", "then", "throw", "to", "true", "try", "trycast", "typeof", "variant", "wend", "uinteger", "ulong", "ushort", "using", "when", "while", "widening", "with", "withevents", "writeonly", "xor", "#const", "#else", "#elseif", "#end", "#if" ] var isKeyword = function(token) { return keywords.indexOf(token.toLowerCase()) != -1; } var isDigit = function(c) { return c >= '0' && c <= '9'; } var getToken = function(tokens) { for (var i = 0; i < tokens.length; i++) if (tokens[i] != undefined) return tokens[i]; return null; } var span = function(class, text) { return "<span class=\"" + class + "\">" + text + "</span>"; } ``` Code for testing: ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load 'set page title Page.Title = "Something" Dim r As String = "Say ""Hello""" Dim i As Integer = 1234 Dim d As Double = 1.23 Dim s As Single = .123F Dim l As Long = 123L Dim ul As ULong = 123UL Dim c As Char = "x"c Dim h As Integer = &amp;H0 Dim t As Date = #5/31/1993 1:15:30 PM# Dim f As Single = 1.32e-5F End Sub ```
Prettify does support VB comments as of the 8th of January 2009. To get vb syntax highlighting working correctly you need three things; ``` <script type="text/javascript" src="/External/css/prettify/prettify.js"></script> <script type="text/javascript" src="/External/css/prettify/lang-vb.js"></script> ``` and a PRE block around your code eg: ``` <PRE class="prettyprint lang-vb"> Function SomeVB() as string ' do stuff i = i + 1 End Function </PRE> ``` Stackoverflow is missing the lang-vb.js inclusion, and the ability to specify which language via Markdown, ie: `class="prettyprint lang-vb"` which is why it doesn't work here. for details on the issue: see [the Prettify issues log](http://code.google.com/p/google-code-prettify/issues/detail?id=68)
Is there a lang-vb or lang-basic option for prettify.js from Google?
[ "", "javascript", "vb.net", "prettify", "" ]
Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#?
Since this question was last answered in 2008, iTextSharp has improved their api dramatically. If you download the latest version of their api from <http://sourceforge.net/projects/itextsharp/>, you can use the following snippet of code to extract all text from a pdf into a string. ``` using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; namespace PdfParser { public static class PdfTextExtractor { public static string pdfText(string path) { PdfReader reader = new PdfReader(path); string text = string.Empty; for(int page = 1; page <= reader.NumberOfPages; page++) { text += PdfTextExtractor.GetTextFromPage(reader,page); } reader.Close(); return text; } } } ```
**[iTextSharp](https://github.com/itext/itextsharp)** is the best bet. Used it to make a spider for lucene.Net so that it could crawl PDF. ``` using System; using System.IO; using iTextSharp.text.pdf; using System.Text.RegularExpressions; namespace Spider.Utils { /// <summary> /// Parses a PDF file and extracts the text from it. /// </summary> public class PDFParser { /// BT = Beginning of a text object operator /// ET = End of a text object operator /// Td move to the start of next line /// 5 Ts = superscript /// -5 Ts = subscript #region Fields #region _numberOfCharsToKeep /// <summary> /// The number of characters to keep, when extracting text. /// </summary> private static int _numberOfCharsToKeep = 15; #endregion #endregion #region ExtractText /// <summary> /// Extracts a text from a PDF file. /// </summary> /// <param name="inFileName">the full path to the pdf file.</param> /// <param name="outFileName">the output file name.</param> /// <returns>the extracted text</returns> public bool ExtractText(string inFileName, string outFileName) { StreamWriter outFile = null; try { // Create a reader for the given PDF file PdfReader reader = new PdfReader(inFileName); //outFile = File.CreateText(outFileName); outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8); Console.Write("Processing: "); int totalLen = 68; float charUnit = ((float)totalLen) / (float)reader.NumberOfPages; int totalWritten = 0; float curUnit = 0; for (int page = 1; page <= reader.NumberOfPages; page++) { outFile.Write(ExtractTextFromPDFBytes(reader.GetPageContent(page)) + " "); // Write the progress. if (charUnit >= 1.0f) { for (int i = 0; i < (int)charUnit; i++) { Console.Write("#"); totalWritten++; } } else { curUnit += charUnit; if (curUnit >= 1.0f) { for (int i = 0; i < (int)curUnit; i++) { Console.Write("#"); totalWritten++; } curUnit = 0; } } } if (totalWritten < totalLen) { for (int i = 0; i < (totalLen - totalWritten); i++) { Console.Write("#"); } } return true; } catch { return false; } finally { if (outFile != null) outFile.Close(); } } #endregion #region ExtractTextFromPDFBytes /// <summary> /// This method processes an uncompressed Adobe (text) object /// and extracts text. /// </summary> /// <param name="input">uncompressed</param> /// <returns></returns> public string ExtractTextFromPDFBytes(byte[] input) { if (input == null || input.Length == 0) return ""; try { string resultString = ""; // Flag showing if we are we currently inside a text object bool inTextObject = false; // Flag showing if the next character is literal // e.g. '\\' to get a '\' character or '\(' to get '(' bool nextLiteral = false; // () Bracket nesting level. Text appears inside () int bracketDepth = 0; // Keep previous chars to get extract numbers etc.: char[] previousCharacters = new char[_numberOfCharsToKeep]; for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' '; for (int i = 0; i < input.Length; i++) { char c = (char)input[i]; if (input[i] == 213) c = "'".ToCharArray()[0]; if (inTextObject) { // Position the text if (bracketDepth == 0) { if (CheckToken(new string[] { "TD", "Td" }, previousCharacters)) { resultString += "\n\r"; } else { if (CheckToken(new string[] { "'", "T*", "\"" }, previousCharacters)) { resultString += "\n"; } else { if (CheckToken(new string[] { "Tj" }, previousCharacters)) { resultString += " "; } } } } // End of a text object, also go to a new line. if (bracketDepth == 0 && CheckToken(new string[] { "ET" }, previousCharacters)) { inTextObject = false; resultString += " "; } else { // Start outputting text if ((c == '(') && (bracketDepth == 0) && (!nextLiteral)) { bracketDepth = 1; } else { // Stop outputting text if ((c == ')') && (bracketDepth == 1) && (!nextLiteral)) { bracketDepth = 0; } else { // Just a normal text character: if (bracketDepth == 1) { // Only print out next character no matter what. // Do not interpret. if (c == '\\' && !nextLiteral) { resultString += c.ToString(); nextLiteral = true; } else { if (((c >= ' ') && (c <= '~')) || ((c >= 128) && (c < 255))) { resultString += c.ToString(); } nextLiteral = false; } } } } } } // Store the recent characters for // when we have to go back for a checking for (int j = 0; j < _numberOfCharsToKeep - 1; j++) { previousCharacters[j] = previousCharacters[j + 1]; } previousCharacters[_numberOfCharsToKeep - 1] = c; // Start of a text object if (!inTextObject && CheckToken(new string[] { "BT" }, previousCharacters)) { inTextObject = true; } } return CleanupContent(resultString); } catch { return ""; } } private string CleanupContent(string text) { string[] patterns = { @"\\\(", @"\\\)", @"\\226", @"\\222", @"\\223", @"\\224", @"\\340", @"\\342", @"\\344", @"\\300", @"\\302", @"\\304", @"\\351", @"\\350", @"\\352", @"\\353", @"\\311", @"\\310", @"\\312", @"\\313", @"\\362", @"\\364", @"\\366", @"\\322", @"\\324", @"\\326", @"\\354", @"\\356", @"\\357", @"\\314", @"\\316", @"\\317", @"\\347", @"\\307", @"\\371", @"\\373", @"\\374", @"\\331", @"\\333", @"\\334", @"\\256", @"\\231", @"\\253", @"\\273", @"\\251", @"\\221"}; string[] replace = { "(", ")", "-", "'", "\"", "\"", "à", "â", "ä", "À", "Â", "Ä", "é", "è", "ê", "ë", "É", "È", "Ê", "Ë", "ò", "ô", "ö", "Ò", "Ô", "Ö", "ì", "î", "ï", "Ì", "Î", "Ï", "ç", "Ç", "ù", "û", "ü", "Ù", "Û", "Ü", "®", "™", "«", "»", "©", "'" }; for (int i = 0; i < patterns.Length; i++) { string regExPattern = patterns[i]; Regex regex = new Regex(regExPattern, RegexOptions.IgnoreCase); text = regex.Replace(text, replace[i]); } return text; } #endregion #region CheckToken /// <summary> /// Check if a certain 2 character token just came along (e.g. BT) /// </summary> /// <param name="tokens">the searched token</param> /// <param name="recent">the recent character array</param> /// <returns></returns> private bool CheckToken(string[] tokens, char[] recent) { foreach (string token in tokens) { if ((recent[_numberOfCharsToKeep - 3] == token[0]) && (recent[_numberOfCharsToKeep - 2] == token[1]) && ((recent[_numberOfCharsToKeep - 1] == ' ') || (recent[_numberOfCharsToKeep - 1] == 0x0d) || (recent[_numberOfCharsToKeep - 1] == 0x0a)) && ((recent[_numberOfCharsToKeep - 4] == ' ') || (recent[_numberOfCharsToKeep - 4] == 0x0d) || (recent[_numberOfCharsToKeep - 4] == 0x0a)) ) { return true; } } return false; } #endregion } } ```
Reading PDF documents in .Net
[ "", "c#", ".net", "pdf", "" ]
Why does C#.Net allow the declaration of the string object to be case-insensitive? ``` String sHello = "Hello"; string sHello = "Hello"; ``` Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this. Can anyone explain why?
**`string`** is a language keyword while `System.String` is the type it aliases. Both compile to exactly the same thing, similarly: * **`int`** is `System.Int32` * **`long`** is `System.Int64` * **`float`** is `System.Single` * **`double`** is `System.Double` * **`char`** is `System.Char` * **`byte`** is `System.Byte` * **`short`** is `System.Int16` * **`ushort`** is `System.UInt16` * **`uint`** is `System.UInt32` * **`ulong`** is `System.UInt64` I think in most cases this is about code legibility - all the basic system value types have aliases, I think the lower case `string` might just be for consistency.
Further to the other answers, it's good practice to use keywords if they exist. E.g. you should use **string** rather than **System.String**.
C#.Net case-insensitive string
[ "", "c#", ".net", "" ]
I've tried several things already, ``` std::stringstream m; m.empty(); m.clear(); ``` both of which don't work.
For all the standard library types the member function `empty()` is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents". The `clear()` member function is inherited from `ios` and is used to clear the error state of the stream, e.g. if a file stream has the error state set to `eofbit` (end-of-file), then calling `clear()` will set the error state back to `goodbit` (no error). For clearing the contents of a `stringstream`, using: ``` m.str(""); ``` is correct, although using: ``` m.str(std::string()); ``` is technically more efficient, because you avoid invoking the `std::string` constructor that takes `const char*`. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.
You can **clear the error state **and** empty the stringstream** all in one line ``` std::stringstream().swap(m); // swap m with a default constructed stringstream ``` This effectively resets m to a default constructed state, meaning that **it actually deletes the buffers allocated by the string stream and resets the error state**. Here's an experimental proof: ``` int main () { std::string payload(16, 'x'); std::stringstream *ss = new std::stringstream; // Create a memory leak (*ss) << payload; // Leak more memory // Now choose a way to "clear" a string stream //std::stringstream().swap(*ss); // Method 1 //ss->str(std::string()); // Method 2 std::cout << "end" << std::endl; } ``` [Demo](http://coliru.stacked-crooked.com/a/937f6a279f4cc876) When the demo is compiled with address sanitizer, memory usage is revealed: ``` ================================================================= ==10415==ERROR: LeakSanitizer: detected memory leaks Direct leak of 392 byte(s) in 1 object(s) allocated from: #0 0x510ae8 in operator new(unsigned long) (/tmp/1637178326.0089633/a.out+0x510ae8) #1 0x514e80 in main (/tmp/1637178326.0089633/a.out+0x514e80) #2 0x7f3079ffb82f in __libc_start_main /build/glibc-Cl5G7W/glibc-2.23/csu/../csu/libc-start.c:291 Indirect leak of 513 byte(s) in 1 object(s) allocated from: #0 0x510ae8 in operator new(unsigned long) (/tmp/1637178326.0089633/a.out+0x510ae8) #1 0x7f307b03a25c in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::reserve(unsigned long) (/usr/local/lib64/libstdc++.so.6+0x13725c) #2 0x603000000010 (<unknown module>) SUMMARY: AddressSanitizer: 905 byte(s) leaked in 2 allocation(s). ``` Pretty steep if you ask me. To hold just 16bytes of payload, we spent 905 bytes ... string streams are no toy. Memory is allocated in two parts: * The constructed string stream (392 bytes) * The extra buffer needed for the payload (513 bytes). The extraneous size has to do with the allocation strategy chosen by the stream and for payloads <= 8 bytes, blocks inside the initial object can be used. If you [enable method 1](http://coliru.stacked-crooked.com/a/a9c231eb2783479b) (the one shown in this answer) the extra 513 (payload) bytes are reclaimed, because the stream is **actually cleared**. If you [enable method2](http://coliru.stacked-crooked.com/a/de372b604e5b9b51) as suggested in the comments or other answers, you can see that all 905 bytes are in use by the time we exit. In terms of program semantics, one may only care that the stream "appears" and "behaves" as empty, similar to how a `vector::clear` may leave the capacity untouched but render the vector empty to the user (of course vector would spend just 16 bytes here). Given the memory allocation that string stream requires, I can imagine this approach being often faster. **This answer's primary goal is to actually clear the string stream, given that memory consumption that comes with it is no joke**. Depending on your use case (number of streams, data they hold, frequency of clearing) you may choose the best approach. Finally note that it's rarely useful to clear the stream without clearing the error state **and all inherited state**. The one liner in this answer does both.
How do you clear a stringstream variable?
[ "", "c++", "stringstream", "" ]
Can I return it as an object if I am doing a ``` Select OneItem from Table Where OtherItem = "blah"? ``` Is there a better way to do this? I am building a constructor to return an object based on its name rather than its ID.
`query.UniqueResult<T>()` returns just one **T**
If there's more than one potential result, then `query.FirstResult()` might be better.
IQuery NHibernate - does it HAVE to be a list?
[ "", "c#", ".net", "nhibernate", "" ]
I have three tables `tag`, `page`, `pagetag` With the data below ***page*** ``` ID NAME 1 page 1 2 page 2 3 page 3 4 page 4 ``` ***tag*** ``` ID NAME 1 tag 1 2 tag 2 3 tag 3 4 tag 4 ``` ***pagetag*** ``` ID PAGEID TAGID 1 2 1 2 2 3 3 3 4 4 1 1 5 1 2 6 1 3 ``` I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output. ``` ID NAME TAGS 1 page 1 tag 1, tag 2, tag 3 2 page 2 tag 1, tag 3 3 page 3 tag 4 4 page 4 ``` Is this possible with SQL? --- I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.
> Sergio del Amo: > > > However, I am not getting the pages without tags. I guess i need to write my query with left outer joins. ``` SELECT pagetag.id, page.name, group_concat(tag.name) FROM ( page LEFT JOIN pagetag ON page.id = pagetag.pageid ) LEFT JOIN tag ON pagetag.tagid = tag.id GROUP BY page.id; ``` Not a very pretty query, but should give you what you want - `pagetag.id` and `group_concat(tag.name)` will be `null` for page 4 in the example you've posted above, but the page shall appear in the results.
Yep, you can do it across the 3 something like the below: ``` SELECT page_tag.id, page.name, group_concat(tags.name) FROM tag, page, page_tag WHERE page_tag.page_id = page.page_id AND page_tag.tag_id = tag.id; ``` Has not been tested, and could be probably be written a tad more efficiently, but should get you started! Also, MySQL is assumed, so may not play so nice with MSSQL! And MySQL isn't wild about hyphens in field names, so changed to underscores in the above examples.
Concatenate several fields into one with SQL
[ "", "sql", "mysql", "" ]
I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage. So far I have this (simplified): ``` DECLARE @ResultTable table ( StaffName nvarchar(100), Stage1Count int, Stage2Count int ) INSERT INTO @ResultTable (StaffName, Stage1Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage1 = 1 GROUP BY StaffName INSERT INTO @ResultTable (StaffName, Stage2Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage2 = 1 GROUP BY StaffName ``` The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist. Does anyone know how to do this, or can suggest a different approach? I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option). I'm using SQL Server 2005. **Edit: @Lee:** Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL. **Edit: @BCS:** I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.
IIRC there is some sort of "On Duplicate" (name might be wrong) syntax that lets you update if a row exists (MySQL) Alternately some form of: ``` INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count) SELECT StaffName,0,0 FROM ViewJob GROUP BY StaffName UPDATE @ResultTable Stage1Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage1 = 1 @ResultTable.StaffName = StaffName) UPDATE @ResultTable Stage2Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage2 = 1 @ResultTable.StaffName = StaffName) ```
Actually, I think you're making it much harder than it is. Won't this code work for what you're trying to do? ``` SELECT StaffName, SUM(InStage1) AS 'JobsAtStage1', SUM(InStage2) AS 'JobsAtStage2' FROM ViewJob GROUP BY StaffName ```
How do I do an Upsert Into Table?
[ "", "sql", "sql-server", "t-sql", "" ]
Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML? Note: * The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point. * The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character. *Background:* I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification. In .NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.
It **may not be perfect** (emphasis added since people missing this disclaimer), but what I've done in that case is below. You can adjust to use with a stream. ``` /// <summary> /// Removes control characters and other non-UTF-8 characters /// </summary> /// <param name="inString">The string to process</param> /// <returns>A string with no control characters or entities above 0x00FD</returns> public static string RemoveTroublesomeCharacters(string inString) { if (inString == null) return null; StringBuilder newString = new StringBuilder(); char ch; for (int i = 0; i < inString.Length; i++) { ch = inString[i]; // remove any characters outside the valid UTF-8 range as well as all control characters // except tabs and new lines //if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r') //if using .NET version prior to 4, use above logic if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4 { newString.Append(ch); } } return newString.ToString(); } ```
I like Eugene's whitelist concept. I needed to do a similar thing as the original poster, but I needed to support all Unicode characters, not just up to 0x00FD. The XML spec is: Char = #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] In .NET, the internal representation of Unicode characters is only 16 bits, so we can't `allow' 0x10000-0x10FFFF explicitly. The XML spec explicitly *disallows* the surrogate code points starting at 0xD800 from appearing. However it is possible that if we allowed these surrogate code points in our whitelist, utf-8 encoding our string might produce valid XML in the end as long as proper utf-8 encoding was produced from the surrogate pairs of utf-16 characters in the .NET string. I haven't explored this though, so I went with the safer bet and didn't allow the surrogates in my whitelist. The comments in Eugene's solution are misleading though, the problem is that the characters we are excluding are not valid in *XML* ... they are perfectly valid Unicode code points. We are not removing `non-utf-8 characters'. We are removing utf-8 characters that may not appear in well-formed XML documents. ``` public static string XmlCharacterWhitelist( string in_string ) { if( in_string == null ) return null; StringBuilder sbOutput = new StringBuilder(); char ch; for( int i = 0; i < in_string.Length; i++ ) { ch = in_string[i]; if( ( ch >= 0x0020 && ch <= 0xD7FF ) || ( ch >= 0xE000 && ch <= 0xFFFD ) || ch == 0x0009 || ch == 0x000A || ch == 0x000D ) { sbOutput.Append( ch ); } } return sbOutput.ToString(); } ```
How do you remove invalid hexadecimal characters from an XML-based data source prior to constructing an XmlReader or XPathDocument that uses the data?
[ "", "c#", "xml", "validation", "encoding", "" ]
I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport. What I've got right now is ``` byte[] buffer = ...; // read from file // a few lines that prove I can process the data successfully String element = new String(buffer); byte[] newBuffer = element.getBytes(); // a few lines that try to process newBuffer and fail because it is not the same data anymore ``` Does anyone know how to convert binary to String and back without data loss? Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem. EDIT: Just for the sake of completeness, I used the [Base64](http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html) class from the [Apache Commons](http://commons.apache.org/) [Codec](http://commons.apache.org/codec/) package to solve this problem.
If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data
[String(byte[])](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) treats the data as the default character encoding. So, how bytes get converted from 8-bit values to 16-bit Java Unicode chars will vary not only between operating systems, but can even vary between different users using different codepages on the same machine! This constructor is only good for decoding one of your own text files. Do not try to convert arbitrary bytes to chars in Java! Encoding as [base64](http://en.wikipedia.org/wiki/Base64) is a good solution. This is how files are sent over SMTP (e-mail). The (free) Apache [Commons Codec](http://commons.apache.org/codec/) project will do the job. ``` byte[] bytes = loadFile(file); //all chars in encoded are guaranteed to be 7-bit ASCII byte[] encoded = Base64.encodeBase64(bytes); String printMe = new String(encoded, "US-ASCII"); System.out.println(printMe); byte[] decoded = Base64.decodeBase64(encoded); ``` Alternatively, you can use the Java 6 [DatatypeConverter](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html): ``` import java.io.*; import java.nio.channels.*; import javax.xml.bind.DatatypeConverter; public class EncodeDecode { public static void main(String[] args) throws Exception { File file = new File("/bin/ls"); byte[] bytes = loadFile(file, new ByteArrayOutputStream()).toByteArray(); String encoded = DatatypeConverter.printBase64Binary(bytes); System.out.println(encoded); byte[] decoded = DatatypeConverter.parseBase64Binary(encoded); // check for (int i = 0; i < bytes.length; i++) { assert bytes[i] == decoded[i]; } } private static <T extends OutputStream> T loadFile(File file, T out) throws IOException { FileChannel in = new FileInputStream(file).getChannel(); try { assert in.size() == in.transferTo(0, in.size(), Channels.newChannel(out)); return out; } finally { in.close(); } } } ```
How do you convert binary data to Strings and back in Java?
[ "", "java", "serialization", "" ]
In what situation would it be more appropriate for me to use a bitset (STL container) to manage a set of flags rather than having them declared as a number of separate (bool) variables? Will I get a significant performance gain if I used a bitset for 50 flags rather than using 50 separate bool variables?
Well, 50 bools as a bitset will take 7 bytes, while 50 bools as bools will take 50 bytes. These days that's not really a big deal, so using bools is probably fine. However, one place a bitset might be useful is if you need to pass those bools around a lot, especially if you need to return the set from a function. Using a bitset you have less data that has to be moved around on the stack for returns. Then again, you could just use refs instead and have even less data to pass around. :)
std::bitset will give you extra points when you need to serialize / deserialize it. You can just write it to a stream or read from a stream with it. But certainly, the separate bools are going to be faster. They are optimized for this kind of use after all, while a bitset is optimized for space, and has still function calls involved. It will never be faster than separate bools. ### Bitset * Very space efficient * Less efficient due to bit fiddling * Provides serialize / de-serialize with `op<<` and `op>>` * All bits packed together: You will have the flags at one place. ### Separate bools * Very fast * Bools are not packed together. They will be members somewhere. Decide on the facts. I, personally, would use `std::bitset` for some not-performance critical, and would use bools if I either have only a few bools (and thus it's quite overview-able), or if I need the extra performance.
When to use STL bitsets instead of separate variables?
[ "", "c++", "performance", "bitsets", "" ]
I have a page using `<ul>` lists for navigation (Javascript changes the styling to display or not on mouseover). This is working fine for me *except* in IE6 and IE7 when I have a Google Map on the page. In this case the drop-down simply does not work. However, the page continues to work in FireFox 2. I have done a little bit of research and discovered that this may be an example of the IE Select Box Bug, but I am not sure as the Google Map appears to be using a `<div>`, not an `<iframe>`. Has anyone else encountered a problem similar to this, and if so do they have any recommendations on the best way to overcome this problem?
I don't know if this will fix your problem but you may want to try [this solution at ccsplay.co.uk](http://www.cssplay.co.uk/menus/pro_drop8.html) which fixes the problem of menus appearing underneath drop-down lists. I don't know if it will work for sure, but it's worth a shot.
I fixed a similar issue with drop-downs not appearing over flash movies in IE6/IE7/IE8 using this [jQuery](http://jquery.com/): ``` $(function () { $("#primary-nav").appendTo("#footer"); }); ``` Where `primary-nav` is the `ID` of the drop-down container element and `footer` is the `ID` of the last element on the page. I then used absolute positioning to relocate the dropdowns back to the top where they belong. The reason this works is because IE respects source ordering more than it does the `z-index`. It still wasn't able to display over top of a Windows Media Player plugin though.
Best way to fix CSS/JS drop-down in IE7 when page includes Google Map
[ "", "javascript", "css", "cross-browser", "browser", "client-side", "" ]
Using C# and WPF under .NET (rather than [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) or console), what is the correct way to create an application that can only be run as a single instance? I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are. The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.
Here is a very good [article](http://sanity-free.org/143/csharp_dotnet_single_instance_application.html) regarding the Mutex solution. The approach described by the article is advantageous for two reasons. First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a dependency on that assembly, I would probably advocate using the approach [shown in another answer](https://stackoverflow.com/a/19326/3195477). But as it is, I do not use the Microsoft.VisualBasic assembly, and I'd rather not add an unnecessary dependency to my project. Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance. That's a very nice touch that the other Mutex solutions described here do not address. --- ### UPDATE As of 8/1/2014, the article I linked to above is still active, but the blog hasn't been updated in a while. That makes me worry that eventually it might disappear, and with it, the advocated solution. I'm reproducing the content of the article here for posterity. The words belong solely to the blog owner at [Sanity Free Coding](http://sanity-free.org/). > Today I wanted to refactor some code that prohibited my application > from running multiple instances of itself. > > Previously I had use [System.Diagnostics.Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx) to search for an > instance of my myapp.exe in the process list. While this works, it > brings on a lot of overhead, and I wanted something cleaner. > > Knowing that I could use a mutex for this (but never having done it > before) I set out to cut down my code and simplify my life. > > In the class of my application main I created a static named [Mutex](http://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx): ``` static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] ... } ``` > Having a named mutex allows us to stack synchronization across > multiple threads and processes which is just the magic I'm looking > for. > > [Mutex.WaitOne](http://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx) has an overload that specifies an amount of time for us > to wait. Since we're not actually wanting to synchronizing our code > (more just check if it is currently in use) we use the overload with > two parameters: [Mutex.WaitOne(Timespan timeout, bool exitContext)](http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx). > Wait one returns true if it is able to enter, and false if it wasn't. > In this case, we don't want to wait at all; If our mutex is being > used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0 > milliseconds), and set the exitContext to true so we can exit the > synchronization context before we try to aquire a lock on it. Using > this, we wrap our Application.Run code inside something like this: ``` static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { MessageBox.Show("only one instance at a time"); } } } ``` > So, if our app is running, WaitOne will return false, and we'll get a > message box. > > Instead of showing a message box, I opted to utilize a little Win32 to > notify my running instance that someone forgot that it was already > running (by bringing itself to the top of all the other windows). To > achieve this I used [PostMessage](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644944(v=vs.85).aspx) to broadcast a custom message to every > window (the custom message was registered with [RegisterWindowMessage](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947(v=vs.85).aspx) > by my running application, which means only my application knows what > it is) then my second instance exits. The running application instance > would receive that notification and process it. In order to do that, I > overrode [WndProc](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.wndproc(v=vs.110).aspx) in my main form and listened for my custom > notification. When I received that notification I set the form's > TopMost property to true to bring it up on top. > > Here is what I ended up with: > > * Program.cs ``` static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { // send our Win32 message to make the currently running instance // jump on top of all the other windows NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); } } } ``` > * NativeMethods.cs ``` // this class just wraps some Win32 stuff that we're going to use internal class NativeMethods { public const int HWND_BROADCAST = 0xffff; public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport("user32")] public static extern int RegisterWindowMessage(string message); } ``` > * Form1.cs (front side partial) ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } protected override void WndProc(ref Message m) { if(m.Msg == NativeMethods.WM_SHOWME) { ShowMe(); } base.WndProc(ref m); } private void ShowMe() { if(WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } // get our current "TopMost" value (ours will always be false though) bool top = TopMost; // make our form jump to the top of everything TopMost = true; // set it back to whatever it was TopMost = top; } } ```
You could use the Mutex class, but you will soon find out that you will need to implement the code to pass the arguments and such yourself. Well, I learned a trick when programming in WinForms when I read [Chris Sell's book](http://sellsbrothers.com/wfbook/). This trick uses logic that is already available to us in the framework. I don't know about you, but when I learn about stuff I can reuse in the framework, that is usually the route I take instead of reinventing the wheel. Unless of course it doesn't do everything I want. When I got into WPF, I came up with a way to use that same code, but in a WPF application. This solution should meet your needs based off your question. First, we need to create our application class. In this class we are going override the OnStartup event and create a method called Activate, which will be used later. ``` public class SingleInstanceApplication : System.Windows.Application { protected override void OnStartup(System.Windows.StartupEventArgs e) { // Call the OnStartup event on our base class base.OnStartup(e); // Create our MainWindow and show it MainWindow window = new MainWindow(); window.Show(); } public void Activate() { // Reactivate the main window MainWindow.Activate(); } } ``` Second, we will need to create a class that can manage our instances. Before we go through that, we are actually going to reuse some code that is in the Microsoft.VisualBasic assembly. Since, I am using C# in this example, I had to make a reference to the assembly. If you are using VB.NET, you don't have to do anything. The class we are going to use is WindowsFormsApplicationBase and inherit our instance manager off of it and then leverage properties and events to handle the single instancing. ``` public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase { private SingleInstanceApplication _application; private System.Collections.ObjectModel.ReadOnlyCollection<string> _commandLine; public SingleInstanceManager() { IsSingleInstance = true; } protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs) { // First time _application is launched _commandLine = eventArgs.CommandLine; _application = new SingleInstanceApplication(); _application.Run(); return false; } protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) { // Subsequent launches base.OnStartupNextInstance(eventArgs); _commandLine = eventArgs.CommandLine; _application.Activate(); } } ``` Basically, we are using the VB bits to detect single instance's and process accordingly. OnStartup will be fired when the first instance loads. OnStartupNextInstance is fired when the application is re-run again. As you can see, I can get to what was passed on the command line through the event arguments. I set the value to an instance field. You could parse the command line here, or you could pass it to your application through the constructor and the call to the Activate method. Third, it's time to create our EntryPoint. Instead of newing up the application like you would normally do, we are going to take advantage of our SingleInstanceManager. ``` public class EntryPoint { [STAThread] public static void Main(string[] args) { SingleInstanceManager manager = new SingleInstanceManager(); manager.Run(args); } } ``` Well, I hope you are able to follow everything and be able use this implementation and make it your own.
What is the correct way to create a single-instance WPF application?
[ "", "c#", ".net", "wpf", "mutex", "" ]
How can I create an [iterator](https://stackoverflow.com/questions/9884132/what-are-iterator-iterable-and-iteration) in Python? For example, suppose I have a class whose instances logically "contain" some values: ``` class Example: def __init__(self, values): self.values = values ``` I want to be able to write code like: ``` e = Example([1, 2, 3]) # Each time through the loop, expose one of the values from e.values for value in e: print("The example object contains", value) ``` More generally, the iterator should be able to control where the values come from, or even compute them on the fly (rather than considering any particular attribute of the instance).
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: `__iter__()` and `__next__()`. * The `__iter__` returns the iterator object and is implicitly called at the start of loops. * The `__next__()` method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. Here's a simple example of a counter: ``` class Counter: def __init__(self, low, high): self.current = low - 1 self.high = high def __iter__(self): return self def __next__(self): # Python 2: def next(self) self.current += 1 if self.current < self.high: return self.current raise StopIteration for c in Counter(3, 9): print(c) ``` This will print: ``` 3 4 5 6 7 8 ``` This is easier to write using a generator, as covered in a previous answer: ``` def counter(low, high): current = low while current < high: yield current current += 1 for c in counter(3, 9): print(c) ``` The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, [Iterators and Simple Generators](https://www.ibm.com/developerworks/library/l-pycon/), is a pretty good introduction.
There are four ways to build an iterative function: * create a generator (uses the [yield keyword](http://docs.python.org/py3k/reference/expressions.html#yield-expressions)) * use a generator expression ([genexp](http://docs.python.org/py3k/reference/expressions.html#generator-expressions)) * create an iterator (defines [`__iter__` and `__next__`](http://docs.python.org/py3k/library/stdtypes.html?highlight=__iter__#iterator-types) (or `next` in Python 2.x)) * create a class that Python can iterate over on its own ([defines `__getitem__`](http://docs.python.org/py3k/reference/datamodel.html?highlight=__getitem__#object.__getitem__)) Examples: ``` # generator def uc_gen(text): for char in text.upper(): yield char # generator expression def uc_genexp(text): return (char for char in text.upper()) # iterator protocol class uc_iter(): def __init__(self, text): self.text = text.upper() self.index = 0 def __iter__(self): return self def __next__(self): try: result = self.text[self.index] except IndexError: raise StopIteration self.index += 1 return result # getitem method class uc_getitem(): def __init__(self, text): self.text = text.upper() def __getitem__(self, index): return self.text[index] ``` To see all four methods in action: ``` for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem: for ch in iterator('abcde'): print(ch, end=' ') print() ``` Which results in: ``` A B C D E A B C D E A B C D E A B C D E ``` **Note**: The two generator types (`uc_gen` and `uc_genexp`) cannot be `reversed()`; the plain iterator (`uc_iter`) would need the `__reversed__` magic method (which, [according to the docs](https://docs.python.org/3/reference/datamodel.html#object.__reversed__), must return a new iterator, but returning `self` works (at least in CPython)); and the getitem iteratable (`uc_getitem`) must have the `__len__` magic method: ``` # for uc_iter we add __reversed__ and update __next__ def __reversed__(self): self.index = -1 return self def __next__(self): try: result = self.text[self.index] except IndexError: raise StopIteration self.index += -1 if self.index < 0 else +1 return result # for uc_getitem def __len__(self) return len(self.text) ``` --- To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above: ``` # generator def even_gen(): result = 0 while True: yield result result += 2 # generator expression def even_genexp(): return (num for num in even_gen()) # or even_iter or even_getitem # not much value under these circumstances # iterator protocol class even_iter(): def __init__(self): self.value = 0 def __iter__(self): return self def __next__(self): next_value = self.value self.value += 2 return next_value # getitem method class even_getitem(): def __getitem__(self, index): return index * 2 import random for iterator in even_gen, even_genexp, even_iter, even_getitem: limit = random.randint(15, 30) count = 0 for even in iterator(): print even, count += 1 if count >= limit: break print ``` Which results in (at least for my sample run): ``` 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 ``` --- How to choose which one to use? This is mostly a matter of taste. The two methods I see most often are generators and the iterator protocol, as well as a hybrid (`__iter__` returning a generator). Generator expressions are useful for replacing list comprehensions (they are lazy and so can save on resources). If one needs compatibility with earlier Python 2.x versions use `__getitem__`.
How to build a basic iterator?
[ "", "python", "object", "iterator", "" ]
Could somebody please do a rundown of how to programmatically encrypt a config-file in .NET, preferably in C#. What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings. Also if anyone could list the types of encryption-providers and what is the difference between them. I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET.
To summarize the answers and what I've found so far, here are some good links to answer this question: * [Encrypting Configuration Information in ASP.NET 2.0 Applications - 4GuysFromRolla.com](https://web.archive.org/web/20211029043331/https://aspnet.4guysfromrolla.com/articles/021506-1.aspx) * [How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI - MSDN](http://msdn.microsoft.com/en-us/library/ms998280.aspx) Please feel free to complement with other links, maybe some to WinForms- or WPF-applications.
There is a good article from 4 guys about [Encrypting Configuration Information in ASP.NET 2.0 Applications](https://web.archive.org/web/20211029043331/https://aspnet.4guysfromrolla.com/articles/021506-1.aspx) Hope this helps
Programmatically encrypting a config-file in .NET
[ "", "c#", ".net", "configuration", "encryption", "configuration-files", "" ]
I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <http://www.dayah.com/periodic/>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (<http://www.dayah.com/periodic/Script/interactivity.js>) I still can't figure out how the url is built. Thanks.
The periodic table example loads the printer-friendly version of the wiki artice into an iframe. <http://en.wikipedia.org/wiki/Potasium>?**printable=yes** it's done in *function click\_wiki(e)* (line 534, interactivity.js) > ``` > var article = el.childNodes[0].childNodes[n_name].innerHTML; > ... > window.frames["WikiFrame"].location.replace("http://" + language + ".wikipedia.org/w/index.php?title=" + encodeURIComponent(article) + "&printable=yes"); > ```
@VolkerK is right, they are using the printable version. Here is an easy way to find out when you know the site is displaying the page in an iframe. In Firefox right click anywhere inside the iframe, from the context menu select "This Frame" then "View frame info" You get the info you need including the Address: > Address: <http://en.wikipedia.org/w/index.php?title=Chromium&printable=yes>
iframe wikipedia article without the wrapper
[ "", "javascript", "iframe", "wikipedia", "" ]
If you're building an `AJA~Xy` app, are there any downsides to using `JSONP` requests/responses even if you're not planning on any `cross-domain` requests? The only thing I can think of is that there are a couple extra bytes for the callback wrapper... **Edit:** I found [this](http://remysharp.com/2007/10/08/what-is-jsonp/) which also suggests `security and error handling` as potential problems... > There's no error handling. The `script injection` either works, or it doesn't. > If there's an error from the `injection`, it'll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the `server side`. I don't think `error handling` is much of a problem... most of us would use a library to generate the `JSON`... the well-formedness of my response isn't a concern for this question. **and security:** > There are documents out on the web that can help, but as a cursory check, I would check the referrer in the `server side` script. it seems like this is a potential problem with any type of response... certainly, there's nothing unique to `JSONP` in the security arena...?
Downside? It's fairly limited - you trigger a "GET" request and get back some script that's executed. You don't get error handling if your server throws an error, so you need to wrap all errors in JSON as well. You can't really cancel or retry the request. You're at the mercy of the various browser author opinions of "correct" behavior for dynamically-generated `<script>` tags. Debugging is somewhat more difficult. That said, i've used it on occasion, and haven't suffered. YMMV.
Retrieving errors when a jsonp call fails is possible. <http://code.google.com/p/jquery-jsonp/> Hope it helps.
Are there reasons not to use JSONP for AJA~X requests?
[ "", "javascript", "ajax", "json", "jsonp", "" ]
If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux?
A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code. **A typical mistake is to write something like**: ``` if os.path.exists(path): os.unlink(path) ``` The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months) So, in your particular case, I would probably do: ``` try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: print 'path %s does not exist or is a broken symlink' % path else: raise e ``` The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink. So, I guess you have no choice than to break the atomicity, and do something like ``` if not os.path.exists(os.readlink(path)): print 'path %s is a broken symlink' % path ```
This is not atomic but it works. `os.path.islink(filename) and not os.path.exists(filename)` Indeed by [RTFM](https://docs.python.org/2/library/os.path.html) (reading the fantastic manual) we see > os.path.exists(path) > > Return True if path refers to an existing path. Returns False for broken symbolic links. It also says: > On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. So if you are worried about permissions, you should add other clauses.
Find broken symlinks with Python
[ "", "python", "linux", "symlink", "" ]
I've seen this done in a few sites, an example is [artofadambetts.com](http://www.artofadambetts.com/weblog/?p=169). The scroll bar on the page scrolls only an element of the page, not the entire page. I looked at the source and havent't been able to figure it out yet. How is this done?
That's pretty nifty. He uses "position:fixed" on most of the divs, and the one that scrolls is the one that doesn't have it.
In fact it is not the scrolling part that is "doing the job", it is the fixed part of the page. In order to do this, you should use CSS and add `position: fixed;` property (use it with `top`, `bottom`, `left` and/or `right` properties) to the elements that you wish not to scroll. And you should not forget to give them a greater `z-index`, if you don't there might be some of the scrolling element that can go over your fixed element as you scroll (and you certainly don't want that).
How to set up the browser scrollbar to scroll part of a page?
[ "", "javascript", "html", "css", "" ]
I'm looking for a key/value pair object that I can include in a web service. I tried using .NET's [`System.Collections.Generic.KeyValuePair<>`](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this. Is there any other generic class that can be used for this situation? I'd use .NET's [`System.Web.UI.Pair`](http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety.
Just define a struct/class. ``` [Serializable] public struct KeyValuePair<K,V> { public K Key {get;set;} public V Value {get;set;} } ```
I don't think there is as `Dictionary<>` itself isn't XML serializable, when I had need to send a dictionary object via a web service I ended up wrapping the `Dictionary<>` object myself and adding support for `IXMLSerializable`. ``` /// <summary> /// Represents an XML serializable collection of keys and values. /// </summary> /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam> /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam> [XmlRoot("dictionary")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { #region Constants /// <summary> /// The default XML tag name for an item. /// </summary> private const string DEFAULT_ITEM_TAG = "Item"; /// <summary> /// The default XML tag name for a key. /// </summary> private const string DEFAULT_KEY_TAG = "Key"; /// <summary> /// The default XML tag name for a value. /// </summary> private const string DEFAULT_VALUE_TAG = "Value"; #endregion #region Protected Properties /// <summary> /// Gets the XML tag name for an item. /// </summary> protected virtual string ItemTagName { get { return DEFAULT_ITEM_TAG; } } /// <summary> /// Gets the XML tag name for a key. /// </summary> protected virtual string KeyTagName { get { return DEFAULT_KEY_TAG; } } /// <summary> /// Gets the XML tag name for a value. /// </summary> protected virtual string ValueTagName { get { return DEFAULT_VALUE_TAG; } } #endregion #region Public Methods /// <summary> /// Gets the XML schema for the XML serialization. /// </summary> /// <returns>An XML schema for the serialized object.</returns> public XmlSchema GetSchema() { return null; } /// <summary> /// Deserializes the object from XML. /// </summary> /// <param name="reader">The XML representation of the object.</param> public void ReadXml(XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) { return; } while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement(ItemTagName); reader.ReadStartElement(KeyTagName); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement(ValueTagName); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } /// <summary> /// Serializes this instance to XML. /// </summary> /// <param name="writer">The writer to serialize to.</param> public void WriteXml(XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement(ItemTagName); writer.WriteStartElement(KeyTagName); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement(ValueTagName); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } #endregion } ```
Is there a serializable generic Key/Value pair class in .NET?
[ "", "c#", ".net", "" ]
Let's say I have the following simple enum: ``` enum Response { Yes = 1, No = 2, Maybe = 3 } ``` How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?
I probably wouldn't **bind** the data as it's an enum, and it won't change after compile time (unless I'm having one of those *stoopid* moments). Better just to iterate through the enum: ``` Dim itemValues As Array = System.Enum.GetValues(GetType(Response)) Dim itemNames As Array = System.Enum.GetNames(GetType(Response)) For i As Integer = 0 To itemNames.Length - 1 Dim item As New ListItem(itemNames(i), itemValues(i)) dropdownlist.Items.Add(item) Next ``` Or the same in C# ``` Array itemValues = System.Enum.GetValues(typeof(Response)); Array itemNames = System.Enum.GetNames(typeof(Response)); for (int i = 0; i <= itemNames.Length - 1 ; i++) { ListItem item = new ListItem(itemNames[i], itemValues[i]); dropdownlist.Items.Add(item); } ```
Use the following utility class `Enumeration` to get an `IDictionary<int,string>` (Enum value & name pair) from an **Enumeration**; you then bind the **IDictionary** to a bindable Control. ``` public static class Enumeration { public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct { var enumerationType = typeof (TEnum); if (!enumerationType.IsEnum) throw new ArgumentException("Enumeration type is expected."); var dictionary = new Dictionary<int, string>(); foreach (int value in Enum.GetValues(enumerationType)) { var name = Enum.GetName(enumerationType, value); dictionary.Add(value, name); } return dictionary; } } ``` **Example:** Using the utility class to bind enumeration data to a control ``` ddlResponse.DataSource = Enumeration.GetAll<Response>(); ddlResponse.DataTextField = "Value"; ddlResponse.DataValueField = "Key"; ddlResponse.DataBind(); ```
How do you bind an Enum to a DropDownList control in ASP.NET?
[ "", "c#", ".net", "asp.net", "" ]
I could only find the function `confirm()` that gives OK/Cancel buttons. Is there any way to give Yes/No buttons?
Javascript offers 3 modal boxes. `prompt`, `confirm` and `alert`. None of those satisfy your request. There are a plethora of js modal popup solutions. Here's an example. * [ModalBox](https://github.com/okonet/modalbox)
No. Instead you could use a in browser modal popup.
Code to ask yes/no question in javascript
[ "", "javascript", "" ]
Best recommendations for accessing and manipulation of sqlite databases from JavaScript.
Well, if you are working on client side JavaScript, I think you will be out of luck... browsers tend to sandbox the JavaScript environment so you don't have access to the machine in any kind of general capacity like accessing a database. If you are talking about an SQLite DB on the server end accessed from the client end, you could set up an AJAX solution that invokes some server side code to access it. If you are talking about Rhino or some other server side JavaScript, you should look into the host language's API access into SQLite (such as the JDBC for Rhino). Perhaps clarify your question a bit more...?
There a project called [`sql.js`](https://github.com/kripken/sql.js) which is a port of SQLite in JavaScript. > sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten.
JavaScript sqlite
[ "", "javascript", "sqlite", "" ]
I need to grab the `base64-encoded` representation of the `ViewState`. Obviously, this would not be available until fairly late in the request lifecycle, which is OK. For example, if the output of the page includes: ``` <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" /> ``` I need a way on the server-side to get the value `"/wEPDwUJODU0Njc5MD...=="` To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being *sent* to the client, not the ViewState I'm getting back from them.
Rex, I suspect a good place to start looking is solutions that **compress the ViewState** -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be. * [Scott Hanselman on ViewState Compression](http://www.hanselman.com/blog/CommentView,guid,febce059-7e7c-439e-af3d-c53d250b3e9c.aspx) (2005) * [ViewState Compression with System.IO.Compression](http://www.bloggingdeveloper.com/post/How-To-Compress-ViewState-in-ASPNET-20-ViewState-Compression-with-SystemIOCompression.aspx) (2007)
See this [blog post](http://aspguy.wordpress.com/2008/07/09/reducing-the-page-size-by-storing-viewstate-on-server/) where the author describes a method for overriding the default behavior for generating the ViewState and instead shows how to save it on the server Session object. > In ASP.NET 2.0, ViewState is saved by > a descendant of PageStatePersister > class. This class is an abstract class > for saving and loading ViewsState and > there are two implemented descendants > of this class in .Net Framework, named > HiddenFieldPageStatePersister and > SessionPageStatePersister. By default > HiddenFieldPageStatePersister is used > to save/load ViewState information, > but we can easily get the > SessionPageStatePersister to work and > save ViewState in Session object. Although I did not test his code, it seems to show exactly what you want: a way to gain access to ViewState code while still on the server, before postback.
How to get the value of built, encoded ViewState?
[ "", "c#", "asp.net", "viewstate", "" ]
I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this: ``` byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3); ``` `smallPortion` would equal 1,2,3,4 `largeBytes` would equal 5,6,7,8,9
This is how I would do that: ``` using System; using System.Collections; using System.Collections.Generic; class ArrayView<T> : IEnumerable<T> { private readonly T[] array; private readonly int offset, count; public ArrayView(T[] array, int offset, int count) { this.array = array; this.offset = offset; this.count = count; } public int Length { get { return count; } } public T this[int index] { get { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else return this.array[offset + index]; } set { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else this.array[offset + index] = value; } } public IEnumerator<T> GetEnumerator() { for (int i = offset; i < offset + count; i++) yield return array[i]; } IEnumerator IEnumerable.GetEnumerator() { IEnumerator<T> enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } } class Program { static void Main(string[] args) { byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ArrayView<byte> p1 = new ArrayView<byte>(arr, 0, 5); ArrayView<byte> p2 = new ArrayView<byte>(arr, 5, 5); Console.WriteLine("First array:"); foreach (byte b in p1) { Console.Write(b); } Console.Write("\n"); Console.WriteLine("Second array:"); foreach (byte b in p2) { Console.Write(b); } Console.ReadKey(); } } ```
In C# with Linq you can do this: ``` smallPortion = largeBytes.Take(4).ToArray(); largeBytes = largeBytes.Skip(4).Take(5).ToArray(); ``` ;)
How to split a byte array
[ "", "c#", "arrays", "split", "" ]
I am using the code snippet below, however it's not working quite as I understand it should. ``` public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line != null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } ``` From reading the Javadoc about `readLine()` it says: Reads a line of text. A line is considered to be terminated by any one of a line feed (`\n`), a carriage return (`\r`), or a carriage return followed immediately by a linefeed. **Returns**: A `String` containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached **Throws**: `IOException` - If an I/O error occurs From my understanding of this, `readLine` should return null the first time no input is entered other than a line termination, like `\r`. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly?
> From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'. That is not correct. `readLine` will return `null` if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses. But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned (`\n` or `\r\n` depending on your OS). So, if you want to break on both the empty string and the end of line, you should do: ``` while (line != null && !line.equals("")) ``` Also, your current program should work as expected if you pipe some file directly into it, like so: ``` java -cp . Echo < test.txt ```
No input is not the same as the end of the stream. You can usually simulate the end of the stream in a console by pressing `Ctrl`+`D` (AFAIK some systems use `Ctrl`+`Z` instead). But I guess this is not what you want so better test for empty strings additionally to null strings.
I Am Not Getting the Result I Expect Using readLine() in Java
[ "", "java", "java-io", "" ]
I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using `File.Delete()`.
Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the [**`MoveFileEx`** API function](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa) to mark the file for deletion upon next reboot. If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions.
The typical method is as follows. You've said you want to do this in C# so here goes... 1. If you don't know which process has the file locked, you'll need to examine each process's handle list, and query each handle to determine if it identifies the locked file. Doing this in C# will likely require P/Invoke or an intermediary C++/CLI to call the native APIs you'll need. 2. Once you've figured out which process(es) have the file locked, you'll need to safely inject a small native DLL into the process (you can also inject a managed DLL, but this is messier, as you then have to start or attach to the .NET runtime). 3. That bootstrap DLL then closes the handle using CloseHandle, etc. Essentially: the way to unlock a "locked" file is to inject a DLL file into the offending process's address space and close it yourself. You can do this using native or managed code. No matter what, you're going to need a small amount of native code or at least P/Invoke into the same. Helpful links: * *[Three Ways to Inject Your Code into Another Process](http://www.codeproject.com/KB/threads/winspy.aspx)* * *[.NET Code Injection](http://damianblog.com/2008/07/02/net-code-injection/)* Good luck!
How do I delete a file which is locked by another process in C#?
[ "", "c#", "file-locking", "" ]