Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of ``` function editRecord() { var gridView = document.getElementById("<%= GridView.ClientID %>"); var id = // somehow get the id here ??? window.open("edit.aspx?id=" + id); } ``` The question is how do I retrieve the selected records ID in javascript?
I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this: ``` <asp:TemplateField ShowHeader="False"> <ItemTemplate> <asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField Visible="False"> <ItemTemplate> <asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" /> </ItemTemplate> </asp:TemplateField> ``` Then on the OnRowDataBind have code to set the selected row ``` protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // Click to highlight row Control lnkSelect = e.Row.FindControl("lnkSelect"); if (lnkSelect != null) { StringBuilder click = new StringBuilder(); click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty)); click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex)); e.Row.Attributes.Add("onclick", click.ToString()); } } } ``` And then in the Javascript I have code like this ``` <script type="text/javascript"> var selectedRowIndex = null; function onGridViewRowSelected(rowIndex) { selectedRowIndex = rowIndex; } function editItem() { if (selectedRowIndex == null) return; var gridView = document.getElementById('<%= GridView1.ClientID %>'); var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0]; var hidID = cell.childNodes[0]; window.open('JobTypeEdit.aspx?id=' + hidID.value); } </script> ``` Works a treat :-)
1) change your javascript function to use a parameter ``` function editRecord(clientId) { .... ``` 2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple ``` <input type="button" onclick="editRecord(your-rows-client-id-goes-here)" /> ```
Get GridView selected row DataKey in Javascript
[ "", "asp.net", "javascript", "gridview", "" ]
I need to do some performance benchmarks on .NET programs (C#) in Windows, but I haven't done benchmarking much in the Windows world. I've looked into using the Windows 2000/XP Performance monitor with custom counters for this, but I don't think this is quite what I want. Are there any good system facilities for this in Windows XP, or do I need to just use System.Diagnostics.Stopwatch [edit] and write text logs for manual interpretation, or is there something else? Edit: is there anything beyond `System.Diagnostics.Stopwatch`?
For micro-benchmarking I really like MeasureIt (can be downloaded from <http://msdn.microsoft.com/en-us/magazine/cc500596.aspx>). It is a test project written by Vance Morrison a Performance Architect on the CLR. It currently has a good set of benchmarks for a number of .Net/CLR core methods. The best part of it is that it is trivial to tweak and add new benchmarks for whatever you would like to test. Simply run "MeasureIt /edit" and it will launch VS with the project for itself so that you can view how those benchmarks are written and add new ones in a similar fashion if you like. As already been stated StopWatch is probably the easiest way to do this and MeasureIt uses StopWatch underneath for its timings but it also does some other things like running a block of code X times and then providing you stats for the runs and what not.
``` using System.Diagnostics; .... Stopwatch sw = new Stopwatch(); sw.Start(); // Code you want to time... // Note: for averaged accuracy (without other OS effects), // run timed code multiple times in a loop // and then divide by the number of runs. sw.Stop(); Console.WriteLine("Took " + sw.ElapsedTicks + " Ticks"); ```
What's the best way to benchmark programs in Windows?
[ "", "c#", ".net", "windows", "performance", "benchmarking", "" ]
I was wondering what are the benefits of using anything else but Java for Mobile Application Development.
Java is the most ubiquitous and for that alone it is your best choice.
I do think that yes, Java is the most common language for devices, with two exceptions: * Windows mobile applications, that are frequently built in C++ but that will be built more on the .NET framework in the future. * iPhone applications, that use Cocoa and Objective-C.
Is Java the best language for Mobile App Devlopment?
[ "", "java", "mobile", "" ]
Consider the following code: ``` void Handler(object o, EventArgs e) { // I swear o is a string string s = (string)o; // 1 //-OR- string s = o as string; // 2 // -OR- string s = o.ToString(); // 3 } ``` What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?
``` string s = (string)o; // 1 ``` Throws [InvalidCastException](https://msdn.microsoft.com/en-us/library/system.invalidcastexception) if `o` is not a `string`. Otherwise, assigns `o` to `s`, even if `o` is `null`. ``` string s = o as string; // 2 ``` Assigns `null` to `s` if `o` is not a `string` or if `o` is `null`. For this reason, you cannot use it with value types (the operator could never return `null` in that case). Otherwise, assigns `o` to `s`. ``` string s = o.ToString(); // 3 ``` Causes a [NullReferenceException](https://msdn.microsoft.com/en-us/library/system.nullreferenceexception) if `o` is `null`. Assigns whatever `o.ToString()` returns to `s`, no matter what type `o` is. --- Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions). 3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
1. `string s = (string)o;` Use when something should *definitely* be the other thing. 2. `string s = o as string;` Use when something *might be* the other thing. 3. `string s = o.ToString();` Use when you don't care what it is but you just want to use the available string representation.
Direct casting vs 'as' operator?
[ "", "c#", "casting", "" ]
I have two tables containing Tasks and Notes, and want to retrieve a list of tasks with the number of associated notes for each one. These two queries do the job: ``` select t.TaskId, (select count(n.TaskNoteId) from TaskNote n where n.TaskId = t.TaskId) 'Notes' from Task t -- or select t.TaskId, count(n.TaskNoteId) 'Notes' from Task t left join TaskNote n on t.TaskId = n.TaskId group by t.TaskId ``` Is there a difference between them and should I be using one over the other, or are they just two ways of doing the same job? Thanks.
On small datasets they are wash when it comes to performance. When indexed, the LOJ is a little better. I've found on large datasets that an inner join (an inner join will work too.) will outperform the subquery by a very large factor (sorry, no numbers).
In most cases, the optimizer will treat them the same. I tend to prefer the second, because it has less nesting, which makes it easier to read and easier to maintain. I have started to use SQL Server's common table expressions to reduce nesting as well for the same reason. In addition, the second syntax is more flexible if there are further aggregates which may be added in the future in addition to COUNT, like MIN(some\_scalar), MAX(), AVG() etc.
Transact-SQL - sub query or left-join?
[ "", "sql", "t-sql", "" ]
Using C# .NET 2.0, I have an owner-drawn ListView where I'm overriding the OnDrawColumnHeader, OnDrawItem and OnDrawSubitem events. If I set the View property to Details at design-time, everything works beautifully and I can switch the View property and all view modes display as they should (I'm not using Tile view). However, if I start in any other View, both the List and Details views are blank. I know you'll probably want to see code, but there's a lot of it, so I'm hesitant to post that much, but can if necessary. I'm more curious if someone has seen this before, and/or might have an inkling of how to fix it. The View property will be a user-saved setting, so I won't always be able to start in Details view by default.
The WinForms ListView is mostly a layer of abstraction of the top of the actual Windows control, so there are aspect of its behaviour that are, well, counterintuitive is a polite way of putting things. I have a vague recollection, from back in my days as a Delphi developer, that when you are Owner drawing a ListView, the subitems of the control aren't actually populated unless your Listview is in "Details" mode when you load the items. Things to try ... ... force the WinForms control to recreate the underlying windows handle after you change the display style. If memory serves, DestroyHandle() is the method you want. ... assuming you have a "Refresh" in your application to reload the data, do things work properly when you refresh after changing the display style? ... if all else fails, beg borrow or steal a copy of Charles' Petzolds classic on windows programming.
Either SubItems are not added, or you didn't add any columns. That's my initial feeling.
Why doesn't my ListView display List or Details items?
[ "", "c#", ".net", "winforms", "listview", "" ]
currently i obtain the below result from the following C# line of code when in es-MX Culture ``` Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-mx"); <span><%=DateTime.Now.ToLongDateString()%></span> ``` # miércoles, 22 de octubre de 2008 i would like to obtain the following # Miércoles, 22 de Octubre de 2008 do i need to Build my own culture?
You don't need to build your own culture. You only need to change the property DateTimeFormat.DayNames and DateTimeFormat.MonthNames in the current culture. i.e. ``` string[] newNames = { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo" }; Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = newNames; ``` However, it's weird that en-US show months and days with the first uppercase letter and for mx-ES not. Hope it helps!.
a little late but this work for me! ``` public static string GetFecha() { System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-EC"); System.Threading.Thread.CurrentThread.CurrentCulture = culture; // maldita sea! string strDate = culture.TextInfo.ToTitleCase(DateTime.Now.ToLongDateString()); return strDate.Replace("De", "de"); } ```
how to uppercase date and month first letter of ToLongDateString() result in es-mx Culture?
[ "", "c#", ".net", "datetime", "internationalization", "culture", "" ]
I'm parsing XML results from an API call using PHP and xpath. ``` $dom = new DOMDocument(); $dom->loadXML($response->getBody()); $xpath = new DOMXPath($dom); $xpath->registerNamespace("a", "http://www.example.com"); $hrefs = $xpath->query('//a:Books/text()', $dom); for ($i = 0; $i < $hrefs->length; $i++) { $arrBookTitle[$i] = $hrefs->item($i)->data; } $hrefs = $xpath->query('//a:Books', $dom); for ($i = 0; $i < $hrefs->length; $i++) { $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal'); } ``` This works but is there a way I can access both the text and the attribute from one query? And if so how do you get to those items once query is executed?
After doing some looking around I came across this solution. This way I can get the element text and access any attributes of the node. ``` $hrefs = $xpath->query('//a:Books', $dom); for ($i = 0; $i < $hrefs->length; $i++) { $arrBookTitle[$i] = $hrefs->item($i)->nodeValue; $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal'); } ```
One single XPath expression that will select both the text nodes of "a:Books" and their "DeweyDecimal" attribute, is the following `//a:Books/text() | //a:Books/@DeweyDecimal` **Do note** the use of the XPath's union operator in the expression above. **Another note**: try to avoid using the "//" abbreviation as it may cause the whole XML document to be traversed and thus is very expensive. It is recommended to use a more specific XPath expression (such as consisting of a chain of specific location steps) always when the structure of the XML document is known.
Pulling both the text and attribute of a given node using Xpath
[ "", "php", "dom", "xpath", "" ]
My 11 year old son is very interested in programming. He has been working with [Scratch](http://scratch.mit.edu) for a couple years but has now outgrown it. I recently helped him install Visual C# Express Edition and he is very excited to work with it, but we're having a hard time finding good resources for him online. He learns best by looking at sample programs, dissecting them, altering them, etc. Searching around I wasn't able to find many good samples for him to download and try in C# Express Edition. Can anyone point me in the direction of a good set of sample programs for a kid learning C#, or any other resources you think might be good for him? BTW I'm a programmer myself but I've been almost exclusively working with Linux for a long time, so when it comes to Microsoft I'm pretty lost!
I would recommend [Coding4Fun](http://blogs.msdn.com/coding4fun/). There are some very nice projects out there which would appeal to an 11 year old. I recall seeing some games, screensavers, and even a sample which shows how to make a WinForms app look like it is bleeding (awesome for Halloween, eh?)
Hmm... given that C# isn't really a "teaching language" (and that's not to say it's a bad choice), I suspect there aren't a lot of tutorials targeted at younger kinds. Have you considered doing some parallel learning and trying to pick up C# with your son? It might be a good bonding experience for both of you, and with your background in programming, you'll likely have a lot of insight to share, even if it's more language agnostic knowledge about things like algorithms, style, commenting, pitfalls to avoid, etc.
Resources for Kids Learning C#
[ "", "c#", "" ]
I have multiple threads (C# application running on IIS) running that all need to communicate with the same MQ backend. To minimize network traffic, I need to only send a backend request when there is work to be done. There will be one thread to monitor if there is work to be done, and it needs to notify the other threads that they should also begin processing. The current solution involves the monitor thread setting a global variable and having the other threads loop and check that, ie in the monitor thread: ``` CheckIfWorkAvailable() { while(true) { if (queue.Empty != true) { workToBeDone = true; } }//end while loop } ``` and then in the worker threads: ``` DoWork() { while(true) { if (workToBeDone == true) { //do work... } else { Thread.Sleep(x seconds) } }//end while loop } ``` Can the monitor thread notify the worker threads when there is work to do instead of having them just loop and sleep? The worker threads also set a counter indicating they are working and the decrement it when their work is done so the workToBeDone flag can be set to false.
Check out [WaitHandle](http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx) and its descending classes. [EventWaitHandle](http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.aspx) may suit your needs.
As well as the WaitHandle classes pointed out by Kent, simple [Monitor.Wait](http://msdn.microsoft.com/en-us/library/system.threading.monitor.wait.aspx) and Monitor.[Pulse](http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx)/[PulseAll](http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulseall.aspx) can do this easily. They're "lighter" than event handles, although somewhat more primitive. (You can't wait on multiple monitors, etc.) I have an example of this (as a producer consumer queue) in my [threading article](http://www.yoda.arachsys.com/csharp/threads/deadlocks.shtml).
Suspending and notifying threads when there is work to do
[ "", "c#", "multithreading", "" ]
## How would you unittest a safe-publication guarantee in Java? To be concrete: I have a Cache interface that has a method getOrLoad(K key, ObjectLoader loader). Thing is, if a Cache cannot find an object for the given key, then it must load it from the ObjectLoader instance. However, the Cache is required to guarantee that the act of loading an object from the loader and putting it into the Cache, constitutes a safe publication. I'm now in the midst of writing a generic junit test for this Cache interface and I wonder how I would test that the Cache implementations adhere to this safe publication guarantee. Any ideas? The actual code is in the test-systest module part of the [code repository](http://github.com/karmazilla/nanocaching/tree/master) in case you want to poke at the real files.
I discovered a [JavaOne presentation](http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-2220&yr=2007&track=5) by Bill Pugh, Brian Goetz and Cliff Click on the subject of testing concurrent code. They suggested this approach, witch I think is the best I've heard: A number of producers create stateful and thread-unsafe objects with a state-dependant hashCode implementation. As the objects are sendt through the supposed synchronizatoin point, the hashCodes are summed up (thread-locally). Likewise, the consumers on the other side of the gate sum up the hashCodes. At the end of the test, we sum up all the results for the producers and consumers respectively. If the two sums are equal, the test passes. We could also use XOR as an alternative to sum. In fact, any commutative operation will do. Just keep in mind that the test harness itself must not introduce any additional synchronization.
Maybe you can use [ConTest](http://www.alphaworks.ibm.com/tech/contest) to at least give you a little more confidence that your code is correct. You'll need to implement a couple of tests that run several threads concurrently. ConTest will then increase the probability that a concurrency bug is actually revealed by instrumenting byte code (adding heuristically-controlled conditional sleep and yield instructions).
Unit testing for safe publication
[ "", "java", "unit-testing", "concurrency", "junit", "" ]
A couple of the options are: ``` $connection = {my db connection/object}; function PassedIn($connection) { ... } function PassedByReference(&$connection) { ... } function UsingGlobal() { global $connection; ... } ``` So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference. I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities. The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.
I use a Singleton ResourceManager class to handle stuff like DB connections and config settings through a whole app: ``` class ResourceManager { private static $DB; private static $Config; public static function get($resource, $options = false) { if (property_exists('ResourceManager', $resource)) { if (empty(self::$$resource)) { self::_init_resource($resource, $options); } if (!empty(self::$$resource)) { return self::$$resource; } } return null; } private static function _init_resource($resource, $options = null) { if ($resource == 'DB') { $dsn = 'mysql:host=localhost'; $username = 'my_username'; $password = 'p4ssw0rd'; try { self::$DB = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } } elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) { self::$$resource = new $resource($options); } } } ``` And then in functions / objects / where ever: ``` function doDBThingy() { $db = ResourceManager::get('DB'); if ($db) { $stmt = $db->prepare('SELECT * FROM `table`'); etc... } } ``` I use it to store messages, error messages and warnings, as well as global variables. There's an interesting question [here](https://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton) on when to actually use this type of class.
Try designing your code in an object-oriented fashion. Methods that use the database should be grouped in a class, and the class instance should contain the database connection as a class variable. That way the database connection is available to the functions that need it, but it's not global. ``` class MyClass { protected $_db; public function __construct($db) { $this->_db = $db; } public function doSomething() { $this->_db->query(...); } } ```
What is the best method for getting a database connection/object into a function in PHP?
[ "", "php", "database", "" ]
This is a bit of a lazyweb question but you get the rep so :-) I have a Java class that returns instances of itself to allow chaining (e.g. ClassObject.doStuff().doStuff()) For instance: ``` public class Chainer { public Chainer doStuff() { /* Do stuff ... */ return this; } } ``` I would like to extend this class. Is there a way, perhaps using generics, to extend this class without having to overwrite each method signature? E.g. not: ``` public class ChainerExtender extends Chainer { public ChainerExtender doStuff() { super.doStuff(); return this; } } ``` I have tried: ``` public class Chainer { public <A extends Chainer> A doStuff() { /* Do stuff ... */ return (A)this; } } public class ChainerExtender extends Chainer { public <A extends Chainer> A doStuff() { /* Do stuff ... */ return super.doStuff(); } } ``` But this didn't work giving the error: ``` type parameters of <A>A cannot be determined; no unique maximal instance exists for type variable A with upper bounds A,Chainer ``` Am I forced to have class declarations like: ``` public class Chainer<T extends Chainer<T>> {} public class ChainerExtender extends Chainer<ChainerExtender> ``` As per [this question](https://stackoverflow.com/questions/153994/generic-type-args-which-specificy-the-extending-class)?
Have you tried the straight-forward ``` public class Chainer { public Chainer doStuff() { /* Do stuff ... */ return this; } } public class ChainerExtender extends Chainer { @Override public ChainerExtender doStuff() { /* Do stuff ... */ super.doStuff(); return this; } } ``` With Java 5, you can declare overriding methods to have co-variant return types, which means just what this says: a subclass can have an overriding method signature with a more specific return type.
Why not have them all return an interface? You'd have to define all of the possible chained methods in the interface and provide "null" implementations in the base class, but you'd be able to chain to your heart's content. ``` public interface IChainer { IChainer doStuff(); IChainer doSomethingElse(); } public class Chainer implements IChainer { public IChainer doStuff() { // really do something return this; } public IChainer doSomethingElse() { return this; // do nothing } } public class ChainerExtender extends Chainer { // simply inherits implementation for doStuff() public override IChainer doSomethingElse() { // really do something return this; } } ``` Note: I may have some syntax issues above. I've been programming mostly in C# for the last few years. Hopefully, you get the idea.
How do I write a Java function that returns a typed instance of 'this' and works when extended?
[ "", "java", "generics", "" ]
I am using the following code: ``` <?php $stock = $_GET[s]; //returns stock ticker symbol eg GOOG or YHOO $first = $stock[0]; $url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html"; $data = file_get_contents($url); $r_header = '/Prev. Week(.+?)Next Week/'; $r_date = '/\<b\>(.+?)\<\/b\>/'; preg_match($r_header,$data,$header); preg_match($r_date, $header[1], $date); echo $date[1]; ?> ``` I've checked the regular expressions [here](http://www.quanetic.com/regex.php) and they appear to be valid. If I check just $url or $data they come out correctly and if I print $data and check the source the code that I'm looking for to use in the regex is in there. If you're interested in checking anything, an example of a proper URL would be <http://biz.yahoo.com/research/earncal/g/goog.html> I've tried everything I could think of, including both var\_dump($header) and var\_dump($date), both of which return empty arrays. I have been able to create other regular expressions that works. For instance, the following correctly returns "Earnings": ``` $r_header = '/Company (.+?) Calendar/'; preg_match($r_header,$data,$header); echo $header[1]; ``` I am going nuts trying to figure out why this isn't working. Any help would be awesome. Thanks.
Problem is that the HTML has newlines in it, which you need to incorporate with the s regex modifier, as below ``` <?php $stock = "goog";//$_GET[s]; //returns stock ticker symbol eg GOOG or YHOO $first = $stock[0]; $url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html"; $data = file_get_contents($url); $r_header = '/Prev. Week(.+?)Next Week/s'; $r_date = '/\<b\>(.+?)\<\/b\>/s'; preg_match($r_header,$data,$header); preg_match($r_date, $header[1], $date); var_dump($header); ?> ```
Your regex doesn't allow for the line breaks in the HTML Try: ``` $r_header = '/Prev\. Week((?s:.*))Next Week/'; ``` The `s` tells it to match the newline characters in the `.` (match any).
Supposedly valid regular expression doesn't return any data in PHP
[ "", "php", "regex", "" ]
[tempfile.mkstemp()](http://www.python.org/doc/2.5.2/lib/module-tempfile.html) returns: > a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order. How do I convert that OS-level handle to a file object? The [documentation for os.open()](http://www.python.org/doc/2.5.2/lib/os-fd-ops.html) states: > To wrap a file descriptor in a "file > object", use fdopen(). So I tried: ``` >>> import tempfile >>> tup = tempfile.mkstemp() >>> import os >>> f = os.fdopen(tup[0]) >>> f.write('foo\n') Traceback (most recent call last): File "<stdin>", line 1, in ? IOError: [Errno 9] Bad file descriptor ```
You can use ``` os.write(tup[0], "foo\n") ``` to write to the handle. If you want to open the handle for writing you need to add the **"w"** mode ``` f = os.fdopen(tup[0], "w") f.write("foo") ```
Here's how to do it using a with statement: ``` from __future__ import with_statement from contextlib import closing fd, filepath = tempfile.mkstemp() with closing(os.fdopen(fd, 'w')) as tf: tf.write('foo\n') ```
Python - How do I convert "an OS-level handle to an open file" to a file object?
[ "", "python", "temporary-files", "mkstemp", "fdopen", "" ]
What is MySQL equivalent of the `Nz` Function in Microsoft Access? Is `Nz` a SQL standard? In Access, the `Nz` function lets you return a value when a variant is null. [Source](http://www.techonthenet.com/access/functions/advanced/nz.php) The syntax for the `Nz` function is: ``` Nz ( variant, [ value_if_null ] ) ```
The [`COALESCE()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce) function does what you describe. It's standard SQL and it should be supported in all SQL databases. The [`IFNULL()`](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull) function is not standard SQL. Only some brands of databases support this function.
COALESCE does just what the OP is asking for, as does IFNULL: ``` SELECT Nz(MightBeNullVar, 0) FROM ... (MS Access version) SELECT COALESCE(MightBeNullVar, 0) FROM ... (MySQL version) SELECT IFNULL(MightBeNullVar, 0) FROM ... (MySQL version) ``` The difference is the COALESCE can search through multiple variables and return the first non-null one: ``` SELECT COALESCE(MightBeNullVar, MightAlsoBeNullVar, CouldBeNullVar, 0) FROM ... (MySQL version) ``` each of these will return a 0 (zero) if none of the values have a set value (are null). The IFNULL is (pretty meaninglessly) faster. There's probably other better things to optimize in your query before bothering with IFNULL vs COALESCE issues. If you have multiple things to check, use COALESCE. If you only have a single value to check, use IFNULL.
What is equivalent of the Nz Function in MS Access in MySQL? Is Nz a SQL standard?
[ "", "sql", "mysql", "database", "ms-access", "" ]
I've been recently asked to learn some MATLAB basics for a class. What does make it so cool for researchers and people that works in university? I saw it's cool to work with matrices and plotting things... (things that can be done easily in Python using some libraries). Writing a function or parsing a file is just painful. I'm still at the start, what am I missing? In the "real" world, what should I think to use it for? When should it can do better than Python? For better I mean: easy way to write something performing. --- **UPDATE 1:** One of the things I'd like to know the most is "Am I missing something?" :D **UPDATE 2:** Thank you for your answers. My question is not about buy or not to buy MATLAB. The university has the possibility to give me a copy of an old version of MATLAB (MATLAB 5 I guess) for free, without breaking the license. I'm interested in its capabilities and if it deserves a deeper study (I won't need anything more than *basic* MATLAB in oder to pass the exam :P ) it will really be better than Python for a specific kind of task in the real world.
Adam is only partially right. Many, if not most, mathematicians will never touch it. If there is a computer tool used at all, it's going to be something like [Mathematica](http://en.wikipedia.org/wiki/Mathematica) or [Maple](http://en.wikipedia.org/wiki/Maple_(software)). Engineering departments, on the other hand, often rely on it and there are definitely useful things for some applied mathematicians. It's also used heavily in industry in some areas. Something you have to realize about MATLAB is that it started off as a wrapper on [Fortran](http://en.wikipedia.org/wiki/Fortran) libraries for linear algebra. For a long time, it had an attitude that "all the world is an array of doubles (floats)". As a language, it has grown very organically, and there are some flaws that are very much baked in, if you look at it just as a programming language. However, if you look at it as an environment for doing certain types of research in, it has some real strengths. It's about as good as it gets for doing floating point linear algebra. The notation is simple and powerful, the implementation fast and trusted. It is very good at generating plots and other interactive tasks. There are a large number of `toolboxes' with good code for particular tasks, that are affordable. There is a large community of users that share numerical codes (Python + [NumPy](http://en.wikipedia.org/wiki/NumPy) has nothing in the same league, at least yet) Python, warts and all, is a much better programming language (as are many others). However, it's a decade or so behind in terms of the tools. The key point is that the majority of people who use MATLAB are not programmers really, and don't want to be. It's a lousy choice for a general programming language; it's quirky, slow for many tasks (you need to vectorize things to get efficient codes), and not easy to integrate with the outside world. On the other hand, for the things it is good at, it is very very good. Very few things compare. There's a company with reasonable support and who knows how many man-years put into it. This can matter in industry. Strictly looking at your Python vs. MATLAB comparison, they are mostly different tools for different jobs. In the areas where they do overlap a bit, it's hard to say what the better route to go is (depends a lot on what you're trying to do). But mostly Python isn't all that good at MATLAB's core strengths, and vice versa.
Most of answers do not get the point. There is ONE reason matlab is so good and so widely used: ## EXTREMELY FAST CODING I am a computer vision phD student and have been using matlab for 4 years, before my phD I was using different languages including C++, java, php, python... Most of the computer vision researchers are using exclusively matlab. ## 1) Researchers need fast prototyping In research environment, we have (hopefully) often new ideas, and we want to test them really quick to see if it's worth keeping on in that direction. And most often only a tiny sub-part of what we code will be useful. Matlab is often **slower at execution time**, but we don't care much. Because we don't know in advance what method is going to be successful, we have to try many things, so **our bottle neck is programming time**, because our code will most often run a few times to get the results to publish, and that's all. So let's see how matlab can help. ## 2) Everything I need is already there Matlab has really a lot of functions that I need, so that I don't have to reinvent them all the time: change the index of a matrix to 2d coordinate: `ind2sub` extract all patches of an image: `im2col`; compute a histogram of an image: `hist(Im(:))`; find the unique elements in a list `unique(list)`; add a vector to all vectors of a matrix `bsxfun(@plus,M,V)`; convolution on n-dimensional arrays `convn(A)`; calculate the computation time of a sub part of the code: `tic; %%code; toc`; graphical interface to crop an image: `imcrop(im)`; The list could be very long... And they are very easy to find by using the help. The closest to that is python...But It's just a pain in python, I have to go to google each time to look for the name of the function I need, and then I need to add packages, and the packages are not compatible one with another, the format of the matrix change, the convolution function only handle doubles but does not make an error when I give it char, just give a wrong output... no ## 3) IDE An example: I launch a script. It produces an error because of a matrix. **I can still execute code with the command line.** I visualize it doing: `imagesc(matrix)`. I see that the last line of the matrix is weird. I fix the bug. **All variables are still set**. I select the remaining of the code, press F9 to execute the selection, and everything goes on. **Debuging becomes fast**, thanks to that. Matlab underlines some of my errors before execution. So I can quickly see the problems. It proposes some way to make my code faster. There is an awesome **profiler** included in the IDE. KCahcegrind is such a pain to use compared to that. python's IDEs are awefull. python without ipython is not usable. I never manage to debug, using ipython. +autocompletion, help for function arguments,... ## 4) Concise code To normalize all the columns of a matrix ( which I need all the time), I do: `bsxfun(@times,A,1./sqrt(sum(A.^2)))` To remove from a matrix all colums with small sum: `A(:,sum(A)<e)=[]` **To do the computation on the GPU**: ``` gpuX = gpuarray(X); %%% code normally and everything is done on GPU ``` To paralize my code: ``` parfor n=1:100 %%% code normally and everything is multi-threaded ``` What language can beat that? And of course, I rarely need to make loops, everything is included in functions, which make the code way easier to read, and no headache with indices. So I can focus, on what I want to program, not how to program it. ## 5) Plotting tools Matlab is famous for its plotting tools. They are very helpful. Python's plotting tools have much less features. But there is one thing super annoying. You can plot figures only once per script??? if I have along script I cannot display stuffs at each step ---> useless. ## 6) Documentation Everything is very quick to access, everything is crystal clear, function names are well chosen. With python, I always need to google stuff, look in forums or stackoverflow.... complete time hog. **PS: Finally, what I hate with matlab: its price**
What is MATLAB good for? Why is it so used by universities? When is it better than Python?
[ "", "python", "matlab", "" ]
How do I check if an object is of a given type, or if it inherits from a given type? How do I check if the object `o` is of type `str`? --- Beginners often wrongly expect the string to *already be* "a number" - either expecting Python 3.x `input` to convert type, or expecting that a string like `'1'` is *also simultaneously* an integer. This is the wrong canonical for those questions. Please carefully read the question and then use [How do I check if a string represents a number (float or int)?](https://stackoverflow.com/questions/354038), [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/) and/or [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/) as appropriate.
Use [`isinstance`](https://docs.python.org/library/functions.html#isinstance) to check if `o` is an instance of `str` or any subclass of `str`: ``` if isinstance(o, str): ``` To check if the type of `o` is exactly `str`, *excluding subclasses of `str`*: ``` if type(o) is str: ``` See [Built-in Functions](http://docs.python.org/library/functions.html) in the Python Library Reference for relevant information. --- #### Checking for strings in Python 2 For Python 2, this is a better way to check if `o` is a string: ``` if isinstance(o, basestring): ``` because this will also catch Unicode strings. [`unicode`](https://docs.python.org/2/library/functions.html#unicode) is not a subclass of `str`; both `str` and `unicode` are subclasses of [`basestring`](https://docs.python.org/2/library/functions.html#basestring). In Python 3, `basestring` no longer exists since there's [a strict separation](https://docs.python.org/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit) of strings ([`str`](https://docs.python.org/3/library/functions.html#func-str)) and binary data ([`bytes`](https://docs.python.org/3/library/functions.html#func-bytes)). Alternatively, `isinstance` accepts a tuple of classes. This will return `True` if `o` is an instance of any subclass of any of `(str, unicode)`: ``` if isinstance(o, (str, unicode)): ```
The **most** Pythonic way to check the type of an object is... not to check it. Since Python encourages [Duck Typing](http://wikipedia.org/wiki/Duck_typing), you should just `try...except` to use the object's methods the way you want to use them. So if your function is looking for a writable file object, *don't* check that it's a subclass of `file`, just try to use its `.write()` method! Of course, sometimes these nice abstractions break down and `isinstance(obj, cls)` is what you need. But use sparingly.
What's the canonical way to check for type in Python?
[ "", "python", "types", "" ]
I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don't want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two functions then the decision has to be made at run-time or at compile-time autonomously).
Short answer: you can't. Longer answer: Use a curses library (ncurses on Unix, [pdcurses](http://pdcurses.sf.net/) on Windows). NCurses should be available through your package manager, and both ncurses and pdcurses have the exact same interface (pdcurses can also create windows independently from the console that behave like console windows). Most difficult answer: Use `#ifdef _WIN32` and stuff like that to make your code act differently on different operating systems.
There is no generic command to [clear the console on both platforms](http://www.daniweb.com/software-development/cpp/threads/95284/clearing-screen-in-the-console). ``` #include <cstdlib> void clear_screen() { #ifdef WINDOWS std::system("cls"); #else // Assume POSIX std::system ("clear"); #endif } ```
How do I clear the console in BOTH Windows and Linux using C++
[ "", "c++", "windows", "linux", "console", "cross-platform", "" ]
I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right? My only experience with garbage collection was on a couple of cheap eighties home computers, where it meant that the system would freeze up for a few seconds every so often. I'm sure it has improved since then, but as you can guess, that didn't leave me with a high opinion of it. What advantages could garbage collection offer an experienced C++ developer?
## I keep hearing people complaining that C++ doesn't have garbage collection. I am so sorry for them. Seriously. C++ has RAII, and I always complain to find no RAII (or a castrated RAII) in Garbage Collected languages. ## What advantages could garbage collection offer an experienced C++ developer? Another tool. Matt J wrote it quite right in his post ([Garbage Collection in C++ -- why?](https://stackoverflow.com/questions/228620/garbage-collection-in-c-why#228640)): We don't need C++ features as most of them could be coded in C, and we don't need C features as most of them could coded in Assembly, etc.. **C++ must evolve.** As a developer: I don't care about GC. I tried both RAII and GC, and I find RAII vastly superior. As said by Greg Rogers in his post ([Garbage Collection in C++ -- why?](https://stackoverflow.com/questions/228620/garbage-collection-in-c-why#228670)), memory leaks are not so terrible (at least in C++, where they are rare if C++ is really used) as to justify GC instead of RAII. GC has non deterministic deallocation/finalization and is just a way to **write a code that just don't care with specific memory choices**. This last sentence is important: It is important to write code that "juste don't care". In the same way in C++ RAII we don't care about ressource freeing because RAII do it for us, or for object initialization because constructor do it for us, it is sometimes important to just code without caring about who is owner of what memory, and what kind pointer (shared, weak, etc.) we need for this or this piece of code. **There seems to be a need for GC in C++.** (even if I personaly fail to see it) ## An example of good GC use in C++ Sometimes, in an app, you have "floating data". Imagine a tree-like structure of data, but no one is really "owner" of the data (and no one really cares about when exactly it will be destroyed). Multiple objects can use it, and then, discard it. You want it to be freed when no one is using it anymore. The C++ approach is using a smart pointer. The boost::shared\_ptr comes to mind. So each piece of data is owned by its own shared pointer. Cool. The problem is that when each piece of data can refer to another piece of data. You cannot use shared pointers because they are using a reference counter, which won't support circular references (A points to B, and B points to A). So you must know think a lot about where to use weak pointers (boost::weak\_ptr), and when to use shared pointers. With a GC, you just use the tree structured data. The downside being that you must not care **when** the "floating data" will really be destroyed. Only that it **will be** destroyed. ## Conclusion So in the end, if done properly, and compatible with the current idioms of C++, GC would be a **Yet Another Good Tool for C++**. C++ is a multiparadigm language: Adding a GC will perhaps make some C++ fanboys cry because of treason, but in the end, it could be a good idea, and I guess the C++ Standards Comitee won't let this kind of major feature break the language, so we can trust them to make the necessary work to enable a correct C++ GC that won't interfere with C++: **As always in C++, if you don't need a feature, don't use it and it will cost you nothing.**
The short answer is that garbage collection is very similar in principle to RAII with smart pointers. If every piece of memory you ever allocate lies within an object, and that object is only referred to by smart pointers, you have something close to garbage collection (potentially better). The advantage comes from not having to be so judicious about scoping and smart-pointering every object, and letting the runtime do the work for you. This question seems analogous to "what does C++ have to offer the experienced assembly developer? instructions and subroutines eliminate the need for it, right?"
Garbage Collection in C++ -- why?
[ "", "c++", "garbage-collection", "c++11", "" ]
I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell': here is my HTML snippet: headerRows[0][10].contents ``` [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3"> </font></font></font>] ``` Note that this is a list item from Python []. I need the value Apples Produced but can't get to it. Any suggestions would be appreciated Suggestions on a good book that explains this would earn my eternal gratitude --- Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute say it is: ``` [<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3"> </font></font></font>] ``` *Apples Produced* I am trying to learn to read/understand the documentation and your response will help I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and now I am learning python and I am amazed at its power - BeautifulSoup is an example. Making a coherent whole of the documentation is tough for me. Cheers
``` headerRows[0][10].contents[0].find('b').string ```
The [BeautifulSoup documentation](http://www.crummy.com/software/BeautifulSoup/documentation.html) should cover everything you need - in this case it looks like you want to use `findNext`: ``` headerRows[0][10].findNext('b').string ``` A more generic solution which doesn't rely on the `<b>` tag would be to use the [text](http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text) argument to `findAll`, which allows you to search only for `NavigableString` objects: ``` >>> s = BeautifulSoup(u'<p>Test 1 <span>More</span> Test 2</p>') >>> u''.join([s.string for s in s.findAll(text=True)]) u'Test 1 More Test 2' ```
How do you get the text from an HTML 'datacell' using BeautifulSoup
[ "", "python", "html", "parsing", "beautifulsoup", "" ]
I'm trying to display an array of files in order of date (last modified). I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?
> **Warning** `create_function()` has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged. For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is: ``` <?php $myarray = glob("*.*"); usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);')); ?> ``` Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well.
``` <?php $items = glob('*', GLOB_NOSORT); array_multisort(array_map('filemtime', $items), SORT_NUMERIC, SORT_DESC, $items); ```
glob() - sort array of files by last modified datetime stamp
[ "", "php", "arrays", "sorting", "filemtime", "" ]
I would like to set the log file name for a log4j and log4net appender to have the current date. We are doing Daily rollovers but the current log file does not have a date. The log file name format would be ``` logname.2008-10-10.log ``` Anyone know the best way for me to do this? edit: I forgot to mention that we would want to do this in log4net as well. Plus any solution would need to be usable in JBoss.
DailyRollingFileAppender is what you exactly searching for. ``` <appender name="roll" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="application.log" /> <param name="DatePattern" value=".yyyy-MM-dd" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n %-5p %m%n"/> </layout> </appender> ```
Using log4j.properties file, and including [apache-log4j-extras](http://logging.apache.org/log4j/extras/) 1.1 in my POM with log4j 1.2.16 ``` log4j.appender.LOGFILE=org.apache.log4j.rolling.RollingFileAppender log4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy log4j.appender.LOGFILE.RollingPolicy.FileNamePattern=/logs/application_%d{yyyy-MM-dd}.log ```
Setting a log file name to include current date in Log4j
[ "", "java", ".net", "logging", "log4net", "log4j", "" ]
This may be a simple fix - but I'm trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0: ``` private long sum(Node<T> thisNode) { if (thisNode.Left == null && thisNode.Right == null) return 0; if (node.Right == null) return sum(thisNode.Left); if (node.Left == null) return sum(thisNode.Right); return sum(thisNode.Left) + sum(thisNode.Right); } ``` Within my Node class I have Data which stores Size and Name in their given properties. I'm just trying to sum the entire size. Any suggestions or ideas?
It's because you're returning zero when you reach a leaf node. You should be returning the size stored in that leaf node. In addition, if your non-leaf nodes also have a size, you'll need to process them as well thus: ``` private long sum(Node<T> thisNode) { if (thisNode.Left == null && thisNode.Right == null) return thisNode.Size; if (node.Right == null) return thisNode.Size + sum(thisNode.Left); if (node.Left == null) return thisNode.Size + sum(thisNode.Right); return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right); } ``` If your non-leaf nodes don't have size, use: ``` private long sum(Node<T> thisNode) { if (thisNode.Left == null && thisNode.Right == null) return thisNode.Size; if (node.Right == null) return sum(thisNode.Left); if (node.Left == null) return sum(thisNode.Right); return sum(thisNode.Left) + sum(thisNode.Right); } ``` A more elegant version of the first one is: ``` private long sum(Node<T> thisNode) { if (thisNode == null) return 0; return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right); } ```
Maybe you meant ``` if (thisNode.Left == null && thisNode.Right == null) return thisNode.Size; ``` ?
Summing up all nodes
[ "", "c#", "recursion", "tree", "subtree", "" ]
I listen to the podcast java posse, on this there is often discussion about components (note components are not (clearly) objects). They lament the fact that Java does not have components, and contrast with .NET that does. Components apparently makes developing applications (not just GUI apps) easier. I can figure from the discussion certain qualities that a component has, its something to-do with decoupling (substituting one component for another is just a matter of plumbing). It has something to-do with properties, it definitely has something to-do with events and delegates. So to the questions: ./ can anyone explain to me what a component is. (and why java beans are not components). ./ can anyone explain how they help development. ./ can anyone explain why java does not have them if they are so useful.
Software Engineering Radio has an episode on exactly this topic: <https://se-radio.net/2008/02/episode-87-software-components/> The general idea is that a software component can describe what its own dependencies and services are, in the form of metadata. I don't know why you might have heard that Java does not have components, since you can certainly imagine an architecture in Java where components do describe themselves through metadata. I suppose it's just that the Java platform definition by itself doesn't really have a component architecture. Update: Indeed, one need not imagine such an architecture because as others pointed out, Java Beans or Servlets could certainly be considered component-based architectures.
The term component is one of the most ambiguous and overused ones in OO. Most people would agree that a component is made up of a group of classes, which collaborate together to implement one or more interfaces. One of the classes takes on the role of the 'front-end' i.e. it implements the interface but delegates the work to the other classes within the group. As you say components should be replaceable without the rest of the system knowing. A great example of a component based architecture was COM. Its a great example because it was so heavily used and rigidly specified. But note that the need for this architecture was based on the inflexibility of the C++ compilation and deployment model. in Java you can do an awful lot to a class without breaking binary compatability with the rest of the system. So there is not as much need to build rigid, component based architectures. But it all depends on how you define the term, e.g any project built using dependency injection could count as 'component based'.
What is a component
[ "", "java", ".net", "object", "" ]
Assume I have a function template like this: ``` template<class T> inline void doStuff(T* arr) { // stuff that needs to use sizeof(T) } ``` Then in another `.h` filee I have a template class `Foo` that has: ``` public: operator T*() const; ``` Now, I realize that those are different Ts. But If I have a variable `Foo<Bar> f` on the stack, the only way to coerce it to *any* kind of pointer would be to invoke `operator T*()`. Yet, if call `doStuff(f)`, GCC complains that `doStuff` can't take `Foo<Bar>` instead of automatically using operator `T*()` to coerce to `Bar*` and then specializing the function template with `Bar` as `T`. Is there anything I can do to make this work with two templates? Or does either the argument of the template function have to be a real pointer type or the template class with the coercion operator be passed to a non-template function?
GCC is correct. In template arguments only exact matches are considered, type conversions are not. This is because otherwise an infinite (or at least exponential) amount of conversions could have to be considered. If Foo<T> is the only other template that you're going to run in to, the best solution would be to add: ``` template<typename T> inline void doStuff(const Foo<T>& arr) { doStuff(static_cast<T*>(arr)); } ``` If you are having this issue with a lot of templates, this one should fix it: ``` #include <boost/type_traits/is_convertible.hpp> #include <boost/utility/enable_if.hpp> template<template <typename> class T, typename U> inline typename boost::enable_if<typename boost::is_convertible<T<U>, U*>::type>::type doStuff(const T<U>& arr) { doStuff(static_cast<U*>(arr)); } ``` It's a bit verbose though ;-)
This might be worth a try: ``` doStuff<Bar>(f); ``` I think this will cause the compiler to expect T\* to be Bar\* and then use Foo's operator T\*() to perform the cast, but I can't say I've tried it.
Coercing template class with operator T* when passing as T* argument of a function template
[ "", "c++", "templates", "coercion", "" ]
Is there a way to deploy a Java program in a format that is not reverse-engineerable? I know how to convert my application into an executable JAR file, but I want to make sure that the code cannot be reverse engineered, or at least, not easily. Obfuscation of the source code doesn't count... it makes it harder to understand the code, but does not hide it. A related question is *[How to lock compiled Java classes to prevent decompilation?](https://stackoverflow.com/questions/49379/how-to-lock-compiled-java-classes-to-prevent-decompilation)* --- Once I've completed the program, I would still have access to the original source, so maintaining the application would not be the problem. If the application is distributed, I would not want any of the users to be able to decompile it. Obfuscation does not achieve this as the users would still be able to decompile it, and while they would have difficulty following the action flows, they would be able to see the code, and potentially take information out of it. What I'm concerned about is if there is any information in the code relating to remote access. There is a host to which the application connects using a user-id and password provided by the user. Is there a way to hide the host's address from the user, if that address is located inside the source code?
You could obfuscate your JAR file with [YGuard](http://www.yworks.com/en/products_yguard_about.htm). **It doesn't obfuscate your source code**, but the compiled classes, so there is no problem about maintaining the code later. If you want to hide some string, you could encrypt it, making it harder to get it through looking at the source code (it is even better if you obfuscate the JAR file).
The short answer is "No, it does not exist". **Reverse engineering is a process that does not imply to look at the code at all**. It's basically trying to understand the underlying mechanisms and then mimic them. For example, that's how JScript appears from MS labs, by copying Netscape's JavaScript behavior, without having access to the code. The copy was so perfect that even the bugs were copied.
Creating non-reverse-engineerable Java programs
[ "", "java", "jar", "compilation", "" ]
I want a true deep copy. In Java, this was easy, but how do you do it in C#?
### Important Note [BinaryFormatter](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-5.0) has been deprecated, and will no longer be available in .NET after November 2023. See [BinaryFormatter Obsoletion Strategy](https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md) --- I've seen a few different approaches to this, but I use a generic utility method as such: ``` public static T DeepClone<T>(this T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T) formatter.Deserialize(ms); } } ``` Notes: * Your class MUST be marked as `[Serializable]` for this to work. * Your source file must include the following code: ``` using System.Runtime.Serialization.Formatters.Binary; using System.IO; ```
I [wrote a deep object copy extension method](https://github.com/Burtsev-Alexey/net-object-deep-copy), based on recursive **"MemberwiseClone"**. It is fast (**three times faster** than BinaryFormatter), and it works with any object. You don't need a default constructor or serializable attributes. Source code: ``` using System.Collections.Generic; using System.Reflection; using System.ArrayExtensions; namespace System { public static class ObjectExtensions { private static readonly MethodInfo CloneMethod = typeof(Object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance); public static bool IsPrimitive(this Type type) { if (type == typeof(String)) return true; return (type.IsValueType & type.IsPrimitive); } public static Object Copy(this Object originalObject) { return InternalCopy(originalObject, new Dictionary<Object, Object>(new ReferenceEqualityComparer())); } private static Object InternalCopy(Object originalObject, IDictionary<Object, Object> visited) { if (originalObject == null) return null; var typeToReflect = originalObject.GetType(); if (IsPrimitive(typeToReflect)) return originalObject; if (visited.ContainsKey(originalObject)) return visited[originalObject]; if (typeof(Delegate).IsAssignableFrom(typeToReflect)) return null; var cloneObject = CloneMethod.Invoke(originalObject, null); if (typeToReflect.IsArray) { var arrayType = typeToReflect.GetElementType(); if (IsPrimitive(arrayType) == false) { Array clonedArray = (Array)cloneObject; clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices)); } } visited.Add(originalObject, cloneObject); CopyFields(originalObject, visited, cloneObject, typeToReflect); RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect); return cloneObject; } private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect) { if (typeToReflect.BaseType != null) { RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType); CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate); } } private static void CopyFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func<FieldInfo, bool> filter = null) { foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags)) { if (filter != null && filter(fieldInfo) == false) continue; if (IsPrimitive(fieldInfo.FieldType)) continue; var originalFieldValue = fieldInfo.GetValue(originalObject); var clonedFieldValue = InternalCopy(originalFieldValue, visited); fieldInfo.SetValue(cloneObject, clonedFieldValue); } } public static T Copy<T>(this T original) { return (T)Copy((Object)original); } } public class ReferenceEqualityComparer : EqualityComparer<Object> { public override bool Equals(object x, object y) { return ReferenceEquals(x, y); } public override int GetHashCode(object obj) { if (obj == null) return 0; return obj.GetHashCode(); } } namespace ArrayExtensions { public static class ArrayExtensions { public static void ForEach(this Array array, Action<Array, int[]> action) { if (array.LongLength == 0) return; ArrayTraverse walker = new ArrayTraverse(array); do action(array, walker.Position); while (walker.Step()); } } internal class ArrayTraverse { public int[] Position; private int[] maxLengths; public ArrayTraverse(Array array) { maxLengths = new int[array.Rank]; for (int i = 0; i < array.Rank; ++i) { maxLengths[i] = array.GetLength(i) - 1; } Position = new int[array.Rank]; } public bool Step() { for (int i = 0; i < Position.Length; ++i) { if (Position[i] < maxLengths[i]) { Position[i]++; for (int j = 0; j < i; j++) { Position[j] = 0; } return true; } } return false; } } } } ```
How do you do a deep copy of an object in .NET?
[ "", "c#", ".net", "serialization", "clone", "" ]
I have a 10 second sound effect wave file. What I would like to do is take that file and repeat it n number of times and then save the longer WAV file to disk. This way I can create a much longer background effect rather than auto-repeat on the media player which is a bit stuttered between repeats. I am trying to do this in C#.
If you only need to do this with a small number of files, you might as well do it by hand with [Audacity](http://audacity.sourceforge.net/).
That's reasonably easy to do, given the [WAV file format](http://ccrma.stanford.edu/courses/422/projects/WaveFormat/) - assuming it's uncompressed audio (most WAV files are - or at least, they were last time I had anything to do with them). There may well be audio APIs you can use to do this without getting stuck into the binary format, but I suspect they'd take as long to learn as just doing it yourself as you're not doing anything particularly complicated.
WAV file auto repeat in C#
[ "", "c#", "audio", "media", "wav", "" ]
I want to continuously sample from my PC's audio line in using C# (then process that data). What is the best way to do the sampling?
You can do some (basic) audio capture using the open source [NAudio](http://www.codeplex.com/naudio) .NET Audio Library. Have a look at the NAudioDemo project to see a simple example of recording to a WAV file using the WaveIn functions. NAudio also now includes the ability to capture audio using WASAPI (Windows Vista and above) and ASIO (if your soundcard has an ASIO driver).
There are no built-in libraries in the .NET framework for dealing with sound, but if you're on Win32, you can use an unmanaged library like DirectSound to do it. Ianier Munoz shows [how to write a full-duplex audio player in C# using **waveIn** via P/Invoke](http://www.codeproject.com/KB/audio-video/cswavrec.aspx?fid=16677&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2525433&fr=151) on CodeProject. He mentions **[Managed DirectSound](http://www.codeproject.com/KB/audio-video/DirectSound9p1.aspx)** as a more general method.
What is the simplest way to continuously sample from the line-in using C#
[ "", "c#", "audio", "signal-processing", "audio-recording", "" ]
I am part of a team creating a web application using PHP and MySQL. The application will have multiple users with different roles. The application will also be used in a geographically distributed manner. Accordingly we need to create an access control system that operates at the following two levels: 1. Controls user permissions for specific php pages i.e. provides or denies access to specific pages (or user interface elements) based on the user's role. For example: a user may be allowed access to the "Students" page but not to the "Teachers" page. 2. Controls user permissions for specific database records i.e. modifies database queries so that only specific records are displayed. For example, for a user at the city level, only those records should be displayed that relate to the user's particular city, while for a user at the national level, records for ALL CITIES in the country should be displayed. I need help on designing a system that can handle both these types of access control. Point no. 1 seems to be simple enough. However, I am completely at a loss on how to do point number 2 without hardcoding the information in the SQL queries. Any help would be appreciated. Thanks in advance Vinayak
I was in similar situation few months ago. I found that tools like Zend\_ACL work great if you just check access level to single item (or reasonably low number of them). It fails when you need to get a huge list of items the user is allowed to access. I crafted custom solution to this problem using [Business Delegate](http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html) pattern. BD provides business logic that can be applied in specific context. In this scenario a SQL logic was delivered and used as filtering condition in subselect. See the following diagrams: [![alt text](https://i.stack.imgur.com/h0TmD.png)](https://i.stack.imgur.com/h0TmD.png) (source: [epsi.pl](http://gruz.epsi.pl/g/uml/permissions.png)) And sequence diagram that illustrates calls order: [![alt text](https://i.stack.imgur.com/eDvrv.png)](https://i.stack.imgur.com/eDvrv.png) (source: [epsi.pl](http://gruz.epsi.pl/g/uml/permissions-s2.png)) [I blogged about this solution](http://stronger.epsi.pl/2008/04/02/prawa-dostepu-the-ultimate-edition/), unfortunately it's all in Polish, but you may find pieces of code and diagrams handy. What I can say, the implementation is not a piece of cake, but performance-wise it's a champion when compared to iterative access checking for each element on the list. Moreover, the infrastructure above handles not only one type of items on the list. It can serve when accessing different lists, be it list of cities, countries, products, or documents as long as items on the list implement `IAuthorizable` interface.
Don't know about the details of your problem but the Zend Framework has a rather potent [ACL](http://framework.zend.com/manual/en/zend.acl.html) and [AUTH](http://framework.zend.com/manual/en/zend.auth.html) set of components you may want to look at. Good stuff like very precise access control, storing data for persistance, advanced conditional rules.
PHP Access Control System
[ "", "php", "database-design", "permissions", "access-control", "database-permissions", "" ]
I have a table that has an insert trigger on it. If I insert in 6000 records into this table in one insert statement from a stored procedure, will the stored procedure return before the insert trigger completes? Just to make sure that I'm thinking correctly, the trigger should only be called (i know 'called' isn't the right word) once because there was only 1 insert statement, right? My main question is: will the sproc finish even if the trigger hasn't completed?
Your insert trigger will run once for the entire insert statement. This is why it is important to use the `inserted` temporary table to see what has actually been inserted, and not just select the most recent single record, or something like that. I just tested an insert and update trigger and indeed, they are considered part of the insert by sql server. the process will not finish until the trigger finishes.
Triggers are part of the transaction that called them. One important thing about triggers that you must be aware of is that the trigger fires once for each transaction (at least in SQL server, you should check other dbs, but even if it will process row by row, that is usually a poor idea), so if you insert 6000 records the trigger fires once not 6000 times. Many people are not aware of this and write triggers as if they will process multiple record inserts one record at a time. This is not true and your trigger must account for handing the multiple record insert.
Are Sql Triggers synchronous or asynchronous?
[ "", "sql", "stored-procedures", "triggers", "timing", "" ]
I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?
[Bitarray](http://pypi.python.org/pypi/bitarray/) was the best answer I found, when I recently had a similar need. It's a C extension (so much faster than BitVector, which is pure python) and stores its data in an actual bitfield (so it's eight times more memory efficient than a numpy boolean array, which appears to use a byte per element.)
If you mainly want to be able to name your bit fields and easily manipulate them, e.g. to work with flags represented as single bits in a communications protocol, then you can use the standard Structure and Union features of [ctypes](http://docs.python.org/library/ctypes.html), as described at [How Do I Properly Declare a ctype Structure + Union in Python? - Stack Overflow](https://stackoverflow.com/questions/10346375/how-do-i-properly-declare-a-ctype-structure-union-in-python) For example, to work with the 4 least-significant bits of a byte individually, just name them from least to most significant in a LittleEndianStructure. You use a union to provide access to the same data as a byte or int so you can move the data in or out of the communication protocol. In this case that is done via the `flags.asbyte` field: ``` import ctypes c_uint8 = ctypes.c_uint8 class Flags_bits(ctypes.LittleEndianStructure): _fields_ = [ ("logout", c_uint8, 1), ("userswitch", c_uint8, 1), ("suspend", c_uint8, 1), ("idle", c_uint8, 1), ] class Flags(ctypes.Union): _fields_ = [("b", Flags_bits), ("asbyte", c_uint8)] flags = Flags() flags.asbyte = 0xc print(flags.b.idle) print(flags.b.suspend) print(flags.b.userswitch) print(flags.b.logout) ``` The four bits (which I've printed here starting with the most significant, which seems more natural when printing) are 1, 1, 0, 0, i.e. 0xc in binary.
Does Python have a bitfield type?
[ "", "python", "bit-fields", "bitarray", "" ]
I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#. Example: ``` 2748 to "ABC" ```
try ``` 2748.ToString("X") ```
If you want exactly 3 characters and are sure the number is in range, use: ``` i.ToString("X3") ``` If you aren't sure if the number is in range, this will give you more than 3 digits. You could do something like: ``` (i % 0x1000).ToString("X3") ``` Use a lower case "x3" if you want lower-case letters.
How do I convert a 12-bit integer to a hexadecimal string in C#?
[ "", "c#", "" ]
I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write ``` myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction); ``` this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too.
Make sure your events are exposed as public. For example... ``` [Browsable(true)] public event EventHandler MyCustomEvent; ```
A solution using delegate. For example i used for a custom ListView which handle item added event : Declare your delegate : ``` public delegate void ItemAddedHandler(object sender, ItemEventArgs e) ``` then declare the event which use the delegate : ``` [Browsable(true)] public event ItemAddedHandler ItemAdded; ``` Note : ItemEventArgs is a custom EventArgs Hope can help you, works fine for me
Design Time viewing for User Control events
[ "", "c#", "winforms", "user-controls", "" ]
As you can see this is a question from a non web developer. I would like to have an ASPX page which, under certain circumstances, can generate a 401 error from code. Ideally it would show the IIS standard page.
Set [Response.StatusCode](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.statuscode.aspx) and then - if you need to stop execution - call [Response.End()](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx).
``` Response.StatusCode = 401; Response.End(); ```
How to generate an 401 error programmatically in an ASP.NET page
[ "", "c#", "asp.net", "iis", "asp.net-2.0", "" ]
For a product in long run (may be 0.5-1 million users) is it good to use java instead of .net from the cost/profitability perspective. To elaborate more..consider web farm scenario in which one will have to purchase windows + Sql server + some antivirus licenses for .net applications. But for java it's almost free. What points should I consider? PS: I am a .net person by heart
I would expect bandwidth to cost more than software licences is you're reasonably successful - although obviously that will depend somewhat on the kind of app, and I haven't run any figures. Are you just starting this up yourself, with little firm idea that it will take off? If so, I suggest you go with whatever makes your life easier to start with. If things take off, you'll either have enough money to pay for the licences easily, or you'll quite possibly need to rewrite the app anyway. Writing an app which provably scales to a million users is likely to cause you a lot more grief than writing one which scales to 10,000. Get the app out there early, get feedback ASAP, and you can do what it takes if it ever becomes truly successful.
Go with what you know. With that many users price may not be important.
For a typical Web 2.0 Social Application - Java vs C#
[ "", "java", ".net", "visual-studio", "" ]
Say I have the classic 4-byte signed integer, and I want something like ``` print hex(-1) ``` to give me something like > 0xffffffff In reality, the above gives me `-0x1`. I'm dawdling about in some lower level language, and python commandline is quick n easy. So.. is there a way to do it?
This will do the trick: ``` >>> print(hex (-1 & 0xffffffff)) 0xffffffff ``` or, a variant that always returns fixed size (there may well be a better way to do this): ``` >>> def hex3(n): ... return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:] ... >>> print hex3(-1) 0xffffffff >>> print hex3(17) 0x00000011 ``` Or, avoiding the hex() altogether, thanks to Ignacio and bobince: ``` def hex2(n): return "0x%x"%(n&0xffffffff) def hex3(n): return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:] ```
Try this function: ``` '%#4x' % (-1 & 0xffffffff) ```
How to get hex string from signed integer
[ "", "python", "" ]
I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect. For example: ``` <-----row 1 interval-------> <---find this--> <--and this--> <--and this--> ``` Please phrase your answer in the form of a SQL `WHERE`-clause, AND consider the case where the end time in the second table may be `NULL`. Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.
``` SELECT * FROM table1,table2 WHERE table2.start <= table1.end AND (table2.end IS NULL OR table2.end >= table1.start) ```
It's sound very complicated until you start working from reverse. Below I illustrated ONLY GOOD CASES (no overlaps)! defined by those 2 simple conditions, we have no overlap ranges if condA OR condB is TRUE, so we going to reverse those: NOT condA AND NOT CondB, in our case I just reversed signs (> became <=) ``` /* |--------| A \___ CondA: b.ddStart > a.ddEnd |=========| B / \____ CondB: a.ddS > b.ddE |+++++++++| A / */ --DROP TABLE ran create table ran ( mem_nbr int, ID int, ddS date, ddE date) insert ran values (100, 1, '2012-1-1','2012-12-30'), ----\ ovl (100, 11, '2012-12-12','2012-12-24'), ----/ (100, 2, '2012-12-31','2014-1-1'), (100, 3, '2014-5-1','2014-12-14') , (220, 1, '2015-5-5','2015-12-14') , ---\ovl (220, 22, '2014-4-1','2015-5-25') , ---/ (220, 3, '2016-6-1','2016-12-16') select DISTINCT a.mem_nbr , a.* , '-' [ ], b.dds, b.dde, b.id FROM ran a join ran b on a.mem_nbr = b.mem_nbr -- match by mem# AND a.ID <> b.ID -- itself AND b.ddS <= a.ddE -- NOT b.ddS > a.ddE AND a.ddS <= b.ddE -- NOT a.ddS > b.ddE ```
What is a simple and efficient way to find rows with time-interval overlaps in SQL?
[ "", "sql", "" ]
We are working on a website for a client that (for once) is expected to get a fair amount of traffic on day one. There are press releases, people are blogging about it, etc. I am a little concerned that we're going to fall flat on our face on day one. What are the main things you would look at to ensure (in advance without real traffic data) that you can stay standing after a big launch? Details: This is a [L/A/M/PHP](https://en.wikipedia.org/wiki/LAMP_%28software_bundle%29) stack, using an internally developed MVC framework. This is currently being launched on one server, with Apache and MySQL both on it, but we can break that up if need be. We are already installing [Memcached](https://en.wikipedia.org/wiki/Memcached) and doing as much PHP-level caching as we can think of. Some of the pages are rather query intensive, and we are using [Smarty](https://en.wikipedia.org/wiki/Smarty_(template_engine)) as our template engine. Keep in mind there is no time to change any of these major aspects--this is the just the setup. What sorts of things should we watch out for?
To prepare or handle a spike (or peak) performance, I would first determine whether you are ready through some simple performance testing with something like [jmeter](http://jakarta.apache.org/jmeter/). It is easy to set up and get started and will give you early metrics whether you will handle an expected peak load. However, given your time constraints, other steps to take would be to prepare static versions of content that will attract the highest attention (such as press releases, if your launch day). Also ensure that you are making the best use of client-side caching (one fewer request to your server can make all the difference). The web is already designed for extremely high scalability and effective use content caching is your best friend in these situations. There is an excellent podcast on high scalability on [software engineering radio on the design of the new Guardian website](http://www.se-radio.net/podcast/2008-05/episode-95-new-guardiancouk-website-matt-wall-and-erik-doernenburg) when things calm down. Good luck on the launch.
Measure first, and then optimize. Have you done any load testing? Where are the bottlenecks? Once you know your bottlenecks then you can intelligently decide if you need additional database boxes or web boxes. Right now you'd just be guessing. Also, how does your load testing results compare against your expected traffic? Can you handle two times the expected traffic? Five times? How easy/fast can you acquire and release extra hardware? I'm sure the business requirement is to not fail during launch, so make sure you have *lots* of capacity available. You can always release it afterwards when the load has stabilized and you know what you need.
Best practices for withstanding launch day traffic burst
[ "", "php", "mysql", "linux", "apache", "lamp", "" ]
I know I'm gonna get down votes, but I have to make sure if this is logical or not. I have three tables A, B, C. B is a table used to make a many-many relationship between A and C. But the thing is that A and C are also related directly in a 1-many relationship A customer added the following requirement: Obtain the information from the Table B inner joining with A and C, and in the same query relate A and C in a one-many relationship Something like: [alt text http://img247.imageshack.us/img247/7371/74492374sa4.png](http://img247.imageshack.us/img247/7371/74492374sa4.png) I tried doing the query but always got 0 rows back. The customer insists that I can accomplish the requirement, but I doubt it. Any comments? PS. I didn't have a more descriptive title, any ideas? UPDATE: Thanks to rcar, In some cases this can be logical, in order to have a history of all the classes a student has taken (supposing the student can only take one class at a time) UPDATE: There is a table for Contacts, a table with the Information of each Contact, and the Relationship table. To get the information of a Contact I have to make a 1:1 relationship with Information, and each contact can have like and an address book with; this is why the many-many relationship is implemented. The full idea is to obtain the contact's name and his address book. Now that I got the customer's idea... I'm having trouble with the query, basically I am trying to use the query that jdecuyper wrote, but as he warns, I get no data back
I'm supposing that s.id\_class indicates the student's current class, as opposed to classes she has taken in the past. The solution shown by rcar works, but it repeats the c1.className on every row. Here's an alternative that doesn't repeat information and it uses one fewer join. You can use an expression to compare s.id\_class to the current c.id\_class matched via the mtm table. ``` SELECT s.name, c.className, (s.id_class = c.id_class) AS is_current FROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student) JOIN c ON (c.id_class = mtm.id_class); ``` So is\_current will be 1 (true) on one row, and 0 (false) on all the other rows. Or you can output something more informative using a `CASE` construct: ``` SELECT s.name, c.className, CASE WHEN s.id_class = c.id_class THEN 'current' ELSE 'past' END AS is_current FROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student) JOIN c ON (c.id_class = mtm.id_class); ```
This is a doable scenario. You can join a table twice in a query, usually assigning it a different alias to keep things straight. For example: ``` SELECT s.name AS "student name", c1.className AS "student class", c2.className as "class list" FROM s JOIN many_to_many mtm ON s.id_student = mtm.id_student JOIN c c1 ON s.id_class = c1.id_class JOIN c c2 ON mtm.id_class = c2.id_class ``` This will give you a list of all students' names and "hardcoded" classes with all their classes from the many\_to\_many table. That said, this schema doesn't make logical sense. From what I can gather, you want students to be able to have multiple classes, so the many\_to\_many table should be where you'd want to find the classes associated with a student. If the id\_class entries used in table s are distinct from those in many\_to\_many (e.g., if s.id\_class refers to, say, homeroom class assignments that only appear in that table while many\_to\_many.id\_class refers to classes for credit and excludes homeroom classes), you're going to be better off splitting c into two tables instead. If that's not the case, I have a hard time understanding why you'd want one class hardwired to the s table. EDIT: Just saw your comment that this was a made-up schema to give an example. In other cases, this could be a sensible way to do things. For example, if you wanted to keep track of company locations, you might have a Company table, a Locations table, and a Countries table. The Company table might have a 1-many link to Countries where you would keep track of a company's headquarters country, but a many-to-many link through Locations where you keep track of every place the company has a store. If you can give real information as to what the schema really represents for your client, it might be easier for us to figure out whether it's logical in this case or not.
Weird many to many and one to many relationship
[ "", "sql", "constraints", "" ]
I want something like an [std::map](http://en.wikipedia.org/wiki/Map_%28C++%29), but I only want to see if the item exists or not, I don't actually need a key AND a value. What should I use?
Looks like you need a [std::set](http://en.cppreference.com/w/cpp/container/set).
If you want the same type of behavior as `std::map`, then you want `std::set`. If you are mixing insert/delete and query operations, then `std::set` is probably the best choice. However, if you can populate the set first and then follow it with the queries, it might be worth looking at using `std::vector`, sorting it, and then using a binary search to check for existence in the vector.
Existence map in C++
[ "", "c++", "stl", "dictionary", "" ]
I wish to search a database table on a nullable column. Sometimes the value I'm search for is itself NULL. Since Null is equal to nothing, even NULL, saying ``` where MYCOLUMN=SEARCHVALUE ``` will fail. Right now I have to resort to ``` where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL)) ``` Is there a simpler way of saying that? (I'm using Oracle if that matters)
You can do the IsNull or NVL stuff, but it's just going to make the engine do more work. You'll be calling functions to do column conversions which then have to have the results compared. Use what you have ``` where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL)) ```
@Andy Lester asserts that the original form of the query is more efficient than using NVL. I decided to test that assertion: ``` SQL> DECLARE 2 CURSOR B IS 3 SELECT batch_id, equipment_id 4 FROM batch; 5 v_t1 NUMBER; 6 v_t2 NUMBER; 7 v_c1 NUMBER; 8 v_c2 NUMBER; 9 v_b INTEGER; 10 BEGIN 11 -- Form 1 of the where clause 12 v_t1 := dbms_utility.get_time; 13 v_c1 := dbms_utility.get_cpu_time; 14 FOR R IN B LOOP 15 SELECT COUNT(*) 16 INTO v_b 17 FROM batch 18 WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL); 19 END LOOP; 20 v_t2 := dbms_utility.get_time; 21 v_c2 := dbms_utility.get_cpu_time; 22 dbms_output.put_line('For clause: WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL)'); 23 dbms_output.put_line('CPU seconds used: '||(v_c2 - v_c1)/100); 24 dbms_output.put_line('Elapsed time: '||(v_t2 - v_t1)/100); 25 26 -- Form 2 of the where clause 27 v_t1 := dbms_utility.get_time; 28 v_c1 := dbms_utility.get_cpu_time; 29 FOR R IN B LOOP 30 SELECT COUNT(*) 31 INTO v_b 32 FROM batch 33 WHERE NVL(equipment_id,'xxxx') = NVL(R.equipment_id,'xxxx'); 34 END LOOP; 35 v_t2 := dbms_utility.get_time; 36 v_c2 := dbms_utility.get_cpu_time; 37 dbms_output.put_line('For clause: WHERE NVL(equipment_id,''xxxx'') = NVL(R.equipment_id,''xxxx'')'); 38 dbms_output.put_line('CPU seconds used: '||(v_c2 - v_c1)/100); 39 dbms_output.put_line('Elapsed time: '||(v_t2 - v_t1)/100); 40 END; 41 / For clause: WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL) CPU seconds used: 84.69 Elapsed time: 84.8 For clause: WHERE NVL(equipment_id,'xxxx') = NVL(R.equipment_id,'xxxx') CPU seconds used: 124 Elapsed time: 124.01 PL/SQL procedure successfully completed SQL> select count(*) from batch; COUNT(*) ---------- 20903 SQL> ``` I was kind of surprised to find out just how correct Andy is. It costs nearly 50% more to do the NVL solution. So, even though one piece of code might not look as tidy or elegant as another, it could be significantly more efficient. I ran this procedure multiple times, and the results were nearly the same each time. Kudos to Andy...
Determine Oracle null == null
[ "", "sql", "oracle", "null", "nullable", "" ]
I am attempting to have a ReportHandler service to handle report creation. Reports can have multiple, differing number of parameters that could be set. In the system currently there are several different methods of creating reports (MS reporting services, html reports, etc) and the way the data is generated for each report is different. I am trying to consolidate everything into ActiveReports. I can't alter the system and change the parameters, so in some cases I will essentially get a where clause to generate the results, and in another case I will get key/value pairs that I must use to generate the results. I thought about using the factory pattern, but because of the different number of query filters this won't work. I would love to have a single ReportHandler that would take my varied inputs and spit out report. At this point I'm not seeing any other way than to use a big switch statement to handle each report based on the reportName. Any suggestions how I could solve this better?
From your description, if you're looking for a pattern that matches better than Factory, try Strategy: [Strategy Pattern](http://en.wikipedia.org/wiki/Strategy_pattern) 1. Your **context** could be a custom class which encapsulates and abstracts the different report inputs (you could use the AbstractFactory pattern for this part) 2. Your **strategy** could implement any number of different query filters or additional logic needed. And if you ever need to change the system in the future, you can switch between report tools by simply creating a new strategy. Hope that helps!
In addition to the strategy pattern, you can also create one adaptor for each of your underlying solutions. Then use strategy to vary them. I've built similar with each report solution being supported by what I called engines, In addition to the variable report solution we have variable storage solution as well - output can be stored in SQL server or file system. I would suggest using a container then initializing it with the correct engine, e.g.: ``` public class ReportContainer{ public ReportContainer ( IReportEngine reportEngine, IStorageEngine storage, IDeliveryEngine delivery...) } } /// In your service layer you resolve which engines to use // Either with a bunch of if statements / Factory / config ... IReportEngine rptEngine = EngineFactory.GetEngine<IReportEngine>( pass in some values) IStorageEngine stgEngine = EngineFactory.GetEngine<IStorageEngien>(pass in some values) IDeliverEngine delEngine = EngineFactory.GetEngine<IDeliverEngine>(pass in some values) ReportContainer currentContext = new ReportContainer (rptEngine, stgEngine,delEngine); ``` then ReportContainer delegates work to the dependent engines...
Report handler architecture question
[ "", "c#", "asp.net", "report", "activereports", "" ]
The coding is done using VS2008 There are two divs in my page namely "dvLeftContent" and "dvRightContent". I cannot statically set the height of the pages since "dvRightContent" have variable heights on various pages (Master Pages are used here) Is there a client side function(javascript or jquery) that takes the height of the right div and assigns it to left div?
Using jQuery: ``` $("#dvRightContent").bind("resize", function(){ $("#dvLeftContent").css('height', $("#dvRightContent").css('height')); }); ```
Thanks micahwittman. Some minor changes ``` $("#dvRightContent").resize(function(){ $("#dvLeftContent").css("height", ($("#dvRightContent").attr("offsetHeight") - 250 ) +"px"); }); ``` Its because height will give only "auto" in this case as its set like that
Dynamically Set the Height of Two floated DIVS
[ "", "asp.net", "javascript", "jquery", "" ]
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it? This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python. ``` def alphCount(text): lowerText = text.lower() for letter in allTheLetters: print letter + ":", lowertext.count(letter) ```
The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string). You can use string.lowercase, as other posters have suggested: ``` import string allTheLetters = string.lowercase ``` To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out: ``` def getAllTheLetters(begin='a', end='z'): beginNum = ord(begin) endNum = ord(end) for number in xrange(beginNum, endNum+1): yield chr(number) ``` You can tell it does the right thing because this code prints `True`: ``` import string print ''.join(getAllTheLetters()) == string.lowercase ``` But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go: ``` from collections import defaultdict def letterOccurrances(string): frequencies = defaultdict(lambda: 0) for character in string: frequencies[character.lower()] += 1 return frequencies ``` Use like so: ``` occs = letterOccurrances("Hello, world!") print occs['l'] print occs['h'] ``` This will print '3' and '1' respectively. Note that this works for unicode as well: ``` # -*- coding: utf-8 -*- occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!") print occs[u'l'] print occs[u'ĺ'] ``` If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters. To implement your original function (print the counts of each letter in alphabetical order) in terms of this: ``` def alphCount(text): for character, count in sorted(letterOccurrances(text).iteritems()): print "%s: %s" % (character, count) alphCount("hello, world!") ```
> the question is how to make > allTheLetters equal to said letters > without something like allTheLetters = > "abcdefg...xyz" That's actually provided by the string module, it's not like you have to manually type it yourself ;) ``` import string allTheLetters = string.ascii_lowercase def alphCount(text): lowerText = text.lower() for letter in allTheLetters: print letter + ":", lowertext.count(letter) ```
How do I iterate through a string in Python?
[ "", "python", "" ]
I basically want to run all JUnit ***unit*** tests in my IntelliJ IDEA project (excluding JUnit integration tests), using the static suite() method of JUnit. Why use the static suite() method? Because I can then use IntelliJ IDEA's JUnit test runner to run all unit tests in my application (and easily exclude all integration tests by naming convention). The code so far looks like this: ``` package com.acme; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class AllUnitTests extends TestCase { public static Test suite() { List classes = getUnitTestClasses(); return createTestSuite(classes); } private static List getUnitTestClasses() { List classes = new ArrayList(); classes.add(CalculatorTest.class); return classes; } private static TestSuite createTestSuite(List allClasses) { TestSuite suite = new TestSuite("All Unit Tests"); for (Iterator i = allClasses.iterator(); i.hasNext();) { suite.addTestSuite((Class<? extends TestCase>) i.next()); } return suite; } } ``` The method getUnitTestClasses() should be rewritten to add all project classes extending TestCase, except if the class name ends in "IntegrationTest". I know I can do this easily in Maven for example, but I need to do it in IntelliJ IDEA so I can use the integrated test runner - I like the green bar :)
I've written some code to do most of the work. It works only if your files are on the local disk instead of in a JAR. All you need is one class in the package. You could, for this purpose, create a Locator.java class, just to be able to find the package. ``` public class ClassEnumerator { public static void main(String[] args) throws ClassNotFoundException { List<Class<?>> list = listClassesInSamePackage(Locator.class, true); System.out.println(list); } private static List<Class<?>> listClassesInSamePackage(Class<?> locator, boolean includeLocator) throws ClassNotFoundException { File packageFile = getPackageFile(locator); String ignore = includeLocator ? null : locator.getSimpleName() + ".class"; return toClassList(locator.getPackage().getName(), listClassNames(packageFile, ignore)); } private static File getPackageFile(Class<?> locator) { URL url = locator.getClassLoader().getResource(locator.getName().replace(".", "/") + ".class"); if (url == null) { throw new RuntimeException("Cannot locate " + Locator.class.getName()); } try { return new File(url.toURI()).getParentFile(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } private static String[] listClassNames(File packageFile, final String ignore) { return packageFile.list(new FilenameFilter(){ @Override public boolean accept(File dir, String name) { if (name.equals(ignore)) { return false; } return name.endsWith(".class"); } }); } private static List<Class<?>> toClassList(String packageName, String[] classNames) throws ClassNotFoundException { List<Class<?>> result = new ArrayList<Class<?>>(classNames.length); for (String className : classNames) { // Strip the .class String simpleName = className.substring(0, className.length() - 6); result.add(Class.forName(packageName + "." + simpleName)); } return result; } } ```
How about putting each major group of junit tests into their own root package. I use this package structure in my project: ``` test. quick. com.acme slow. com.acme ``` Without any coding, you can set up IntelliJ to run all tests, just the quick ones or just the slow ones.
How can I run all JUnit unit tests except those ending in "IntegrationTest" in my IntelliJ IDEA project using the integrated test runner?
[ "", "java", "unit-testing", "reflection", "junit", "intellij-idea", "" ]
Full disclaimer: I'm a CS student, and this question is related to a recently assigned Java program for Object-Oriented Programming. Although we've done some console stuff, this is the first time we've worked with a GUI and Swing or Awt. We were given some code that created a window with some text and a button that rotated through different colors for the text. We were then asked to modify the program to create radio buttons for the colors instead—this was also intended to give us practice researching an API. I've already handed in my assignment and received permission from my instructor to post my code here. What's the best way to implement button actions in Java? After some fiddling around, I created the buttons like this: ``` class HelloComponent3 extends JComponent implements MouseMotionListener, ActionListener { int messageX = 75, messageY= 175; String theMessage; String redString = "red", blueString = "blue", greenString = "green"; String magentaString = "magenta", blackString = "black", resetString = "reset"; JButton resetButton; JRadioButton redButton, blueButton, greenButton, magentaButton, blackButton; ButtonGroup colorButtons; public HelloComponent3(String message) { theMessage = message; //intialize the reset button resetButton = new JButton("Reset"); resetButton.setActionCommand(resetString); resetButton.addActionListener(this); //intialize our radio buttons with actions and labels redButton = new JRadioButton("Red"); redButton.setActionCommand(redString); ... ``` And added action listeners... ``` redButton.addActionListener(this); blueButton.addActionListener(this); ... ``` A stub was already created for the actionPerformed method to give us an idea on how to use it, but since there was only a single button in the template, it wasn't clear how to implement multiple buttons. I tried switching on a String, but quickly realized that, since a String isn't a primitive type, I couldn't use it for a switch statement. I could have improvised with an if-else chain, but this is what I came up with instead. It seems far from elegant, and there must be a better way. If there is, what is it? Is there a way to switch on a string? Or choose an action in a more scaleable fashion? ``` public void actionPerformed(ActionEvent e){ if (e.getActionCommand().equals(resetString)) { messageX = 75; messageY = 175; setForeground(Color.black); blackButton.setSelected(true); repaint(); return; } if ( e.getActionCommand().equals(redString) ) { setForeground(Color.red); repaint(); return; } if ( e.getActionCommand().equals(blueString) ) { setForeground(Color.blue); repaint(); return; } if ( e.getActionCommand().equals(greenString) ) { setForeground(Color.green); repaint(); return; } if ( e.getActionCommand().equals(magentaString) ) { setForeground(Color.magenta); repaint(); return; } if ( e.getActionCommand().equals(blackString) ) { setForeground(Color.black); repaint(); return; } } ```
Instead of writing this: ``` resetButton.addActionListener(this); ``` You could also write this: ``` resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { resetButtonActionPerformed(evt); } }); ``` And instead of writing one big actionPerformed() for all actions, you can (and then have to) write this: ``` public void resetButtonActionPerformed(ActionEvent evt) { messageX = 75; messageY = 175; setForeground(Color.black); blackButton.setSelected(true); repaint(); } ``` I don't know if this is the most elegant solution, but at least you no longer have that big if construct.
As suggested already, you can use anonymous inner classes to implement the ActionListener interface. As an alternative, you don't have to use anonymous inner classes, but you can use a simple nested class instead: ``` resetButton = new JButton(new ResetAction()); redButton = new JButton(new ColorAction("Red", Color.red)); ``` and then... ``` private class ResetAction extends AbstractAction { public ResetAction() { super("Reset"); } public void actionPerformed(ActionEvent e) { messageX = 75; messageY = 175; setForeground(Color.black); blackButton.setSelected(true); repaint(); } } private class ResetAction extends AbstractAction { private Color color; public ColorAction(String title, Color color) { super(title); this.color = color; } public void actionPerformed(ActionEvent e) { setForeground(color); repaint(); } } ``` For why this approach - or any approach involving inner classes - is better than implementing ActionListener in the outer class see "Design Patterns": "Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20) Choosing between anonymous inner classes and these named inner classes is a largely a matter of style, but I think this version is easier to understand, and clearer when there are lots of actions.
Switching on a string/implementing button actions
[ "", "java", "swing", "awt", "" ]
I am trying to send an email from a site I am building, but it ends up in the yahoo spam folder. It is the email that sends credentials. What can I do to legitimize it? ``` $header = "From: site <sales@site.com>\r\n"; $header .= "To: $name <$email>\r\n"; $header .= "Subject: $subject\r\n"; $header .= "Reply-To: site <sales@site.com>" . "\r\n"; $header .= "MIME-VERSION: 1.0\r\n"; $header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $phpversion = phpversion(); $header .= "X-Mailer: PHP v$phpversion\r\n"; mail($email,$subject,$body,$header); ```
In addition to Ted Percival's suggestions, you could try using [PHPMailer](http://phpmailer.codeworxtech.com/index.php?pg=phpmailer) to create the emails for you rather than manually building the headers. I've used this class extensively and not had any trouble with email being rejected as spam by Yahoo, or anyone else.
* Don't use HTML in your email. * Send it via a legitimate mail server with a static IP and reverse-DNS (PTR) that points to the machine's real host name (and matches a forward lookup). * Include a Message-ID (or ensure that the local mailer adds one for you). * Run your email through [SpamAssassin](http://spamassassin.apache.org/) and see which bad-scoring rules it matches. Avoid matching them. * Use [DomainKeys Identified Mail](http://en.wikipedia.org/wiki/DKIM) to digitally sign your messages.
What do I need for a compliant email header
[ "", "php", "email", "header", "" ]
This question may sound fairly elementary, but this is a debate I had with another developer I work with. I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder and commented that it wasn't necessary because they are the same performance wise. I was always under the impression that growing the stack was constant time, and heap allocation's performance depended on the current complexity of the heap for both allocation (finding a hole of the proper size) and de-allocating (collapsing holes to reduce fragmentation, as many standard library implementations take time to do this during deletes if I am not mistaken). This strikes me as something that would probably be very compiler dependent. For this project in particular I am using a [Metrowerks](http://en.wikipedia.org/wiki/Metrowerks) compiler for the [PPC](http://en.wikipedia.org/wiki/PowerPC) architecture. Insight on this combination would be most helpful, but in general, for GCC, and MSVC++, what is the case? Is heap allocation not as high performing as stack allocation? Is there no difference? Or are the differences so minute it becomes pointless micro-optimization.
Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches. Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.
Stack is much faster. It literally only uses a single instruction on most architectures, in most cases, e.g. on x86: ``` sub esp, 0x10 ``` (That moves the stack pointer down by 0x10 bytes and thereby "allocates" those bytes for use by a variable.) Of course, the stack's size is very, very finite, as you will quickly find out if you overuse stack allocation or try to do recursion :-) Also, there's little reason to optimize the performance of code that doesn't verifiably need it, such as demonstrated by profiling. "Premature optimization" often causes more problems than it's worth. My rule of thumb: if I know I'm going to need some data *at compile-time*, and it's under a few hundred bytes in size, I stack-allocate it. Otherwise I heap-allocate it.
Which is faster: Stack allocation or Heap allocation
[ "", "c++", "performance", "memory", "stack", "heap-memory", "" ]
I'm trying to do some async stuff in a webservice method. Let say I have the following API call: <http://www.example.com/api.asmx> and the method is called *GetProducts()*. I this GetProducts methods, I do some stuff (eg. get data from database) then just before i return the result, I want to do some async stuff (eg. send me an email). So this is what I did. ``` [WebMethod(Description = "Bal blah blah.")] public IList<Product> GetProducts() { // Blah blah blah .. // Get data from DB .. hi DB! // var myData = ....... // Moar clbuttic blahs :) (yes, google for clbuttic if you don't know what that is) // Ok .. now send me an email for no particular reason, but to prove that async stuff works. var myObject = new MyObject(); myObject.SendDataAsync(); // Ok, now return the result. return myData; } } public class TrackingCode { public void SendDataAsync() { var backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += BackgroundWorker_DoWork; backgroundWorker.RunWorkerAsync(); //System.Threading.Thread.Sleep(1000 * 20); } private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { SendEmail(); } } ``` Now, when I run this code the email is never sent. If I uncomment out the Thread.Sleep .. then the email is sent. So ... why is it that the background worker thread is torn down? is it dependant on the parent thread? Is this the wrong way I should be doing background or forked threading, in asp.net web apps?
`BackgroundWorker` is useful when you need to synchronize back to (for example) a UI\* thread, eg for affinity reasons. In this case, it would seem that simply using `ThreadPool` would be more than adequate (and much simpler). If you have high volumes, then a producer/consumer queue may allow better throttling (so you don't drown in threads) - but I suspect `ThreadPool` will be fine here... ``` public void SendDataAsync() { ThreadPool.QueueUserWorkItem(delegate { SendEmail(); }); } ``` Also - I'm not quite sure what you want to achieve by sleeping? This will just tie up a thread (not using CPU, but doing no good either). Care to elaborate? It *looks* like you are pausing your actual web page (i.e. the Sleep happens on the web-page thread, not the e-mail thread). What are you trying to do here? \*=actually, it will use whatever sync-context is in place
Re producer/consumer; basically - it is just worth keeping *some* kind of throttle. At the simplest level, a `Semaphore` could be used (along with the regular `ThreadPool`) to limit things to a known amount of work (to avoid saturating the thread pool); but a producer/consumer queue would probably be more efficient and managed. Jon Skeet has such a queue [here](http://www.yoda.arachsys.com/csharp/miscutil/) (`CustomThreadPool`). I could probably write some notes about it if you wanted. That said: if you are calling off to an external web-site, it is quite likely that you will have a lot of waits on network IO / completion ports; as such, you can have a slightly higher number of threads... obviously (by contrast) if the work was CPU-bound, there is no point having more threads than you have CPU cores.
.NET Web Service & BackgroundWorker threads
[ "", "c#", "asp.net", "multithreading", "backgroundworker", "" ]
Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them. How can you coerce an arbitrary java application to use AA fonts? (both for applications I'm running, and applications I'm developing)
If you have access to the source, you can do this in the main method: ``` // enable anti-aliased text: System.setProperty("awt.useSystemAAFontSettings","on"); ``` or, (and if you do not have access to the source, or if this is easier) you can simply pass the system properties above into the jvm by adding these options to the command line: ``` -Dawt.useSystemAAFontSettings=on ```
Swing controls in the latest versions of Java 6 / 7 should automatically abide by system-wide preferences. (If you're using the Windows L&F on a Windows OS then text should render using ClearType if you have that setting enabled system-wide.) So perhaps one solution could simply be: enable the native Look and Feel? In applications you're developing, if you render your own text directly, you also need to do something like this (at some point before calling `Graphics.drawText` or friends): ``` if (desktopHints == null) { Toolkit tk = Toolkit.getDefaultToolkit(); desktopHints = (Map) (tk.getDesktopProperty("awt.font.desktophints")); } if (desktopHints != null) { g2d.addRenderingHints(desktopHints); } ``` Reference: <http://weblogs.java.net/blog/chet/archive/2007/01/font_hints_for.html>
How do you enable anti aliasing in arbitrary Java apps?
[ "", "java", "antialiasing", "" ]
Given a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, how do I get its index `1`?
``` >>> ["foo", "bar", "baz"].index("bar") 1 ``` See [the documentation](https://docs.python.org/tutorial/datastructures.html#more-on-lists) for the built-in `.index()` method of the list: > ``` > list.index(x[, start[, end]]) > ``` > > Return zero-based index in the list of the first item whose value is equal to *x*. Raises a [`ValueError`](https://docs.python.org/library/exceptions.html#ValueError) if there is no such item. > > The optional arguments *start* and *end* are interpreted as in the [slice notation](https://docs.python.org/tutorial/introduction.html#lists) and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument. ## Caveats ### Linear time-complexity in list length An `index` call checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code. This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the `start` and `end` parameters can be used to narrow the search. For example: ``` >>> import timeit >>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000) 9.356267921015387 >>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000) 0.0004404920036904514 ``` The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million. ### Only the index of the *first match* is returned A call to `index` searches through the list in order until it finds a match, and *stops there.* If there could be more than one occurrence of the value, and all indices are needed, `index` cannot solve the problem: ``` >>> [1, 1].index(1) # the `1` index is not found. 0 ``` Instead, use a [list comprehension or generator expression to do the search](/questions/34835951/), with [`enumerate` to get indices](/questions/522563/): ``` >>> # A list comprehension gives a list of indices directly: >>> [i for i, e in enumerate([1, 2, 1]) if e == 1] [0, 2] >>> # A generator comprehension gives us an iterable object... >>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1) >>> # which can be used in a `for` loop, or manually iterated with `next`: >>> next(g) 0 >>> next(g) 2 ``` The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable. ### Raises an exception if there is no match As noted in the documentation above, using `.index` will raise an exception if the searched-for value is not in the list: ``` >>> [1, 1].index(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 2 is not in list ``` If this is a concern, either [explicitly check first](https://stackoverflow.com/questions/12934190) using `item in my_list`, or handle the exception with `try`/`except` as appropriate. The explicit check is simple and readable, but it must iterate the list a second time. See [What is the EAFP principle in Python?](https://stackoverflow.com/questions/11360858) for more guidance on this choice.
The majority of answers explain how to find **a single index**, but their methods do not return multiple indexes if the item is in the list multiple times. Use [`enumerate()`](https://docs.python.org/library/functions.html#enumerate): ``` for i, j in enumerate(['foo', 'bar', 'baz']): if j == 'bar': print(i) ``` The `index()` function only returns the first occurrence, while `enumerate()` returns all occurrences. As a list comprehension: ``` [i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar'] ``` --- Here's also another small solution with [`itertools.count()`](http://docs.python.org/library/itertools.html#itertools.count) (which is pretty much the same approach as enumerate): ``` from itertools import izip as zip, count # izip for maximum efficiency [i for i, j in zip(count(), ['foo', 'bar', 'baz']) if j == 'bar'] ``` This is more efficient for larger lists than using `enumerate()`: ``` $ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ['foo', 'bar', 'baz']*500) if j == 'bar']" 10000 loops, best of 3: 174 usec per loop $ python -m timeit "[i for i, j in enumerate(['foo', 'bar', 'baz']*500) if j == 'bar']" 10000 loops, best of 3: 196 usec per loop ```
How to find the index for a given item in a list?
[ "", "python", "list", "indexing", "" ]
I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this?
Adding "return false;" to the onclick attribute of the button will prevent the automatic postback.
Is this what you are trying to do? ``` <input type="button" id="myButton" value="Click!" /> <script type="text/javascript"> document.getElementById('myButton').onclick = function() { var agree = confirm('Are you sure?'); if (!agree) return false; }; </script> ```
How to avoid a postback in JavaScript?
[ "", "javascript", "asp.net", "" ]
It's common in C++ to name member variables with some kind of prefix to denote the fact that they're member variables, rather than local variables or parameters. If you've come from an MFC background, you'll probably use `m_foo`. I've also seen `myFoo` occasionally. C# (or possibly just .NET) seems to recommend using just an underscore, as in `_foo`. Is this allowed by the C++ standard?
The rules (which did not change in C++11): * Reserved in any scope, including for use as [implementation](https://stackoverflow.com/questions/4297933/c-implementation#4297974) macros: + identifiers beginning with an underscore followed immediately by an uppercase letter + identifiers containing adjacent underscores (or "double underscore") * Reserved in the global namespace: + identifiers beginning with an underscore * Also, everything in the `std` namespace is reserved. (You are allowed to add template specializations, though.) From the 2003 C++ Standard: > ### 17.4.3.1.2 Global names [lib.global.names] > > Certain sets of names and function signatures are always reserved to the implementation: > > * Each name that contains a double underscore (`__`) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use. > * Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165 > > 165) Such names are also reserved in namespace `::std` (17.4.3.1). The C++ language is based on the C language (1.1/2, C++03), and C99 is a normative reference (1.2/1, C++03), so it's useful to know the restrictions from the 1999 C Standard (although they do not apply to C++ directly): > ### 7.1.3 Reserved identifiers > > Each header declares or defines all identifiers listed in its associated subclause, and > optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers. > > * All identifiers that begin with an underscore and either an uppercase letter or another > underscore are always reserved for any use. > * All identifiers that begin with an underscore are always reserved for use as identifiers > with file scope in both the ordinary and tag name spaces. > * Each macro name in any of the following subclauses (including the future library > directions) is reserved for use as specified if any of its associated headers is included; > unless explicitly stated otherwise (see 7.1.4). > * All identifiers with external linkage in any of the following subclauses (including the > future library directions) are always reserved for use as identifiers with external > linkage.154 > * Each identifier with file scope listed in any of the following subclauses (including the > future library directions) is reserved for use as a macro name and as an identifier with > file scope in the same name space if any of its associated headers is included. > > No other identifiers are reserved. If the program declares or defines an identifier in a > context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved > identifier as a macro name, the behavior is undefined. > > If the program removes (with `#undef`) any macro definition of an identifier in the first > group listed above, the behavior is undefined. > > 154) The list of reserved identifiers with external linkage includes `errno`, `math_errhandling`, `setjmp`, and `va_end`. Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code: * Names beginning with a capital `E` followed a digit or uppercase letter: * may be used for additional error code names. * Names that begin with either `is` or `to` followed by a lowercase letter * may be used for additional character testing and conversion functions. * Names that begin with `LC_` followed by an uppercase letter * may be used for additional macros specifying locale attributes. * Names of all existing mathematics functions suffixed with `f` or `l` are reserved * for corresponding functions that operate on float and long double arguments, respectively. * Names that begin with `SIG` followed by an uppercase letter are reserved * for additional signal names. * Names that begin with `SIG_` followed by an uppercase letter are reserved * for additional signal actions. * Names beginning with `str`, `mem`, or `wcs` followed by a lowercase letter are reserved * for additional string and array functions. * Names beginning with `PRI` or `SCN` followed by any lowercase letter or `X` are reserved * for additional format specifier macros * Names that end with `_t` are reserved * for additional type names. While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard. --- Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore. After doing research on this article I no longer end my identifiers with `_t` as this is reserved by the POSIX standard. The rule about any identifier ending with `_t` surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the [GNU libtool manual](http://www.gnu.org/software/libtool/manual/libc/Reserved-Names.html), listing reserved names. CesarB provided the following link to the [POSIX 2004](http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html) reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The [POSIX 2008](http://www.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html) reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.
The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.). ## Personal rule Because I did not want to deal with cases, and wanted a simple rule, I have designed a **personal** one that is both simple and correct: **When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:** * never start a symbol with an underscore * never name a symbol with two consecutive underscores inside. Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros) ## Some examples (I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name) ``` #define _WRONG #define __WRONG_AGAIN #define RIGHT_ #define WRONG__WRONG #define RIGHT_RIGHT #define RIGHT_x_RIGHT ``` ## Extracts from C++0x draft From the [n3242.pdf](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf) file (I expect the final standard text to be similar): > **17.6.3.3.2 Global names [global.names]** > > Certain sets of names and function signatures are always reserved to the implementation: > > — Each name that contains a double underscore \_ \_ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use. > > — Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace. But also: > **17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]** > > Literal suffix identifiers that do not start with an underscore are reserved for future standardization. This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if *not* defined in the global namespace...
What are the rules about using an underscore in a C++ identifier?
[ "", "c++", "language-lawyer", "naming-conventions", "c++-faq", "" ]
I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less. If I pass in a char-array of characters from **0** to **J**, and set length to 5, I want results like *00000, 00001, 00002... HJJJJ, IJJJJJ, JJJJJ*. Here is the base, please help me expand: ``` protected void Main() { char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' }; BruteForce(chars, 5); } private void BruteForce(char[] chars, int length) { // for-loop (?) console-writing all possible combinations from 00000 to JJJJJ // (when passed in length is 5) // TODO: Implement code... } ```
This is one of the solutions I've found. I like the compactness and separation of it: ``` private static char[] characters = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' }; // length: The length of the string created by bruteforce public static void PerformBruteForce(int length) { int charactersLength = characters.Length; int[] odometer = new int[length]; long size = (long)Math.Pow(charactersLength, length); for (int i = 0; i < size; i++) { WriteBruteForce(odometer, characters); int position = 0; do { odometer[position] += 1; odometer[position] %= charactersLength; } while (odometer[position++] == 0 && position < length); } } private static void WriteBruteForce(int[] odometer, char[] characters) { // Print backwards for (int i = odometer.Length - 1; i >= 0; i--) { Console.Write(characters[odometer[i]]); } Console.WriteLine(); } ```
This isn't *quite* a duplicate of ["recursion instead of multi-loops"](https://stackoverflow.com/questions/207889/recursion-instead-of-multi-loops) but it's pretty close. I'll write up a solution if this doesn't help you. EDIT: Here's a non-recursive solution. The recursive one is slightly harder to return an `IEnumerable<string>` from, but returning an iterator gives a nice interface IMO :) ``` private static IEnumerable<string> GetAllMatches(char[] chars, int length) { int[] indexes = new int[length]; char[] current = new char[length]; for (int i=0; i < length; i++) { current[i] = chars[0]; } do { yield return new string(current); } while (Increment(indexes, current, chars)); } private static bool Increment(int[] indexes, char[] current, char[] chars) { int position = indexes.Length-1; while (position >= 0) { indexes[position]++; if (indexes[position] < chars.Length) { current[position] = chars[indexes[position]]; return true; } indexes[position] = 0; current[position] = chars[0]; position--; } return false; } ```
Algorithm: Odometer / Brute force
[ "", "c#", "algorithm", "" ]
I have a very basic question about MVC web applications in Java. Since the olden days of raw JSP up until current technologies like Seam, a very basic pattern has always been the internal dispatch from the controller that initially accepted the request to the view layer that creates the output to be sent to the client. This internal dispatch is generally done (although the mechanism may be hidden through an extra layer of configuration) by asking the servlet container for a new resource using a URL. The mapping of these URL are done by the same web.xml that also defines the "real" URL to the outside. Unless special measures are taken, it is often possible to directly access the view layer directly. Witness the Seam "registration" demo, where you can bypass "register.seam" and directly go to "registered.xhtml". This is a potential security problem. At the very least, it leaks view template source code. I am aware that this is only a basic sample application, but it is also strange that any extra measures should need to be taken to declare these internal resources invisible to the outside. What is the easiest way to restrict URL entry points? Is there maybe something like the "WEB-INF" directory, a magic URL path component that can only be accessed by internal requests?
I have now seen a couple of applications that put their internal JSP into `WEB-INF/jsp`. That seems to do the trick, at least for JSP, and also for Velocity. It [does not seem to work for JSF](http://www.coderanch.com/t/212515/JSF/java/hiding-pages-behind-WEB-INF), though.
You can prevent access to internal resources by using a [`security-constraint`](http://wiki.metawerx.net/wiki/Web.xml.SecurityConstraint) in your `web.xml` deployment descriptor. For example, I use the following configuration to prevent direct access to JSPs: ``` <!-- Prevent direct access to JSPs. --> <security-constraint> <web-resource-collection> <web-resource-name>JSP templates</web-resource-name> <url-pattern>*.jsp</url-pattern> </web-resource-collection> <auth-constraint/> <!-- i.e. nobody --> </security-constraint> ```
Protecting internal view layer template pages in servlet applications
[ "", "java", "architecture", "servlets", "" ]
I am curious if anyone has done a comparison between the different options out there. So far I am leaning towards using Moo.fx because loading prototype.js just to use scriptaculous seems a bit much. Does that make sense? Are there any other effects libraries worth trying? Thanks.
I've found a viable alternative to the recommended JS libraries -- a GWT-native Java library called [GWT-FX](http://code.google.com/p/gwt-fx/) developed by Adam Tacy. Some of its features include built-in effects (Fade, Slide, Highlight), physics transition types (linear, ease in/out, elastic), and the ability to build your own effects by specifying CSS rules or "properties" (declarations). Check out the [google code wiki](http://code.google.com/p/gwt-fx/wiki/StartPage) and/or [demo](http://gwtfx.adamtacy.com/EffectsExample.html#intro) pages for more info.
"Smart GWT" has interesting effects, especially to mimic desktop items. I pass the ShowCase: [Smart GWT Showcase](http://www.smartclient.com/smartgwt/showcase/#main)
Which effects library should I integrate with GWT?
[ "", "javascript", "css", "gwt", "comparison", "effects", "" ]
Some of the other questions and answers here on SO extol the virtues of using an enterprise repository tool like Archiva, Artifactory, or Nexus. What are the pros and cons of each? How do I choose between them? In case it helps: * We use both Maven 1 and Maven 2 (at least for a while) * We want to store both internally-generated artifacts, publicly-available ones (ibiblio, codehaus, etc.), and proprietary ones (e.g. Sun's licensed JARs like the Servlet API). * We would like something that runs on Windows, Linux, or both. * We use Luntbuild as our CI server (but intend moving to Hudson some time). N.B. this question is not a duplicate of either [this one](https://stackoverflow.com/questions/161819/what-are-mainbest-maven-respositories-to-use) or [this one](https://stackoverflow.com/questions/157463/host-maven-repository).
We had been using Archiva for a while, and were happy with it. We recently switched hardware, and decided to try out Nexus because we had read some good things about it. We didn't know what we were missing in Archiva, but Nexus is far better. The repository aspect is easier because it "groups" all the repositories into one url, for easier settings.xml configuration. Further, the web site rocks -- easy search for artifacts, and even searches the global central repo, without having downloaded it all to your proxy. I highly recommend Nexus!
I have used Archiva for over a year and found it met all of the basic requirements, however, we were restricted to a Windows server and as such found a few limitations and had a large memory footprint. The main reason we started looking for an alternative, however, was the painful process to upload artifacts to the repository that didn't exist in the Maven repositories on the web (such as some of the Sun or IBM jar files). We made the switch to Nexus about two months ago and have been impressed very much by its clean interface, ease of use, and general non-invasiveness. Uploading new artifacts is a breeze, and we haven't had a single issue. We've been using Mule and CXF a bit, and so we've had to download from both legacy (Maven1) and standard (Maven2) repositories - these are straightforward to set up and require little (if any) administration. The documentation is excellent with the free PDF on the Nexus site (also you can buy the hardcopy version if you like). I've used it on both Windows (at work) and Linux (at home) without any problems.
Best enterprise repository tool for Maven 2?
[ "", "java", "maven-2", "build-automation", "devtools", "" ]
I guess the real question is: If I don't care about dirty reads, will adding the **with (NOLOCK)** hint to a SELECT statement affect the performance of: 1. the current SELECT statement 2. other transactions against the given table Example: ``` Select * from aTable with (NOLOCK) ```
1) **Yes**, a select with `NOLOCK` will complete faster than a normal select. 2) **Yes**, a select with `NOLOCK` will allow other queries against the effected table to complete faster than a normal select. **Why would this be?** `NOLOCK` typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous. You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a `NOLOCK` read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed. *You really have no way to know what the state of the data is.* If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then `NOLOCK` is a good way to boost performance for these queries and avoid having them negatively impact database performance. **Always use the `NOLOCK` hint with great caution and treat any data it returns suspiciously.**
NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT. NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table. Here is information about all of the isolation levels at your disposal, as well as table hints. [SET TRANSACTION ISOLATION LEVEL](http://msdn.microsoft.com/en-us/library/ms173763(SQL.90).aspx) [Table Hint (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms187373(SQL.90).aspx)
Effect of NOLOCK hint in SELECT statements
[ "", "sql", "sql-server", "locking", "" ]
I've noticed for quite a long time that strange domains such like jsev.com, cssxx.com appered in my firefox status bar from time to time, I always wonder why so many web pages contains resources from these strange domains. I googled it, but found nothing. I guess it's some kind of virus which infect the servers and insert the code. Here is a sample taken from page header of <http://www.eflorenzano.com/threadexample/blog/>: ``` <script language="javascript" src="http://i.jsev.com./base.2032621946.js"> </script> <body onmousemove="return fz3824();"> <LINK REL="stylesheet" TYPE="text/css" HREF="http://i.cssxx.com./base2032621947.css"> <A HREF = "http://i.html.com./base2032621947.html"></A> <SCRIPT LANGUAGE="JAVASCRIPT" SRC="http://i.js.com./base2032621947.js"></SCRIPT> <SCRIPT LANGUAGE="JAVASCRIPT"> function getuseragnt() { var agt = navigator.userAgent.toLowerCase(); agt = agt.replace(/ /g, ""); return agt; } document.write("<LINK REL='stylesheet' TYPE='text/css' HREF='http://i.css2js.com./base.css" + getuseragnt() + "_2032621947'>") </SCRIPT> ``` edit: I am on a debian box, only on firefox I see this code, I just tried opera, this code doesn't appear in opera, really strange, never heard of firefox having such problems.
This happens if you are using one of Princeton university's CoDeeN project proxy servers. CoDeeN is an academic testbed content distribution network. When you browse a web page using CoDeeN proxy it injects some HTML code to the site's original HTML and redirects requests sent to pseudo adresses to the project's servers. Some of the pseudo addresses are: <http://i.cssxx.com./base0877861956.css> | i.cssxx.com. <http://i.jsev.com./base.0877861955.js> | i.jsev.com./ <http://i.html.com./base0877861956.html> | i.html.com. <http://i.js.com./base0877861956.js> | i.js.com./ <http://i.css2js.com./base.css> | i.css2js.com. Some or all CoDeeN's proxy servers appear as anonymous proxy servers list. CoDeeN project page: <http://codeen.cs.princeton.edu/>
It may be a browser worm installed on your machine. Should scan entire system.
Why so many web pages contain such a strange code snippet in header?
[ "", "javascript", "html", "virus", "" ]
I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too. Does anyone know of a premade component that could do this?
Referencing [Wayne's post](https://stackoverflow.com/questions/124975/windows-forms-textbox-that-has-line-numbers#125093), here is the relevant code. It is using GDI to draw line numbers next to the text box. ``` Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call SetStyle(ControlStyles.UserPaint, True) SetStyle(ControlStyles.AllPaintingInWmPaint, True) SetStyle(ControlStyles.DoubleBuffer, True) SetStyle(ControlStyles.ResizeRedraw, True) End Sub Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged FindLine() Invalidate() End Sub Private Sub FindLine() Dim intChar As Integer intChar = RichTextBox1.GetCharIndexFromPosition(New Point(0, 0)) intLine = RichTextBox1.GetLineFromCharIndex(intChar) End Sub Private Sub DrawLines(ByVal g As Graphics, ByVal intLine As Integer) Dim intCounter As Integer, intY As Integer g.Clear(Color.Black) intCounter = intLine + 1 intY = 2 Do g.DrawString(intCounter.ToString(), Font, Brushes.White, 3, intY) intCounter += 1 intY += Font.Height + 1 If intY > ClientRectangle.Height - 15 Then Exit Do Loop End Sub Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs) DrawLines(e.Graphics, intLine) End Sub Private Sub RichTextBox1_VScroll(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.VScroll FindLine() Invalidate() End Sub Private Sub RichTextBox1_UserScroll() Handles RichTextBox1.UserScroll FindLine() Invalidate() End Sub ``` The RichTextBox is overridden like this: ``` Public Class UserControl1 Inherits System.Windows.Forms.RichTextBox Public Event UserScroll() Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) If m.Msg = &H115 Then RaiseEvent UserScroll() End If MyBase.WndProc(m) End Sub End Class ``` (Code by divil on the xtremedotnettalk.com forum.)
Take a look at the [SharpDevelop](https://github.com/icsharpcode) C# compiler/IDE source code. They have a sophisticated text box with line numbers. You could look at the source, figure out what they're doing, and then implement it yourself. Here's a sample of what I'm referencing: [![alt text](https://i.stack.imgur.com/rRtmS.png)](https://i.stack.imgur.com/rRtmS.png) (source: [sharpdevelop.net](http://community.sharpdevelop.net/photos/mattward/images/original/FeatureTourQuickClassBrowser.aspx))
Windows Forms textbox that has line numbers?
[ "", "c#", ".net", "winforms", "" ]
I need to perform Diffs between Java strings. I would like to be able to rebuild a string using the original string and diff versions. Has anyone done this in Java? What library do you use? ``` String a1; // This can be a long text String a2; // ej. above text with spelling corrections String a3; // ej. above text with spelling corrections and an additional sentence Diff diff = new Diff(); String differences_a1_a2 = Diff.getDifferences(a,changed_a); String differences_a2_a3 = Diff.getDifferences(a,changed_a); String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3}; String new_a3 = Diff.build(diffs); a3.equals(new_a3); // this is true ```
This library seems to do the trick: [google-diff-match-patch](https://github.com/google/diff-match-patch). It can create a patch string from differences and allow to reapply the patch. **edit**: Another solution might be to <https://code.google.com/p/java-diff-utils/>
Apache Commons has String diff org.apache.commons.lang.StringUtils ``` StringUtils.difference("foobar", "foo"); ```
How to perform string Diffs in Java?
[ "", "java", "diff", "" ]
what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?
When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files: * lang.en.js * lang.it.js * lang.fr.js Each of the files declares an object which is basically just a map from key word to language phrase: ``` // lang.en.js lang = { greeting : "Hello" }; // lang.fr.js lang = { greeting : "Bonjour" }; ``` Dynamically load one of those files and then all you need to do is reference the key from your map: ``` document.onload = function() { alert(lang.greeting); }; ``` There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your "dictionary" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc. ``` var l = new Language('en'); l.get('greeting'); ```
There are a few things you need to keep in mind when designing multilanguage support: 1 - Separate code from data (i.e. don't hard-code strings right into your functions) 2 - create a formatting hook function to deal with localization differences. Allowing formattable strings (**"{0}"**) is better than concatenating (**"Welcome to" + value**), for a lot of reasons: * in some languages, a number is formatted like 1.234.678,00 instead of 1,234,567.00 * pluralization is often not as simple as appending an "s" at the end of the singular * grammar rules are different and can affect the order of things so you should allow dynamic data to be appended after the translation hook: for example, **"Welcome to {0}"** turns into **"{0} he youkoso"** in japanese (this happens in pretty much every language, mind you). 3 - Make sure that you can actually format strings **after** the translation hook runs, so you can reuse keys. 4 - **Do not, under any circunstance, hook database outputs to the translator utility**. If you have multilingual data, create separate tables / rows in your database. I've seen people get this no-brainer wrong fairly often (usually for countries and states/provinces in forms). 5 - Create explicit coding practices rules for creating keys. The formatter utility function (which will look something like **translate("hello world")** will take a key as a parameter, and keys with slight variations make maintainance very annoying. For instance, you might end up with three keys in the following example: "enter you name", "enter your name:", "enter your name: ". Choose one format (e.g. no colon, trimmed) and catch discrepancies in code reviews. Don't do this filtering programmatically, as it can trigger false positives. 6 - Be mindful that HTML markup could potentially be needed in the translation table (e.g. if you need to bold a word in a sentence, or have footnote medical references). Test for this extensively. 7 - There are several ways of importing language strings. Ideally, you should have multiple versions of a language.lang.js file, switch between them with server side code, and reference the file from the bottom of the HTML file. Pulling the file via AJAX is also an alternative, but could introduce delays. Merging language.js into your main code file is not advisable, since you lose the benefits of file caching. 8 - **Test with your target languages.** This sounds silly, but I've seen a serious bug once because the programmer didn't bother to check for the existence of "é" in the key.
Best practice javascript and multilanguage
[ "", "javascript", "internationalization", "" ]
My question is quite relevant to [something asked before](https://stackoverflow.com/questions/42785/how-do-you-retrofit-unit-tests-into-a-code-base) but I need some practical advice. I have "Working effectively with legacy code" in my hands and I 'm using advice from the book as I read it in the project I 'm working on. The project is a C++ application that consists of a few libraries but the major portion of the code is compiled to a single executable. I 'm using googletest for adding unit tests to existing code when I have to touch something. My problem is how can I setup my build process so I can build my unit tests since there are two different executables that need to share code while I am not able to extract the code from my "under test" application to a library. Right now I have made my build process for the application that holds the unit tests link against the object files generated from the build process of the main application but I really dislike it. Are there any suggestions?
If your test app is only linking the object files it needs to test then you are effectively already treating them as a library, it should be possible to group those object files into a separate library for the main and the test app. If you can't then I don't see that what you are doing is too bad an alternative. If you are having to link other object files not under test then that is a sign of dependencies that need to be broken, for which you have the perfect book. We have similar problems and use a system like the one suggested by Vlion
[Working Effectively With Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052) is the best resource for how to start testing old code. There are really no short term solutions that won't result in things getting worse.
Adding unit tests to an existing project
[ "", "c++", "unit-testing", "legacy", "" ]
I have this regex I built and tested in regex buddy. ``` "_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}" ``` When I use this in .Net C# I receive the exception ``` "parsing \"_ [ 0-9]{10}+ +[ 0-9]{10}+ +[ 0-9]{6}+ [ 0-9]{2}\" - Nested quantifier +." ``` What does this error mean? Apparently .net doesn't like the expression. Here is the regex buddy so u can understand my intention with the regex... ``` _ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2} Match the characters "_ " literally «_ » Match a single character present in the list below «[ 0-9]{10}+» Exactly 10 times «{10}+» The character " " « » A character in the range between "0" and "9" «0-9» Match the character " " literally « {1}+» Exactly 1 times «{1}+» Match a single character present in the list below «[ 0-9]{10}+» Exactly 10 times «{10}+» The character " " « » A character in the range between "0" and "9" «0-9» Match the character " " literally « {2}+» Exactly 2 times «{2}+» Match a single character present in the list below «[ 0-9]{6}+» Exactly 6 times «{6}+» The character " " « » A character in the range between "0" and "9" «0-9» Match the character " " literally « {2}» Exactly 2 times «{2}» Match a single character present in the list below «[ 0-9]{2}» Exactly 2 times «{2}» The character " " « » A character in the range between "0" and "9" «0-9» ``` In short... What is a Nested quantifier?
.NET is complaining about the `+` after the `{n}` style quantifier as it doesn't make any sense. `{n}` means match exactly n of a given group. `+` means match one or more of a given group. Remove the `+`'s and it'll compile fine. ``` "_ [ 0-9]{10} {1}[ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}" ```
.NET doesn't support the [possessive quantifier](http://www.regular-expressions.info/possessive.html) ``` {10}+ ``` However, {10} should have exactly the same effect. The + avoids backtracking and trying shorter matches if the longest match fails, but since {10} can only match exactly 10 characters to start with this doesn't achieve much. ``` "_ [ 0-9]{10} [ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}" ``` should be fine. I've also dropped the "{1}+" bit .Since it matches exactly once, "A{1}+" is equivalent to just "A". **EDIT** As Porges says, if you do need possessive quantifiers in .NET, then atomic groups give the same functionality with `(?>[0-9]*)` being equivalent to `[0-9]*+`.
What is a "Nested Quantifier" and why is it causing my regex to fail?
[ "", "c#", ".net", "regex", "" ]
Wanted to see peoples thoughts on best way to organize directory and project structure on a project / solution for a winforms C# app. Most people agree its best to seperate view, business logic, data objects, interfaces but wanted to see how different people tackle this. In addition, isolate third party dependencies into implementation projects and then have interface exported projects that consumers reference - View.csproj- BusinessLogic.csproj- Data.csproj- CalculatorService.Exported.csproj (interfaces)- CalculatorService.MyCalcImpl.csproj (one implementation)- CalculatorService.MyCalcImpl2.csproj (another implementation) Also, in terms of folder structure, what is better nesting: Interfaces ---IFoo ---IData Impl ---Foo ---Data or Product ---Interfaces/IProduct ---Impl/Product Foo ---Impl/Foo ---Interfaces/IFoo All trying to push for decoupled dependencies on abstractions and quick ability to changed implementations. Thoughts? Best practices?
For me it depends on the model I'm following. If I'm using MVC it would be ``` Project -Models -Controllers -Views ``` Or for MVP it would be ``` Project -Models -Presenters -Views ``` Under the views I seperate them into namespaces relevant to the controllers, i.e. if I have a controller to handle inventory transactions I might have it as ``` Project -Models --Inventory -Controllers --Inventory ---TransactionsController.cs -Views --Inventory ---Transactions ----EditTransactionsView.dfm ``` For interfaces I put the interface in the same directory as the implementations.
Bit of a late answer but may as well chime in. I have been personally using folders based on the actual type of item it is. For example: ``` - Project + Forms + Classes + UserControls + Resources + Data ``` So I end up with: ``` new Forms.AboutForm().ShowDialog(); Controls.Add(new Controls.UberTextBox()); ```
Winforms - best directory / project structure
[ "", "c#", "winforms", "" ]
I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing: ``` rename('/correct/path/to/dir/1', '/correct/path/to/dir/2'); ```
You're editing the higher level directory, so the PHP user needs to have write access to that directory.
Thats probably because apache is not the owner of the parent directory. Renaming (or moving) a file is basically the same thing as creating a new file.
Why do I get "permission denied" in PHP when trying to rename a directory?
[ "", "php", "permissions", "rename", "" ]
Definition of variables in use: ``` Guid fldProId = (Guid)ffdPro.GetProperty("FieldId"); string fldProValue = (string)ffdPro.GetProperty("FieldValue"); FormFieldDef fmProFldDef = new FormFieldDef(); fmProFldDef.Key = fldProId; fmProFldDef.Retrieve(); string fldProName = (string)fmProFldDef.GetProperty("FieldName"); string fldProType = (string)fmProFldDef.GetProperty("FieldType"); ``` Lines giving the problem (specifically line 4 (hTxtBox.Text = ...)): ``` if (fldProType.ToLower() == "textbox") { Label hTxtBox = (Label)findControl(fldProName); hTxtBox.Text = fldProValue; } ``` All data is gathered from the database correctly, however the label goes screwy. Any ideas?
Are you sure that findControl is returning a value? Is hTxtBox.Text a property that does any computation on a set that could be throwing the NullReferenceException?
findControl is returning a null value. It could be that the particular Label is not a direct child of the current page, i.e., inside an UpdatePanel or some other control so that the actual name of the control is different than the name applied (and thus it can't find it). For example, if it is named "name", the actual name may be ctl0$content$name because it is nested inside another control on the page. You don't really give enough information about the context for me to give you a better answer.
C#, ASP.NET - NullReferenceException - Object reference not set to an instance of an object
[ "", "c#", "asp.net", "" ]
I am using a Session Parameter on an ObjectDataSource. It works fine on the local development machine but I get this error after copying the website to the production server: Type 'System.Web.UI.WebControls.SessionParameter' does not have a public property named 'DbType'.
Me again! First Answer I gave was WRONG! Correct answer is that .NET Framework v3.5 was installed, and it needs to be updated to .NET framework 3.5 SP1
I found the answer but I don't know why it does this. I just removed the DBType property and it worked fine.
Type 'System.Web.UI.WebControls.SessionParameter' does not have a public property named 'DbType'
[ "", "asp.net", "sql", "parameters", "objectdatasource", "" ]
Coming from a desktop background I'm not sure exactly how to pass the exceptions I have caught to an Error page in order to avoid the standard exception screen being seen by my users. My general question is how do I pass the exception from page X to my Error page in ASP.net?
I suggest using the customErrors section in the web.config: ``` <customErrors mode="RemoteOnly" defaultRedirect="/error.html"> <error statusCode="403" redirect="/accessdenied.html" /> <error statusCode="404" redirect="/pagenotfound.html" /> </customErrors> ``` And then using [ELMAH](https://code.google.com/archive/p/elmah/) to email and/or log the error.
The pattern I use is to log the error in a try/catch block (using log4net), then do a response.redirect to a simple error page. This assumes you don't need to show any error details. If you need the exception details on a separate page, you might want to look at Server.GetLastError. I use that in global.asax (in the Application\_Error event) to log unhandled exceptions and redirect to an error page.
Passing Exceptions to an error screen in ASP.net/C#
[ "", "c#", "asp.net", "error-handling", "" ]
What's the best way to connect to a Informix database from .Net? I'm developing a client-server application based on a legacy Informix DB which used to be connected by JDBC. I need it, from the most important to the least: 1. To be fast 2. DB server changes not needed 3. No ODBC and no dependencies, other than de .Net Framework 2.0 Thanks in advance for your help.
The connections strings to use with OleDb or ADO.NET can be found [here](http://www.connectionstrings.com/?carrier=informix). Take a look at this [article](https://www.ibm.com/developerworks/data/library/techarticle/dm-0510durity/index.html) on how to connect to an Informix database using ADO.NET.
We connect to Informix from .NET, but we do it via web services that are written in FourJ's BDL
Connecting to Informix database from .Net
[ "", "c#", ".net", "database-connection", "informix", "" ]
I have a C++ program representing a TCP header as a struct: ``` #include "stdafx.h" /* TCP HEADER 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ typedef struct { // RFC793 WORD wSourcePort; WORD wDestPort; DWORD dwSequence; DWORD dwAcknowledgment; unsigned int byReserved1:4; unsigned int byDataOffset:4; unsigned int fFIN:1; unsigned int fSYN:1; unsigned int fRST:1; unsigned int fPSH:1; unsigned int fACK:1; unsigned int fURG:1; unsigned int byReserved2:2; unsigned short wWindow; WORD wChecksum; WORD wUrgentPointer; } TCP_HEADER, *PTCP_HEADER; int _tmain(int argc, _TCHAR* argv[]) { printf("TCP header length: %d\n", sizeof(TCP_HEADER)); return 0; } ``` If I run this program I get the size of this header as 24 bytes, which is not the size I was expecting. If I change the type of the field "wWindow" to "unsigned int wWindow:16", which has the same number of bits as an unsigned short, the program tells me the size of the struct is now 20 bytes, the correct size. Why is this? I am using Microsoft Visual Studio 2005 with SP1 on a 32-bit x86 machine.
See this question: [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-does-the-sizeof-operator-return-a-size-larger-for-a-structure-than-the-tota) . I believe that compiler takes a hint to disable padding when you use the "unsigned int wWindow:16" syntax. Also, note that a short is not guaranteed to be 16 bits. The guarantee is that: 16 bits <= size of a short <= size of an int.
Because the compiler is packing your bitfield into a 32-bit int, not a 16-bit entity. In general you should avoid bitfields and use other manifest constants (enums or whatever) with explicit bit masking and shifting to access the 'sub-fields' in a field. Here's one reason why bitfields should be avoided - they aren't very portable between compilers even for the same platform. from the C99 standard (there's similar wording in the C90 standard): > An implementation may allocate any > addressable storage unit large enough > to hold a bitfield. If enough space > remains, a bit-field that immediately > follows another bit-field in a > structure shall be packed into > adjacent bits of the same unit. If > insufficient space remains, whether a > bit-field that does not fit is put > into the next unit or overlaps > adjacent units is > implementation-defined. The order of > allocation of bit-fields within a unit > (high-order to low-order or low-order > to high-order) is > implementation-defined. The alignment > of the addressable storage unit is > unspecified. You cannot guarantee whether a bit field will 'span' an int boundary or not and you can't specify whether a bitfield starts at the low-end of the int or the high end of the int (this is independant of whether the processor is big-endian or little-endian).
Getting different header size by changing window size
[ "", "c++", "c", "struct", "packing", "" ]
What's the best way to format this for readability? ``` if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) { createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize); fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n"); } ```
I'd extract the "is an image" logic into its own function, which makes the `if` more readable and also allows you to centralize the logic. ``` function is_image($filename) { $image_extensions = array('png', 'gif', 'jpg'); foreach ($image_extensions as $extension) if (strrpos($filename, ".$extension") !== FALSE) return true; return false; } if (is_image($file) && !file_exists("$thumbsdir/$file")) { createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize); fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n"); } ```
``` if ((strpos($file, '.jpg',1) || strpos($file, '.gif',1) || strpos($file, '.png',1)) && file_exists("$thumbsdir/$file") == false) { createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize); fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n"); } ```
Formatting an if statement for readability
[ "", "php", "formatting", "readability", "" ]
Recently, I noticed some people mentioning that `std::list::size()` has a linear complexity. According to [some](http://www.cplusplus.com/reference/stl/list/size.html) [sources](http://bytes.com/forum/thread60248.html), this is in fact implementation dependent as the standard doesn't say what the complexity has to be. The comment [in this blog entry](http://ahlamnote.blogspot.com/2006/11/stl-list-size-method-is-slow.html) says: > Actually, it depends on which STL you > are using. Microsoft Visual Studio V6 > implements size() as {return (\_Size); > } whereas gcc (at least in versions > 3.3.2 and 4.1.0) do it as { return std::distance(begin(), end()); } The > first has constant speed, the second > has o(N) speed 1. So my guess is that for the VC++ crowd `size()` has constant complexity as Dinkumware probably won't have changed that fact since VC6. Am I right there? 2. What does it look like currently in `gcc`? If it is really O(n), why did the developers choose to do so?
## Pre-C++11 answer You are correct that the standard does not state what the complexity of `list::size()` must be - however, it does recommend that it "should have constant complexity" (Note A in Table 65). [Here's an interesting article by Howard Hinnant](http://howardhinnant.github.io/On_list_size.html) that explains why some people think `list::size()` should have O(N) complexity (basically because they believe that O(1) `list::size()` makes `list::splice()` have O(N) complexity) and why an O(1) `list::size()` is be a good idea (in the author's opinion): * <http://howardhinnant.github.io/On_list_size.html> I think the main points in the paper are: * there are few situations where maintaining an internal count so `list::size()` can be O(1) causes the splice operation to become linear * there are probably many more situations where someone might be unaware of the negative effects that might happen because they call an O(N) `size()` (such as his one example where `list::size()` is called while holding a lock). * that instead of permitting `size()` be O(N), in the interest of 'least surprise', the standard should require any container that implements `size()` to implement it in an O(1) fashion. If a container cannot do this, it should not implement `size()` at all. In this case, the user of the container will be made aware that `size()` is unavailable, and if they still want or need to get the number of elements in the container they can still use `container::distance( begin(), end())` to get that value - but they will be completely aware that it's an O(N) operation. I think I tend to agree with most of his reasoning. However, I do not like his proposed addition to the `splice()` overloads. Having to pass in an `n` that must be equal to `distance( first, last)` to get correct behavior seems like a recipe for hard to diagnose bugs. I'm not sure what should or could be done moving forward, as any change would have a significant impact on existing code. But as it stands, I think that existing code is already impacted - behavior might be rather significantly different from one implementation to another for something that should have been well-defined. Maybe onebyone's comment about having the size 'cached' and marked known/unknown might work well - you get amortized O(1) behavior - the only time you get O(N) behavior is when the list is modified by some splice() operations. The nice thing about this is that it can be done by implementors today without a change to the standard (unless I'm missing something). ~~As far as I know, C++0x is not changing anything in this area.~~
In C++11 it is required that for *any* standard container the `.size()` operation must be complete in "constant" complexity (O(1)). (Table 96 — Container requirements). Previously in C++03 `.size()` *should* have constant complexity, but is not required (see [Is std::string size() a O(1) operation?](https://stackoverflow.com/questions/256033/is-stdstring-size-a-o1-operation)). The change in standard is introduced by [n2923: Specifying the complexity of size() (Revision 1)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2923.pdf). However, the implementation of `.size()` in libstdc++ still uses an O(N) algorithm in gcc up to 4.8: ``` /** Returns the number of elements in the %list. */ size_type size() const _GLIBCXX_NOEXCEPT { return std::distance(begin(), end()); } ``` See also [Why is std::list bigger on c++11?](https://stackoverflow.com/questions/10065055/why-is-stdlist-bigger-on-c11) for detail why it is kept this way. ***Update***: `std::list::size()` is [properly O(1)](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=49561#c20) when using gcc **5.0** in C++11 mode (or above). --- By the way, the `.size()` in libc++ is correctly O(1): ``` _LIBCPP_INLINE_VISIBILITY size_type size() const _NOEXCEPT {return base::__sz();} ... __compressed_pair<size_type, __node_allocator> __size_alloc_; _LIBCPP_INLINE_VISIBILITY const size_type& __sz() const _NOEXCEPT {return __size_alloc_.first();} ```
Is list::size() really O(n)?
[ "", "c++", "list", "big-o", "std", "complexity-theory", "" ]
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name. I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use: ``` for item in self.inventory_names: self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item) self.cursor.close() ``` I get the error: > sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied. I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings. ``` cursor.execute("""CREATE TABLE Equipment (id INTEGER PRIMARY KEY, name TEXT, price INTEGER, weight REAL, info TEXT, ammo_cap INTEGER, availability_west TEXT, availability_east TEXT)""") ``` However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so: ``` for item in self.inventory_names: self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item) self.cursor.close() ``` I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?
The `Cursor.execute()` method expects a sequence as second parameter. You are supplying a string which happens to be 8 characters long. Use the following form instead: ``` self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item]) ``` Python library reference: sqlite3 [Cursor Objects](https://docs.python.org/2/library/sqlite3.html#cursor-objects).
I have spent half a day trying to figure out why something like this would give me an error: ``` cursor.execute("SELECT * from ? WHERE name = ?", (table_name, name)) ``` only to find out that table names *cannot be parametrized*. Hope this will help other people save some time.
SQLite parameter substitution problem
[ "", "python", "sqlite", "" ]
I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread. I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework. Is there any good general purpose way to indefinitely pause a worker thread in C# .NET. I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case.
Never, ever use `Thread.Suspend`. The major problem with it is that 99% of the time you can't know what that thread is doing when you suspend it. If that thread holds a lock, you make it easier to get into a deadlock situation, etc. Keep in mind that code you are calling may be acquiring/releasing locks behind the scenes. Win32 has a similar API: `SuspendThread` and `ResumeThread`. The following docs for `SuspendThread` give a nice summary of the dangers of the API: <http://msdn.microsoft.com/en-us/library/ms686345(VS.85).aspx> > This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately. The proper way to suspend a thread indefinitely is to use a `ManualResetEvent`. The thread is most likely looping, performing some work. The easiest way to suspend the thread is to have the thread "check" the event each iteration, like so: ``` while (true) { _suspendEvent.WaitOne(Timeout.Infinite); // Do some work... } ``` You specify an infinite timeout so when the event is not signaled, the thread will block indefinitely, until the event is signaled at which point the thread will resume where it left off. You would create the event like so: ``` ManualResetEvent _suspendEvent = new ManualResetEvent(true); ``` The `true` parameter tells the event to start out in the signaled state. When you want to pause the thread, you do the following: ``` _suspendEvent.Reset(); ``` And to resume the thread: ``` _suspendEvent.Set(); ``` You can use a similar mechanism to signal the thread to exit and wait on both events, detecting which event was signaled. Just for fun I'll provide a complete example: ``` public class Worker { ManualResetEvent _shutdownEvent = new ManualResetEvent(false); ManualResetEvent _pauseEvent = new ManualResetEvent(true); Thread _thread; public Worker() { } public void Start() { _thread = new Thread(DoWork); _thread.Start(); } public void Pause() { _pauseEvent.Reset(); } public void Resume() { _pauseEvent.Set(); } public void Stop() { // Signal the shutdown event _shutdownEvent.Set(); // Make sure to resume any paused threads _pauseEvent.Set(); // Wait for the thread to exit _thread.Join(); } public void DoWork() { while (true) { _pauseEvent.WaitOne(Timeout.Infinite); if (_shutdownEvent.WaitOne(0)) break; // Do the work here.. } } } ```
The [Threading in C#](http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming) ebook summarises Thread.Suspend and Thread.Resume thusly: > The deprecated Suspend and Resume methods have two modes – dangerous and useless! The book recommends using a synchronization construct such as an [AutoResetEvent](http://www.albahari.com/threading/part2.aspx#_AutoResetEvent) or [Monitor.Wait](http://www.albahari.com/threading/part4.aspx#_Wait_and_Pulse) to perform thread suspending and resuming.
Is there a way to indefinitely pause a thread?
[ "", "c#", ".net", "multithreading", "" ]
I have a simple web form that has a several fields and a gridview on it. I also have a save and cancel button. I would like a way to undo what was done to the data on the form when the user presses cancel. This is simple enough with the fields however since changes to the gridview happen in real time against the database I do not know how to get undo functionality. I have thought of storing the changes to gridview in viewstate but I would rather not because of the extra space requirement. I have also thought of a temporary table that would stored the changes then roll them back as needed. Does anyone have an idea how to get undo functionality from the form?
Keep all the data in a session object and write that to the database when you are ready. If you abstract your data layer you can use the ObjectDataSource that interacts with the session objects. I'm currently using this method on a checkout system for an e-commerce site. I store the data in custom objects that mimic the database schema.
The simplest solution is to not commit the changes in the gridview to the database until the user clicks the "save" button. If you do decide to use viewstate or some such to record changes that you will later undo, don't forget to take the same sorts of precautions re: update collisions that you would when making the initial changes.
ASP.net Web App undo support
[ "", "c#", "asp.net", "web-applications", "undo", "" ]
I'm building an ASP.NET AJAX application that uses JavaScript to call web services to get its data, and also uses Silverlights Isolated Storage to cache the data on the client machine. Ultimately once the data is downloaded it is passed to JavaScript which displays in on the page using the HTML DOM. What I'm trying to figure out is, does it make sense for me to make these Web Service calls in Silverlight then pass the data to JavaScript once it's loaded? Also, Silverlight will be saving the data to disk using Isolated Storage whether I call the Web Services with JavaScript or Silverlight. If I call the Web Services with JavaScript, the data will be passed to Silverlight to cache. I've done some prototyping both ways, and I'm finding the performance to pretty much be the same either way. Also, one of the kickers that is pointing me towards using Silverlight for the whole client-side data access layer, is I need to have timers periodically check for updated data and download it to the cache so the JavaScript can loading when it needs to. Has anyone done anything similar to this? If so, what are your experiences relating to performance with either the JavaScript or Silverlight method described?
Since Silverlight can handle JSON and XML based services, the format of the response is totally irrelevant. What you must consider, however, is the following: 1) Silverlight is approximately 1000 times faster than JavaScript 2) If your web service is natively SOAP based, Visual Studio can generate a proxy for you, so that you don't need to parse the SOAP message. 3) Silverlight has LINQ to XML and LINQ to JSON, which makes parsing both POX and JSON a breeze. In a perfect world, I would go with Silverlight for the "engine", and fall back to JavaScript in case Silverlight is not available. Greetings, Laurent
Another thing to consider - getting your data in JSON format will be faster than XML and Web Services. JSON becomes a JavaScript object pretty quickly and doesn't have to be parsed like XML does. Personally, I'd go with JavaScript. article: [Speeding Up AJAX with JSON](http://www.developer.com/lang/jscript/article.php/10939_3596836_2)
Call Web Services Using Ajax or Silverlight? Which performs best?
[ "", "javascript", "ajax", "silverlight", "web-services", "asp.net-ajax", "" ]
I am having a problem with FCKeditor reverting html entities entered in the source view back to their original unicode representations. For example when I enter `&euro;` into the source view, switch to html and then back to source view, the entity is replaced by an actual € symbol. The bigger problem, as a result, is that this unicode character is then sent back to the server on submit causing character encoding issues with the underlying database table. Anyone else come across this? I have tried many combinations of config settings but all to no avail.
The problem was a configuration setting - `FCKConfig.ProcessHTMLEntities=true`. Altough I had tried changing this in fckconfig.js, I did not realise that the value was being over-ridden in a secondary custom configuration file which had been created by a previous developer. Thanks Anne.
What version of FCKeditor are you using? The current version is 2.6.3. I tested the € symbol in their demo by copying `&euro;` into source view, switched back to display and then back to HTML the ASCII `&euro;` was retained correctly. As such it sounds like there might be a configuration problem with your install of FCKEditor or you need to upgrade. **Edit:** Just found this gem in the FCKEditor documentation: <http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options/ProcessNumericEntities>
How do I stop FCKeditor reverting html entities back to their unicode characters
[ "", "javascript", "fckeditor", "" ]
We try to convert from string to `Byte[]` using the following Java code: ``` String source = "0123456789"; byte[] byteArray = source.getBytes("UTF-16"); ``` We get a byte array of length 22 bytes, we are not sure where this padding comes from. How do I get an array of length 20?
[Alexander's answer](https://stackoverflow.com/questions/228987/convert-string-to-byte-in-java#228998) explains why it's there, but not how to get rid of it. You simply need to specify the endianness you want in the encoding name: ``` String source = "0123456789"; byte[] byteArray = source.getBytes("UTF-16LE"); // Or UTF-16BE ```
May be the first two bytes are the [Byte Order Mark](http://en.wikipedia.org/wiki/Byte_Order_Mark). It specifies the order of bytes in each 16-bit word used in the encoding.
Why does byteArray have a length of 22 instead of 20?
[ "", "java", "encoding", "string", "arrays", "" ]
Java & Oracle both have a *timestamp* type called Date. Developers tend to manipulate these as if they were *calendar* dates, which I've seen cause nasty one-off bugs. 1. For a basic date quantity you can simply chop off the time portion upon input, i.e., reduce the precision. But if you do that with a date range, (e.g.: **9/29-9/30**), the difference between these two values is 1 day, rather than 2. Also, range comparisons require either 1) a truncate operation: `start < trunc(now) <= end`, or 2) arithmetic: `start < now < (end + 24hrs)`. Not horrible, but not [DRY](http://www.artima.com/intv/dry.html). 2. An alternative is to use true timestamps: **9/29** 00:00:00 - **10/1** 00:00:00. (midnight-to-midnight, so does not include any part of Oct). Now durations are intrinsically correct, and range comparisons are simpler: `start <= now < end`. Certainly cleaner for internal processing, however end dates do need to be converted upon initial input (+1), and for output (-1), presuming a calendar date metaphor at the user level. How do you handle date ranges on your project? Are there other alternatives? I am particularly interested in how you handle this on both the Java and the Oracle sides of the equation.
Here's how we do it. 1. Use timestamps. 2. Use Half-open intervals for comparison: `start <= now < end`. Ignore the whiners who insist that BETWEEN is somehow essential to successful SQL. With this a series of date ranges is really easy to audit. The database value for `9/30 to 10/1` encompass one day (9/30). The next interval's start must equal the previous interval's end. That `interval[n-1].end == interval[n].start` rule is handy for audit. When you display, if you want, you can display the formatted `start` and `end`-1. Turns out, you *can* educate people to understand that the "end" is actually the first day the rule is no longer true. So "9/30 to 10/1" means "valid starting 9/30, no longer valid starting 10/1".
Oracle has the [TIMESTAMP datatype](http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements001.htm#SQLRF00203). It stores the year, month, and day of the DATE datatype, plus hour, minute, second and fractional second values. Here is a [thread on asktom.oracle.com](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:96012348060) about date arithmetic.
How do you store Date ranges, which are actually timestamps
[ "", "java", "oracle", "architecture", "types", "date-range", "" ]
I would really like to annotate a method with a reference to a single property in a property file for injection. ``` @Resource("${my.service.url}") private String myServiceUrl; ``` Of course, this syntax does not work ;) Thats why I'm asking here. I am aware that I can inject the full properties file, but that just seems excessive, I dont want the property file - I want the configured value. Edit: I can only see PropertyPlaceholderConfigurer examples where XML is used to wire the property to the given field. I still cannot figure out how this can be achieved with an annotation ?
There's a thread about this on the [Spring forum](http://forum.springframework.org/showthread.php?t=50790). The short answer is that there's really no way to inject a single property using annotations. I've heard that the support for using annotations will be improved in Spring 3.0, so it's likely this will be addressed soon.
I know it has been a while since the original post but I have managed to stumble across a solution to this for spring 2.5.x You can create instances of "String" beans in the spring xml configuration which can then be injected into the Annotated components ``` @Component public class SomeCompent{ @Autowired(required=true @Resource("someStringBeanId") private String aProperty; ... } <beans ....> <context:component-scan base-package="..."/> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> ... </bean> <bean id="someStringId" class="java.lang.String" factory-method="valueOf"> <constructor-arg value="${place-holder}"/> </bean> </beans> ```
How do I inject a single property value into a string using spring 2.5.x?
[ "", "java", "spring", "" ]
Is there any free java library which I can use to convert string in one encoding to other encoding, something like [`iconv`](https://en.wikipedia.org/wiki/Iconv)? I'm using Java version 1.3.
You don't need a library beyond the standard one - just use [Charset](https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html). (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.) EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: [new String(bytes, charset)](https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String%28byte%5B%5D%2C%20java.nio.charset.Charset%29) and [String.getBytes(charset)](https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#getBytes%28java.nio.charset.Charset%29). See "[URL Encoding (or: 'What are those "`%20`" codes in URLs?')](http://www.blooberry.com/indexdot/html/topics/urlencoding.htm)".
[`CharsetDecoder`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/nio/charset/CharsetDecoder.html) should be what you are looking for, no ? Many network protocols and files store their characters with a byte-oriented character set such as `ISO-8859-1` (`ISO-Latin-1`). However, Java's native character encoding is [~~Unicode~~](http://www.joelonsoftware.com/articles/Unicode.html) UTF16BE (Sixteen-bit UCS Transformation Format, big-endian byte order). See [`Charset`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/nio/charset/Charset.html). That doesn't mean `UTF16` is the default charset (i.e.: the default "mapping between sequences of sixteen-bit **[Unicode code units](http://download-llnw.oracle.com/javase/6/docs/api/java/lang/Character.html#unicode)** and sequences of bytes"): > Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets. > [`US-ASCII`, `ISO-8859-1` a.k.a. `ISO-LATIN-1`, `UTF-8`, `UTF-16BE`, `UTF-16LE`, `UTF-16`] > The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system. This example demonstrates how to convert `ISO-8859-1` encoded bytes in a `ByteBuffer` to a string in a `CharBuffer` and visa versa. ``` // Create the encoder and decoder for ISO-8859-1 Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharsetEncoder encoder = charset.newEncoder(); try { // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer // The new ByteBuffer is ready to be read. ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string")); // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string. // The new ByteBuffer is ready to be read. CharBuffer cbuf = decoder.decode(bbuf); String s = cbuf.toString(); } catch (CharacterCodingException e) { } ```
Encoding conversion in java
[ "", "java", "character-encoding", "converters", "" ]
We want to show a hint for a JList that the user can select multiple items with the platform dependent key for multiselect. However I have not found any way to show the OS X COMMAND symbol in a JLabel, which means the symbol that's printed on the apple keyboard on the command key, also called apple key. Here's a picture of the symbol I want to display on OS X. [![COMMAND SYMBOL](https://i.stack.imgur.com/VKGb4.png)](https://i.stack.imgur.com/VKGb4.png) (source: [wikimedia.org](https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Command_key.svg/120px-Command_key.svg.png)) Also I do want to have it platform independent. I.e. something like ``` component.add( new JList() , BorderLayout.CENTER ); component.add( new JLabel( MessageFormat.format("With {0} you can " + "select multiple items", KeyStroke.getKeyStroke( ... , ... ) ) ) , BorderLayout.SOUTH ); ``` Where instead of the *{0}* there should appear above seen symbol... Does any one of you guys know how to do this? I know it must be possible somehow since in the JMenuItems there is the symbol... My own (non graphical solutions) looks like this: ``` add( new JLabel( MessageFormat.format( "With {0} you can select multiple items" , System.getProperty( "mrj.version" ) != null ? "COMMAND" : "CTRL" ) ) , BorderLayout.SOUTH ); ```
The symbol in question is avaiable through Unicode, and the HTML character sets. All you need to do is make your JLabel display HTML by starting its text string with <html> and then include the character code. ``` JLabel label = new JLabel( "<html>&#8984; is the Apple command symbol." ); ``` This will work on a Mac, but I've no idea what it'll do on other platforms, although you do seem to have that covered off.
As David points out, you can use the Unicode escape sequence `\u2318` although it must be displayed with a font supporting it.
Display the OSX Command symbol key in a JLabel
[ "", "java", "macos", "command", "key", "" ]
How to add offline access functionality to [MoinMoin wiki](http://moinmo.in)? As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online. Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome. An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question. Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.
*By using Gears with the Firefox Greasemonkey plugin, you can inject Gears code into any website that you want. Don't wait for your favorite website to enable offline support -- do it yourself.* <http://code.google.com/apis/gears/articles/gearsmonkey.html>
If you have the freedom to change the wiki software, I might suggest looking at [ikiwiki](http://ikiwiki.info). You can set it up so the pages are backed by a real VCS such as Git, in which case you can clone the whole wiki and read and even update it offline.
Offline access to MoinMoin wiki using Google Gears
[ "", "python", "wiki", "offline", "google-gears", "moinmoin", "" ]
I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target. Is there some kind of configuration that needs to be done somewhere for this work?
Sure. From a [mindless technology article called "Make Python Scripts Droppable in Windows"](http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/), you can add a drop handler by adding a registry key: > Here’s a registry import file that you can use to do this. Copy the > following into a .reg file and run it > (Make sure that your .py extensions > are mapped to Python.File). > > ``` > Windows Registry Editor Version 5.00 > > [HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] > @="{60254CA5-953B-11CF-8C96-00AA00B8708C}" > ``` This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with `86C86720-42A0-1069-A2E8-08002B30309D`. A comment in that post indicates that one can enable dropping on "no console Python files (`.pyw`)" or "compiled Python files (`.pyc`)" by using the `Python.NoConFile` and `Python.CompiledFile` classes.
write a simple shell script (`file.bat`) ``` "C:\python27\python.exe" yourprogram.py %* ``` where `%*` stands for the all arguments you pass to the script. Now drag & drop your target files on the `file.bat` icon.
Drag and drop onto Python script in Windows Explorer
[ "", "python", "windows", "drag-and-drop", "windows-explorer", "" ]
I'm working on an application that consists of an overall Quartz-based scheduler and "CycledJob" run using CronTriggers. The purpose of the application is to process inputs from different email inboxes based on the source country. Based on the country that it comes in from (i.e. US, UK, FR, etc.) the application triggers one job thread to run each country's processing cycle, so there would be a UK Worker thread, one for US, France, etc. When formatting the output to log4j, I'm using the thread parameter, so it emits [ApplicationName\_Worker-1], [ApplicationName\_Worker-2] etc. Try as I might, I can't find a way to name the threads since they're pulled out of Quartz's Thread Pools. Although I could possibly go so far as to extend Quartz, I'd like to work out a different solution instead of messing with the standard library. Here's the problem: When using log4j, I'd like to have all log items from the US thread output to a US only file, likewise for each of the country threads. I don't care if they stay in one unified ConsoleAppender, the FileAppender split is what I'm after here. I already know how to specify multiple file appenders and such, my issue is I can't differentiate based on country. There are 20+ classes within the application that can be on the execution chain, very few of which I want to burden with the knowledge of passing an extra "context" parameter through EVERY method... I've considered a Strategy pattern extending a log4j wrapper class, but unless I can let every class in the chain know which thread it's on to parameterize the logger call, that seems impossible. Without being able to name the thread also creates a challenge (or else this would be easy!). So here's the question: What would be a suggested approach to allow many subordinate classes in an application that are each used for every different thread to process the input know that they are within the context of a particular country thread when they are logging? Good luck understanding, and please ask clarifying questions! I hope someone is able to help me figure out a decent way to tackle this. All suggestions welcome.
At the top of each country's processing thread, put the country code into Log4j's mapped diagnostic context (MDC). This uses a ThreadLocal variable so that you don't have to pass the country up and down the call stack explicitly. Then create a custom filter that looks at the MDC, and filters out any events that don't contain the current appender's country code. In your `Job`: ``` ... public static final String MDC_COUNTRY = "com.y.foo.Country"; public void execute(JobExecutionContext context) /* Just guessing that you have the country in your JobContext. */ MDC.put(MDC_COUNTRY, context.get(MDC_COUNTRY)); try { /* Perform your job here. */ ... } finally { MDC.remove(MDC_COUNTRY); } } ... ``` Write a custom [Filter](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html): ``` package com.y.log4j; import org.apache.log4j.spi.LoggingEvent; /** * This is a general purpose filter. If its "value" property is null, * it requires only that the specified key be set in the MDC. If its * value is not null, it further requires that the value in the MDC * is equal. */ public final class ContextFilter extends org.apache.log4j.spi.Filter { public int decide(LoggingEvent event) { Object ctx = event.getMDC(key); if (value == null) return (ctx != null) ? NEUTRAL : DENY; else return value.equals(ctx) ? NEUTRAL : DENY; } private String key; private String value; public void setContextKey(String key) { this.key = key; } public String getContextKey() { return key; } public void setValue(String value) { this.value = value; } public String getValue() { return value; } } ``` In your log4j.xml: ``` <appender name="fr" class="org.apache.log4j.FileAppender"> <param name="file" value="france.log"/> ... <filter class="com.y.log4j.ContextFilter"> <param name="key" value="com.y.foo.Country" /> <param name="value" value="fr" /> </filter> </appender> ```
I wish I could be a bit more helpful than this, but you may want to investigate using some filters? Perhaps your logging could output the country code and you could match your filter based on that? A StringMatchFilter should probably be able to match it for you. Couldn't get the below address to work properly as a link, but if you look at it, it has some stuff on separate file logging using filters. <http://mail-archives.apache.org/mod_mbox/logging-log4j-user/200512.mbox/><1CC26C83B6E5AA49A9540FAC8D35158B01E2968E@pune.kaleconsultants.com > (just remove the space before the >) <http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html>
Splitting log4j Output with Quartz Worker Threads
[ "", "java", "multithreading", "log4j", "quartz-scheduler", "scheduler", "" ]
This Linq to SQL query ... ``` Return (From t In Db.Concessions Where t.Country = "ga" Select t.ConcessionID, t.Title, t.Country) ``` ... is generating this SQL: ``` SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country] FROM [dbo].[Concessions] AS [t0] WHERE [t0].[Country] = ga ``` ... when what I want is ``` WHERE [t0].[Country] = 'ga' ``` Any ideas why?
## Answer The Country field was a char(2); I changed it to nvarchar(50), and that fixed the problem. Is this a bug in Linq to SQL?
Wild guess.... could it be? `t.Country = "ga"` vs. `t.Country == "ga"`
Why is LINQ to SQL converting my string parameter to a column name?
[ "", "asp.net", "sql", "vb.net", "linq-to-sql", "" ]
Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the `EventHandler`/`EventArgs` practice, but what I like to do is have something like: ``` public delegate void EventHandler<T>(object src, EventArgs<T> args); public class EventArgs<T>: EventArgs { private T item; public EventArgs(T item) { this.item = item; } public T Item { get { return item; } } } ``` Later, I can have my ``` public event EventHandler<Foo> FooChanged; public event EventHandler<Bar> BarChanged; ``` However, it seems that the standard for .NET is to create a new delegate and `EventArgs` subclass for each type of event. Is there something wrong with my generic approach? --- EDIT: The reason for this post is that I just re-created this in a new project, and wanted to make sure it was ok. Actually, I was re-creating it as I posted. I found that there is a generic `EventHandler<TEventArgs>`, so you don't need to create the generic delegate, but you still need the generic `EventArgs<T>` class, because `TEventArgs: EventArgs`. --- Another EDIT: One downside (to me) of the built-in solution is the extra verbosity: ``` public event EventHandler<EventArgs<Foo>> FooChanged; ``` vs. ``` public event EventHandler<Foo> FooChanged; ``` It can be a pain for clients to register for your events though, because the System namespace is imported by default, so they have to manually seek out your namespace, even with a fancy tool like Resharper... Anyone have any ideas pertaining to that?
Delegate of the following form has been added since .NET Framework 2.0 ``` public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs ``` You approach goes a bit further, since you provide out-of-the-box implementation for EventArgs with single data item, but it lacks several properties of the original idea: 1. You cannot add more properties to the event data without changing dependent code. You will have to change the delegate signature to provide more data to the event subscriber. 2. Your data object is generic, but it is also "anonymous", and while reading the code you will have to decipher the "Item" property from usages. It should be named according to the data it provides. 3. Using generics this way you can't make parallel hierarchy of EventArgs, when you have hierarchy of underlying (item) types. E.g. EventArgs<BaseType> is not base type for EventArgs<DerivedType>, even if BaseType is base for DerivedType. So, I think it is better to use generic EventHandler<T>, but still have custom EventArgs classes, organized according to the requirements of the data model. With Visual Studio and extensions like ReSharper, it is only a matter of few commands to create new class like that.
To make generic event declaration easier, I created a couple of code snippets for it. To use them: * Copy the whole snippet. * Paste it in a text file (e.g. in Notepad). * Save the file with a .snippet extension. * Put the .snippet file in your appropriate snippet directory, such as: **Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets** Here's one that uses a custom EventArgs class with one property: ``` <?xml version="1.0" encoding="utf-8" ?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>Generic event with one type/argument.</Title> <Shortcut>ev1Generic</Shortcut> <Description>Code snippet for event handler and On method</Description> <Author>Ryan Lundy</Author> <SnippetTypes> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>type</ID> <ToolTip>Type of the property in the EventArgs subclass.</ToolTip> <Default>propertyType</Default> </Literal> <Literal> <ID>argName</ID> <ToolTip>Name of the argument in the EventArgs subclass constructor.</ToolTip> <Default>propertyName</Default> </Literal> <Literal> <ID>propertyName</ID> <ToolTip>Name of the property in the EventArgs subclass.</ToolTip> <Default>PropertyName</Default> </Literal> <Literal> <ID>eventName</ID> <ToolTip>Name of the event</ToolTip> <Default>NameOfEvent</Default> </Literal> </Declarations> <Code Language="CSharp"><![CDATA[public class $eventName$EventArgs : System.EventArgs { public $eventName$EventArgs($type$ $argName$) { this.$propertyName$ = $argName$; } public $type$ $propertyName$ { get; private set; } } public event EventHandler<$eventName$EventArgs> $eventName$; protected virtual void On$eventName$($eventName$EventArgs e) { var handler = $eventName$; if (handler != null) handler(this, e); }]]> </Code> <Imports> <Import> <Namespace>System</Namespace> </Import> </Imports> </Snippet> </CodeSnippet> </CodeSnippets> ``` And here's one that has two properties: ``` <?xml version="1.0" encoding="utf-8" ?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>Generic event with two types/arguments.</Title> <Shortcut>ev2Generic</Shortcut> <Description>Code snippet for event handler and On method</Description> <Author>Ryan Lundy</Author> <SnippetTypes> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>type1</ID> <ToolTip>Type of the first property in the EventArgs subclass.</ToolTip> <Default>propertyType1</Default> </Literal> <Literal> <ID>arg1Name</ID> <ToolTip>Name of the first argument in the EventArgs subclass constructor.</ToolTip> <Default>property1Name</Default> </Literal> <Literal> <ID>property1Name</ID> <ToolTip>Name of the first property in the EventArgs subclass.</ToolTip> <Default>Property1Name</Default> </Literal> <Literal> <ID>type2</ID> <ToolTip>Type of the second property in the EventArgs subclass.</ToolTip> <Default>propertyType1</Default> </Literal> <Literal> <ID>arg2Name</ID> <ToolTip>Name of the second argument in the EventArgs subclass constructor.</ToolTip> <Default>property1Name</Default> </Literal> <Literal> <ID>property2Name</ID> <ToolTip>Name of the second property in the EventArgs subclass.</ToolTip> <Default>Property2Name</Default> </Literal> <Literal> <ID>eventName</ID> <ToolTip>Name of the event</ToolTip> <Default>NameOfEvent</Default> </Literal> </Declarations> <Code Language="CSharp"> <![CDATA[public class $eventName$EventArgs : System.EventArgs { public $eventName$EventArgs($type1$ $arg1Name$, $type2$ $arg2Name$) { this.$property1Name$ = $arg1Name$; this.$property2Name$ = $arg2Name$; } public $type1$ $property1Name$ { get; private set; } public $type2$ $property2Name$ { get; private set; } } public event EventHandler<$eventName$EventArgs> $eventName$; protected virtual void On$eventName$($eventName$EventArgs e) { var handler = $eventName$; if (handler != null) handler(this, e); }]]> </Code> <Imports> <Import> <Namespace>System</Namespace> </Import> </Imports> </Snippet> </CodeSnippet> </CodeSnippets> ``` You can follow the pattern to create them with as many properties as you like.
.NET EventHandlers - Generic or no?
[ "", "c#", ".net", "generics", "events", "" ]
*Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate? I also believe the question, detail, and response is much better than the referenced question.* I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse. I want to use the [touch graph "Graph Layout" code](http://sourceforge.net/project/showfiles.php?group_id=30469&package_id=23976) to visualize some data I'm working with. This code is organized like this: ``` ./com ./com/touchgraph ./com/touchgraph/graphlayout ./com/touchgraph/graphlayout/Edge.java ./com/touchgraph/graphlayout/GLPanel.java ./com/touchgraph/graphlayout/graphelements ./com/touchgraph/graphlayout/graphelements/GESUtils.java ./com/touchgraph/graphlayout/graphelements/GraphEltSet.java ./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java ./com/touchgraph/graphlayout/graphelements/Locality.java ./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java ./com/touchgraph/graphlayout/graphelements/TGForEachNode.java ./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java ./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java ./com/touchgraph/graphlayout/graphelements/VisibleLocality.java ./com/touchgraph/graphlayout/GraphLayoutApplet.java ./com/touchgraph/graphlayout/GraphListener.java ./com/touchgraph/graphlayout/interaction ./com/touchgraph/graphlayout/interaction/DragAddUI.java ./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java ./com/touchgraph/graphlayout/interaction/DragNodeUI.java ./com/touchgraph/graphlayout/interaction/GLEditUI.java ./com/touchgraph/graphlayout/interaction/GLNavigateUI.java ./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java ./com/touchgraph/graphlayout/interaction/HVScroll.java ./com/touchgraph/graphlayout/interaction/HyperScroll.java ./com/touchgraph/graphlayout/interaction/LocalityScroll.java ./com/touchgraph/graphlayout/interaction/RotateScroll.java ./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java ./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java ./com/touchgraph/graphlayout/interaction/TGUIManager.java ./com/touchgraph/graphlayout/interaction/TGUserInterface.java ./com/touchgraph/graphlayout/interaction/ZoomScroll.java ./com/touchgraph/graphlayout/LocalityUtils.java ./com/touchgraph/graphlayout/Node.java ./com/touchgraph/graphlayout/TGAbstractLens.java ./com/touchgraph/graphlayout/TGException.java ./com/touchgraph/graphlayout/TGLayout.java ./com/touchgraph/graphlayout/TGLensSet.java ./com/touchgraph/graphlayout/TGPaintListener.java ./com/touchgraph/graphlayout/TGPanel.java ./com/touchgraph/graphlayout/TGPoint2D.java ./com/touchgraph/graphlayout/TGScrollPane.java ./TG-APACHE-LICENSE.txt ./TGGL ReleaseNotes.txt ./TGGraphLayout.html ./TGGraphLayout.jar ``` How do I add this project in Eclipse and get it compiling and running quickly?
1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files). 2. Also create a lib folder (the name isn't that important, but it follows standard conventions). 3. Copy the `./com/*` folders into the `/src` folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI). 4. Copy any dependencies (`jar` files that your project itself depends on) into `/lib` (note that this **should NOT** include the `TGGL jar` - *thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!*) 5. Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app) 6. Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents. 7. The content of the `/src` folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). **If you have dependencies** (which you don't in your current project, but I'll include this here for completeness), **the compile will fail initially because you are missing the dependency `jar files` from the project classpath.** 8. Finally, open the `/lib` folder in Eclipse, `right click` on each required `jar file` and choose `Build Path->Add` to build path. That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.
I think you'll have to import the project via the file->import wizard: <http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse> It's not the last step, but it will start you on your way. I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).
How do I import a pre-existing Java project into Eclipse and get up and running?
[ "", "java", "eclipse", "" ]
How would you go about dead code detection in C/C++ code? I have a pretty large code base to work with and at least 10-15% is dead code. Is there any Unix based tool to identify this areas? Some pieces of code still use a lot of preprocessor, can automated process handle that?
You could use a code coverage analysis tool for this and look for unused spots in your code. A popular tool for the gcc toolchain is gcov, together with the graphical frontend lcov (<http://ltp.sourceforge.net/coverage/lcov.php>). If you use gcc, you can compile with gcov support, which is enabled by the '--coverage' flag. Next, run your application or run your test suite with this gcov enabled build. Basically gcc will emit some extra files during compilation and the application will also emit some coverage data while running. You have to collect all of these (.gcdo and .gcda files). I'm not going in full detail here, but you probably need to set two environment variables to collect the coverage data in a sane way: GCOV\_PREFIX and GCOV\_PREFIX\_STRIP... After the run, you can put all the coverage data together and run it through the lcov toolsuite. Merging of all the coverage files from different test runs is also possible, albeit a bit involved. Anyhow, you end up with a nice set of webpages showing some coverage information, pointing out the pieces of code that have no coverage and hence, were not used. Off course, you need to double check if the portions of code are not used in any situation and a lot depends on how good your tests exercise the codebase. But at least, this will give an idea about possible dead-code candidates...
Compile it under gcc with -Wunreachable-code. I think that the more recent the version, the better results you'll get, but I may be wrong in my impression that it's something they've been actively working on. Note that this does flow analysis, but I don't believe it tells you about "code" which is already dead by the time it leaves the preprocessor, because that's never parsed by the compiler. It also won't detect e.g. exported functions which are never called, or special case handling code which just so happen to be impossible because nothing ever calls the function with that parameter - you need code coverage for that (and run the functional tests, not the unit tests. Unit tests are *supposed* to have 100% code coverage, and hence execute code paths which are 'dead' as far as the application is concerned). Still, with these limitations in mind it's an easy way to get started finding the most completely bollixed routines in the code base. [This CERT advisory lists some other tools for static dead code detection](https://www.securecoding.cert.org/confluence/display/seccode/MSC07-C.+Detect+and+remove+dead+code)
Dead code detection in legacy C/C++ project
[ "", "c++", "automation", "static-analysis", "legacy-code", "dead-code", "" ]
The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number. Any help would be much appreciated. ``` function validate_phone($phone) { $phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$"; $phonevalid = 0; if (ereg($phoneregexp, $phone)) { $phonevalid = 1; }else{ $phonevalid = 0; } } ```
If this is PHP, then the regex must be enclosed in quotes. ~~Furthermore, what's `preg`? Did you mean `preg_match`?~~ Another thing. PHP knows boolean values. The canonical solution would rather look like this: ``` return preg_match($regex, $phone) !== 0; ``` EDIT: Or, using `ereg`: ``` return ereg($regex, $phone) !== FALSE; ``` (Here, the explicit test against `FALSE` isn't strictly necessary but since `ereg` returns a number upon success I feel safer coercing the value into a `bool`).
Hmm well the code you pasted isn't quite valid, I fixed it up by adding the missing quotes, missing delimiters, and changed preg to preg\_match. I didn't get the warning. **Edit**: after seeing the other comment, you meant "ereg" not "preg"... that gives the warning. Try using `preg_match()` instead ;) ``` <?php function validate_phone($phone) { $phoneregexp ='/^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$/'; $phonevalid = 0; if (preg_match($phoneregexp, $phone)) { $phonevalid = 1; } else { $phonevalid = 0; } } validate_phone("123456"); ?> ```
Regex error: 'Warning: ereg() [function.ereg]: REG_ERANGE' in PHP
[ "", "php", "regex", "" ]
Is there a best-practice or common way in JavaScript to have class members as event handlers? Consider the following simple example: ``` <head> <script language="javascript" type="text/javascript"> ClickCounter = function(buttonId) { this._clickCount = 0; document.getElementById(buttonId).onclick = this.buttonClicked; } ClickCounter.prototype = { buttonClicked: function() { this._clickCount++; alert('the button was clicked ' + this._clickCount + ' times'); } } </script> </head> <body> <input type="button" id="btn1" value="Click me" /> <script language="javascript" type="text/javascript"> var btn1counter = new ClickCounter('btn1'); </script> </body> ``` The event handler buttonClicked gets called, but the \_clickCount member is inaccessible, or *this* points to some other object. Any good tips/articles/resources about this kind of problems?
``` ClickCounter = function(buttonId) { this._clickCount = 0; var that = this; document.getElementById(buttonId).onclick = function(){ that.buttonClicked() }; } ClickCounter.prototype = { buttonClicked: function() { this._clickCount++; alert('the button was clicked ' + this._clickCount + ' times'); } } ``` EDIT almost 10 years later, with ES6, arrow functions and [class properties](https://babeljs.io/docs/plugins/transform-class-properties/) ``` class ClickCounter { count = 0; constructor( buttonId ){ document.getElementById(buttonId) .addEventListener( "click", this.buttonClicked ); } buttonClicked = e => { this.count += 1; console.log(`clicked ${this.count} times`); } } ``` <https://codepen.io/anon/pen/zaYvqq>
I don't know why [`Function.prototype.bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) wasn't mentioned here yet. So I'll just leave this here ;) ``` ClickCounter = function(buttonId) { this._clickCount = 0; document.getElementById(buttonId).onclick = this.buttonClicked.bind(this); } ClickCounter.prototype = { buttonClicked: function() { this._clickCount++; alert('the button was clicked ' + this._clickCount + ' times'); } } ```
Class methods as event handlers in JavaScript?
[ "", "javascript", "html", "function", "class", "" ]
I have been attempting to write some routines to read RSS and ATOM feeds using the new routines available in System.ServiceModel.Syndication, but unfortunately the Rss20FeedFormatter bombs out on about half the feeds I try with the following exception: > ``` > An error was encountered when parsing a DateTime value in the XML. > ``` This seems to occur whenever the RSS feed expresses the publish date in the following format: > Thu, 16 Oct 08 14:23:26 -0700 If the feed expresses the publish date as GMT, things go fine: > Thu, 16 Oct 08 21:23:26 GMT If there's some way to work around this with XMLReaderSettings, I have not found it. Can anyone assist?
RSS 2.0 formatted syndication feeds utilize the [RFC 822 date-time specification](http://www.w3.org/Protocols/rfc822/#z28) when serializing elements like *pubDate* and *lastBuildDate*. The RFC 822 date-time specification is unfortunately a very 'flexible' syntax for expressing the time-zone component of a DateTime. *Time zone may be indicated in several ways. "UT" is Universal Time (formerly called "Greenwich Mean Time"); "GMT" is permitted as a reference to Universal Time. The military standard uses a single character for each zone. "Z" is Universal Time. "A" indicates one hour earlier, and "M" indicates 12 hours earlier; "N" is one hour later, and "Y" is 12 hours later. The letter "J" is not used. The other remaining two forms are taken from ANSI standard X3.51-1975. One allows explicit indication of the amount of offset from UT; the other uses common 3-character strings for indicating time zones in North America.* I believe the issue involves how the **zone** component of the RFC 822 date-time value is being processed. The feed formatter appears to not be handling date-times that utilize a **local differential** to indicate the time zone. As RFC 1123 extends the RFC 822 specification, you could try using the [DateTimeFormatInfo.RFC1123Pattern](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.rfc1123pattern.aspx) ("r") to handle converting problamatic date-times, or write your own parsing code for RFC 822 formatted dates. Another option would be to use a third party framework instead of the System.ServiceModel.Syndication namespace classes. It appears there are some [known issues](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=325421) with date-time parsing and the Rss20FeedFormatter that are in the process of being addressed by Microsoft.
Based on the workaround posted in the [bug report to Microsoft about this](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=325421&wa=wsignin1.0) I made an XmlReader specifically for reading SyndicationFeeds that have non-standard dates. The code below is slightly different than the code in the workaround at Microsoft's site. It also takes [Oppositional's advice](https://stackoverflow.com/questions/210375/problems-reading-rss-with-c-and-net-3-5/263137#263137) on using the RFC 1123 pattern. Instead of simply calling XmlReader.Create() you need to create the XmlReader from a Stream. I use the WebClient class to get that stream: ``` WebClient client = new WebClient(); using (XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(feedUrl))) { SyndicationFeed feed = SyndicationFeed.Load(reader); .... //do things with the feed .... } ``` Below is the code for the SyndicationFeedXmlReader: ``` public class SyndicationFeedXmlReader : XmlTextReader { readonly string[] Rss20DateTimeHints = { "pubDate" }; readonly string[] Atom10DateTimeHints = { "updated", "published", "lastBuildDate" }; private bool isRss2DateTime = false; private bool isAtomDateTime = false; public SyndicationFeedXmlReader(Stream stream) : base(stream) { } public override bool IsStartElement(string localname, string ns) { isRss2DateTime = false; isAtomDateTime = false; if (Rss20DateTimeHints.Contains(localname)) isRss2DateTime = true; if (Atom10DateTimeHints.Contains(localname)) isAtomDateTime = true; return base.IsStartElement(localname, ns); } public override string ReadString() { string dateVal = base.ReadString(); try { if (isRss2DateTime) { MethodInfo objMethod = typeof(Rss20FeedFormatter).GetMethod("DateFromString", BindingFlags.NonPublic | BindingFlags.Static); Debug.Assert(objMethod != null); objMethod.Invoke(null, new object[] { dateVal, this }); } if (isAtomDateTime) { MethodInfo objMethod = typeof(Atom10FeedFormatter).GetMethod("DateFromString", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(objMethod != null); objMethod.Invoke(new Atom10FeedFormatter(), new object[] { dateVal, this }); } } catch (TargetInvocationException) { DateTimeFormatInfo dtfi = CultureInfo.CurrentCulture.DateTimeFormat; return DateTimeOffset.UtcNow.ToString(dtfi.RFC1123Pattern); } return dateVal; } } ``` Again, this is copied almost exactly from the workaround posted on the Microsoft site in the link above. ...except that this one works for me, and the one posted at Microsoft did not. **NOTE**: One bit of customization you may need to do is in the two arrays at the start of the class. Depending on any extraneous fields your non-standard feed might add, you may need to add more items to those arrays.
Problems Reading RSS with C# and .net 3.5
[ "", "c#", "rss", "syndication", "" ]
What's the best way to get an array of all elements in an html document with a specific CSS class using javascript? No javascript frameworks like jQuery allowed here right now, and I could loop all the elements and check them manually myself. I'm hoping for something a little more elegant.
The below answer is now pushing four years old, so it's worth noting that native browser support for [`getElementsByClassName()`](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName) has gotten a *lot* better. But if you must support older browsers, then... Use one that's already been written. Most major JS libraries include one in some form or another, but if you aren't using one of them then i can recommend Robert Nyman's excellent implementation: <http://code.google.com/p/getelementsbyclassname/> <http://www.robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/> There are just too many ways to make this (conceptually-simple) routine *slow and buggy* to justify writing your own implementation at this point.
1) Get all elements in the document (document.getElementsByTagName('\*')) 2) Do a regular expression match on the element's className attribute for each element
Get All Elements in an HTML document with a specific CSS Class
[ "", "javascript", "html", "css", "" ]
I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?
Hmmm, isn't simply overriding Form.ShowWithoutActivation enough? ``` protected override bool ShowWithoutActivation { get { return true; } } ``` And if you don't want the user to click this notification window either, you can override CreateParams: ``` protected override CreateParams CreateParams { get { CreateParams baseParams = base.CreateParams; const int WS_EX_NOACTIVATE = 0x08000000; const int WS_EX_TOOLWINDOW = 0x00000080; baseParams.ExStyle |= ( int )( WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW ); return baseParams; } } ```
Stolen from [PInvoke.net](http://www.pinvoke.net/)'s [ShowWindow](http://www.pinvoke.net/default.aspx/user32/ShowWindow.html) method: ``` private const int SW_SHOWNOACTIVATE = 4; private const int HWND_TOPMOST = -1; private const uint SWP_NOACTIVATE = 0x0010; [DllImport("user32.dll", EntryPoint = "SetWindowPos")] static extern bool SetWindowPos( int hWnd, // Window handle int hWndInsertAfter, // Placement-order handle int X, // Horizontal position int Y, // Vertical position int cx, // Width int cy, // Height uint uFlags); // Window positioning flags [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); static void ShowInactiveTopmost(Form frm) { ShowWindow(frm.Handle, SW_SHOWNOACTIVATE); SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST, frm.Left, frm.Top, frm.Width, frm.Height, SWP_NOACTIVATE); } ``` (Alex Lyman answered this, I'm just expanding it by directly pasting the code. Someone with edit rights can copy it over there and delete this for all I care ;) )
Show a Form without stealing focus?
[ "", "c#", ".net", "winforms", "" ]
I have a Java client that calls a web service at the moment using the Http protocol. When i try to use the Https protocol i keep getting this error java.io.IOException: DerInputStream.getLength(): lengthTag=127, too big. Any ideas what could be up? Thanks Damien
Due to american export regulations in encryption technologies, you can't use strong encryption out of the box. Your error looks like you (or your framework) is trying to use strong encryption, and other parts of the framework is not allowing it. A discussion of a case that looks similar to yours can be found [here](http://www.codecomments.com/archive253-2004-4-173117.html). A good crypto provider is [BouncyCastle](http://www.bouncycastle.org/java.html). Takes some reading, but it's not that hard to make it work. Good luck,
Are you sure you are connecting your HTTPS client to the server port that talks over HTTPS (TLS/SSL) rather than HTTP?
Webservices client and ssl
[ "", "java", "web-services", "ssl", "client", "" ]
I have a VB 6 application and we are starting to port it over to C#. We have finished one of the screens and wanted to see if there was an incremental way of hosting the winform within VB to start to have the existing users get used to new screens. This is a migration strategy.. Any thoughts.
Have you [looked at this?](http://hubpages.com/hub/Interop_Forms_Toolkit_10) Direct Link to [Product here](http://msdn.microsoft.com/en-us/vbasic/bb419144.aspx)
The Interop Forms Toolkit allows you to create .NET Forms and User Controls that can be used in VB 6.0 applications. This allows you to migrate VB 6.0 applications to .NET over time (a form or part of a form at a time). However, the toolkit relies on features from the Microsoft.VisualBasic assembly and the VB.NET compiler so it doesn't work with C#. There are a couple articles/samples on [CodeProject.com](http://www.codeproject.com/) that discuss the toolkit and how to use it with C#. [Interop Forms Toolkit 2.0 Tutorial](http://www.codeproject.com/KB/vb-interop/VB6InteropToolkit2.aspx) [VB6 - C# Interop Form Toolkit](http://www.codeproject.com/KB/dotnet/VB6_-_C__Interop_Form.aspx) Beth Massi has several articles and webcasts on the use of the Toolkit you can use for reference. Check out [her blog](http://blogs.msdn.com/bethmassi) for links to resources.
Host C# winforms in VB6 applications
[ "", "c#", "winforms", "vb6", "" ]
How can I find out the folder where the windows service .exe file is installed dynamically? ``` Path.GetFullPath(relativePath); ``` returns a path based on `C:\WINDOWS\system32` directory. However, the `XmlDocument.Load(string filename)` method appears to be working against relative path inside the directory where the service .exe file is installed to.
Try ``` System.Reflection.Assembly.GetEntryAssembly().Location ```
Try this: ``` AppDomain.CurrentDomain.BaseDirectory ``` (Just like here: [How to find windows service exe path](https://stackoverflow.com/questions/2833959/how-to-find-windows-service-exe-path))
Getting full path for Windows Service
[ "", "c#", ".net", "windows-services", "" ]