Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've seen this pattern used a lot in C & C++. ``` unsigned int flags = -1; // all bits are true ``` Is this a good portable way to accomplish this? Or is using `0xffffffff` or `~0` better?
I recommend you to do it exactly as you have shown, since it is the most straight forward one. Initialize to `-1` which will work *always*, independent of the actual sign representation, while `~` will sometimes have surprising behavior because you will have to have the right operand type. Only then you will get the most high value of an `unsigned` type. For an example of a possible surprise, consider this one: ``` unsigned long a = ~0u; ``` It won't necessarily store a pattern with all bits 1 into `a`. But it will first create a pattern with all bits 1 in an `unsigned int`, and then assign it to `a`. What happens when `unsigned long` has more bits is that not all of those are 1. And consider this one, which will fail on a non-two's complement representation: ``` unsigned int a = ~0; // Should have done ~0u ! ``` The reason for that is that `~0` has to invert all bits. Inverting that will yield `-1` on a two's complement machine (which is the value we need!), but will *not* yield `-1` on another representation. On a one's complement machine, it yields zero. Thus, on a one's complement machine, the above will initialize `a` to zero. The thing you should understand is that it's all about values - not bits. The variable is initialized with a *value*. If in the initializer you modify the bits of the variable used for initialization, the value will be generated according to those bits. The value you need, to initialize `a` to the highest possible value, is `-1` or `UINT_MAX`. The second will depend on the type of `a` - you will need to use `ULONG_MAX` for an `unsigned long`. However, the first will not depend on its type, and it's a nice way of getting the highest value. **We are *not* talking about whether `-1` has all bits one (it doesn't always have). And we're *not* talking about whether `~0` has all bits one (it has, of course).** But what we are talking about is what the result of the initialized `flags` variable is. And for it, **only `-1`** will work with every type and machine.
* `unsigned int flags = -1;` is portable. * `unsigned int flags = ~0;` isn't portable because it relies on a two's-complement representation. * `unsigned int flags = 0xffffffff;` isn't portable because it assumes 32-bit ints. If you want to set all bits in a way guaranteed by the C standard, use the first one.
Is it safe to use -1 to set all bits to true?
[ "", "c++", "c", "binary", "bit-fields", "" ]
I'm using PHPMyAdmin and I've got a MySQL table column called "timestamp." The type (surprise!) is `TIMESTAMP`, and in 'attributes' I've set it to `ON UPDATE CURRENT_TIMESTAMP`. However, each new record gets a timestamp that looks like this: ``` 0000-00-00 00:00:00 ``` I have explicitly set the default value to none, but when I save and come back to look, it is set to all zeros as above. The relevant PHP records page hits with this query: ``` $query = "INSERT INTO `pagehit` (user_id, pageurl) VALUES ('" . $userid . "', '" . $pageurl . "')"; ``` The whole thing is running under XAMPP. What am I missing?
> What am I missing? You don't update :) Use `DEFAULT CURRENT_TIMESTAMP` along with `ON UPDATE CURRENT_TIMESTAMP`
Try setting the default value to `CURRENT_TIMESTAMP` instead of putting that in the attributes. [MySQL Reference](http://dev.mysql.com/doc/refman/5.0/en/timestamp.html)
MySQL Timestamp - why all zeros?
[ "", "php", "mysql", "timestamp", "phpmyadmin", "" ]
I am a C# beginner. I found there are 2 way to write codes and output the same results. Could you explain the different between them? And when to use #1 and #2? ## `#1` ``` class Program { static void Main() { Program min = new Program(); Console.WriteLine(min.isMin(1, 2)); Console.ReadLine(); } int isMin(int value1, int value2) { int Min; return Min = Math.Min(value1, value2); } } ``` ## `#2` ``` class Program2 { static void Main() { Console.WriteLine(isMin(1, 2)); Console.ReadLine(); } static int isMin(int value1, int value2) { int Min; return Min = Math.Min(value1, value2); } } ```
The difference between #1 and #2 is that in #1, isMin is an instance member function of the class Program, therefore you have to create an instance of the Program class ``` Program min = new Program() ``` and only then call the instance member function isMin: ``` min.isMin(..) ``` In #2, isMin is a static member function of the Program class, and since Main is also a static member function of the same class, you can make a direct call to isMin from the Main function. Both are valid. The static function Main is the "entry point" into the program which means it gets executed first. The rest is just Object-Oriented semantics. **EDIT** It seems that in order to better illustrate the point an example would be in order. The two programs below are pretty useless outside of their intended purpose of showing the differences between encapsulating your program logic into objects, and the alternative -using static functions. The program defines two operation and will work on two numbers (10 and 25 in the example). As the program runs, it will trace its' operations to a log file (one for each number). It is useful to imagine that the two operations could be replaced by more serious algorithms and that the two numbers could be replaced by a series of more useful input data. ``` //The instance-based version: class Program { private System.IO.StreamWriter _logStream; private int _originalNumber; private int _currentNumber; public Program(int number, string logFilePath) { _originalNumber = number; _currentNumber = number; try { _logStream = new System.IO.StreamWriter(logFilePath, true); _logStream.WriteLine("Starting Program for {0}", _originalNumber); } catch { _logStream = null; } } public void Add(int operand) { if (_logStream != null) _logStream.WriteLine("For {0}: Adding {1} to {2}", _originalNumber, operand, _currentNumber); _currentNumber += operand; } public void Subtract(int operand) { if (_logStream != null) _logStream.WriteLine("For {0}: Subtracting {1} from {2}", _originalNumber, operand, _currentNumber); _currentNumber -= operand; } public void Finish() { Console.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber); if (_logStream != null) { _logStream.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber); _logStream.Close(); _logStream = null; } } static void Main(string[] args) { Program p = new Program(10, "log-for-10.txt"); Program q = new Program(25, "log-for-25.txt"); p.Add(3); // p._currentNumber = p._currentNumber + 3; p.Subtract(7); // p._currentNumber = p._currentNumber - 7; q.Add(15); // q._currentNumber = q._currentNumber + 15; q.Subtract(20); // q._currentNumber = q._currentNumber - 20; q.Subtract(3); // q._currentNumber = q._currentNumber - 3; p.Finish(); // display original number and final result for p q.Finish(); // display original number and final result for q } } ``` Following is the static functions based implementation of the same program. Notice how we have to "carry our state" into and out of each operation, and how the Main function needs to "remember" which data goes with which function call. ``` class Program { private static int Add(int number, int operand, int originalNumber, System.IO.StreamWriter logFile) { if (logFile != null) logFile.WriteLine("For {0}: Adding {1} to {2}", originalNumber, operand, number); return (number + operand); } private static int Subtract(int number, int operand, int originalNumber, System.IO.StreamWriter logFile) { if (logFile != null) logFile.WriteLine("For {0}: Subtracting {1} from {2}", originalNumber, operand, number); return (number - operand); } private static void Finish(int number, int originalNumber, System.IO.StreamWriter logFile) { Console.WriteLine("Program finished. {0} --> {1}", originalNumber, number); if (logFile != null) { logFile.WriteLine("Program finished. {0} --> {1}", originalNumber, number); logFile.Close(); logFile = null; } } static void Main(string[] args) { int pNumber = 10; int pCurrentNumber = 10; System.IO.StreamWriter pLogFile; int qNumber = 25; int qCurrentNumber = 25; System.IO.StreamWriter qLogFile; pLogFile = new System.IO.StreamWriter("log-for-10.txt", true); pLogFile.WriteLine("Starting Program for {0}", pNumber); qLogFile = new System.IO.StreamWriter("log-for-25.txt", true); qLogFile.WriteLine("Starting Program for {0}", qNumber); pCurrentNumber = Program.Add(pCurrentNumber, 3, pNumber, pLogFile); pCurrentNumber = Program.Subtract(pCurrentNumber, 7, pNumber, pLogFile); qCurrentNumber = Program.Add(qCurrentNumber, 15, qNumber, qLogFile); qCurrentNumber = Program.Subtract(qCurrentNumber, 20, qNumber, qLogFile); qCurrentNumber = Program.Subtract(qCurrentNumber, 3, qNumber, qLogFile); Program.Finish(pCurrentNumber, pNumber, pLogFile); Program.Finish(qCurrentNumber, qNumber, qLogFile); } } ``` Another point to note is that although the first instance-based example works, it is more common in practice to encapsulate your logic in a different class which can be used in the Main entry point of your program. This approach is more flexible because it makes it very easy to take your program logic and move it to a different file, or even to a different assembly that could even be used by multiple applications. This is one way to do that. ``` // Another instance-based approach class ProgramLogic { private System.IO.StreamWriter _logStream; private int _originalNumber; private int _currentNumber; public ProgramLogic(int number, string logFilePath) { _originalNumber = number; _currentNumber = number; try { _logStream = new System.IO.StreamWriter(logFilePath, true); _logStream.WriteLine("Starting Program for {0}", _originalNumber); } catch { _logStream = null; } } public void Add(int operand) { if (_logStream != null) _logStream.WriteLine("For {0}: Adding {1} to {2}", _originalNumber, operand, _currentNumber); _currentNumber += operand; } public void Subtract(int operand) { if (_logStream != null) _logStream.WriteLine("For {0}: Subtracting {1} from {2}", _originalNumber, operand, _currentNumber); _currentNumber -= operand; } public void Finish() { Console.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber); if (_logStream != null) { _logStream.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber); _logStream.Close(); _logStream = null; } } } class Program { static void Main(string[] args) { ProgramLogic p = new ProgramLogic(10, "log-for-10.txt"); ProgramLogic q = new ProgramLogic(25, "log-for-25.txt"); p.Add(3); // p._number = p._number + 3; p.Subtract(7); // p._number = p._number - 7; q.Add(15); // q._number = q._number + 15; q.Subtract(20); // q._number = q._number - 20; q.Subtract(3); // q._number = q._number - 3; p.Finish(); q.Finish(); } } ```
The key difference here is based on object oriented programming. C# is an object oriented language, and most of the things in it are objects. In this case Program is an object. It is special because it has the static void Main() function, that is the 'entry point' for the program. The difference comes because of the static modifier on the isMin function. Classes define how the objects work. When you actually make one, as you do with new Program() you have 'instantiated', or made an actual working copy of that object. Usually this is done to track a set of variables that are part of that object, but in this case there are no such variables. In the first case, you are making an instance of the object program, and telling it to execute its "isMin" function on that instance. In the second case, you are not making any instances, and you are telling it to execute the "isMin" function that is associated with the class (not the instance of the object). There is no real difference here except some easier syntax, because there is no data being tracked in an object. You will find that it matter when you have data on the objects, because you will not be able to access 'instance' data when you are in a static function. To understand more, look into object oriented programming.
What does the static keyword mean?
[ "", "c#", "" ]
I have been whipped into submission and have started learning Fluent NHibernate (no previous NHibernate experience). In my project, I am programming to interfaces to reduce coupling etc. That means pretty much "everything" refers to the interface instead of the concrete type (IMessage instead of Message). The thought behind this is to help make it more testable by being able to mock dependencies. However, (Fluent) NHibernate doesn't love it when I try to map to interfaces instead of concrete classes. The issue is simple - according to the Fluent Wiki, it is smart to define the ID field of my class as for instance ``` int Id { get; private set; } ``` to get a typical auto-generated primary key. However, that only works with concrete classes - I can't specify an access level on an interface, where the same line has to be ``` int Id { get; set; } ``` and I guess that negates making the setter private in the concrete class (the idea being that only NHibernate should ever set the ID as assigned by the DB). For now, I guess I will just make the setter public and try to avoid the temptation of writing to it.. But does anyone have an idea of what would be the "proper", best-practice way to create a proper primary-key field that only NHibernate can write to while still only programming to interfaces? **UPDATED** From what I understand after the two answers below from mookid and James Gregory, I may well be on the wrong track - there shouldn't be a reason for me to have an interface per entity as I have now. That's all well and good. I guess my question then becomes - is there no reason to program 100% against an interface for any entities? And if there is even a single situation where this could be justified, is it possible to do this with (Fluent) NHibernate? I ask because I don't know, not to be critical. Thanks for the responses. :)
**UPDATE:** using union-subclass is not supported via the fluent interface fluent-nhibernate provides. You'll have to use a regular hbm mapping file and add it. I too I'm trying do this with fluent NHibernate. I don't think it should be a problem mapping interfaces. You want to use an inheritance strategy, specifically the [table-per-concrete-class strategy](http://docs.jboss.org/hibernate/stable/core/reference/en/html/inheritance.html). Essentially, you create a mapping definition for the base class (in this case your interface) and specify how to NHibernate should deal with implementers by using union-subclass. So, for example, this should allow you to make polymorphic associations: ``` <class name="IAccountManager" abstract="true" table="IAccountManager"> <id name="Id"> <generator class="hilo"/> </id> <union-subclass table="DefaultAccountManager" name="DefaultAccountManager"> <property name="FirstName"/> </union-subclass> <union-subclass table="AnotherAccountManagerImplementation" name="AnotherAccountManagerImplementation"> <property name="FirstName"/> </union-subclass> ... </class> ``` Note how the Id is the same for all concrete implementers. NHibernate required this. Also, IAccountManager table doesn't actually exist. You can also try and leverage NHibernate's Implicit Polymorphism (documented below the table-per-concrete-class strategy) - but it has tons of limitations.
*I realise this is a diversion, and not an answer to your question (although I think mookid has got that covered).* You should really evaluate whether interfaces on your domain entities are actually providing anything of worth; it's rare to find a situation where you actually need to do this. For example: How is relying on `IMessage` any less coupled than relying on `Message`, when they both (almost) undoubtedly share identical signatures? You shouldn't need to mock an entity, because it's rare that it has enough behavior to require being mocked.
Programming to interfaces while mapping with Fluent NHibernate
[ "", "c#", "nhibernate", "fluent-nhibernate", "nhibernate-mapping", "" ]
`No` * The JIT compiler may "transform" the bytecode into something completely different anyway. * It will lead you to do premature optimization. `Yes` * You do not know which method will be compiled by the JIT, so it is better if you optimize them all. * It will make you a better Java programmer. I am asking without really knowing (obviously) so feel free to redirect to JIT hyperlinks.
Yes, but to a certain extent -- it's good as an educational opportunity to see what is going on under the hood, but probably should be done in moderation. It can be a good thing, as looking at the bytecode may help in understanding how the Java source code will be compiled into Java bytecode. Also, it may give some ideas about what kind of optimizations will be performed by the compiler, and perhaps some limitations to the amount of optimization the compiler can perform. For example, if a string concatenation is performed, `javac` will optimize the concatenation into using a `StringBuilder` and performing `append` methods to concatenate the `String`s. However, if the string concatenation is performed in a loop, a new `StringBuilder` may be instantiated on each iteration, leading to possible performance degradation compared to manually instantiating a `StringBuilder` outside the loop and only performing `append`s inside the loop. On the issue of the JIT. The just-in-time compilation is going to be JVM implementation specific, so it's not very easy to find out what is actually happening to the bytecode when it is being converted to the native code, and furthermore, we can't tell which parts are being JITted (at least not without some JVM-specific tools to see what kind of JIT compilation is being performed -- I don't know any specifics in this area, so I am just speculating.) That said, the JVM is going to execute the bytecode anyway, the way it is being executed is more or less opaque to the developer, and again, JVM-specific. There may be some performance tricks that one JVM performs while another doesn't. When it comes down to the issue of looking at the bytecode generated, it comes down to learning what is actually happening to the source code when it is compiled to bytecode. Being able to see the kinds of optimizations performed by the compiler, but also understanding that there are limits to the way the compiler can perform optimizations. All that said, I don't think it's a really good idea to become obsessive about the bytecode generation and trying to write programs that will emit the most optimized bytecode. What's more important is to write Java source code that is readable and maintainable by others.
That depends entirely on what you're trying to do. If you're trying to optimize a method/module, looking at the byte code is going to be a waste of your time. Always profile first to find where your bottlenecks are, then optimize the bottlenecks. If your bottleneck seems as tight as it possibly can be and you need to make it faster, you may have no choice but to rewrite that in native code and interface with JNI. Trying to optimize the generated bytecode will be of little help, since the JIT compiler will do a lot of work, and you won't have much of an idea of exactly what it's doing.
Should I look at the bytecode that is produce by a java compiler?
[ "", "java", "compiler-construction", "jvm", "bytecode", "jit", "" ]
in function need key to encrypt string without mcrypt libraly in php ``` function encrypt($str, $pass){ $str_arr = str_split($str); $pass_arr = str_split($pass); $add = 0; $div = strlen($str) / strlen($pass); while ($add <= $div) { $newpass .= $pass; $add++; } $pass_arr = str_split($newpass); foreach($str_arr as $key =>$asc) { $pass_int = ord($pass_arr[$key]); $str_int = ord($asc); $int_add = $str_int + $pass_int; $ascii .= chr($int_add); } return $ascii; } function decrypt($enc, $pass){ $enc_arr = str_split($enc); $pass_arr = str_split($pass); $add = 0; $div = strlen($enc) / strlen($pass); while ($add <= $div) { $newpass .= $pass; $add++; } $pass_arr = str_split($newpass); foreach($enc_arr as $key =>$asc) { $pass_int = ord($pass_arr[$key]); $enc_int = ord($asc); $str_int = $enc_int - $pass_int; $ascii .= chr($str_int); } return $ascii; } ``` in this not work for i character i test it
This code is rather inefficient, I'm not surprised it doesn't give intended results. ``` echo RotEncrypt('cheese', 'pie') . "\n<br>\n" .RotDecrypt(RotEncrypt('cheese', 'pie'), 'pie'); // ÓÑÊÕÜÊ // cheese function RotEncrypt($str, $pass){ $pass = str_split(str_pad('', strlen($str), $pass, STR_PAD_RIGHT)); $stra = str_split($str); foreach($stra as $k=>$v){ $tmp = ord($v)+ord($pass[$k]); $stra[$k] = chr( $tmp > 255 ?($tmp-256):$tmp); } return join('', $stra); } function RotDecrypt($str, $pass){ $pass = str_split(str_pad('', strlen($str), $pass, STR_PAD_RIGHT)); $stra = str_split($str); foreach($stra as $k=>$v){ $tmp = ord($v)-ord($pass[$k]); $stra[$k] = chr( $tmp < 0 ?($tmp+256):$tmp); } return join('', $stra); } ``` Tested and it appears to work fine for me. Either way I feel I should warn you that this is a really insecure form of encryption, most passwords use the same sets of characters and a fairly small range of lengths, which makes this system very vulnerable to people being able to work out with a fairly good level of accuracy the password.
Here's another method: ``` $key = 'the quick brown fox jumps over the lazy '; $string = 'Hey we are testing encryption'; echo enc_encrypt($string, $key)."\n"; echo enc_decrypt(enc_encrypt($string, $key), $key)."\n"; function enc_encrypt($string, $key) { $result = ''; for($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key))-1, 1); $char = chr(ord($char) + ord($keychar)); $result .= $char; } return base64_encode($result); } function enc_decrypt($string, $key) { $result = ''; $string = base64_decode($string); for($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key))-1, 1); $char = chr(ord($char) - ord($keychar)); $result .= $char; } return $result; } ``` Again, don't expect this to be very secure.
How to encrypt string without mcrypt library in php
[ "", "php", "encryption", "" ]
Is it possible to convert some of the dlls of .Net framework 3.5 and use it in .Net framework 2.0? I really need the managed named pipes namespace in .Net 2.0 :-( Thanks
You can use the C# 3.0 compiler features in .NET 2.0 with a few tricks - but you aren't going to be able to use framework dlls / types / methods that don't exist in 2.0. I **don't** recommend trying to simply deploy any 3.5 dlls without having the client have .NET 3.5 installed. My expectation is that you'll have to install .NET 3.5 on the machine, or make do without the framework feature you want.
Yes, you can. I've done it. I use System.Core, System.Xml.Linq, System.Data.Linq, and other 3.5 stuff on a Windows 2000 server with .NET 2.0 There's no need to 'convert' anything, 3.5 assemblies (green bits) target the 2.0 version of the CLR. What you need to do is install the latest service pack for .NET 2.0 (SP2 I think), that will update the red bits assemblies. <http://www.danielmoth.com/Blog/2007/06/net-framework-35.html>
Using .Net framework 3.5 features in .Net framework 2.0
[ "", "c#", ".net", "" ]
I want to determine the scroll of the users. I'm using jQuery.. And jquery have .scroll event.. But the .scroll event can't determine whether the user is scrolling the page downwards or upwards.
You can start with a variable like this: ``` var position = $(window).scrollTop(); // should start at 0 ``` And then have something that monitors whether the scrollTop is going up or down: ``` $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > position) { console.log("scrolling downwards"); } else { console.log("scrolling upwards"); } position = scroll; }); ``` ``` var position = $(window).scrollTop(); $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > position) { console.log("scrolling downwards"); } else { console.log("scrolling upwards"); } position = scroll; }); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p style="font-size: 40px;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae erat et lacus facilisis hendrerit ac nec lectus. Aenean hendrerit maximus tempus. Phasellus feugiat odio vitae ligula eleifend condimentum. Vestibulum id faucibus magna, sit amet consequat nunc. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum pellentesque, magna ut ultricies lacinia, nisi dui condimentum ante, vitae euismod arcu eros vitae nulla. Donec finibus erat sed libero commodo tincidunt. Curabitur pulvinar, nisl vitae tempus commodo, felis nisi pretium arcu, sed gravida risus sapien eu ipsum. In metus magna, consequat eleifend sem a, condimentum imperdiet augue. Fusce blandit dui eu erat lacinia, vitae laoreet orci porttitor. Nulla tortor nibh, porttitor at augue quis, elementum hendrerit velit. Fusce at risus in massa pellentesque dapibus id ut velit. In tempor magna vitae diam posuere pharetra. Aliquam sed semper sem. Nam dapibus pretium tempus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cras ex odio, auctor eget mauris eget, dignissim rutrum mauris. Nulla porttitor leo nec enim gravida scelerisque. Nam consectetur malesuada enim eu tincidunt. Morbi posuere imperdiet nisl. Aenean non tortor porttitor, aliquam lectus a, scelerisque risus. Donec eu felis non justo sollicitudin venenatis eget eu mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam fringilla mi ut purus ornare, et interdum est accumsan. Donec dapibus enim non sem dictum pretium. Pellentesque quis velit sem. Duis rutrum vulputate sem eget fringilla. Pellentesque vel enim nulla. Aliquam erat volutpat. Maecenas lacinia condimentum semper. Quisque gravida orci ut mauris rhoncus interdum. Pellentesque id augue vitae leo accumsan vehicula. Fusce sed justo id metus ornare ultrices. Vestibulum gravida lacus vitae finibus viverra. Maecenas dapibus quam et pulvinar tempus. Maecenas at molestie justo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus non elementum dui, a rutrum ligula. Ut ut odio feugiat, suscipit arcu eget, feugiat leo. Nunc elit erat, ultricies vel volutpat vitae, dignissim vel nunc. Sed pharetra lacus sem, quis dignissim metus ullamcorper a. Vivamus ac augue libero. Donec consectetur sem non ipsum faucibus cursus. Morbi facilisis efficitur urna sit amet vehicula. Proin nec finibus magna. Cras suscipit nec eros sit amet vestibulum. Integer aliquam a mauris non interdum. Fusce eu mattis enim. Vestibulum congue ullamcorper velit ut tempus. Curabitur et pretium massa, ac condimentum massa. </p> ```
Here is an example with plain javascript: ``` var previousPosition = window.pageYOffset || document.documentElement.scrollTop; window.onscroll = function() { var currentPosition = window.pageYOffset || document.documentElement.scrollTop; if (previousPosition > currentPosition) { console.log('scrolling up'); } else { console.log('scrolling down'); } previousPosition = currentPosition; }; ``` ``` <h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1><h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1><h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1><h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1> ```
How can I know whether the scroll of the user is UP or DOWN?
[ "", "javascript", "jquery", "" ]
I have a listbox (detailed view). How do I get the index of the selected item? I also eventually want to get the text at the index, but that should be easy.
[ListBox.SelectedItem](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditem.aspx) Property: > Gets or sets the currently selected item in the ListBox. Or, naturally, [ListBox.SelectedItems](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems.aspx) Propery: > Gets a collection containing the currently selected items in the ListBox. > > ... Remarks > > For a multiple-selection ListBox, this property returns a collection containing all items that are selected in the ListBox. For a single-selection ListBox, this property returns a collection containing a single element containing the only selected item in the ListBox. For more information about how to manipulate the items of the collection, see ListBox..::.SelectedObjectCollection. > > The ListBox class provides a number of ways to reference selected items. Instead of using the SelectedItems property to obtain the currently selected item in a single-selection ListBox, you can use the SelectedItem property. If you want to obtain the index position of an item that is currently selected in the ListBox, instead of the item itself, use the SelectedIndex property. In addition, you can use the SelectedIndices property if you want to obtain the index positions of all selected items in a multiple-selection ListBox.
The selected index is in the `SelectedIndex` property. The selected text is in the `Text` property.
C#: How to get the index of the selected item(and the text) in ListBox
[ "", "c#", "winforms", "properties", "listbox", "" ]
Is there anything in Python that works like the `final` keyword in Java - i.e., to disallow assigning to a specific attribute of the instances of a class, after those instances have been created? I couldn't find anything like this in the documentation. I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a `final`-like feature in Python would be nice for this.
Having a variable in Java be `final` basically means that once you assign to a variable, you may not reassign that variable to point to another object. It actually doesn't mean that the object can't be modified. For example, the following Java code works perfectly well: ``` public final List<String> messages = new LinkedList<String>(); public void addMessage() { messages.add("Hello World!"); // this mutates the messages list } ``` but the following wouldn't even compile: ``` public final List<String> messages = new LinkedList<String>(); public void changeMessages() { messages = new ArrayList<String>(); // can't change a final variable } ``` So your question is about whether `final` exists in Python. It does not. However, Python does have immutable data structures. For example, while you can mutate a `list`, you can't mutate a `tuple`. You can mutate a `set` but not a `frozenset`, etc. My advice would be to just not worry about enforcing non-mutation at the language level and simply concentrate on making sure that you don't write any code which mutates these objects after they're assigned.
There is no `final` equivalent in Python. To create read-only fields of class instances, you can use the [property](http://docs.python.org/3.0/library/functions.html#property) function, or you could do something like this: ``` class WriteOnceReadWhenever: def __setattr__(self, attr, value): if hasattr(self, attr): raise Exception("Attempting to alter read-only value") self.__dict__[attr] = value ``` Also note that while there's [`@typing.final`](https://docs.python.org/3.8/library/typing.html?highlight=final#typing.final) as of Python 3.8 (as [Cerno](https://stackoverflow.com/users/949251/cerno) mentions), that will *not* actually make values `final` at runtime.
In Python, how can I make unassignable attributes (like ones marked with `final` in Java)?
[ "", "python", "attributes", "immutability", "" ]
A list of every update and hotfix that has been installed on my computer, coming from either Microsoft Windows Update or from the knowledge base. I need the ID of each in the form of KBxxxxxx or some similar representation... Currently I have: ``` const string query = "SELECT HotFixID FROM Win32_QuickFixEngineering"; var search = new ManagementObjectSearcher(query); var collection = search.Get(); foreach (ManagementObject quickFix in collection) Console.WriteLine(quickFix["HotFixID"].ToString()); ``` But this does not seem to list everything, it only lists QFE's. I need it to work on Windows XP, Vista and 7.
You can use [IUpdateSession3::QueryHistory Method](http://msdn.microsoft.com/en-us/library/bb394842(VS.85).aspx). The properties of the returned entries are described at <http://msdn.microsoft.com/en-us/library/aa386400(VS.85).aspx> ``` Set updateSearch = CreateObject("Microsoft.Update.Session").CreateUpdateSearcher Set updateHistory = updateSearch.QueryHistory(1, updateSearch.GetTotalHistoryCount) For Each updateEntry in updateHistory Wscript.Echo "Title: " & updateEntry.Title Wscript.Echo "application ID: " & updateEntry.ClientApplicationID Wscript.Echo " --" Next ``` edit: also take a look at <http://msdn.microsoft.com/en-us/library/aa387287%28VS.85%29.aspx>
After some further search on what I've found earlier. (Yes, the same as VolkerK suggests first) 1. Under VS2008 CMD in %SystemRoot%\System32\ run a command to get a managed dll: **tlbimp.exe wuapi.dll /out=WUApiInterop.dll** 2. Add WUApiInterop.dll as a project reference so we see the functions. Using the following code I can get a list from which I can extract the KB numbers: ``` var updateSession = new UpdateSession(); var updateSearcher = updateSession.CreateUpdateSearcher(); var count = updateSearcher.GetTotalHistoryCount(); var history = updateSearcher.QueryHistory(0, count); for (int i = 0; i < count; ++i) Console.WriteLine(history[i].Title); ```
How do I get a list of installed updates and hotfixes?
[ "", "c#", ".net", "windows", "list", "" ]
Im just learning SQLite and I can't get my parameters to compile into the command properly. When I execute the following code: ``` this.command.CommandText = "INSERT INTO [StringData] VALUE (?,?)"; this.data = new SQLiteParameter(); this.byteIndex = new SQLiteParameter(); this.command.Parameters.Add(this.data); this.command.Parameters.Add(this.byteIndex); this.data.Value = data.Data; this.byteIndex.Value = data.ByteIndex; this.command.ExecuteNonQuery(); ``` I get a SQLite Exception. Upon inspecting the CommandText I discover that whatever I'm doing is not correctly adding the parameters: `INSERT INTO [StringData] VALUE (?,?)` Any ideas what I'm missing? Thanks
Try `VALUES` instead of `VALUE`.
Try a different approach, naming your fields in the query and naming the parameters in the query: ``` this.command.CommandText = "INSERT INTO StringData (field1, field2) VALUES(@param1, @param2)"; this.command.CommandType = CommandType.Text; this.command.Parameters.Add(new SQLiteParameter("@param1", data.Data)); this.command.Parameters.Add(new SQLiteParameter("@param2", data.ByteIndex)); ... ```
Adding parameters in SQLite with C#
[ "", "c#", "sqlite", "system.data.sqlite", "" ]
I'm trying to come up with a solution to programmatically enable/disable the network card - I've done a ton of research and nothing seems to be a workable solution in both XP and Vista environments. What I'm talking about is if you went into the Control Panel 'Network Connections', right clicked on one and picked either enable or disable. Ideally I'd like to use a library, but if worse comes to worse I supposed I could call out to a commandline app, but that's absolute worst case. Here's what I've tried so far and where/why they failed: This previous post: [How to programmatically enable/disable network interfaces? (Windows XP)](https://stackoverflow.com/questions/83756/how-to-programmatically-enabledisable-network-interfaces-windows-xp) Lists a couple of methods - the first is using netsh, which appears to be the same as using the IPHelper function SetIfEntry(). The problem with this is that it sets the interface as Administratively enabled or disable, not the normal enabled/disabled so it doesn't actually shut down the NIC. Another solution proposed is using WMI and in particular Win32\_NetworkAdapter class, which has an Enable and Disable method: <http://msdn.microsoft.com/en-us/library/aa394216(VS.85).aspx> Great right? Works fine in Vista, those methods don't exist in a normal XP install... Another suggestion is to use DevCon, which really uses the SetupAPI, in particular SetupDiSetClassInstallParams() with the DICS\_ENABLE. After spending countless hours with this wonderful class, and trying to disable/enable the device both at the global level as well as the specific configuration level (and every combination), it doesn't consistently work either - sometimes working fine, but other times disabling the device in the Device Manager, but still leaving it up and operational in the Network Connections. I then tried using the INetConnection interface, specifically INetConnection->Connect/Disconnect: <http://msdn.microsoft.com/en-us/library/aa365084(VS.85).aspx> But I was never able to get this to have any effect on the connections on either my Vista or XP test boxes. Finally, I found this C# script called ToggleNic: <http://channel9.msdn.com/playground/Sandbox/154712/> Which looks like it's going through the Shell somehow to effectively cause the right-click behavior. The limitation (at least of this implementation) is that it doesn't work (without modification) on non-English systems, which I need mine to work with. To be fair, this solution looks like the most viable, but my familiarity with C# is low and I couldn't find if the API it's using is available in C++. Any help or insights would be greatly appreciated - or ideas on how to accomplish what the togglenic script does in C++. Thanks!
After testing on more platforms and more approaches, I've basically given up on this functionality (at least for my purposes). The problem for me is that I want to have something that works in 90%+ of the situations, and the reality is that with everything I could come up with, it's closer to 70%. The ironic thing is that it's actually just as flaky through the normal Windows method. For those who still want to go down this perilous path, here's what I found: Of the API direct methods described above, the one which worked the most consistently was using the SetupAPI (SetupDiSetClassInstallParams) - the biggest problem I ran into with this is that sometimes it would get in a state where it would require a reboot and no changes would work until that happened. The only other thing to be aware of when using this is that there are two profiles for devices, so you need to toggle them both in some cases. The DDK contains the source to the devcon tool, which shows you exactly how to do everything. This ultimately looked like it was the closest to right-clicking, but it still exhibited some strange behavior that Network Connections didn't. This approach seemed to work about 70% of the time (in both tests and on test systems). From the total hack approach, the best I found was not using the technique that ToggleNIC did, but instead use the IShellFolder stuff - this allows you to use GetCommandString which is language-independent. The problem with this is that under XP GetCommandString doesn't return anything (oh joy), but it did appear that the menu ID's for 'enable' and 'disable' were consistent (16 and 17 respectively), so if I failed to GetCommandString, I just fell back to the menu ID's. To Toggle, just call InvokeCommand with either the string if it returned one, or the menu ID if it didn't. The problem with this was that just like the normal Windows way, sometimes it doesn't work, nor does it give you any indication of what's going on or why it failed. This approach seemed to work about 70% of the time as well, but was much harder to tell if something went wrong, plus the normal "Enabling interface..." text would pop up. Hopefully this helps anyone else - and if anyone manages to find another way that works in more situations, I'd love to hear it!
Try the "*Shell Network Interfaces*" C++-code [here](http://www.gershnik.com/faq/manage.asp#enable). This should work under XP and higher.
Programmatically disable/enable network interface
[ "", "c++", "windows", "windows-vista", "windows-xp", "nic", "" ]
I just started programming in C# and was reading about dividing your application / website into the three different layers was the best practice but I am having a hard time understanding exactly how. Im working on a pet project to lean more about C# but I dont want to start on any bad habits. Can you look at what I have and see if I am doing this right? Offer some hints suggestions as to how to break everything down to the different layers? **Presentation Layer** ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Project: Ruth</title> <link href="CSS/StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div class="Body"> <div class="Header"> <div class="Nav"> <img src="images/Header_Main.gif" alt="" width="217" height="101" /> <div class="Menu"> <a href="Default.aspx"> <img src="images/Header_Home-Off.gif" alt="" /></a> <a href="Default.aspx"> <img src="images/Header_About-Off.gif" alt="" /></a> <a href="Register.aspx"> <img src="images/Header_Register-Off.gif" alt="" /></a> <a href="Default.aspx"> <img src="images/Header_Credits-Off.gif" alt="" /></a> </div> </div> </div> <div class="Content"> <div class="CurrentlyListening"> <asp:Label ID="lblCurrentListen" runat="server" Text="(Nothing Now)" CssClass="Txt"></asp:Label> </div> <asp:GridView ID="gvLibrary" runat="server" AutoGenerateColumns="False" DataKeyNames="lib_id" DataSourceID="sdsLibrary" EmptyDataText="There are no data records to display." Width="760" GridLines="None"> <RowStyle CssClass="RowStyle" /> <AlternatingRowStyle CssClass="AltRowStyle" /> <HeaderStyle CssClass="HeaderStyle" /> <Columns> <asp:BoundField DataField="artist_name" HeaderText="Artist" SortExpression="artist_name" HeaderStyle-Width="200" /> <asp:BoundField DataField="album_title" HeaderText="Album" SortExpression="album_title" HeaderStyle-Width="200" /> <asp:BoundField DataField="song_title" HeaderText="Track" SortExpression="song_title" HeaderStyle-Width="200" /> <asp:TemplateField HeaderText="DL"> <ItemTemplate> <a href="http://####/Proj_Ruth/Data/<%# Eval("file_path") %>" class="lnk">Link</a> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="sdsLibrary" runat="server" ConnectionString="<%$ ConnectionStrings:MusicLibraryConnectionString %>" DeleteCommand="DELETE FROM [Library] WHERE [lib_id] = @lib_id" InsertCommand="INSERT INTO [Library] ([artist_name], [album_title], [song_title], [file_path]) VALUES (@artist_name, @album_title, @song_title, @file_path)" ProviderName="<%$ ConnectionStrings:MusicLibraryConnectionString.ProviderName %>" SelectCommand="SELECT [lib_id], [artist_name], [album_title], [song_title], [file_path] FROM [Library] ORDER BY [artist_name], [album_title]" UpdateCommand="UPDATE [Library] SET [artist_name] = @artist_name, [album_title] = @album_title, [song_title] = @song_title, [file_path] = @file_path WHERE [lib_id] = @lib_id"> <DeleteParameters> <asp:Parameter Name="lib_id" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="artist_name" Type="String" /> <asp:Parameter Name="album_title" Type="String" /> <asp:Parameter Name="song_title" Type="String" /> <asp:Parameter Name="file_path" Type="String" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="artist_name" Type="String" /> <asp:Parameter Name="album_title" Type="String" /> <asp:Parameter Name="song_title" Type="String" /> <asp:Parameter Name="file_path" Type="String" /> <asp:Parameter Name="lib_id" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> </div> </div> </form> </body> </html> ``` **Business Layer** ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; public class User { DA da = new DA(); public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string Password { get; set; } public string AccessCode { get; set; } public User(string firstName, string lastName, string emailAddress, string password, string accessCode) { FirstName = firstName; LastName = lastName; EmailAddress = emailAddress; Password = password; AccessCode = accessCode; } public void CreateUser(User newUser) { if (da.IsValidAccessCode(newUser.AccessCode)) { da.CreateUser(newUser); } } } ``` **Data Access Layer (DAL)** ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlTypes; using System.Data.SqlClient; using System.Configuration; public class DA { public DA() { } public bool IsValidAccessCode(string accessCode) { bool isValid = false; int count = 0; using (SqlConnection sqlCnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MusicLibraryConnectionString"].ConnectionString)) { sqlCnn.Open(); using (SqlCommand sqlCmd = new SqlCommand(String.Format("SELECT COUNT(*) FROM [AccessCodes] WHERE [accessCode_accessCode] = '{0}';", accessCode), sqlCnn)) { count = (int)sqlCmd.ExecuteScalar(); if (count == 1) { isValid = true; } } } return isValid; } public void CreateUser(User newUser) { using (SqlConnection sqlCnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MusicLibraryConnectionString"].ConnectionString)) { sqlCnn.Open(); using (SqlCommand sqlCmd = new SqlCommand(String.Format("INSERT INTO [Users] (user_firstName, user_lastName, user_emailAddress, user_password, user_accessCode) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}');", newUser.FirstName, newUser.LastName, newUser.EmailAddress, newUser.Password, newUser.AccessCode), sqlCnn)) { sqlCmd.ExecuteNonQuery(); } } DeleteAccessCode(newUser.AccessCode); } public void DeleteAccessCode(string accessCode) { using (SqlConnection sqlCnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MusicLibraryConnectionString"].ConnectionString)) { sqlCnn.Open(); using (SqlCommand sqlCmd = new SqlCommand(String.Format("DELETE FROM [AccessCodes] WHERE [accessCode_accessCode] = '{0}';", accessCode), sqlCnn)) { sqlCmd.ExecuteNonQuery(); } } } } ```
Jon, One of the first things to understand is that if you intend to build layer-based applications, then you should not be storing SQL statements directly within ASPX pages (as the `SqlDataSource` requires). The `SqlDataSource` control was built to demonstrate how easy it is to bind and update an application with database data and is not intended to be used in real world applications, because it kinda defeats the purpose of having a BL layer and Datalayer if you are going to store Select/Update/Delete/Insert statements in the ASPX page. The whole purpose of layer-based application design is to encapsulate each layer so that there is no intersection. Each layer interacts with the public interface of the other layers and knows nothing about their internal implementation. The viable alternative, therefore, is to use the `ObjectDataSource` control. This control allows you to bind directly to a DataLayer or to a Biz logic layer which in turn can call the Datalayer. Binding to a Datalayer directly has the drawback that you will be returning data structures which expose the schema of the database tables (for e.g., DataTables or DataViews). So, the recommended flow of logic is as follows: The ASPX page uses a DataSource control to bind to a BL class. This BL class provides appropriate functions such as `GetData, UpdateData, DeleteData and InsertData` (with any required overloads) and these functions return strongly typed objects or collections that the `ObjectDataSource` can work with and display. Each public function in the BL class internally calls into the DataLayer to select/update/delete/insert data to/from the database. An excellent introduction to this layer based design in ASP.NET is provided in the [Quickstarts](http://quickstarts.asp.net/QuickStartv20/aspnet/doc/data/objects.aspx) **P.S**: @Andy mentioned generic datalayers that work with all scenarios. See [this question](https://stackoverflow.com/questions/619855/code-review-ado-net-data-access-utility-class-vb/) for an example of what it would look like.
The greatest explanation of logic layers in ASP.NET applications come from two sources. The first is Microsoft's own ASP.NET website written by Scott Mitchell it provides a good introduction to the separation of logic. The tutorials are quite wordy but I found them very useful. The URL is <http://www.asp.net/learn/data-access/>. The second resource I found very useful followed on from that and it was written by Imar Spaanjaars and is available [here](http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=476). It is a much more technical article but provides a great way of adding the structure to your application. I hope that helps. Ian.
Presentation, Business and Data Layer
[ "", "c#", "data-access-layer", "layer", "presentation", "" ]
I know VS code folding issues are an old chestnut, but I haven't been able to find this in all the other discussions I have browsed through: We have a team of C# guys, some love regions and others hate them and we don't seem to have much middle ground to work with. Is there a plug- or add-in for VS that will just 'hide' the regions? So that those that want them will see them as normal, but the people that install the add-in and view a .cs file the regions just aren't there, as if they don't exist. I can see this might be an issue when moving code around that it might cause issues of certain methods being in or outside of the wrong region, but that might be a tradeoff the team is happy with...
I hate regions (my team loves them) and was surprised to find that nobody has written an extension to make them better. I finally wrote one myself called **I Hate #Regions**: *Make #regions suck less (for free):* <http://visualstudiogallery.msdn.microsoft.com/0ca60d35-1e02-43b7-bf59-ac7deb9afbca> * Auto Expand regions when a file is opened * Optionally prevent regions from being collapsed (but still be able to collapse other code) * Give the #region / #end region lines a smaller, lighter background so they are less noticeable (also an option) * Works in C# and VB ![Region Tool Screenshot](https://i.stack.imgur.com/nPFCK.png)
There are shortcut keys to deal with them: ``` Ctrl+M, Ctrl+M Collapse or expand the block you're currently in. Ctrl+M, Ctrl+O Collapse all blocks in the file Ctrl+M, Ctrl+L Expand all blocks in the file Ctrl+M, Ctrl+P Stop outlining mode. (Ctrl+M, Ctrl+O resumes) ``` See [The Problem With Code Folding](https://blog.codinghorror.com/the-problem-with-code-folding/)
Hiding the regions in Visual Studio
[ "", "c#", "visual-studio-2008", "regions", "" ]
I know that one of the differences between classes and structs is that struct instances get stored on stack and class instances(objects) are stored on the heap. Since classes and structs are very similar. Does anybody know the difference for this particular distinction?
(edited to cover points in comments) To emphasise: there are differences and similarities between value-types and reference-types, but those differences have **nothing** to do with stack vs heap, and everything to do with copy-semantics vs reference-semantics. In particular, if we do: ``` Foo first = new Foo { Bar = 123 }; Foo second = first; ``` Then are "first" and "second" talking about the same copy of `Foo`? or different copies? It just so happens that the stack is a convenient and efficient way of *handling* value-types as variables. But that is an implementation detail. (end edit) Re the whole "value types go on the stack" thing... - value types **don't** always go on the stack; * if they are fields on a class * if they are boxed * if they are "captured variables" * if they are in an iterator block then they go on the heap (the last two are actually just exotic examples of the first) i.e. ``` class Foo { int i; // on the heap } static void Foo() { int i = 0; // on the heap due to capture // ... Action act = delegate {Console.WriteLine(i);}; } static IEnumerable<int> Foo() { int i = 0; // on the heap to do iterator block // yield return i; } ``` Additionally, Eric Lippert (as already noted) has an [excellent blog entry](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-stack-is-an-implementation-detail-part-one) on this subject
It's useful in practice to be able to allocate memory on the stack for some purposes, since those allocations are very fast. However, it's worth noting that there's no fundamental guarantee that all structs will be placed on the stack. Eric Lippert recently wrote [an interesting blog entry](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-stack-is-an-implementation-detail-part-one) on this topic.
Why are structs stored on the stack while classes get stored on the heap(.NET)?
[ "", "c#", ".net", "" ]
Is there a SQL command that will list all the tables in a database and which is provider independent (works on MSSQLServer, Oracle, MySQL)?
The closest option is to query the `INFORMATION_SCHEMA` for tables. ``` SELECT * FROM INFORMATION_SCHEMA.Tables WHERE table_schema = 'mydatabase'; ``` The `INFORMATION_SCHEMA` is part of standard SQL, but not all vendors support it. As far as I know, the only RDBMS vendors that support it are: * [MySQL](http://dev.mysql.com/doc/refman/5.1/en/information-schema.html) * [PostgreSQL](http://www.postgresql.org/docs/current/static/information-schema.html) * Microsoft SQL Server [2000](http://msdn.microsoft.com/en-us/library/aa933204.aspx)/[2005](http://msdn.microsoft.com/en-us/library/ms186778(SQL.90).aspx)/[2008](http://msdn.microsoft.com/en-us/library/ms186778.aspx) Some brands of database, e.g. Oracle, IBM DB2, Firebird, Derby, etc. have similar "catalog" views that give you an interface where you can query metadata on the system. But the names of the views, the columns they contain, and their relationships don't match the ANSI SQL standard for `INFORMATION_SCHEMA`. In other words, similar information is available, but the query you would use to get that information is different. (footnote: the catalog views in IBM DB2 UDB for System i are different from the catalog views in IBM DB2 UDB for Windows/\*NIX -- so much for the *Universal* in UDB!) Some other brands (e.g. SQLite) don't offer any queriable interface for metadata at all.
No. They all love doing it their own little way.
Listing all tables in a database
[ "", "sql", "database", "" ]
Are there any guidelines to writing [Google App Engine](http://en.wikipedia.org/wiki/Google_App_Engine) Python code that would work without Google's infrastructure on other platforms? Is there any known attempt to create an open source framework which can run applications designed for Google App Engine on other platforms? Edit: To clarify, the question really is: If I develop an application on Google App Engine now, will I be able to migrate to another platform later, or is it a lock in?
There's a number of components required to make an app fully portable: * The runtime environment itself. This can be ported relatively simply, by setting up a CGI or FastCGI server that emulates the App Engine environment (which itself is basically slightly-enhanced CGI). Most of the code to do this is already in the SDK. Unfortunately, there's no easy pre-packaged toolkit for this yet. * The datastore. By far the most complicated API to port. There are a number of efforts underway: [AppScale](http://appscale.cs.ucsb.edu/) runs on EC2/Eucalyptus/Xen and uses a HyperTable or HBase backend; it's still very much beta quality and they don't distribute the data connector separately (it's the beginnings of a complete run-your-app-on-your-own-cloud solution). Jens is/was writing an [SQLite backend](http://blog.appenginefan.com/2008/09/appengine-and-sqlite-getting-values-out.html), and there's my own project, [BDBDatastore](http://arachnid.github.com/bdbdatastore/), which uses BDB-JE as the backend, and is fully functional (though beta quality). [AppDrop](http://jchrisa.net/drl/_design/sofa/_show/post/announcing_appdrop_com__host_go), which others have mentioned, simply uses the development server as a backend, and hence isn't suitable for production use. * The users API needs replacing with something else, such as an OpenID based API. Again, fairly simple, but no premade solutions yet. * The Memcache API needs a backend that uses standard C memcache backends. * The other APIs have perfectly functional backends as part of the SDK, so don't really need porting. * Cron support would also need implementing, as would background processing, XMPP, etc, when they become available. As you can see, there's a lot of work to be done, but no fundamental barriers to making your App Engine app run outside Google's environment. In fact, if you're interested, you're more than welcome to participate - I and others have plans to combine the solutions for the various pieces into a single 'OpenEngine' solution for hosting your own apps.
Use a high level framework that works on App-Engine. That way you can port your code to other servers when you want. django has been patched and ported to work in the [Appengine patch](http://code.google.com/p/app-engine-patch/) project and is the most used FW on appengine. You may want to refer this step by step intro to [running a django app on App engine](http://uswaretech.com/blog/2009/04/develop-twitter-api-application-in-django-and-deploy-on-google-app-engine/) As far as the parallel infrastructure to run an app engine application is concerned, it is still way far. App Engine itself hasn't got as popular as people believed it to and google wanted it to be. Plus it is harder to develop on the builtin WebApp framework than on django. Its quite unlikely to see a parallel infrastructure to run app engine application on, atleast for years to come. Rather it is likely to see django and other popular frameworks work out of the box on app engine and the work on this is currently underway in the referred project.
Breaking out of the Google App Engine Python lock-in?
[ "", "python", "google-app-engine", "open-source", "lock-in", "" ]
I want to enforce on my code base immutable rule with following test ``` [TestFixture] public class TestEntityIf { [Test] public void IsImmutable() { var setterCount = (from s in typeof (Entity).GetProperties(BindingFlags.Public | BindingFlags.Instance) where s.CanWrite select s) .Count(); Assert.That(setterCount == 0, Is.True, "Immutable rule is broken"); } } ``` It passes for: ``` public class Entity { private int ID1; public int ID { get { return ID1; } } } ``` but doesn't for this: ``` public class Entity { public int ID { get; private set; } } ``` And here goes the question "WTF?"
A small modification to answers posted elsewhere. The following will return non-zero if there is at least one property with a protected or public setter. Note the check for GetSetMethod returning null (no setter) and the test for IsPrivate (i.e. not public or protected) rather than IsPublic (public only). ``` var setterCount = (from s in typeof(Entity).GetProperties( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) where s.GetSetMethod(true) != null // setter available && (!s.GetSetMethod(true).IsPrivate) select s).Count(); ``` Nevertheless, as [pointed out in Daniel Brückner's answer](https://stackoverflow.com/questions/839066/net-immutable-objects/839113#839113), the fact that a class has no publicly-visible property setters is a necessary, but not a sufficient condition for the class to be considered immutable.
The problem is, that the property is public - because of the public getter - and it is writeable - because of the private setter. You will have to refine your test. Further I want to add, that you cannot guarantee immutability this way because you could modify private data inside methods. To guarantee immutability you have to check that all fields are declared readonly and there are no auto-implemented properties. ``` public static Boolean IsImmutable(this Type type) { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; return type.GetFields(flags).All(f => f.IsInitOnly); } public static Boolean IsImmutable(this Object @object) { return (@object == null) || @object.GetType().IsImmutable(); } ``` With this extension method you can easily test types ``` typeof(MyType).IsImmutable() ``` and instances ``` myInstance.IsImmutable() ``` for their immutability. **Notes** * Looking at instance fields allows you to have writable properties, but ensures that there are now fields that could be modified. * Auto-implemented properties will fail the immutability test as exspected because of the private, anonymous backing field. * You can still modify `readonly` fields using reflection. * Maybe one should check that the types of all fields are immutable, too, because this objects belong to the state. * This cannot be done with a simple `FiledInfo.FieldType.IsImmutable()` for all fields because of possible cycles and because the base types are mutable.
.net Immutable objects
[ "", "c#", "reflection", "properties", "" ]
I am trying to get the `rowcount` of a `sqlite3` `cursor` in my Python3k program, but I am puzzled, as the `rowcount` is always `-1`, despite what Python3 docs say (actually it is contradictory, it should be `None`). Even after fetching all the rows, `rowcount` stays at `-1`. Is it a `sqlite3` bug? I have already checked if there are rows in the table. I can get around this checking if a `fetchone()` returns something different than `None`, but I thought this issue would be nice to discuss. Thanks.
From the [documentation](http://docs.python.org/3.0/library/sqlite3.html#sqlite3.Cursor.rowcount): > As required by the Python DB API Spec, > the rowcount attribute “is -1 in case > no executeXX() has been performed on > the cursor or the rowcount of the last > operation is not determinable by the > interface”. > > **This includes `SELECT` statements > because we cannot determine the number > of rows a query produced until all > rows were fetched.** That means **all** `SELECT` statements **won't have a `rowcount`**. The behaviour you're observing is documented. **EDIT:** Documentation doesn't say anywhere that `rowcount` **will** be updated after you do a `fetchall()` so it is just wrong to assume that.
``` cursor = newdb.execute('select * from mydb;') print len(cursor.fetchall()) ``` The fetchall() will return a list of the rows returned from the select. Len of that list will give you the rowcount.
cursor.rowcount always -1 in sqlite3 in python3k
[ "", "python", "database", "sqlite", "" ]
I would like to run the following SQL select: `SELECT ID, NUMERATOR, (SELECT m.COLUMNNAME FROM m.TABLENAME p WHERE p.numerator = m.numerator ) VALUE, TABLENAME, COLUMNNAME FROM MainTable m;` at the current state it doesn't run at all, naturally, because oracle doesn't recognize the m.TABLENAME at all. Is it possible to somehow do this sort of thing? The same for the `COLUMNNAME` - even if I temporarily replace the table to some "real" table I've got, at the current syntax it just outputs the value inside `m.COLUMNNAME` instead of the value inside p, at the column whose name is `m.COLUMNNAME`. Hope I managed to be clear about it. I guess my other way to go about it is to create a procedure that iterates over the first query's results, and execute another select for each of them to fill the `VALUE` column. Is that the best I can hope to do?
You're going to have to do that with [dynamic SQL](http://www.cs.umbc.edu/help/oracle8/server.815/a68022/dynsql.htm) ie PL/SQL or dynamically construct your SQL statement in your application. As you note, Oracle does not support this behaviour.
**It is probably easier to use the solutions of cletus.** But it is not entirely impossible to do that, you can use `dbms_xmlgen.getxml(' ')`, using `dbms_xmlgen.getxml(' ')` makes it possible to make dynamic sql statements inside a sql statement. Don't expect good performance!! See for example: [Identify a table with maximum rows in Oracle](https://stackoverflow.com/questions/390945/identify-a-table-with-maximum-rows-in-oracle/391026#391026)
oracle subselect with dynamic table and column
[ "", "sql", "oracle", "" ]
Is there any way I can add a static extension method to a class. specifically I want to overload `Boolean.Parse` to allow an `int` argument.
In short, no, you can't. Long answer, extension methods are just syntactic sugar. IE: If you have an extension method on string let's say: ``` public static string SomeStringExtension(this string s) { //whatever.. } ``` When you then call it: ``` myString.SomeStringExtension(); ``` The compiler just turns it into: ``` ExtensionClass.SomeStringExtension(myString); ``` So as you can see, there's no way to do that for static methods. And another thing just dawned on me: what would really be the *point* of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do: ``` Bool.Parse(..) ``` vs. ``` Helper.ParseBool(..); ``` Doesn't really bring much to the table...
> specifically I want to overload `Boolean.Parse` to allow an int argument. Would an extension for int work? ``` public static bool ToBoolean(this int source){ // do it // return it } ``` Then you can call it like this: ``` int x = 1; bool y = x.ToBoolean(); ```
Static extension methods
[ "", "c#", "extension-methods", "" ]
In MySQL you can use the syntax ``` DELETE t1,t2 FROM table1 AS t1 INNER JOIN table2 t2 ... INNER JOIN table3 t3 ... ``` How do I do the same thing in SQL Server?
You can take advantage of the "deleted" pseudo table in this example. Something like: ``` begin transaction; declare @deletedIds table ( id int ); delete from t1 output deleted.id into @deletedIds from table1 as t1 inner join table2 as t2 on t2.id = t1.id inner join table3 as t3 on t3.id = t2.id; delete from t2 from table2 as t2 inner join @deletedIds as d on d.id = t2.id; delete from t3 from table3 as t3 ... commit transaction; ``` Obviously you can do an 'output deleted.' on the second delete as well, if you needed something to join on for the third table. As a side note, you can also do inserted.\* on an insert statement, and both inserted.\* and deleted.\* on an update statement. **EDIT:** Also, have you considered adding a trigger on table1 to delete from table2 + 3? You'll be inside of an implicit transaction, and will also have the "inserted.*" and "deleted.*" pseudo-tables available.
You can use JOIN syntax in FROM clause in DELETE in SQL Server but you still delete from first table only and it's proprietary Transact-SQL extension which is alternative to sub-query. From example [here](http://msdn.microsoft.com/en-us/library/ms189835.aspx): ``` -- Transact-SQL extension DELETE FROM Sales.SalesPersonQuotaHistory FROM Sales.SalesPersonQuotaHistory AS spqh INNER JOIN Sales.SalesPerson AS sp ON spqh.BusinessEntityID = sp.BusinessEntityID WHERE sp.SalesYTD > 2500000.00; ```
How do I delete from multiple tables using INNER JOIN in SQL server
[ "", "sql", "sql-server", "t-sql", "" ]
I was trying to erase a range of elements from map based on particular condition. How do I do it using STL algorithms? Initially I thought of using `remove_if` but it is not possible as remove\_if does not work for associative container. Is there any "remove\_if" equivalent algorithm which works for map ? As a simple option, I thought of looping through the map and erase. But is looping through the map and erasing a safe option?(as iterators get invalid after erase) I used following example: ``` bool predicate(const std::pair<int,std::string>& x) { return x.first > 2; } int main(void) { std::map<int, std::string> aMap; aMap[2] = "two"; aMap[3] = "three"; aMap[4] = "four"; aMap[5] = "five"; aMap[6] = "six"; // does not work, an error // std::remove_if(aMap.begin(), aMap.end(), predicate); std::map<int, std::string>::iterator iter = aMap.begin(); std::map<int, std::string>::iterator endIter = aMap.end(); for(; iter != endIter; ++iter) { if(Some Condition) { // is it safe ? aMap.erase(iter++); } } return 0; } ```
Almost. ``` for(; iter != endIter; ) { if (Some Condition) { iter = aMap.erase(iter); } else { ++iter; } } ``` What you had originally would increment the iterator *twice* if you did erase an element from it; you could potentially skip over elements that needed to be erased. This is a common algorithm I've seen used and documented in many places. [EDIT] You are correct that iterators are invalidated after an erase, but only iterators referencing the element that is erased, other iterators are still valid. Hence using `iter++` in the `erase()` call.
## erase\_if for std::map (and other containers) I use the following template for this very thing. ``` namespace stuff { template< typename ContainerT, typename PredicateT > void erase_if( ContainerT& items, const PredicateT& predicate ) { for( auto it = items.begin(); it != items.end(); ) { if( predicate(*it) ) it = items.erase(it); else ++it; } } } ``` This won't return anything, but it will remove the items from the std::map. Usage example: ``` // 'container' could be a std::map // 'item_type' is what you might store in your container using stuff::erase_if; erase_if(container, []( item_type& item ) { return /* insert appropriate test */; }); ``` Second example (allows you to pass in a test value): ``` // 'test_value' is value that you might inject into your predicate. // 'property' is just used to provide a stand-in test using stuff::erase_if; int test_value = 4; // or use whatever appropriate type and value erase_if(container, [&test_value]( item_type& item ) { return item.property < test_value; // or whatever appropriate test }); ```
remove_if equivalent for std::map
[ "", "c++", "stl", "dictionary", "" ]
Earlier today, I [asked a question](https://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop) about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples. I'd like to know more. How can I disassemble my own Python code?
Look at the [dis](http://docs.python.org/library/dis.html) module: ``` def myfunc(alist): return len(alist) >>> dis.dis(myfunc) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_FAST 0 (alist) 6 CALL_FUNCTION 1 9 RETURN_VALUE ```
Besides using `dis` as module, you can also run it as command line tool For example, on windows you can run: ``` c:\Python25\Lib\dis.py test.py ``` And it will output the disassembed result to console.
How do I disassemble a Python script?
[ "", "python", "debugging", "reverse-engineering", "" ]
I am trying to modify the amcap, an application from Windows SDK's example to capture video from UVC webcam having resolution 1600x1200px. I am trying to hardcode some variables here like filename, default resolution, type of format etc. ``` WCHAR wszCaptureFile[260]; gcap.wszCaptureFile = (WCHAR)"Capture.avi\0" //modified ``` gettnig error: > 1>.\amcap.cpp(3887) : error C2440: '=' > : cannot convert from 'WCHAR' to > 'WCHAR [260]' What can I do to correct this?
Provide a literal wide string and use the secure copy function: ``` wcscpy_s(gcap.wszCaptureFile, L"Capture.avi"); ``` The literal string provides the terminating zero bytes.
You cannot assign the array wszCaptureFile with = (as you have done). You can use the copy methods like [strcpy](http://msdn.microsoft.com/en-us/library/kk6xf663(VS.80).aspx). > wcscpy and \_mbscpy are wide-character > and multibyte-character versions of > strcpy ex: wcscpy( gcap.wszCaptureFile, L"Capture.avi");
cannot convert from 'WCHAR' to 'WCHAR [260]'
[ "", ".net", "c++", "visual-c++", "" ]
What is the difference between "`new`" and "`malloc`" and "`calloc`" and others in family? (When) Do I need anything other than "`new`" ? Is one of them implemented using any other?
`new` and `delete` are C++ specific features. They didn't exist in C. `malloc` is the old school C way to do things. Most of the time, you won't need to use it in C++. * `malloc` allocates uninitialized memory. The allocated memory has to be released with `free`. * `calloc` is like `malloc` but initializes the allocated memory with a constant (0). It needs to be freed with `free`. * `new` initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with `new` should be released with `delete` (which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, it's more modern and less prone to errors.
**`new`/`delete` + `new[]`/`delete[]`:** * `new`/`delete` is the C++ way to allocate memory and deallocate memory from the heap. * `new[]` and `delete[]` is the C++ way to allocate arrays of contiguous memory. * Should be used because it is more type safe than `malloc` * Should be used because it calls the constructor/destructor * Cannot be used in a `realloc` way, but can use placement new to re-use the same buffer of data * Data cannot be allocated with `new` and freed with `free`, nor `delete[]` **`malloc`/`free` + family:** * `malloc`/`free`/family is the C way to allocate and free memory from the heap. * `calloc` is the same as `malloc` but also initializes the memory * Should be used if you may need to reallocate the memory * Data cannot be allocated with `malloc` and freed with delete nor delete[] Also see my [related answer here](https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new/184540#184540)
What is the difference between "new" and "malloc" and "calloc" in C++?
[ "", "c++", "memory-management", "malloc", "heap-memory", "" ]
Having some issues getting my head around the differences between UTF-8, UTF-16, ASCII and ANSI. After doing some research I have some idea but it would be really useful if someone could explain exactly the difference between them (including the byte representation of a typical character from each). I quess my question boils down to > ``` > 1) How do each of the above store characters as bytes > 2) What are the differences between the above standards > 3) What is a code page > 4) Method of converting characters between the various types. > ``` Many many thanks :)
I've found [Joel's article](http://www.joelonsoftware.com/articles/Unicode.html) on Unicode to explain this very well. Specifically it covers the history (essential for this subject), encodings (UTF-8/16 etc.) and code pages.
To quickly attempt to answer your specific questions. 1: A certain combination of bits represents a certain character. A single character may be stored in multiple bytes. 2: Brief information on and differences between the encodings you mentioned. **ASCII** Includes definitions for 128 characters. **ANSI** Has more characters than ASCII, but still fits in an octet. Requires a code page. **UTF-8** This can be used to represent any Unicode character. There are many many more Unicode characters than there are ASCII ones. It stores each character in one to four octets of data. **UTF-16** Similar to UTF-8 but the basic unit is 16 bits. If you're just using English then you're wasting 8 bits on every character. 3: A code page is what specifies to the computer which (combination of bits) refers to which character. Unicode does not need code pages since each character has it's own unique bit combination. ANSI has code pages because it only has 256 available characters. For example if you were on an Arabic computer you would have Arabic set as the code page and Arabic characters could be displayed. 4: The method of conversion depends on the character set you are converting to and from and the code pages used (if any). Some conversions may not be possible. UTF-8 is backward compatible with ASCII, meaning if your text only includes the first 128 US characters it's exactly the same as the same text in ASCII encoding. This answer was ad-hoc and there may be mistakes, corrections welcome.
Character encoding confusion!
[ "", "c++", "unicode", "character", "encoding", "" ]
In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc. While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language. Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules? **EDIT:** I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.
Here are a couple of links to give you an idea on what you're up against: * [How can I run an untrusted Python script safely (i.e. Sandbox)](https://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20(i.e.%20Sandbox)) * [Capabilities for Python?](http://neopythonic.blogspot.com/2009/03/capabilities-for-python.html) by Guido himself There is also a dead google code project at <http://code.google.com/p/sandbox-python/>
The pypy project offers sandboxing features, see <http://doc.pypy.org/en/latest/sandbox.html> .
Is there a "safe" subset of Python for use as an embedded scripting language?
[ "", "python", "security", "scripting", "scripting-language", "embedded-language", "" ]
I am using a *javax.servlet.http.HttpServletRequest* to implement a web application. I have no problem to get the parameter of a request using the *getParameter* method. However I don't know how to set a parameter in my request.
You can't, not using the standard API. `HttpServletRequest` represent a request received by the server, and so adding new parameters is not a valid option (as far as the API is concerned). You could in principle implement a subclass of `HttpServletRequestWrapper` which wraps the original request, and intercepts the `getParameter()` methods, and pass the wrapped request on when you forward. If you go this route, you should use a `Filter` to replace your `HttpServletRequest` with a `HttpServletRequestWrapper`: ``` public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (servletRequest instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) servletRequest; // Check wether the current request needs to be able to support the body to be read multiple times if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) { // Override current HttpServletRequest with custom implementation filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse); return; } } filterChain.doFilter(servletRequest, servletResponse); } ```
If you really want to do this, create an HttpServletRequestWrapper. ``` public class AddableHttpRequest extends HttpServletRequestWrapper { private HashMap params = new HashMap(); public AddableingHttpRequest(HttpServletRequest request) { super(request); } public String getParameter(String name) { // if we added one, return that one if ( params.get( name ) != null ) { return params.get( name ); } // otherwise return what's in the original request HttpServletRequest req = (HttpServletRequest) super.getRequest(); return validate( name, req.getParameter( name ) ); } public void addParameter( String name, String value ) { params.put( name, value ); } } ```
How to set a parameter in a HttpServletRequest?
[ "", "java", "web-applications", "" ]
I've got a very simple map : ``` std::map<int, double> distances; distances[20.5] = 1; distances[19] = 2; distances[24] = 3; ``` How do i know if there isn't any returned value, when using a map::upper\_bound() in this case for example: ``` std::map<int, double>::iterator iter = distances.upper_bound(24); ``` (24 is the max key so an unexpected result is returned, but how to know that through the code ? How to know i've reached the max key ?). Thanks !
``` if (iter == distances.end()) // no upper bound ```
Most iterators in C++ will be set to the end of the collection to represent an absent value. This is the only valid value for an iterator to represent "no more data". So you can compare `iter` with `distances.end()`, and if they are equal, then you've got your answer.
C++ - How to know if there is no returned value from a map::upper_bound()?
[ "", "c++", "stl", "" ]
Is there a way to retrieve first n elements from a Dictionary in C#?
Note that there's no explicit ordering for a `Dictionary`, so although the following code will return `n` items, there's no guarantee as to how the framework will determine which `n` items to return. ``` using System.Linq; yourDictionary.Take(n); ``` The above code returns an `IEnumerable<KeyValuePair<TKey,TValue>>` containing `n` items. You can easily convert this to a `Dictionary<TKey,TValue>` like so: ``` yourDictionary.Take(n).ToDictionary(); ```
Dictionaries are not ordered *per se*, you can't rely on the "first" actually meaning that. From MSDN: "For enumeration... The order in which the items are returned is undefined." You may be able to use an [OrderedDictionary](http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx) depending on your platform version, and it's not a particularly complex thing to create as a custom descendant class of Dictionary.
How can I retrieve first n elements from Dictionary<string, int>?
[ "", "c#", "dictionary", "" ]
How do I use Visual Studio to develop applications on Mono? Is this possible?
You just build the applications in Visual Studio, and run them under Mono instead of under .NET. The binaries should be compatible... but you'll need to make sure you don't use any libraries which aren't available in Mono - see the [Mono Application Compatibility Guidelines](http://mono-project.com/Guidelines:Application_Portability). (According to that page, you need to turn off incremental builds in Visual Studio though - a point I wasn't aware of before :)
See [this](http://tirania.org/blog/archive/2006/Feb-25.html) article on how to run your apps while targeting the mono framework from VS.
Using visual studio for developing mono applications
[ "", "c#", "visual-studio", "visual-studio-2008", "mono", "" ]
I am trying to change the bindingRedirect element at install time by using the XmlDocument class and modifying the value directly. Here is what my app.config looks like: ``` <configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> ... </sectionGroup> </configSections> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="MyDll" publicKeyToken="31bfe856bd364e35"/> <bindingRedirect oldVersion="0.7" newVersion="1.0"/> </dependentAssembly> </assemblyBinding> </runtime> ... </configuration> ``` I then try to use the following code to change 1.0 to 2.0 ``` private void SetRuntimeBinding(string path, string value) { XmlDocument xml = new XmlDocument(); xml.Load(Path.Combine(path, "MyApp.exe.config")); XmlNode root = xml.DocumentElement; if (root == null) { return; } XmlNode node = root.SelectSingleNode("/configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect/@newVersion"); if (node == null) { throw (new Exception("not found")); } node.Value = value; xml.Save(Path.Combine(path, "MyApp.exe.config")); } ``` However, it throws the 'not found' exception. If I back the path up to /configuration/runtime it works. However once I add assemblyBinding, it does not find the node. Possibly this has something to do with the xmlns? Any idea how I can modify this? ConfigurationManager also does not have access to this section.
I found what I needed. The XmlNamespaceManager is required as the assemblyBinding node contains the xmlns attribute. I modified the code to use this and it works: ``` private void SetRuntimeBinding(string path, string value) { XmlDocument doc = new XmlDocument(); try { doc.Load(Path.Combine(path, "MyApp.exe.config")); } catch (FileNotFoundException) { return; } XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1"); XmlNode root = doc.DocumentElement; XmlNode node = root.SelectSingleNode("//bindings:bindingRedirect", manager); if (node == null) { throw (new Exception("Invalid Configuration File")); } node = node.SelectSingleNode("@newVersion"); if (node == null) { throw (new Exception("Invalid Configuration File")); } node.Value = value; doc.Save(Path.Combine(path, "MyApp.exe.config")); } ```
Sounds like you've got your configuration file tweak working now, but I thought you might still be interested in how to adjust binding redirects at run time. The key is to use the [AppDomain.AssemblyResolve](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx) event, and the details are in [this answer](https://stackoverflow.com/questions/1460271/how-to-use-assembly-binding-redirection-to-ignore-revision-and-build-numbers/2344624#2344624). I prefer it over using the configuration file, because my version number comparison can be a bit more sophisticated and I don't have to tweak the configuration file during every build.
How to programmatically modify assemblyBinding in app.config?
[ "", "c#", "xml", "configuration", "configuration-files", "xmldocument", "" ]
I've got a SQL Server table with about 50,000 rows in it. I want to select about 5,000 of those rows at random. I've thought of a complicated way, creating a temp table with a "random number" column, copying my table into that, looping through the temp table and updating each row with `RAND()`, and then selecting from that table where the random number column < 0.1. I'm looking for a simpler way to do it, in a single statement if possible. [This article](http://www.sql-server-helper.com/tips/generate-random-numbers.aspx) suggest using the `NEWID()` function. That looks promising, but I can't see how I could reliably select a certain percentage of rows. Anybody ever do this before? Any ideas?
``` select top 10 percent * from [yourtable] order by newid() ``` In response to the "pure trash" comment concerning large tables: you could do it like this to improve performance. ``` select * from [yourtable] where [yourPk] in (select top 10 percent [yourPk] from [yourtable] order by newid()) ``` The cost of this will be the key scan of values plus the join cost, which on a large table with a small percentage selection should be reasonable.
Depending on your needs, `TABLESAMPLE` will get you nearly as random and better performance. this is available on MS SQL server 2005 and later. `TABLESAMPLE` will return data from random pages instead of random rows and therefore deos not even retrieve data that it will not return. On a very large table I tested ``` select top 1 percent * from [tablename] order by newid() ``` took more than 20 minutes. ``` select * from [tablename] tablesample(1 percent) ``` took 2 minutes. Performance will also improve on smaller samples in `TABLESAMPLE` whereas it will not with `newid()`. Please keep in mind that this is not as random as the `newid()` method but will give you a decent sampling. See the [MSDN page](http://msdn.microsoft.com/en-us/library/ms189108.aspx).
Select n random rows from SQL Server table
[ "", "sql", "sql-server", "random", "" ]
I have a synchronous web service call that returns a message. I need to quickly return a message that basically says that order was received. I then need to spend a couple of minutes processing the order, but cannot block the service call for that long. So how can I return from the web service, and then do some more stuff? I'm guessing I need to fork some other thread or something before I return, but I'm not sure of the best approach. ``` string ProcessOrder(Order order) { if(order.IsValid) { return "Great!"; //Then I need to process the order } } ```
You can open a new thread and have it do what you need, while you're main thread returns great. ``` string ProcessOrder(Order order) { if(order.IsValid) { //Starts a new thread ThreadPool.QueueUserWorkItem(th => { //Process Order here }); return "Great!"; } } ```
You could start your big amount of work in a seperate thread ``` public string ProcessOrder(Order order) { if(order.IsValid) { System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(DoHardWork); System.Threading.Thread t = new System.Threading.Thread(pts); t.Start(order); return "Great!!!"; } } public void DoHardWork(object order) { //Stuff Goes Here } ```
How can I return a response from a WCF call and then do more work?
[ "", "c#", ".net", "wcf", "multithreading", "" ]
How can I set an environment variable in WSH jscript file that calls another program? Here's the reduced test case: ``` envtest.js ---------- var oShell = WScript.CreateObject("WScript.Shell"); var oSysEnv = oShell.Environment("SYSTEM"); oSysEnv("TEST_ENV_VAR") = "TEST_VALUE"; oExec = oShell.Run("envtest.bat", 1, true); envtest.bat ----------- set pause ``` I expect to see TEST\_ ENV \_VAR in the list of variables, but it's not there. What's wrong? edit: If someone can produce a working code sample, I'll mark that as the correct answer. :)
The problem is not in your code, but it is in execution of the process. The complete system variables are assigned to the process which is executed. so, your child process also had the same set of variables. Your code-sample works good. It adds the variable to the SYSTEM environment. So, you need to set the variable not only for your system but also for your process. Here's the code. ``` var oShell = WScript.CreateObject("WScript.Shell"); var oSysEnv = oShell.Environment("SYSTEM"); oSysEnv("TEST1") = "TEST_VALUE"; var oSysEnv = oShell.Environment("PROCESS"); oSysEnv("TEST1") = "TEST_VALUE"; oExec = oShell.Run("envtest.bat", 1, true); ``` Once you created the system variable. It will assign the newly created variable for the current process. So, your child process can get that variable while the "SET" command executed. Sorry for my bad-english.
There are 4 "collections" (System, User, Volatile, and Process) you probably want Process if you just need a child process to see the variable
Setting an environment variable in javascript
[ "", "javascript", "environment", "batch-file", "wsh", "" ]
I am working on porting an existing VB.Net application to Java, and could not find an equivalent to Random.Next(Int32, Int32). I could find only `java.util.Random.next(int val)` in the Java API. Is there an Equivalent of .Net framework's Random.Next(Int32, Int32) in the Java API?
As Marc says, just adapt `Random.nextInt(int)`, with a couple of sanity checks: ``` public static int nextInt(Random rng, int lower, int upper) { if (upper < lower) { throw new IllegalArgumentException(); } if ((long) upper - lower > Integer.MAX_VALUE) { throw new IllegalArgumentException(); } return rng.nextInt(upper-lower) + lower; } ```
no but you can have it this way: ``` public static int randomInRange(int min, int max){ return min+Random.next(max-min); } ```
Is there an Equivalent of .Net framework's Random.Next(Int32, Int32) in the Java API?
[ "", "random", "java", "" ]
In the application I am writing, I need to write lots of base types, which will most likely be immutable. But I am wondering how mutable types compare in parallel applications to immutable ones. You can use locks with mutable objects, right? How does it compare to other techniques used with immutable types in parallel applications? You are at least away from using locks with immutable types, right?
Types * Use immutable types as much as possible. * Use thread-safe collections instead of explicit locks as much as possible. * Only use mutable types when you have no other reasonable choice. Threads * Use thread pools as much as possible. * Use endless loops when thread pools aren't possible. * Manually start and stop threads as a last resort. If you do have to use explicit locks, document them throughly. Especially when it comes to the order in which you lock objects. If you know that Foo objects are always locked before Bar objects and that Foo(key 100) is always locked before Foo(key = 200), you won't get deadlocks.
The key to writing parallelizable applications is to stay away from mutable shared state. Sharing mutable state between threads requires synchronization which typically entails some form of locking. Using immutable types can help ensure that you are not accidentally sharing state, by making it impossible to change the state of those objects. However, this is not a magic bullet, but simply a design choice. If the algorithm you are attempting to parallelize requires shared state, you are going to have to create some sort of synchronization. Mutability does not affect locking.
Mutable vs Immutable for parallel applications
[ "", "c#", ".net", "parallel-processing", "immutability", "mutable", "" ]
What's the best way going forward to implement Wake on LAN using C#? The functionality is needed for machines in a LAN environment (and not over the internet). The method needs to be robust enough to take care of firewalls and other such issues. Also, for systems not supporting this functionality, or having it disabled, is there an alternative? The primary objective - wake up machines (from shutdown/hibernate state) over the LAN - this is to be programmed using C#. Please guide. PS: I've come across the following: 1. <http://blog.memos.cz/index.php/team/2008/06/12/wake-on-lan-in-csharp> 2. <http://community.bartdesmet.net/blogs/bart/archive/2006/04/02/3858.aspx> 3. <http://www.codeproject.com/KB/IP/cswol.aspx> However, I'm new to this and hence couldn't figure if the solutions were comprehensive enough. If someone could recommend following either of the above articles, that'd help.
For the WOL problem you have to clarify three problems to get it to work: 1. Send a WOL over the ethernet cable 2. Configure your PC to listen for such a packet and wake up 3. Make sure the packet will come from sender to receiver (firewall, gateways, etc.) As you already found on the net there are existing several solutions for the first problem programmed in C# (and after skimming your links, I would start with the first one). The second one is something you can only achieve by configuring your network adapter. Just open the device manager and take a look into the properties of your network adapter, if such an option exists and if you can enable it. This can't be programmed, due to the fact that every network adapter has another implementation of that function and how it can be enabled. The third problem can't also be solved by C#. It is a pure network problem, where you have to configure your router, gateways, ids-systems, etc. to allow such a packet and let it flow from sender to receiver. Due to the fact, that a WOL packet is always a broadcast packet (dest-ip 255.255.255.255) it won't leave your local network and will always be dropped from router, gateways or any other bridge between to networks (e.g. vpns, etc.). Last but not least, I will just remind you, that the first problem can be divided into some smaller packets but as far as I could see these problems are all capped by the links you provided.
Very old question, I know, but still valid. Since I didn't see any C# in the accepted answer, I wrote my own 'Wake On Lan' code. My goal was to make a **universal and easy `Wake On Lan class`** that: * works with *ipv4*, *ipv6* and *dual-stack*. * works with *one or multiple network cards* (NICS) connected to different networks (both computers). * works with *macaddress* in any standard hex format. * works using *multicast* (broadcast is buggy in Windows when using multiple NICs and is not supported when using ipv6). **How to use:** All you need, is the **MAC address** of the **wired** nic on the computer you wish to wake up. Any standard hex representation will do. Then call the code like this: ``` string mac = "01-02-03-04-05-06"; await WOL.WakeOnLan(mac); ``` **Here's the class:** ``` using System; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Threading.Tasks; public static class WOL { public static async Task WakeOnLan(string macAddress) { byte[] magicPacket = BuildMagicPacket(macAddress); foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces().Where((n) => n.NetworkInterfaceType != NetworkInterfaceType.Loopback && n.OperationalStatus == OperationalStatus.Up)) { IPInterfaceProperties iPInterfaceProperties = networkInterface.GetIPProperties(); foreach (MulticastIPAddressInformation multicastIPAddressInformation in iPInterfaceProperties.MulticastAddresses) { IPAddress multicastIpAddress = multicastIPAddressInformation.Address; if (multicastIpAddress.ToString().StartsWith("ff02::1%", StringComparison.OrdinalIgnoreCase)) // Ipv6: All hosts on LAN (with zone index) { UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) => u.Address.AddressFamily == AddressFamily.InterNetworkV6 && !u.Address.IsIPv6LinkLocal).FirstOrDefault(); if (unicastIPAddressInformation != null) { await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket); break; } } else if (multicastIpAddress.ToString().Equals("224.0.0.1")) // Ipv4: All hosts on LAN { UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) => u.Address.AddressFamily == AddressFamily.InterNetwork && !iPInterfaceProperties.GetIPv4Properties().IsAutomaticPrivateAddressingActive).FirstOrDefault(); if (unicastIPAddressInformation != null) { await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket); break; } } } } } static byte[] BuildMagicPacket(string macAddress) // MacAddress in any standard HEX format { macAddress = Regex.Replace(macAddress, "[: -]", ""); byte[] macBytes = new byte[6]; for (int i = 0; i < 6; i++) { macBytes[i] = Convert.ToByte(macAddress.Substring(i * 2, 2), 16); } using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { for (int i = 0; i < 6; i++) //First 6 times 0xff { bw.Write((byte)0xff); } for (int i = 0; i < 16; i++) // then 16 times MacAddress { bw.Write(macBytes); } } return ms.ToArray(); // 102 bytes magic packet } } static async Task SendWakeOnLan(IPAddress localIpAddress, IPAddress multicastIpAddress, byte[] magicPacket) { using (UdpClient client = new UdpClient(new IPEndPoint(localIpAddress, 0))) { await client.SendAsync(magicPacket, magicPacket.Length, multicastIpAddress.ToString(), 9); } } } ``` **How it works:** The code works by enumerating all network cards that are 'up' and connected to your network (that's usually just one). It will send out the 'magic packet' to all your connected networks using multicast, which works with both ipv4 and ipv6 (don't worry about flooding your network, it's only 102 bytes). To work, the computer, you want to wake up, must have a **wired** connection (wireless computers can't be woken up, since they aren't connected to any network, when they are off). The computer, that sends the packet, can be wireless connected. Firewalls are usually no problem, since the computer is off and hence the firewall is not active. **You must make sure that `'Wake on lan'` is `enabled` in the computer's `BIOS` and on the network card.** **Update for .Net 6 (and a bug fix):** Fixed a bug, where if Ipv6 was functioning on the computer that sends the packet but not on the one, that should be awakened, then it would not try Ipv4 (this is fixed in the code above). Here's the code that works on .Net 6 (borrowed some of @Oskar Sjôberg's code) - `implicit usings turned on`: ``` using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text.RegularExpressions; public static class WOL { public static async Task WakeOnLan(string macAddress) { byte[] magicPacket = BuildMagicPacket(macAddress); foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces().Where((n) => n.NetworkInterfaceType != NetworkInterfaceType.Loopback && n.OperationalStatus == OperationalStatus.Up)) { IPInterfaceProperties iPInterfaceProperties = networkInterface.GetIPProperties(); foreach (MulticastIPAddressInformation multicastIPAddressInformation in iPInterfaceProperties.MulticastAddresses) { IPAddress multicastIpAddress = multicastIPAddressInformation.Address; if (multicastIpAddress.ToString().StartsWith("ff02::1%", StringComparison.OrdinalIgnoreCase)) // Ipv6: All hosts on LAN (with zone index) { UnicastIPAddressInformation? unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) => u.Address.AddressFamily == AddressFamily.InterNetworkV6 && !u.Address.IsIPv6LinkLocal).FirstOrDefault(); if (unicastIPAddressInformation != null) { await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket); } } else if (multicastIpAddress.ToString().Equals("224.0.0.1")) // Ipv4: All hosts on LAN { UnicastIPAddressInformation? unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) => u.Address.AddressFamily == AddressFamily.InterNetwork && !iPInterfaceProperties.GetIPv4Properties().IsAutomaticPrivateAddressingActive).FirstOrDefault(); if (unicastIPAddressInformation != null) { await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket); } } } } } static byte[] BuildMagicPacket(string macAddress) // MacAddress in any standard HEX format { macAddress = Regex.Replace(macAddress, "[: -]", ""); byte[] macBytes = Convert.FromHexString(macAddress); IEnumerable<byte> header = Enumerable.Repeat((byte)0xff, 6); //First 6 times 0xff IEnumerable<byte> data = Enumerable.Repeat(macBytes, 16).SelectMany(m => m); // then 16 times MacAddress return header.Concat(data).ToArray(); } static async Task SendWakeOnLan(IPAddress localIpAddress, IPAddress multicastIpAddress, byte[] magicPacket) { using UdpClient client = new(new IPEndPoint(localIpAddress, 0)); await client.SendAsync(magicPacket, magicPacket.Length, new IPEndPoint(multicastIpAddress, 9)); } } ```
Wake on LAN using C#
[ "", "c#", "wake-on-lan", "" ]
I have a table and I am hiding some rows. I want to get the first td in all of the rows that are showing. I have the following statement ``` $("table.SimpleTable tbody tr:visible td:first-child"); ``` this works in FireFox but not in IE any ideas?
I am running the code on a click event. The html that you have written is pretty much spot on but for the some reason unknown to me it is not working. I have found a work around though. (I am trying to get a comma delimited string of all values in the first td for the visible rows) Anyway the following work around gets the job done. ``` var notfirst = false; var serials = ""; var tds = $("table.SimpleTable tbody tr:visible td:first-child"); for (var i = 0; i < tds.length; i++) { var td = $(tds[i]); if (td.is(":hidden")) continue; if (notfirst) serials += ","; else notfirst = true; serials += $.trim(td.text()); } ``` For some reason the :hidden tag works correctly but not the :visible in IE7
That *should* work. With HTML that looks like this: ``` <table class='SimpleTable'> <tr style='display: none;'> <td>test1</td> </tr> <tr> <td>test2</td> </tr> <tr> <td>test3</td> </tr> <tr style='display: none;'> <td>test4</td> </tr> <tr> <td>test5</td> </tr> <tr> <td>test6</td> </tr> </table> ``` Doing this: ``` $("table.SimpleTable tbody tr:visible td:first-child").css('color','red'); ``` Makes the color red in Firefox, IE7 for me. What does your HTML look like? [Here's what I tested the above on](http://jsbin.com/ekuyu) **EDIT**: It is very weird to me that you need to do what you're doing right now. You should be able to replace what you have right now with this: ``` var serials = []; $("table.SimpleTable tbody tr:visible td:first-child").each(function() { serials.push($.trim($(this).text())); }); var serials = serials.join(','); ``` If the TDs are being populated from the selector they should only be the visible ones. If you are getting hidden TDs into the serials (which, I must stress, should really not be happening and is a bug or a sign of an error somewhere), try this selector instead: ``` $("table.SimpleTable tbody tr:not(:hidden) td:first-child") ```
jQuery error?? How to get the first "td" in all rows that are visible
[ "", "javascript", "jquery", "" ]
I have a very large possible data set that I am trying to visualize at once. The set itself consists of hundreds of thousands of segments, each of which is mapped to an id. I have received a second data source that gives more real-time information for each segment, but the id's do not correspond to the id's I have. I have a 1:1 mapping of the data id's (9-character strings) to the current id's (long integers). The problem is that there are a lot of id's, and the data that is coming in is in no specific order. The solution I came up with is to have a hash-map that maps the strings to the road id's. The problem is that I don't know if the hash-map will be efficient enough to have all 166k data entries. Does anyone have any suggestions and/or hashing algorithms that I can use for this?
If you're only dealing with hundreds of thousands of datapoints, it will likely not be a problem to go with the naive way and just stick with a hash-map. Even if you have 500,000 9-character strings and an equal number of `long`s, that still only 16ish bytes per item, or 8,000,000 bytes total. Even if you double that for overhead, 16 MB is hardly too big to have in memory at one time. Basically, try the easy way first, and only worry about it when your profiling tells you it's taking too long.
[Judy Arrays](http://judy.sourceforge.net/) are designed for this sort of thing: "Judy's key benefits are scalability, high performance, and memory efficiency. [...] Judy can replace many common data structures, such as arrays, sparse arrays, hash tables, B-trees, binary trees, linear lists, skiplists, other sort and search algorithms, and counting functions."
Using Hash Maps to represent an extremely large data source
[ "", "c++", "stl", "hashmap", "hash", "" ]
I wrote a small internal web app using (a subset of) [pylons](http://pylonshq.com/). As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes. What is the simplest way I can make sure this site is securely available to that user, but no one else? I'm thinking something like apache's simple HTTP authentication, but more secure. (Is OpenID a good match?) There is only one user. No need for any user management, not even to change password. Also, I trust the user not to damage the server (it's actually his). If it was for me, I would just keep it behind the firewall and use ssh port forwarding, but I would like to have something simpler for this user. **EDIT**: Hmm... judging by the answers, this should have been on serverfault. If a moderator is reading this, consider migrating it.
if there's only a single user, [using a certificate](http://impetus.us/~rjmooney/projects/misc/clientcertauth.html) would probably be easiest.
How about VPN? There should be plenty of user-friendly VPN clients. He might already be familiar with the technology since many corporations use them to grant workers access to internal network while on the road.
Dead-simple web authentication for a single user
[ "", "python", "security", "authentication", "web-applications", "" ]
I'm using POI HSSF API for my excel manipulations in Java. I've a date value "8/1/2009" in one of my excel cell and while I try to read this value using HSSF API, it detects the cell type as Numeric and returns the 'Double' value of my date. See the sample code below: ``` cell = row.getCell(); // date in the cell '8/1/2009' switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getRichStringCellValue().getString(); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = new Double(cell.getNumericCellValue()).toString(); break; default: } ``` Cell.getCellType() returns NUMERIC\_TYPE and thus this code converts the date to double! :( Is there any way to read the date as it is in HSSF POI !?
You could take a look at: ``` HSSFDateUtil.isCellDateFormatted() ``` See the POI Horrible Spreadsheet Format API for more details on HSSFDateUtil: <http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html> That also provides some helper methods for returning Excel `getExcelDate()` and Java dates `getJavaDate()`. You need to be somewhat wary of different date formats though...
If you want to reference the date in the same format in as in the Excel file, you should use the CellDateFormatter. Sample code: ``` CellValue cValue = formulaEv.evaluate(cell); double dv = cValue.getNumberValue(); if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = HSSFDateUtil.getJavaDate(dv); String dateFmt = cell.getCellStyle().getDataFormatString(); /* strValue = new SimpleDateFormat(dateFmt).format(date); - won't work as Java fmt differs from Excel fmt. If Excel date format is mm/dd/yyyy, Java will always be 00 for date since "m" is minutes of the hour.*/ strValue = new CellDateFormatter(dateFmt).format(date); // takes care of idiosyncrasies of Excel } ```
Reading date values from excel cell using POI HSSF API
[ "", "java", "excel", "apache-poi", "poi-hssf", "" ]
I would like to send a html string with a GET request like this with Apaches HttpClient: ``` http://sample.com/?html=<html><head>... ``` This doesnt work at the moment, i think its an encoding problem. Do you have any ideas how to do that? ``` method.setQueryString(new NameValuePair[] {new NameValuePair("report", "<html>....")}); client.executeMethod(method) ``` This fails with `org.apache.commons.httpclient.NoHttpResponseException: The server localhost failed to respond`. If i replace `"<html>"` by "test.." it works fine. **EDIT** It seams to be a problem of URL length after encoding, the server doesnt except such long URls. Sending it as POST solves the problem.
Try using URL Encoding to format your html string first. ``` String yourHtmlString = java.net.URLEncoder.encode("<html>...."); method.setQueryString(new NameValuePair[] {new NameValuePair("report", yourHtmlString)}); ```
I'd go with base64 encoding and maybe some sort of compression before it depending on the length of your content given: RFC 2068 states: Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths. The spec for URL length does not dictate a minimum or maximum URL length, but implementation varies by browser. On Windows: Opera supports ~4050 characters, IE 4.0+ supports exactly 2083 characters, Netscape 3 -> 4.78 support up to 8192 characters before causing errors on shut-down, and Netscape 6 supports ~2000 before causing errors on start-up.
How to send HTML as GET-Request parameter?
[ "", "java", "http", "encoding", "httpclient", "" ]
``` int main() { int var = 0;; // Typo which compiles just fine } ``` In both C and C++, this is allowed because an *[expression-statement](https://eel.is/c++draft/stmt.expr#nt:expression-statement)* may be just a `;`, which makes it a "null statement". Why is this allowed?
This is the way C and C++ express [NOP](http://en.wikipedia.org/wiki/NOP).
How else could `assert(foo == bar);` compile down to nothing when `NDEBUG` is defined?
Why are empty statements legal?
[ "", "c++", "c", "syntax", "language-design", "" ]
I want to load and instantiate classes located in my App\_Code folder at run-time. The classes implements `IModule`: ``` public interface IModule { String Test(); } ``` A test class: ``` // ~/App_Code/Test.cs namespace ModuleManagementSystem { class Test : IModule { public String Test() { return "Testing! One, two, thee!"; } } } ``` The class-files are uploaded by the system users and acts as modules. The class-name of the modules will always be the same as the module filename. I am looking for functioning example-code. I will place a bounty as soon as I am able to. ## **Update:** ``` namespace ModuleManagementSystem { public sealed class Compile { public void ToDLL(String sourcefile, String outputfile) { var compilerResults = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromFile( new CompilerParameters { OutputAssembly = outputfile, GenerateInMemory = false, TreatWarningsAsErrors = false, GenerateExecutable = false, }, sourcefile ); } } } ``` The above works fine for: ``` // ~/App_Code/Test.cs public class Test { // ... } ``` But if I implement my `IModule` interface: ``` namespace ModuleManagementSystem { public interface IModule { String HelloWorld(); } } ``` I get the following error: > {c:\inetpub\wwwroot\ModuleManagementSystemWeb\App\_Code\Test.cs(4,21) > : error CS0246: The type or namespace > name 'ModuleManagementSystem' could > not be found (are you missing a using > directive or an assembly > reference?)} System.CodeDom.Compiler.CompilerError Both the `IModule` interface and `Compile` class is located in the same class library, which is referenced from a web application: <http://roosteronacid.com/ModuleManagementSystem.jpg>
I decided that classes which loads at run-time has to implement a given interface and that the name of the class has to be the same as the filename. The folder the classes are uploaded to and compiled to is irrelevant. **Loading a compiled class (.dll) and instantiating it:** ``` return (IInterfaceClassesMustImplement)Assembly /* continued --> */ .LoadFile("c:\...\SomeClass.dll") /* continued --> */ .CreateInstance("SomeClass"); ``` **Compile a class:** ``` internal static class Compiler { internal static void AssemblyFromFile( String classFilePath, String assemblyFilePath, String[] referencedAssemblies ) { var cp = new CompilerParameters { OutputAssembly = assemblyFilePath }; foreach (String ra in referencedAssemblies) { cp.ReferencedAssemblies.Add(ra); } CompilerResults cr = CodeDomProvider.CreateProvider("CSharp") /* continued --> */ .CompileAssemblyFromFile(cp, classFilePath); if (cr.Errors.Count > 0) // throw new Exception(); } } ```
It strikes me as a bad idea to actually upload into your App\_Code folder. I'd use a separate folder which ASP.NET doesn't know anything about. That way you won't get the framework trying to automatically compile code for you. You can easily compile and run code on the fly with [`CSharpCodeProvider`](http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx) - see [my source code for Snippy](http://csharpindepth.com/Downloads.aspx) for an example. I hope this is only for internal (and authenticated) use though - I wouldn't recommend letting untrusted users execute their code on your web server. You can make it all *slightly* safer by running the code which very much reduced permissions, but you still risk the code tight-looping etc. EDIT: In response to your updated question, you just need to provide the appropriate assembly to reference, containing `IModule`. See the `CompilerParameters.ReferencedAssembles` property.
List, load and instantiate unknown classes in App_Code at run-time
[ "", "c#", "" ]
I have some code using a `System.Transactions.TransactionScope`, that creating a new instance of the transaction scope simply halts the program. There are no exceptions or messages, the program simply stops and Visual Studio returns to code editing mode. The process is completely gone. There are no exceptions, messages or events in the event viewer. I have another test app that uses TransactionScope with no problem, so it shouldn't be an environment issue. I just don't know how to get the exception detail. I've turned on all the "thrown" checkboxes in the Debug->Exceptions dialog within Visual Studio, hoping that VS would automatically break when the exception was thrown, but it doesn't. Can anyone help me get the reason for the program exiting? **EDIT:** I just found something new. The TransactionScope is being created in a method running on a background thread via `ThreadPool.QueueUserWorkItem`. If I just call the method directly on the main application thread, this problem goes away. So now my question is "what is the problem with using TransactionScope on a threadpool thread?". Note I'm *not* starting a transaction scope *before* invoking the new thread, it's all within one method running on the threadpool thread.
I've found the problem. It was the squishy organic component that operates my computer. `ThreadPool.QueueUserWorkItem()` will start work on a threadpool thread. Which means a [background thread](http://msdn.microsoft.com/en-us/library/h339syd0.aspx). The code was running in a test console application, and of course I'd forgotten to put anything in `Main()` to stop the program exiting after it called `ThreadPool.QueueUserWorkItem()`. This meant that by the time I got to pressing F10 to step to the next line, the program had actually already stopped, so the debugger closed itself. All I did to fix it was add a call to `Console.ReadKey()` at the end of `Program.Main()` and now it all works beautifully. Note that the problem had nothing to do with `System.Transactions.TransactionScope` or threadpool threads. It would've happened no matter what line I put my breakpoint on. **Note**: If you're thinking I should've seen a `ThreadAbortException`, then reading the article linked above will point out why that didn't happen. Here's a direct quote: > When the runtime stops a background > thread because the process is shutting > down, no exception is thrown in the > thread. However, when threads are > stopped because the AppDomain.Unload > method unloads the application domain, > a ThreadAbortException is thrown in > both foreground and background > threads.
One wild guess: the Microsoft Distributed Transaction Coordinator service (MSDTC) is stopped? That is the case by default on Vista, for example. Still, I would have expected an exception to be thrown, so I am not sure why you observe that behavior.
new System.Transactions.TransactionScope() on background thread halts program
[ "", "c#", "crash", "transactionscope", "" ]
I have a large string, similar to this one: > BREW pot HTCPCP/1.0 > > Accept-Additions: #milk;3#whiskey;splash > > Content-Length: 5 > > Content-Type: message/coffeepot I also have an array with several additions (#whiskey, #espresso, etc). What I need to do is send an error if this large string contains an addition that is NOT in the array of available additions. For example, if the "Accept-Additions" part of the string contained "#bricks;3" an error was produced as it is not in the array. How would I go about this in Java? I'm having trouble implementing this part, although I've coded the rest of the program (which many of you may recognise). How would I code the following problem, with emphasis on the addition not being available?
This code makes a few assumptions about the input. It does look like you could split each token up even further into #; components. Using a List for your acceptable liquids parameter would clean up the code a bit (just use liquids.contains(String s)) ``` static String[] liquids = {"#milk;3", "#whiskey;splash"}; public static void parseString(String input) { // Break the String down into line-by-line. String[] lines = input.split("" + '\n'); for (int line_index = 0; line_index < lines.length; line_index++) { if (lines[line_index].length() > 16) { // Assume you're delimiting by '#' String[] tokens = lines[line_index].split("#"); if (tokens.length > 1) { // Start at index = 1 to kill "Accept-Additions:" for (int token_index = 1; token_index < tokens.length; token_index++) { boolean valid = false; for (int liquids_index = 0; liquids_index < liquids.length; liquids_index++) { if (liquids[liquids_index].equals("#" + tokens[token_index])) { valid = true; // break to save some time if liquids is very long break; } } if (!valid) { throwError("#" + tokens[token_index]); } } } } } } public static void throwError(String error) { System.out.println(error + " is not in the Array!"); } ```
You'd parse the string. Looking at it, you one set of options per line, so you can look for all the lines that start with ACCEPT-ADDITIONS. Then you have to extract the additions, which appear to be separate with semi-colons, indicating String.split(). Then iterate over the resuling array to find additions. Or you could create a grammar, and use a tool such as ANTLR to generate your parser.
Searching a large string to see if invalid "parameter" exists
[ "", "java", "string", "" ]
I want to find the first item in a sorted vector that has a field less than some value x. I need to supply a compare function that compares 'x' with the internal value in MyClass but I can't work out the function declaration. Can't I simply overload '<' but how do I do this when the args are '&MyClass' and 'float' ? ``` float x; std::vector< MyClass >::iterator last = std::upper_bound(myClass.begin(),myClass.end(),x); ```
What function did you pass to the sort algorithm? You should be able to use the same one for upper\_bound and lower\_bound. The easiest way to make the comparison work is to create a dummy object with the key field set to your search value. Then the comparison will always be between like objects. **Edit:** If for some reason you can't obtain a dummy object with the proper comparison value, then you can create a comparison functor. The functor can provide three overloads for operator() : ``` struct MyClassLessThan { bool operator() (const MyClass & left, const MyClass & right) { return left.key < right.key; } bool operator() (const MyClass & left, float right) { return left.key < right; } bool operator() (float left, const MyClass & right) { return left < right.key; } }; ``` As you can see, that's the long way to go about it.
You can further improve Mark's solution by creating a static instance of MyClassLessThan in MyClass ``` class CMyClass { static struct _CompareFloatField { bool operator() (const MyClass & left, float right) //... // ... } CompareFloatField; }; ``` This way you can call lower\_bound in the following way: ``` std::lower_bound(coll.begin(), coll.end(), target, CMyClass::CompareFloatField); ``` This makes it a bit more readable
compare function for upper_bound / lower_bound
[ "", "c++", "algorithm", "stl", "" ]
"Cleanup failed to process the following paths The system cannot find the file specified" Am having this issue with Tortoise SVN going to a SAMBA share.. any thoughts on setup? Its probably permissions getting mucked up, but this setup doesn't feel very robust.. am having to delete the affected directory, then recreate from svn. I do all my dev in notepad++ on the windows box, and use a windows shared drive through Samba. Windows Vista laptop running subversion and tortoise. Ubuntu8.10 running under VMWare which runs PHP4 and a old sybase\_ct driver talking back to MSSQL on the host machine. I need this to mirror the production environment.
we have the same issue at work often Tsvn (TortoiseSVN) has a problem to move folders created by itself, so we get an error like '**Can't move xxx to yyy...**' '**Working copy locked, please cleanup**' or something like, then the cleanup fails. we tried with '`readonly = yes`' in samba share definitions but it didn't work. After that we find that folders created by the Tsvn creates folder with 444 or something like (readonly for the owner too), so that folders can't be deleted when it needs to move them. We solve the problem with `'force create mode = 600'` in the share definitions. And more, i tell you that you don't need to delete the entire project and checkout from SVN a new working copy when you're blocked with that error: it's enough to launch from shell this command when you are in the target shared root folder of the project ``` rm -rf `find . -type d -name .svn` ``` to remove the .svn folder recursively and then checkout (the files already there will be only re-versioned, not downloaded).
In my experience using Apache + SVN is a lot more robust than sharing a file repository, albeit harder to set up (probably not too bad with Ubuntu as it has apt) Alternatively, you could use ssh+svn, i.e tunnel to the linux box. Both methods eliminate samba and file sharing which sounds suspicious.
PHP4 on Linux, Dev on Windows... Subversion problem
[ "", "php", "svn", "tortoisesvn", "" ]
I am new to JavaScript OOP. Can you please explain the difference between the following blocks of code? I tested and both blocks work. What's the best practice and why? First block: ``` function Car(name){ this.Name = name; } Car.prototype.Drive = function(){ console.log("My name is " + this.Name + " and I'm driving."); } SuperCar.prototype = new Car(); SuperCar.prototype.constructor = SuperCar; function SuperCar(name){ Car.call(this, name); } SuperCar.prototype.Fly = function(){ console.log("My name is " + this.Name + " and I'm flying!"); } var myCar = new Car("Car"); myCar.Drive(); var mySuperCar = new SuperCar("SuperCar"); mySuperCar.Drive(); mySuperCar.Fly(); ``` Second block: ``` function Car(name){ this.Name = name; this.Drive = function(){ console.log("My name is " + this.Name + " and I'm driving."); } } SuperCar.prototype = new Car(); function SuperCar(name){ Car.call(this, name); this.Fly = function(){ console.log("My name is " + this.Name + " and I'm flying!"); } } var myCar = new Car("Car"); myCar.Drive(); var mySuperCar = new SuperCar("SuperCar"); mySuperCar.Drive(); mySuperCar.Fly(); ``` Why did the author add the `Drive` and `Fly` methods using `prototype`, and did not declare them as a `this.Drive` method inside the `Car` class and as `this.Fly` in the `SuperCar` class? Why does `SuperCar.prototype.constructor` need to be set back to `SuperCar`? Is the `constructor` property overridden when `prototype` is set? I commented out this line and nothing changed. Why call `Car.call(this, name);` in the `SuperCar` constructor? Won't properties and methods of `Car` be 'inherited' when I do ``` var myCar = new Car("Car"); ```
The two blocks differ in a way that in the first example `Drive()` will only exist once while at the second approach `Drive()` will exist per instance (Every time you do `new Car()` the function `drive()` will be created again). Or different said the first uses the prototype to store the function and the second the constructor. The lookup for functions is constructor and then prototype. So for your lookup of `Drive()` it finds it regardless if it is in the constructor or in the prototype. Using the prototype is more efficient because usually you need a function only once per type. The `new` call in javascript automatically sets the constructor in the prototype. If you are overwriting the prototype so you have to set the constructor manually. Inheritance in javascript has nothing like `super`. So if you have a subclass the only chance to call the super constructor is by its name.
To add to [Norbert Hartl's answer](https://stackoverflow.com/questions/892595/understanding-prototypal-inheritance-in-javascript/892632#892632), SuperCar.prototype.constructor isn't needed, but some people use it as a convenient way of getting the constructing function of an object (SuperCar objects in this case). Just from the first example, Car.call(this, name) is in the SuperCar constructor function because when you do this: ``` var mySuperCar = new SuperCar("SuperCar"); ``` This is what JavaScript does: 1. A fresh, blank object is instantiated. 2. The fresh object's internal prototype is set to Car. 3. The SuperCar constructor function runs. 4. The finished object is returned and set in mySuperCar. Notice how JavaScript didn't call Car for you. Prototypes being as they are, any property or method that you don't set yourself for SuperCar will be looked up in Car. Sometimes this is good, e.g. SuperCar doesn't have a Drive method, but it can share Car's one, so all SuperCars will use the same Drive method. Other times you don't want sharing, like each SuperCar having its own Name. So how does one go about setting each SuperCar's name to its own thing? You could set this. Name inside the SuperCar constructor function: ``` function SuperCar(name){ this.Name = name; } ``` This works, but wait a second. Didn't we do exactly the same thing in the Car constructor? Don't want to repeat ourselves. Since Car sets the name already, let's just call it. ``` function SuperCar(name){ this = Car(name); } ``` Whoops, you never want to change the special `this` object reference. Remember the 4 steps? Hang onto that object that JavaScript gave you, because it's the only way to keep the precious internal prototype link between your SuperCar object and Car. So how do we set Name, without repeating ourselves and without throwing away our fresh SuperCar object JavaScript spent so much special effort to prepare for us? Two things. One: the meaning of `this` is flexible. Two: Car is a function. It's possible to call Car, not with a pristine, fresh instantiated object, but instead with, say, a SuperCar object. That gives us the final solution, which is part of the first example in your question: ``` function SuperCar(name){ Car.call(this, name); } ``` As a function, Car is allowed to be invoked with the function's [call method](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call), which changes the meaning of `this` within Car to the SuperCar instance we're building up. Presto! Now each SuperCar gets its own Name property. To wrap up, `Car.call(this, name)` in the SuperCar constructor gives each new SuperCar object its own unique Name property, but without duplicating the code that's already in Car. Prototypes aren't scary once you understand them, but they're not much like the classic class/inheritence OOP model at all. I wrote an article about [the prototypes concept in JavaScript](http://www.spheredev.org/wiki/Prototypes_in_JavaScript). It's written for a game engine that uses JavaScript, but it's the same JavaScript engine used by Firefox, so it should all be relevant.
Understanding prototypal inheritance in JavaScript
[ "", "javascript", "oop", "inheritance", "constructor", "prototype-programming", "" ]
I was wondering about `??` signs in `C#` code. What is it for? And how can I use it? What about `int?`? Is it a nullable int? ### See also: > [?? Null Coalescing Operator —> What does coalescing mean?](https://stackoverflow.com/questions/770186/null-coalescing-operator-what-does-coalescing-mean)
It's called the "null coalescing operator" and works something like this: Instead of doing: ``` int? number = null; int result = number == null ? 0 : number; ``` You can now just do: ``` int result = number ?? 0; ```
It's the [*null coalescing operator*](http://msdn.microsoft.com/en-us/library/ms173224.aspx). It was introduced in C# 2. The result of the expression `a ?? b` is `a` if that's not null, or `b` otherwise. `b` isn't evaluated unless it's needed. Two nice things: * The overall type of the expression is that of the second operand, which is important when you're using nullable value types: ``` int? maybe = ...; int definitely = maybe ?? 10; ``` (Note that you can't use a non-nullable value type as the first operand - it would be pointless.) * The associativity rules mean you can chain this really easily. For example: ``` string address = shippingAddress ?? billingAddress ?? contactAddress; ``` That will use the first non-null value out of the shipping, billing or contact address.
What is the "??" operator for?
[ "", "c#", "operators", "coalesce", "null-coalescing-operator", "" ]
I have a controller called `articles`, which creates the articles model which gets the relevant data from the database. I want to, if the method I call returns `false`, to trigger a 404 error. This is what I have so far. ``` $articleName = $this->uri->segment('articles'); $article = new Articles_Model(); $data = $article->getArticleUsingSlug($articleName); if (!$data) { Kohana::show_404; // This doesn't work. } ``` I just added my own custom hook which redirects the user to an actual 404 (/articles/page-not-found/) as triggered by Kohana, but is there a way I can invoke its internal 404 method to make Kohana give up processing my controller and use my new hook ?
This works for me: ``` Event::run('system.404'); ``` What version of Kohana are you using?
Kohana / General / Error-handling / [Kohana\_404\_Exception](http://docs.kohanaphp.com/general/errorhandling#kohana_404_exception) ``` /** * @param string URL of page * @param string custom error template */ throw new Kohana_404_Exception([string $page [, string $template]]); ```
In Kohana, can you trigger a 404 error?
[ "", "php", "kohana", "http-status-code-404", "" ]
I'm a little surprised that it is not possible to set up a binding for Canvas.Children through XAML. I've had to resort to a code-behind approach that looks something like this: ``` private void UserControl_Loaded(object sender, RoutedEventArgs e) { DesignerViewModel dvm = this.DataContext as DesignerViewModel; dvm.Document.Items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Items_CollectionChanged); foreach (UIElement element in dvm.Document.Items) designerCanvas.Children.Add(element); } private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { ObservableCollection<UIElement> collection = sender as ObservableCollection<UIElement>; foreach (UIElement element in collection) if (!designerCanvas.Children.Contains(element)) designerCanvas.Children.Add(element); List<UIElement> removeList = new List<UIElement>(); foreach (UIElement element in designerCanvas.Children) if (!collection.Contains(element)) removeList.Add(element); foreach (UIElement element in removeList) designerCanvas.Children.Remove(element); } ``` I'd much rather just set up a binding in XAML like this: ``` <Canvas x:Name="designerCanvas" Children="{Binding Document.Items}" Width="{Binding Document.Width}" Height="{Binding Document.Height}"> </Canvas> ``` Is there a way to accomplish this without resorting to a code-behind approach? I've done some googling on the subject, but haven't come up with much for this specific problem. I don't like my current approach because it mucks up my nice Model-View-ViewModel by making the View aware of it's ViewModel.
I don't believe its possible to use binding with the Children property. I actually tried to do that today and it errored on me like it did you. The Canvas is a very rudimentary container. It really isn't designed for this kind of work. You should look into one of the many ItemsControls. You can bind your ViewModel's ObservableCollection of data models to their ItemsSource property and use DataTemplates to handle how each of the items is rendered in the control. If you can't find an ItemsControl that renders your items in a satisfactory way, you might have to create a custom control that does what you need.
``` <ItemsControl ItemsSource="{Binding Path=Circles}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="White" Width="500" Height="500" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Ellipse Fill="{Binding Path=Color, Converter={StaticResource colorBrushConverter}}" Width="25" Height="25" /> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="Canvas.Top" Value="{Binding Path=Y}" /> <Setter Property="Canvas.Left" Value="{Binding Path=X}" /> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl> ```
Is it possible to bind a Canvas's Children property in XAML?
[ "", "c#", "wpf", "data-binding", ".net-3.5", "canvas", "" ]
I'm trying to learn about this feature of javascript I keep seeing in code, but I don't know the name of the construction to google for... ``` var Stats = { onLoad: function(e) { // content this.variable++; }, variable: 1 }; ``` Is this way of organising functions and variables based on JSON?
It's an "Object Literal" - see the [JavaScript Guide](https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Literals#Object_Literals).
It's called the [Object Literal](http://www.dyn-web.com/tutorials/obj_lit.php) syntax. It's a superset of JSON.
In JS, what is this feature called?
[ "", "javascript", "json", "" ]
Why does the `Iterator` interface not extend `Iterable`? The `iterator()` method could simply return `this`. Is it on purpose or just an oversight of Java's designers? It would be convenient to be able to use a for-each loop with iterators like this: ``` for(Object o : someContainer.listSomeObjects()) { .... } ``` where `listSomeObjects()` returns an iterator.
Because an iterator generally points to a single instance in a collection. Iterable implies that one may obtain an iterator from an object to traverse over its elements - and there's no need to iterate over a single instance, which is what an iterator represents.
An iterator is stateful. The idea is that if you call `Iterable.iterator()` twice you'll get *independent* iterators - for most iterables, anyway. That clearly wouldn't be the case in your scenario. For example, I can usually write: ``` public void iterateOver(Iterable<String> strings) { for (String x : strings) { System.out.println(x); } for (String x : strings) { System.out.println(x); } } ``` That should print the collection twice - but with your scheme the second loop would always terminate instantly.
Why is Java's Iterator not an Iterable?
[ "", "java", "iterator", "iterable", "" ]
Why does Sql server doesn't allow more than one IDENTITY column in a table?? Any specific reasons.
An Identity column is a column ( also known as a field ) in a database table that :- 1. Uniquely identifies every row in the table 2. Is made up of values generated by the database This is much like an AutoNumber field in Microsoft Access or a sequence in Oracle. An identity column differs from a primary key in that its values are managed by the server and ( except in rare cases ) can't be modified. In many cases an identity column is used as a primary key, however this is not always the case. SQL server uses the identity column as the key value to refer to a particular row. So only a single identity column can be created. Also if no identity columns are explicitly stated, Sql server internally stores a separate column which contains key value for each row. As stated if you want more than one column to be having unique value, you can make use of UNIQUE keyword.
Why would you need it? SQL Server keeps track of **a single value** (current identity value) for each table with `IDENTITY` column so it can have just one identity column per table.
identity column in Sql server
[ "", "sql", "sql-server", "" ]
I'm wondering is there a JavaScript library available that would allow me to generate an Image from the contents of a DIV. Basically this is required for some Server-Side Printing code, which needs to print a background from the Browser. What I'd ultimately like to do would be encode the DIV contents into PNG format and post up the encoded data with the print operation. Any ideas if this is possible ? [EDIT] What I have is a mapping application where background data is coming from an image server straight into a browser DIV (Think Google Maps). That div is background to me main data. When Print is pressed the server generates a PDF from the data it knows about, but knows nothing about the browser's background data. What I'd really like is to be able to provide the server with the browsers background image in some way! Cheers, Ro
I think I've worked out a way to do it. 1) When the user presses Print, interrogate the DIV 2) Images on that DIV are being generated by the OpenLayers API 3) Grab the URL of each Image 4) Grab the location on screen of each image 5) Translate the screen location into a Real-World location (I have API for this) 6) As part of the print send up all the image URL's along with their real-world extents 7) Allow the server to re-request the Images and draw them into their appropriate locations.
Maybe it's possible with the `Canvas`: [MDN - Drawing Graphics with Canvas](https://developer.mozilla.org/en/drawing_graphics_with_canvas)
Create an Image of a DIV in JavaScript (GIF/PNG)
[ "", "javascript", "image", "" ]
First of all, what's the difference between: > www.domain.com and > domain.com Should I pay attention to this when I do the coding?
I would highly recommend to use relative paths. This has many advantages, for instance: * Paths are shorter * If you want to move to a different domainname you don't have to check through thousands of codelines In general there IS a difference between: www.domain.com and domain.com. The "www" prefix is nothing more than an ordinary subdomain: <http://en.wikipedia.org/wiki/Subdomain>
``` domain.com ``` Is the registered domain and ``` www.domain.com ``` Is a sub-domain of `domain.com`, they are not alway the same. Most web sites will set up their webserver to redirect domain.com to www.doamin.com or vice versa. Depending on the DNS Zone file configuration sub-domains can point to different IP addresses (possibly different physical servers). ``` example.com. A 10.0.0.1 ; ip address for "example.com" ns A 10.0.0.2 ; ip address for "ns.example.com" www CNAME ns ; "www.example.com" is an alias for "ns.example.com" wwwtest CNAME www ; "wwwtest.example.com" is another alias for "www.example.com" mail A 10.0.0.3 ; ip address for "mail.example.com", any MX record host must be ``` Taken form Wikipedia - [DNS Zone File](http://en.wikipedia.org/wiki/Zone_file)
Use subdomain name in my PHP code?
[ "", "php", "url", "" ]
I have an object in C# with lets say 20 properties and it's part of a datacontract. I also have another business entity with similar properties, which I want to populate from the response object. Is there any way to do this other than assigning each property of one object to the corresponding properties of the other?
Yes, take a look at [Automapper](http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/22/automapper-the-object-object-mapper.aspx)
[MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/) has an answer to this (`PropertyCopy`) that uses `Expression` (.NET 3.5) and a static field to cache the compiled delegate (so there is negligible cost per invoke): ``` DestType clone = PropertyCopy<DestType>.CopyFrom(original); ``` If you are using 2.0, then probably reflection would be your friend. You can use [`HyperDescriptor`](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx) to improve the performance if you need.
Creating objects from another object with same properties
[ "", "c#", ".net", "" ]
Does [`FileChannel#map`](http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html#map(java.nio.channels.FileChannel.MapMode,%20long,%20long)) allocate all the memory needed for the resulting `ByteBuffer` immediately, or is it only allocated on-demand during reads from the buffer? I just tried mapping all of a 500+ MB file in a trivial test program, and looked at the memory usage of the process. (Using both `Runtime#totalMemory` and eyeballing it in the OS X Activity Monitor for a groovysh process.) The memory usage never passed 30-ish MB. So, could a Java implementation "hide" some of its memory usage in native calls? And if so, is there a way to find out how much that is on OS X?
Memory usage is never straightforward. The actual buffer used by `FileChannel.map` is not part of the Java heap. Indeed the memory might be shared with other processes. The file may not even be read from the disc until the pages are touched.
Yes. It's not part of the heap. Still, depending on the OS there will still be memory reserved. On OS X, because it's UNIX-like you should be able to use top or ps to check how much memory it needs.
Memory usage of FileChannel#map
[ "", "java", "memory-management", "mmap", "" ]
I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time\_it" that takes another function, runs it, and returns the time it took to run. ``` def time_it(f, *args): start = time.clock() f(*args) return (time.clock() - start)*1000 ``` i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.) This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running. Is there a more standard or accepted way to do this? When i changed my test function to call a print so that it takes longer, my time\_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here? One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.
Instead of writing your own profiling code, I suggest you check out the built-in Python profilers (`profile` or `cProfile`, depending on your needs): <http://docs.python.org/library/profile.html>
Use the [`timeit` module](http://docs.python.org/library/timeit.html) from the Python standard library. Basic usage: ``` from timeit import Timer # first argument is the code to be run, the second "setup" argument is only run once, # and it not included in the execution time. t = Timer("""x.index(123)""", setup="""x = range(1000)""") print t.timeit() # prints float, for example 5.8254 # ..or.. print t.timeit(1000) # repeat 1000 times instead of the default 1million ```
Accurate timing of functions in python
[ "", "python", "testing", "time", "profiling", "" ]
I have a `CMFCToolBar`-derived class and an insance thereof is the member of a `CDockablePane`-derived class. I looked at the VisualStudioDemo sample to see how it's done and have this so far: ``` int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Removed all "return -1 on error" code for better readability CDockablePane::OnCreate(lpCreateStruct); if(m_toolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_MY_TOOLBAR) && m_toolBar.LoadToolBar(IDR_MY_TOOLBAR, 0, 0, TRUE /* Is locked */)) { if(theApp.m_bHiColorIcons) // Is true, i.e. following code is executed { m_toolBar.CleanUpLockedImages(); m_toolBar.LoadBitmap(IDB_MY_TOOLBAR_24, 0, 0, TRUE /*Locked*/); } m_toolBar.SetPaneStyle(m_toolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY); m_toolBar.SetPaneStyle(m_toolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT)); m_toolBar.SetOwner(this); // All commands will be routed via this control , not via the parent frame: m_toolBar.SetRouteCommandsViaFrame(FALSE); } return 0; } ``` The high-color image (24bit) is loaded but the magenta mask (R255 G0 B255) is visible. I don't see how I can tell the toolbar to recognize the mask. Is this even possible?
I don't know if this works every time but I use `RGB(192, 192, 192)` as the mask color and it does get recognized. (Seems like the CMFCToolBar control is prepared to use `::GetSysColor(COLOR_BTNFACE)` as the transparent color...)
I just found out that a workaround is to use 32bit images together with their alpha channel. I tried using a 32bit image earlier but didn't get it to work for some other reason and then figured 32bit images won't work.
How do I make a CMFCToolBar recognize image masks?
[ "", "c++", "transparency", "mask", "mfc-feature-pack", "24-bit", "" ]
I am looking to get into [operating system kernel development](http://www.jbox.dk/sanos) and figured and have been reading books on operating systems (Tannenbaum) as well as studying how BSD and Linux have tackled this challenge but still am stuck on several concepts. 1. If I wanted to mimic the Windows Blue Screen of Death on an operating system, would I simply put this logic in the [panic](http://www.jbox.dk/sanos) kernel method? 2. Are there ways to improve upon how Windows currently performs this functionality?
I'm not exactly sure where to look in the source but you might want to look into ReactOS, an open source Windows clone which has BSOD already.
BSDs actually handled this much better then Windows with [DDB](http://www.openbsd.org/cgi-bin/man.cgi?query=ddb) :) Here's another link to [FreeBSD Kernel Debugging](http://www.freebsd.org/doc/en/books/developers-handbook/kerneldebug.html) docs.
Adding Blue Screen of Death to Non-Windows OS
[ "", "c++", "linux", "operating-system", "kernel", "bsd", "" ]
I created an anchor like this: ``` <a id="create" /> ``` and it works in IE 7 but not in IE 6. How do I fix it in IE6? Further Info: I am using asp.net c#. I am running it in IE6 and in an iframe. The screen just refreshes and the panel doesn't show. But if I don't use: > Response.Redirect(Request.Url.PathAndQuery > + "&New=1#create"); i.e. If I do: > Response.Redirect(Request.Url.PathAndQuery > + "&New=1"); It works fine, but doesn't goto the panel. btw: it all works fine under IE 7. It doesnt work in IE 6 or in IE 6 in an iframe
IE 6 has a strange behaviour, it does not recognizes redirects with anchors in it. The workaround is to add additional ampersand symbol '&' before the '#'. So, in your example, the code will look like `Response.Redirect(Request.Url.PathAndQuery + "&New=1&#create");` I suggest you to check User-Agent on the server side and add this additional ampersand if the browser is IE 6.
from memory you use the 'name' attribute
anchor IE 6 bug
[ "", "c#", "asp.net", "internet-explorer-6", "anchor", "" ]
I have a shtml file index.shtml in which I want to include a PHP file which performs some programing and returns HTML data. I am trying to include my PHP file but I don't know how to do that, I tried following but nothing is working, Following line is just printing an error, "**[an error occurred while processing this directive]** ": ``` <!--#include file="/SSI/test.php"--> ``` This line is displaying some junk characters: ``` <!--#include virtual="/SSI/test.php"--> ``` This line is doing nothing and displaying the command as is in the .shtml page ``` <?PHP include("/SSI/test.php"); ?> ``` Thanks
If there is no particular reason that you are using .shtml aside from what you mentioned regarding traffic, you can change its processing in your .htaccess file: ``` <Files *.shtml> ForceType application/x-httpd-php </Files> ``` Or you can specify that file in particular: ``` <Files filename.shtml> ForceType application/x-httpd-php </Files> ``` This will tell the server to parse the .shtml like it was a .php file, and therefore any PHP commands should be processed, such as your include statement. No need to change the file extension.
I could be wrong, but given the error you are getting, the problem may not in the include statement but an error in the php file to be included that is causing the problem.
How to include PHP file in SHTML pages?
[ "", "php", "file", "include", "html", "shtml", "" ]
I am developing a website using Google App Engine and Django 1.0 (app-engine-patch) A major part of my program has to run in the background and change local data and also post to a remote URL Can someone suggest an effective way of doing this?
Without using a third-party system, I think currently your only option is to use the [cron functionality](http://code.google.com/appengine/docs/python/config/cron.html). You'd still be bound by the usual GAE script-execution-time limitations, but it wouldn't happen on a page load. There is plans for background processing, see [this App Engine issue #6](http://code.google.com/p/googleappengine/issues/detail?id=6), and this [roadmap update](http://googleappengine.blogspot.com/2009/02/roadmap-update.html)
Check out [The Task Queue Python API](http://code.google.com/appengine/docs/python/taskqueue/).
Background process in GAE
[ "", "python", "django", "google-app-engine", "backgroundworker", "" ]
``` int somefunction(bool a) { try { if(a) throw Error("msg"); return 2; } catch (Error const & error) { //do i need to return anything here?? //return -1; } } ```
You need to either return something or re-throw the exception (or throw a new one). You can rethrow the same exception by just using the keyword ``` throw ``` in the catch block with no exception or arguments afterwards.
If you won't return anything there, the callee will perhaps do the wrong thing afterwards because the return value will be undefined and perhaps gets one of the valid return codes! Try this: ``` printf("%i\n", somefunction(false)); printf("%i\n", somefunction(true)); ``` Output: ``` 2 2293512 ``` The compiler also gives a warning for this (f.e. "control reaches end of non-void function").
object returned after an exception?
[ "", "c++", "exception", "return-value", "" ]
My boss wants me to encrypt some information used during data transfer. The individual strings to be encrypted are between eight and twenty characters long. A single password must be used to encrypt and decrypt so I need a symmetric alogrithm. I don't want to roll my own - I want to use one built into .NET from C#. So, which algorithm is best?
TripleDes ? You can use the [`System.Security.Cryptography.TripleDESCryptoServiceProvider`](http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx) Small amount of code to encrypy/decrypt... does exactly what it says on the tin :)
TripleDES is a very good option, but you can also consider [AesCryptoServiceProvider](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aescryptoserviceprovider.aspx) (AES), which is a modern symmetric cipher.
What's the best way to encrypt short strings in .NET?
[ "", "c#", ".net", "security", "" ]
I need to independently record events on different computers and reconstruct which order those events happened relative to each other. The solution calls for each computer to be relatively independent; they cannot directly talk to each other or a single source. My initial solution recorded the time on each machine, but since times can be different on different machines, and can change throughout the day, this did not completely solve my problem. I decided to share with all machines whenever a machine (1) starts the process, or (2) has its system clock change. So from each machine I get a log full of these ``` public class Activity { DateTime TimeOccurred { get; set; } string Description { get; set; } } ``` Whenever (1) or (2) happens above, I add an activity to the log and broadcast it to the other machines, who add the same activity to their log, with the TranslatedTime being their own time: ``` public class TimeSynchronization : Activity { string SourceMachine { get; set; } DateTime TranslatedTime { get; set; } } ``` So machine A would have (in order): ``` TimeSynchronization "started" at 3:00 am. Activity "asked a question" at 3:05 am. TimeSynchronization from machine B at 3:05 am. TimeSynchronization "clock changed" at 3:03 am. Activity "received an answer" at 3:04 am. ``` And machine B would have (in order): ``` TimeSynchronization "started" at 3:05 am. TimeSynchronization "clock changed" at 3:06 ``` So I need to reconstruct the same order and timing of these above events, to something like: ``` On machine A: TimeSynchronization "started" at 0:00 On machine A: Activity "asked a question" at 0:05 On machine B: TimeSynchronization "started" at 0:05 On machine A: TimeSychronization from machine B at 0:05 On machine A: TimeSynchronization "clock changed" at 0:06 On machine B: TimeSynchronization "clock changed" at 0:06 On machine A: Activity "received an answer" at 0:07 ``` What is the best way to take a `List<Activity>` from each machine and merge it into one list with the events in order?
If the two machines are connected via the network your program can ask the other machine what time it is. That way your program on machine A could ask for the time on both A and B and then log both times. You mention that the time could change during the day (presumably the user changed the time). You can detect this by using the Win32.TimeChanged event.
Atomic time, and a webservice that would give it to you. That's what you need. Realistic? No idea. But at least you wouldn't need to worry about the n computers trying to sync their clocks.
How to record relative times between computers?
[ "", "c#", "time", "computer-science", "" ]
I have been trying to find a code snippet to do an unsharp mask in C# but cant find one that works or is complete. I found a PHP version but I would like to find one in C# before I go through all the hard work converting this from PHP. I am just a beginner. Can anyone point me in the right direction?
The [AForge.NET Framework](http://www.aforgenet.com/framework/) includes many image processing filters and support plugging your own. You can see it in action in their own [Image Processing Lab](http://www.aforgenet.com/projects/iplab/) application. --- UPDATE: AForge.NET has a convolution-based [sharpen](http://www.aforgenet.com/framework/docs/html/c5a43907-302d-3d0d-1ab1-a39b9d0f7013.htm) filter (see [convolution filters](http://www.aforgenet.com/framework/features/convolution_filters.html)), but there's no mention of an unsharp mask filter per se. Then again, you can use the Gaussian blur filter and subtract the result from the original image, which is basically what the unsharp mask filter does. Or maybe the basic sharpen is enough for your needs. --- UPDATE: Looked further, and AForge.NET does have a [Gaussian sharpen](http://www.aforgenet.com/framework/docs/html/4600a4d7-825b-138f-5c31-249a10335b26.htm) which seems to be an implemenation of an unsharp mask filter, and you *can* control some parameters.
Would you care to use FFTs? Transform, remove or accentuate high freqs to taste, invert the transform, recombine with the original if desired? Hardly any licensing issues there, as FFT libraries abound. Alternately, you can make up masks by hand, varying size and constants as you like, then convolve them with your image pixels (nested 'for' loops ...). Here's a 3x3x1 mask as a text file with its dimensions given before the values: //3x3x1 // x size 3 // y size 3 //z size 1 //z = 0 2 3 2 3 5 3 2 3 2 //end This can be extended to 3 dimensions (hence the z size being given).
Where can I find an unsharp mask for C#?
[ "", "c#", "image-processing", "image-manipulation", "" ]
I've got a situation where I'm using an XML parser to extract data from a php://input. The data being sent in looks like: ``` <this>foo</this> <that>bar></that> <data><dong>zebras</dong><fong>monkeys</fong></data> ``` Now, the issue is that because the handler: ``` $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); xml_set_element_handler($xml_parser, "startTag", "endTag"); xml_set_character_data_handler($xml_parser, "contents"); $document = file_get_contents("php://input"); xml_parse($xml_parser, $document); xml_parser_free($xml_parser); ``` ...is interpreting tags for me to decipher the contents to make it useful... It seems to be missing anything within `<data>` i.e. I need to find out how i can get it to ignore the child/nested elements/tags and just bosh out the data whatever.
WideDonkey, have you considered using the DOM instead? You can easily do : ``` $dom = new DOMDocument(); $dom->loadXML(file_get_contents('php://input')); $data = $dom->getElementsByTagName('data'); $data = $data[0]->asXML(); ```
I'm not sure if I understood the question correctly, but ``` <?php function contents($parser, $data) { echo $data; } $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); // xml_set_element_handler($xml_parser, "startTag", "endTag"); xml_set_character_data_handler($xml_parser, "contents"); // $document = file_get_contents("php://input"); $document = '<x><this>foo</this><that>bar</that><data><dong>zebras</dong><fong>monkeys</fong></data></x>'; xml_parse($xml_parser, $document); xml_parser_free($xml_parser); ``` prints ``` foobarzebrasmonkeys ```
PHP XML Parser - ignoring nested/child tags
[ "", "php", "xml", "parsing", "" ]
``` class foo { public: void say_type_name() { std::cout << typeid(this).name() << std::endl; } }; int main() { foo f;; f.say_type_name(); } ``` Above code prints *P3foo* on my ubuntu machine with g++. I am not getting why it is printing *P3foo* instead of just *foo*. If I change the code like ``` std::cout << typeid(*this).name() << std::endl; ``` it prints *3foo*. Any thoughts?
Because it is a pointer to foo. And foo has 3 characters. So it becomes `P3foo`. The other one has type `foo`, so it becomes `3foo`. Note that the text is implementation dependent, and in this case GCC just gives you the internal, mangled name. Enter that mangled name into the program `c++filt` to get the unmangled name: ``` $ c++filt -t P3foo foo* ```
`std::type_info::name()` returns an implementation specific name. AFAIK, there is no portable way to get a "nice" name, although GCC [has one](http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html). Look at [`abi::__cxa_demangle()`](http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html). ``` int status; char *realname = abi::__cxa_demangle(typeid(obj).name(), 0, 0, &status); std::cout << realname; free(realname); ```
typeid() returns extra characters in g++
[ "", "c++", "g++", "name-mangling", "typeid", "" ]
I am wondering how to capture all links on a page using jQuery. The idea being similar to Facebook. In Facebook, if you click on a link it captures the link and loads the same link using ajax. Only when you open a link in new tab etc. will it load the page using regular call. Any clue on how to achieve such kind of functionality? Am sure capturing links should not be a problem, but what about capture form submissions and then submitting the entire data via ajax and then displaying the results? Is there any plugin which already exists? Thank you for your time.
Alec, You can definitely do this. I have a form that is handled in just this way. It uses the jquery form plugin kgiannakakis mentioned above. Example javascript below shows how it might work. ``` $("form").ajaxForm({ beforeSubmit: function(){ //optional: startup a throbber to indicate form is being processed var _valid = true; var _msg = ''; //optional: validation code goes here. Example below checks all input //elements with rel attribute set to required to make sure they are not empty $(":input [rel='required']").each(function(i){ if (this.value == '') { _valid = false; _msg += this.name + " may not be empty.\n"; $(this).addClass("error"); } }); alert(_msg); return _valid; }, success: function(response){ //success here means that the HTTP response code indicated success //process response: example assumes JSON response $("body").prepend('<div id="message" class="' + response.status + '"></div>'); $("#message").text(response.message).fadeIn("slow", function(){ $(this).fadeOut("slow").remove(); }); } }); ```
[Form plug-in](http://www.malsup.com/jquery/form/) can transform a regular form to an Ajax one: ``` $("#myForm").ajaxForm( {beforeSubmit: validate, success: showResponse} ); ``` It would be difficult to do what you want however for an arbitrary form. What if the form uses validation or is submitted by Ajax to begin with? The same thing applies for links. What if there are some javascript navigations scripts (window.location = Url)? If you don't have full control of the page, it will be difficult to do what you want.
Capture all links including form submission
[ "", "javascript", "jquery", "" ]
When an exception is thrown or encountered: ``` void ThrowException() { try { throw new Exception("Error"); } catch { } } ``` **is it & how is it disposed from memory?** and how does the above code differ from the below code in respect of the disposal from memory of the Exception object? ``` void ThrowException() { try { throw new Exception("Error"); } catch(Exception e) { } } ```
The Exception instance simply acts as another object in memory - after the catch method, there aren't any remaining references to the instance, so it will get removed in the next garbage collection sweep. Exceptions generally don't inherit from IDisposable, as there shouldn't really be external resources associated with an Exception. If you *do*. have an IDisposable exception, you should look really hard at whether your architecture & code design is correct.
Exception does not inherit from IDisposable so it does not need to be disposed. Memory deallocation is done by the GC like for all .NET objects.
Exceptions and memory
[ "", "c#", "exception", "garbage-collection", "" ]
I am trying to loop though my users database to show each username in the table in their own row. I can only get it to show one user but loops through this the number of rows there are. Code is below ``` <?php require_once ('../login/connection.php'); include ('functions.php'); $query = "SELECT * FROM users"; $results=mysql_query($query); $row_count=mysql_num_rows($results); $row_users = mysql_fetch_array($results); echo "<table>"; for ($i=0; $i<$row_count; $i++) { echo "<table><tr><td>".($row_users['email'])."</td></tr>"; } echo "</table>"; ?> ``` Thanks
[mysql\_fetch\_array](http://php.net/mysql_fetch_array) fetches a single row - you typically use it in a while loop to eat all the rows in the result set, e.g. ``` echo "<table>"; while ($row_users = mysql_fetch_array($results)) { //output a row here echo "<tr><td>".($row_users['email'])."</td></tr>"; } echo "</table>"; ```
You're only fetching one row: ``` $row_users = mysql_fetch_array($results); ``` You're never calling a fetch again so you're not really looping through anything. I'd suggest changing your loop to the following: ``` echo "<table>"; while ($row = mysql_fetch_array($results)) { echo "<tr><td>".($row['email'])."</td></tr>"; } echo "</table>"; ``` The while loop will loop through the results and assign a row to $row, until you run out of rows. Plus no need to deal with getting the count of results at that point. This is the "usual" way to loop through results from a DB in php.
loop through database and show in table
[ "", "php", "mysql", "" ]
I was asked this question by a friend, and it piqued my curiosity, and I've been unable to find a solution to it yet, so I'm hoping someone will know. Is there any way to programatically detect what type of keyboard a user is using? My understanding of the keyboard is that the signal sent to the computer for 'A' on a DVORAK keyboard is the same as the signal sent to the computer for an 'A' in a QUERTY keyboard. However, I've read about ways to [switch to/from dvorak](https://stackoverflow.com/questions/167031/programatically-change-keyboard-to-dvorak), that highlight registry tweaking, but I'm hoping there is a machine setting or some other thing that I can query. Any ideas?
You can do this by calling the GetKeyboardLayoutName() Win32 API method. Dvorak keyboards have specific names. For example, the U.S. Dvorak layout has a name of 00010409. Code snippet: ``` public class Program { const int KL_NAMELENGTH = 9; [DllImport("user32.dll")] private static extern long GetKeyboardLayoutName( System.Text.StringBuilder pwszKLID); static void Main(string[] args) { StringBuilder name = new StringBuilder(KL_NAMELENGTH); GetKeyboardLayoutName(name); Console.WriteLine(name); } } ```
that probably depends on the OS. I'm sure that there is an operatingsystem setting somewhere that registers the nationality of the keyboard. (Dvorak is considered a nationality because French keyboards are different from US keyboards are different from ...) Also, just a side note: 'A' was a bad example, as 'A' happens to be the same key in dvorak and qwerty... B-)
Keyboard Type (Qwerty or Dvorak) detection
[ "", "c#", "" ]
> **Possible Duplicate:** > [Finding the Variable Name passed to a Function in C#](https://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp) In C#, is there a way (terser the better) to resolve the name of a parameter at runtime? For example, in the following method, if you renamed the method parameter, you'd also have to remember to update the string literal passed to ArgumentNullException. ``` public void Woof(object resource) { if (resource == null) { throw new ArgumentNullException("resource"); } // .. } ```
One way: ``` static void Main(string[] args) { Console.WriteLine("Name is '{0}'", GetName(new {args})); Console.ReadLine(); } ``` This code also requires a supporting function: ``` static string GetName<T>(T item) where T : class { var properties = typeof(T).GetProperties(); Enforce.That(properties.Length == 1); return properties[0].Name; } ``` Basically the code works by defining a new Anonymous Type with a single Property consisting of the parameter who's name you want. GetName() then uses reflection to extract the name of that Property. There are more details here: <http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html>
Short answer: No, there isn't. (Is that terse enough? ;) (EDIT: Justin's answer probably counts. It leaves a bad taste in my mouth, but it accomplishes the goal of "no need to put the parameter name into a string". I don't think I'd really count AOP though, as that's really changing to a completely different approach rather than answering the original question of getting a parameter name from within a method.) Longer answer: There's a way to find out *all the parameters* of a method, but I don't think it's useful in this case. Here's an example which displays the parameter names from a couple of methods: ``` using System; using System.Reflection; class Test { static void Main() { Foo(null); Bar(null); } static void Foo(object resource) { PrintParameters(MethodBase.GetCurrentMethod()); } static void Bar(object other) { PrintParameters(MethodBase.GetCurrentMethod()); } static void PrintParameters(MethodBase method) { Console.WriteLine("{0}:", method.Name); foreach (ParameterInfo parameter in method.GetParameters()) { Console.WriteLine(" {0} {1}", parameter.ParameterType, parameter.Name); } } } ``` So that does that, but if you have multiple parameters and you wanted to throw an appropriate exception, how would you know (in a safe way) which to use? Ideally you want something like: ``` public void Woof(object resource) { if (resource == null) { throw new ArgumentNullException(infoof(resource)); } // .. } ``` where the mythical `infoof` operator would return a `ParameterInfo`. Unfortunately this doesn't exist.
Resolving a parameter name at runtime
[ "", "c#", "reflection", "anonymous-types", "" ]
I need to build a primary key consisting of 3 sections. * The first section is 3 letters long and must be an a followed by two digits eg "a00" * The second section is a 3 digit unique identifier INCLUDING LEADING ZEROES, example "003" * The third section is the year section of the date, eg "2008" This is all separated with dashes, so a complete key would look like "a00-014-2008" My solution is to hold three separate columns with the data for each, unformatted, then add the clustered primary key constraint and format it when I need to display it in a view. Is this a good way of going about it? I think there might be a way to make the whole key on update using a trigger but I don't know how. Also how would I concatenate and display it in a view? Though not a homework question, this will help me academically.
``` CREATE TABLE mytable ( first TINYINT NOT NULL CHECK(first BETWEEN 0 AND 99), second INT NOT NULL CHECK (second BETWEEN 0 AND 999), third INT NOT NULL, CONSTRAINT pk_mytable_123 PRIMARY KEY (first, second, third) ) GO CREATE VIEW v_mytable AS SELECT 'a' + RIGHT('00' + CAST(first AS VARCHAR), 2) AS first, RIGHT('0000' + CAST(second AS VARCHAR), 4) AS second, third FROM mytable GO INSERT INTO mytable VALUES (1, 1, 2008) GO SELECT * FROM v_mytable GO first second third ---- ---- ---- a01 0001 2008 ``` This primary key will hold only `INT` values, all formatting will be done in the view. Note that to achive best results in terms of performance, you better create computed columns instead of the view, and create an additional `UNIQUE` index in these columns: ``` CREATE TABLE mytable ( _first TINYINT NOT NULL CHECK(_first BETWEEN 0 AND 99), _second INT NOT NULL CHECK (_second BETWEEN 0 AND 999), third INT NOT NULL, first AS 'a' + RIGHT('00' + CAST(_first AS VARCHAR), 2), second AS RIGHT('0000' + CAST(_second AS VARCHAR), 4) CONSTRAINT pk_mytable_123 PRIMARY KEY (_first, _second, third) ) CREATE UNIQUE INDEX ux_mytable_123 ON mytable (first, second, third) ```
My question is: do any of these three values have meaning by themselves? Or are they simply components of a primary key? If they have absolutely no other meaning then imho you are better off just creating a single column with the whole value. Now "meaning" may be hard to qualify. It could mean that it's a particular customer code or something that is searched on or, well, lots of things. Generally I try and avoid composite keys as they complicate joins and usually make your life difficult with ORMs (that typically view such practice - rightly or wrongly - as "legacy"). If those fields do have meaning then arguably they shouldn't be part of the primary key. I view such a practice as a [mistake](https://stackoverflow.com/questions/621884/database-development-mistakes-made-by-appdevelopers/621891#621891). I nearly always use auto number columns or sequences for primary key values (known as a "technical key" as opposed to a semantic key). Given that the user supplies part of this and it needs to be formatted a particular way, I am assuming the key has a whole has a meaning, be it a product code, patient code, booking number or something like that. Would that be correct? If so, given that and my almost complete preference for technical keys (opinions vary on this issue) I would consider not making this the primary key. Create an auto number field for that. Just make this as acolumn with a unique index that is varchar(12) or whatever.
Build and display a complex composite primary key in a column
[ "", "sql", "sql-server", "" ]
What's the equivalent of an MS-Access crosstab query in TSQL? And Is there a better way? I have a data organised like this: ``` Fish ID Name ---- --------- 1 Jack 2 Trout 3 Bass 4 Cat FishProperty ID FishID Property Value ---- ------ -------- ----- 1 1 Length 10 2 1 Girth 6 3 1 Weight 4 4 2 Length 6 5 2 Weight 2 6 3 Girth 12 ``` I have a number of users who need to do reporting on the data and (obviously) it would be easier for them if they could see it like this: ``` Fish ID Name Length Girth Weight ---- --------- ------ ----- ------ 1 Jack 10 6 4 2 Trout 6 2 3 Bass 12 ``` My plan was to create a crosstab-like view that they could report on directly.
Are you looking for [PIVOT](http://www.databasejournal.com/features/mssql/article.php/3516331/SQL-Pivot-and-Cross-Tab.htm)? **Edit**: You may have to get to the second page before you see the usage of the PIVOT syntax. **Edit 2**: Another [example](http://www.mssqltips.com/tip.asp?tip=1019). **Example**: ``` SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles FROM (SELECT SalesPerson, Product, SalesAmount FROM ProductSales ) ps PIVOT ( SUM (SalesAmount) FOR Product IN ( [Oranges], [Pickles]) ) AS pvt ``` **Edit 3** CodeSlave, take a look at this [blog entry](http://sqlserver-qa.net/blogs/t-sql/archive/2008/08/27/4809.aspx) for some more information concerning dynamic pivot queries.
As an alternative for a PIVOT query, you could create a view like this: ``` create view dbo.myview as select fish.ID , fish.Name , len.Value as Length , gir.Value as Girth , wei.Value as Weight from fish left join fishproperty len on len.fishid = fish.id and len.property = 'Length' left join fishproperty gir on gir.fishid = fish.id and gir.property = 'Girth' left join fishproperty wei on wei.fishid = fish.id and wei.property = 'Weight' ``` If you don't know the columns ahead of time, the only solution I can think of is to generate the query dynamically and use "exec sp\_executesql" to run it. For example: ``` declare @query nvarchar(4000) set @query = 'select ... from fish' -- For each column set @query = @query + ' left join fishproperty ' + propname + ' on ' + propname + '.fishid = fish.id ' + 'and ' + propname + '.property = ''' + propname + ''' ' exec sp_executesql @query ``` Warning: dynamic queries can be a maintenance headache.
TSQL equivalent of an MS Access Crosstab query
[ "", "sql", "sql-server", "t-sql", "ms-access", "" ]
We are using C# and Linq2SQL to get data from a database for some reports. In some cases this takes a while. More than 30 seconds, which seems to be the default `CommandTimeout`. So, I guess I have to up the `CommandTimeout`. But question is, how much? Is it bad to just set it very high? Wouldn't it be bad if a customer was trying to do something and just because he happend to have a lot more data in his database than the average customer he couldn't get his reports out because of timeouts? But how can I know how much time it potentially could take? Is there some way to set it to infinity? Or is that considered very bad? And where should I set it? I have a static database class which generates a new datacontext for me when I need it. Could I just create a constant and set it whenever I create a new datacontext? Or should it be set to different values depending on the usecase? Is it bad to have a high timeout for something that wont take much time at all? Or doesn't it really matter? Too high `ConnectionTimeout` can of course be more annoying. But is there a case where a user/customer would like something to time out? Can the SQL server freeze so that a command never finishes?
`CommandTimeout` etc should indeed only be increased on per-specific-scenario basis. This can avoid unexpectedly long blocking etc scenarios (or worse: the undetected deadlock scenario). As for *how* high... how long does the query take? Add some headroom and you have your answer. The other thing to do, of course, is to reduce the time the query takes. This might mean hand-optimising some TSQL in a sproc, usually in combination with checking the indexing strategy, and perhaps bigger changes such as denormalization, or other schema changes. This might also involve a data-warehousing strategy so you can shift load to a separate database (away from the transactional data), with a schema optimised for reporting. Maybe a star-schema. I wouldn't set it to infinity... I don't expect it to take forever to run a report. Pick a number that makes sense for the report. Yes, SQL Server can freeze so that a command never finishes. An open blocking transaction would be the simplest... get two and you can deadlock. Usually the system will detect a local deadlock - but not always, especially if DTC is involved (i.e. non-local locks).
IMHO, An advanced option for your user to set the ConnectionTimeout value would be better than any constant value you determine.
C#, Linq2SQL: How long should CommandTimeout be and where should it be set?
[ "", "c#", "sql-server", "linq-to-sql", "timeout", "command", "" ]
This is a simple question I think. I am trying to search for the occurrence of a string in another string using regex in JavaScript like so: ``` var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: "; var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g"); if(content.search(gent) != -1){ alert('worked'); } ``` This doesn't work because of the `?` character....I tried escaping it with `\`, but that doesn't work either. Is there another way to use `?` literally instead of as a special character?
You need to escape it with two backslashes ``` \\? ``` See this for more details: <http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm>
You should use double slash: ``` var regex = new RegExp("\\?", "g"); ``` Why? because in JavaScript the `\` is also used to escape characters in strings, so: "\?" becomes: `"?"` And `"\\?"`, becomes `"\?"`
escaping question mark in regex javascript
[ "", "javascript", "regex", "literals", "" ]
I'm trying to parse through e-mails in Outlook 2007. I need to streamline it as fast as possible and seem to be having some trouble. Basically it's: ``` foreach( Folder fld in outllookApp.Session.Folders ) { foreach( MailItem mailItem in fld ) { string body = mailItem.Body; } } ``` and for 5000 e-mails, this takes over 100 seconds. It doesn't seem to me like this should be taking anywhere near this long. If I add: ``` string entry = mailItem.EntryID; ``` It ends up being an extra 30 seconds. I'm doing all sorts of string manipulations including regular expressions with these strings and writing out to database and still, those 2 lines take 50% of my runtime. I'm using Visual Studio 2008
Doing this kind of thing will take a long time as you having to pull the data from the exchange store for each item. I think that you have a couple of options here.. Process this information out of band use CDO/RDO in some other process. Or Use MapiTables as this is the fastest way to get properties there are caveats with this though and you may be doing things in your processin that can be brought into a table. Redemption wrapper - <http://www.dimastr.com/redemption/mapitable.htm> MAPI Tables <http://msdn.microsoft.com/en-us/library/cc842056.aspx>
I do not know if this will address your specific issue, but the latest Office 2007 service pack made a synificant performance difference (improvement) for Outlook with large numbers of messages.
Outlook 2007 MailItem Info - slow
[ "", "c#", "visual-studio-2008", "outlook", "outlook-2007", "" ]
I was reading a [blog post](http://forums.introversion.co.uk/defcon/introversion/viewtopic.php?p=79603#79603) by a game coder for [Introversion](http://Introversion.co.uk) and he is busily trying to squeeze every [CPU](http://en.wikipedia.org/wiki/Central_processing_unit) tick he can out of the code. One trick he mentions off-hand is to > "re-order the member variables of a > class into most used and least used." I'm not familiar with C++, nor with how it compiles, but I was wondering if 1. This statement is accurate? 2. How/Why? 3. Does it apply to other (compiled/scripting) languages? I'm aware that the amount of (CPU) time saved by this trick would be minimal, it's not a deal-breaker. But on the other hand, in most functions it would be fairly easy to identify which variables are going to be the most commonly used, and just start coding this way by default.
Two issues here: * Whether and when keeping certain fields together is an optimization. * How to do actually do it. The reason that it might help, is that memory is loaded into the CPU cache in chunks called "cache lines". This takes time, and generally speaking the more cache lines loaded for your object, the longer it takes. Also, the more other stuff gets thrown out of the cache to make room, which slows down other code in an unpredictable way. The size of a cache line depends on the processor. If it is large compared with the size of your objects, then very few objects are going to span a cache line boundary, so the whole optimization is pretty irrelevant. Otherwise, you might get away with sometimes only having part of your object in cache, and the rest in main memory (or L2 cache, perhaps). It's a good thing if your most common operations (the ones which access the commonly-used fields) use as little cache as possible for the object, so grouping those fields together gives you a better chance of this happening. The general principle is called "locality of reference". The closer together the different memory addresses are that your program accesses, the better your chances of getting good cache behaviour. It's often difficult to predict performance in advance: different processor models of the same architecture can behave differently, multi-threading means you often don't know what's going to be in the cache, etc. But it's possible to talk about what's *likely* to happen, most of the time. If you want to *know* anything, you generally have to measure it. Please note that there are some gotchas here. If you are using CPU-based atomic operations (which the atomic types in C++0x generally will), then you may find that the CPU locks the entire cache line in order to lock the field. Then, if you have several atomic fields close together, with different threads running on different cores and operating on different fields at the same time, you will find that all those atomic operations are serialised because they all lock the same memory location even though they're operating on different fields. Had they been operating on different cache lines then they would have worked in parallel, and run faster. In fact, as Glen (via Herb Sutter) points out in his answer, on a coherent-cache architecture this happens even without atomic operations, and can utterly ruin your day. So locality of reference is not *necessarily* a good thing where multiple cores are involved, even if they share cache. You can expect it to be, on grounds that cache misses usually are a source of lost speed, but be horribly wrong in your particular case. Now, quite aside from distinguishing between commonly-used and less-used fields, the smaller an object is, the less memory (and hence less cache) it occupies. This is pretty much good news all around, at least where you don't have heavy contention. The size of an object depends on the fields in it, and on any padding which has to be inserted between fields in order to ensure they are correctly aligned for the architecture. C++ (sometimes) puts constraints on the order which fields must appear in an object, based on the order they are declared. This is to make low-level programming easier. So, if your object contains: * an int (4 bytes, 4-aligned) * followed by a char (1 byte, any alignment) * followed by an int (4 bytes, 4-aligned) * followed by a char (1 byte, any alignment) then chances are this will occupy 16 bytes in memory. The size and alignment of int isn't the same on every platform, by the way, but 4 is very common and this is just an example. In this case, the compiler will insert 3 bytes of padding before the second int, to correctly align it, and 3 bytes of padding at the end. An object's size has to be a multiple of its alignment, so that objects of the same type can be placed adjacent in memory. That's all an array is in C/C++, adjacent objects in memory. Had the struct been int, int, char, char, then the same object could have been 12 bytes, because char has no alignment requirement. I said that whether int is 4-aligned is platform-dependent: on ARM it absolutely has to be, since unaligned access throws a hardware exception. On x86 you can access ints unaligned, but it's generally slower and IIRC non-atomic. So compilers usually (always?) 4-align ints on x86. The rule of thumb when writing code, if you care about packing, is to look at the alignment requirement of each member of the struct. Then order the fields with the biggest-aligned types first, then the next smallest, and so on down to members with no aligment requirement. For example if I'm trying to write portable code I might come up with this: ``` struct some_stuff { double d; // I expect double is 64bit IEEE, it might not be uint64_t l; // 8 bytes, could be 8-aligned or 4-aligned, I don't know uint32_t i; // 4 bytes, usually 4-aligned int32_t j; // same short s; // usually 2 bytes, could be 2-aligned or unaligned, I don't know char c[4]; // array 4 chars, 4 bytes big but "never" needs 4-alignment char d; // 1 byte, any alignment }; ``` If you don't know the alignment of a field, or you're writing portable code but want to do the best you can without major trickery, then you assume that the alignment requirement is the largest requirement of any fundamental type in the structure, and that the alignment requirement of fundamental types is their size. So, if your struct contains a uint64\_t, or a long long, then the best guess is it's 8-aligned. Sometimes you'll be wrong, but you'll be right a lot of the time. Note that games programmers like your blogger often know everything about their processor and hardware, and thus they don't have to guess. They know the cache line size, they know the size and alignment of every type, and they know the struct layout rules used by their compiler (for POD and non-POD types). If they support multiple platforms, then they can special-case for each one if necessary. They also spend a lot of time thinking about which objects in their game will benefit from performance improvements, and using profilers to find out where the real bottlenecks are. But even so, it's not such a bad idea to have a few rules of thumb that you apply whether the object needs it or not. As long as it won't make the code unclear, "put commonly-used fields at the start of the object" and "sort by alignment requirement" are two good rules.
Depending on the type of program you're running this advice may result in increased performance or it may slow things down drastically. Doing this in a multi-threaded program means you're going to increase the chances of 'false-sharing'. Check out Herb Sutters articles on the subject [here](https://web.archive.org/web/20130723111632/http://www.drdobbs.com/article/print?articleId=217500206&siteSectionName=parallel) I've said it before and I'll keep saying it. The only real way to get a real performance increase is to measure your code, and use tools to identify the real bottle neck instead of arbitrarily changing stuff in your code base.
Optimizing member variable order in C++
[ "", "c++", "performance", "optimization", "embedded", "" ]
Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?
The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent. * Last known Twisted version of BitTorrent + <http://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz> * Older versions + <http://download.bittorrent.com/dl/archive/> As an alternative, you also might want to take a look at [Vertex](https://github.com/twisted/vertex). It is a p2p library built on top of Twisted and comes with goodies like bypassing firewalls. Its probably more complete than the other people's sample. * Link to Vertex + <https://github.com/twisted/vertex>
[bittorrent twisted python client/server](http://code.activestate.com/recipes/440555/)
Twisted and p2p applications
[ "", "python", "twisted", "protocols", "p2p", "" ]
I am completely new to flash. We need to load a binary file from the user system (must work in Flash 9) and do some process in flash and save it back to the file system. I think that this would have to be done by getting the file in JavaScript and then encoding it send it to Flash.
Local file system access is in [Flash 10](http://www.adobe.com/products/flashplayer/features/) with the [File Reference](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/FileReference.html) enhancements. You're out of luck if targetting Flash 9. Javascript cannot access the local filesystem either.
<http://weblogs.macromedia.com/flashjavascript/> <http://kb2.adobe.com/cps/156/tn_15683.html> Those are two good links reguarding javascript communications
JavaScript to Flash and Back?
[ "", "javascript", "flash", "" ]
I've seen any number of examples and they all seem to solve this problem differently. Basically I just want the simplest way to make the request that won't lock the main thread and is cancelable. It also doesn't help that we have (at least) 2 HTTP libraries to choose from, java.net.\* (such as HttpURLConnection) and org.apache.http.\*. Is there any consensus on what the best practice is?
The Android 1.5 SDK introduced a new class, [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) designed to make running tasks on a background thread and communicating a result to the UI thread a little simpler. An example given in the [Android Developers Blog](http://android-developers.blogspot.com/2009/05/painless-threading.html) gives the basic idea on how to use it: ``` public void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png"); } private class DownloadImageTask extends AsyncTask { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); } } ``` The `doInBackgroundThread` method is called on a separate thread (managed by a thread pooled `ExecutorService`) and the result is communicated to the `onPostExecute` method which is run on the UI thread. You can call `cancel(boolean mayInterruptIfRunning)` on your `AsyncTask` subclass to cancel a running task. As for using the `java.net` or `org.apache.http` libraries for network access, it's up to you. I've found the `java.net` libraries to be quiet pleasant to use when simply trying to issue a `GET` and read the result. The `org.apache.http` libraries will allow you to do almost anything you want with `HTTP`, but they can be a little more difficult to use and I found them not to perform as well (on Android) for simple `GET` requests.
Actually there are a couple of flaws in the design of AsyncTasks that prevent it from being really usable for networking. An easy example is that you will loose the link between your AsyncTask and your Activity ... just by rotating your device. Have a look at [this thread](https://stackoverflow.com/q/3357477/693752) : you will see that AsyncTask also very easily create memory leaks. The AsyncTask documentation is clear about that : AsyncTask should only be used for short living tasks and, obvisouly enough, networking doesn't belong to that category. So, I really suggest you have a look at [RoboSpice](https://github.com/octo-online/robospice). This library has been designed for asynchronous networking and it's a very robust way to implement it. If you only have a few seconds to be convinced, look at this [inforgraphics](http://goo.gl/jxNin). RoboSpice also as a demo application on the store : [RoboSpice Motivations](http://goo.gl/pzqH4) that will explain everything, in depth, about asynchronous networking on Android.
Is there an accepted best-practice on making asynchronous HTTP requests in Android?
[ "", "java", "android", "http", "" ]
According to [here](http://c-faq.com/struct/padding.html), the C compiler will pad out values when writing a structure to a binary file. As the example in the link says, when writing a struct like this: ``` struct { char c; int i; } a; ``` to a binary file, the compiler will usually leave an unnamed, unused hole between the char and int fields, to ensure that the int field is properly aligned. How could I to create an exact replica of the binary output file (generated in C), using a different language (in my case, Java)? Is there an automatic way to apply C padding in Java output? Or do I have to go through compiler documentation to see how it works (the compiler is g++ by the way).
This is true not only when writing to files, but also in memory. It is the fact that the struct is padded in memory, that leads to the padding showing up in the file, if the struct is written out byte-by-byte. It is in general very hard to replicate with certainty the exact padding scheme, although I guess some heuristics would get you quite far. It helps if you have the struct declaration, for analysis. Typically, fields larger than one char will be aligned so that their starting offset inside the structure is a multiple of their size. This means `short`s will generally be on even offsets (divisible by 2, assuming `sizeof (short) == 2`), while `double`s will be on offsets divisible by 8, and so on. **UPDATE**: It is for reasons like this (and also reasons having to do with endianness) that it is generally a bad idea to dump whole structs out to files. It's better to do it field-by-field, like so: ``` put_char(out, a.c); put_int(out, a.i); ``` Assuming the `put`-functions only write the bytes needed for the value, this will emit a padding-less version of the struct to the file, solving the problem. It is also possible to ensure a proper, known, byte-ordering by writing these functions accordingly.
Don't do this, it is brittle and will lead to alignment and endianness bugs. For external data it is much better to explicitly define the format in terms of bytes and write explicit functions to convert between internal and external format, using shift and masks (not union!).
Replicating C struct padding in Java
[ "", "java", "c", "compiler-construction", "padding", "" ]
I have this code for doing an ajax request to a webservice: ``` var MyCode = { req: new XMLHttpRequest(), // firefox only at the moment service_url: "http://url/to/Service.asmx", sayhello: function() { if (this.req.readyState == 4 || this.req.readyState == 0) { this.req.open("POST", this.service_url + '/HelloWorld', true); this.req.setRequestHeader('Content-Type','application/json; charset=utf-8'); this.req.onreadystatechange = this.handleReceive; var param = '{}'; this.req.send(param); } }, handleReceive: function() { if (this.req.readyState == 4) { // todo: using eval for json is dangerous var response = eval("(" + this.req.responseText + ")"); alert(response); } } } ``` It is called with MyCode.sayhello() of course. The problem with it is that "req is not defined" at the first line in the handleReceive function. It does get called 4 times, so I know the code above sends the request to the server. How can I solve this?
Classic closure problem. When you get the callback, the closure actually refers already to the HTTP object. You can do the following as someone suggests: ``` var that = this; this.req.onreadystatechange = function() { this.handleReceive.apply(that, []); }; ``` OR just do the following: ``` var that = this; this.req.onreadystatechange = function() { that.handleReceive(); }; ```
You can solve that by makeing a variable refering to this in MyCode. Like ``` var MyCode = { req: new XMLHttpRequest(), // firefox only at the moment self = this ... } ``` Then you can refer to self in stead of this.
The value of 'this' in a callback function
[ "", "javascript", "ajax", "" ]
Let's say I have a structure named vertex with a method that adds two vertices: ``` struct vertex { float x, y, z; // constructs the vertex with initial values vertex(float ix, float iy, float iz); // returns the value c = this + b vertex operator+(vertex b); }; vertex::vertex(float ix, float iy, float iz){ this->x = ix; this->y = iy; this->z = iz; } vertex vertex::operator+(vertex b){ vertex c; c.x = this->x + b.x; c.y = this->y + b.y; c.z = this->z + b.z; return c; } ``` In another calling function I want to add two vertices together and add the result to a `vector<vertex*>`. When is it safe to use the returned value to add to the given vector? If never, how would I implement it? For example, ``` vector<vertex*> v; vertex a(1, 2, 3); vertex b(4, 5, 6); v.push_back(&(a + b)); ```
This is not safe, since you are storing a pointer to an automatic or temporary variable, which will be reclaimed when the current function terminates. Mixing dynamically allocated objects with automatically-allocated ones is a serious risk. Sometimes the best strategy is to completely disallow automatic allocation (e.g., by making the constructor private and using a factory method to create new instance). You would then be responsible for eliminating these at some point. A second option (not necessarily what you want) is to do everything by value. Have a vector of Vertex rather than Vertex\*, and just have the vertices copied when they are stored. The way your class is written, all the fields are primitives, so this might be good enough and you wouldn't run into performance or deep-copy semantic problems.
It's never save, since you add a pointer to a temporary object to the vector. That temporary object will be destroyed after the line is executed, leaving the vector with an invalid pointer. You have two possibilities. Either you don't store pointers in the vector and use a `vector<vertex>` instead, or you explicitly allocate a new copy of the temporary object when you add it: ``` v.push_back(new vertex(a+b)); ```
When is it safe to add object values to vectors on the heap?
[ "", "c++", "" ]
I would really like to do something like this: ``` Callable<MyObject> myCallable = .... Future<MyObject> = new Thread( myCallable).start(); ``` I basically want to start a single long-running task that runs in parallel with my main task, and I do not want pooling or thread re-use. The Executors stuff seems to be very pooling oriented and it requires me to shut down the pool, all of which I don't want to do. I *want* to use the "Callable/Future" pattern because I may later have to introduce Executors, but as things currently stand they're just overhead. Any suggestions ?
Try FutureTask. It doesn't have any explicit dependency on the Executor framework and can be instantiated as is, or you can extend it to customize it.
Well, you can fairly easily write a helper method: ``` public static Future<T> createFuture(Callable<T> callable) { ExecutorService service = Executors.newSingleThreadExecutor(); Future<T> ret = service.submit(callable); // Let the thread die when the callable has finished service.shutdown(); return ret; } ``` EDIT: To expand on [alphazero's answer](https://stackoverflow.com/questions/839440/how-can-i-get-a-futuremyobject-without-using-executorservice/839467#839467), you'd use `FutureTask` like this: ``` FutureTask<MyObject> future = new FutureTask<MyObject>(myCallable); new Thread(future).start(); // FutureTask implements Runnable // Now use the future however you want ``` And yes, I'd say this is nicer than my first answer :)
How can I get a Future<MyObject> without using ExecutorService?
[ "", "java", "multithreading", "" ]
As I try to modernize my C++ skills, I keep encountering this situation where "the STL way" isn't obvious to me. I have an object that wants to gather contributions from multiple sources into a container (typically a `std::vector`). Each source is an object, and each of those objects provides a method `get_contributions()` that returns any number of contributions (from 0 to many). The gatherer will call `get_contributions()` on each contributor and aggregate the results into a single collection. The question is, what's the best signature for `get_contributions()`? Option 1: `std::vector<contribution> get_contributions() const` This is the most straightforward, but it leads to lots of copying as the gatherer copies each set of results into the master collection. And yes, performance matters here. For example, if the contributors were geometric models and getting contributions amounted to tesselating them into triangles for rendering, then speed would count and the number of contributions could be enormous. Option 2: `template <typename container> void get_contributions(container &target) const` This allows each contributor to add its contributions directly to the master container by calling `target.push_back(foo)`. The drawback here is that we're exposing the container to other types of inspection and manipulation. I'd prefer to keep the interface as narrow as possible. Option 3: `template <typename out_it> void get_contributions(out_it &it) const` In this solution, the aggregator would pass a `std::back_insert_iterator` for the master collection, and the individual contributors would do `*it++ = foo;` for each contribution. This is the best I've come up with so far, but I'm left with the feeling that there must be a more elegant way. The `back_insert_iterator` feels like a kludge. Is Option 3 the best, or is there a better approach? Does this gathering pattern have a name?
Option 3 is the most idiomatic way. Note that you don't have to use back\_insert\_iterator. If you know how many elements are going to be added, you can resize the vector, and then provide a regular vector iterator instead. It won't call push\_back then (and potentially save you some copying) `back_insert_iterator`'s main advantage is that it expands the vector as needed. It's not a kludge though. It's designed for this exact purpose. One minor adjustment would be to take pass the iterator by value, and then return it when the function returns.
There's a fourth, that would require you to define you iterator ranges. Check out Alexandrescu's presentation on ["Iterators must go"](http://www.boostcon.com/site-media/var/sphene/sphwiki/attachment/2009/05/08/iterators-must-go.pdf).
Aggregating contributions from multiple donors
[ "", "c++", "generics", "stl", "" ]
This Codes give me error: **Msg 156, Level 15, State 1, Procedure DefaultActivity, Line 2 Incorrect syntax near the keyword 'RETURN'. Msg 137, Level 15, State 2, Procedure DefaultActivity, Line 3 Must declare the scalar variable "@returnTable". Msg 1087, Level 15, State 2, Procedure DefaultActivity, Line 18 Must declare the table variable "@returnTable".** ``` CREATE FUNCTION dbo.DefaultActivity RETURNS @returnTable table ( [VisitingCount] int, [Time] nvarchar(50) ) AS BEGIN DECLARE @DateNow DATETIME,@i int set @DateNow='00:00' set @i=1; while(@i<1440) begin set @DateNow=DATEADD(minute, 1, @DateNow) insert into @returnTable ([VisitingCount], [Time]) values(0, right(left(convert(nvarchar, @DateNow, 121), 16), 5)) set @i=@i+1 end RETURN END ```
This should work: ``` CREATE FUNCTION dbo.DefaultActivity () RETURNS @returnTable TABLE ( [VisitingCount] int, [Time] nvarchar(50) ) AS BEGIN DECLARE @DateNow DATETIME,@i int set @DateNow='00:00' set @i=1; while(@i<1440) begin set @DateNow=DATEADD(minute, 1, @DateNow) insert into @returnTable ([VisitingCount], [Time]) values(0, right(left(convert(nvarchar, @DateNow, 121), 16), 5)) set @i=@i+1 end RETURN END GO select * from dbo.DefaultActivity() ```
Try specifying an empty argument list? ``` CREATE FUNCTION dbo.DefaultActivity() RETURNS ... ```
How to convert datatable from UDF in SQL?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
For **those of you using Expression Blend** as well as Visual Studio in your real projects, please help me understand **how you use Blend and Visual Studio in your everyday development/design tasks**, here is a real scenario: I created the following simple WPF application in Visual Studio. It **shows a list of customer objects with a DataTemplate** that shows the customers in simple orange boxes. I now **want put some pizazz into this DataTemplate** by using Expression Blend. I **open the project in Expression Blend** thinking that I'm going to see the orange boxes which I can change the color of, create an animation as I mouse over them, resize it, etc. However, **all I see in Expression Blend is a completely blank box**. So I understand: * Expression Blend **can't seem to understand that my data is coming from the ViewModel** and hence doesn't display it. Is this a limitation of Blend or do I need to change my code in some way so that Blend can interpret what data will be coming out at run-time? * I'm using Expression Blend 3 which has "sample data" capability. **What is the best way to use this sample data feature** so that even if it can't interpret the C# and understand what data will be coming out of the ViewModel property to fill the Listbox, how can I get it to at least produce some dummy data so that I can manipulate the DataTemplate? **XAML:** ``` <Window x:Class="TestStringFormat234.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Window.Resources> <DataTemplate x:Key="DataTemplateCustomers"> <Border CornerRadius="5" Background="Orange" Padding="5" Margin="3"> <StackPanel Orientation="Horizontal"> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0} {1} (hired on {2:MMM dd, yyyy})"> <Binding Path="FirstName"/> <Binding Path="LastName"/> <Binding Path="HireDate"/> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel> </Border> </DataTemplate> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding GetAllCustomers}" ItemTemplate="{StaticResource DataTemplateCustomers}"> </ListBox> </Grid> </Window> ``` **Code Behind:** ``` using System.Windows; using System.Collections.ObjectModel; using System; namespace TestStringFormat234 { public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = new CustomerViewModel(); } } //view model public class CustomerViewModel { public ObservableCollection<Customer> GetAllCustomers { get { ObservableCollection<Customer> customers = new ObservableCollection<Customer>(); customers.Add(new Customer { FirstName = "Jim", LastName = "Smith", HireDate = DateTime.Parse("2007-12-31") }); customers.Add(new Customer { FirstName = "Jack", LastName = "Jones", HireDate = DateTime.Parse("2005-12-31") }); return customers; } } } //model public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime HireDate { get; set; } } } ```
I just figured this out so allow me to answer my own question. I read [Laurent's Bugnion enlighting article on this](http://www.galasoft.ch/mydotnet/articles/article-2007091401.html) and it turns out I just had to tweak the above code so that I could see the Data from my ViewModel displayed in the Expression Blend GUI and was able to edit the DataTemplate in Blend, save it, and then continued editing in Visual Studio. Basically the changes are: (1) take out the DataContext statement from code behind, (2) add the "local" namespace in XAML, (3) define a local data provider in XAML ("TheDataProvider"), (4) bind to it directly from the ListBox. Here is the code that works in Expression Blend and Visual Studio in full: **XAML:** ``` <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestStringFormat234" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Name="window" x:Class="TestStringFormat234.Window1" Title="Window1" Height="300" Width="300" mc:Ignorable="d"> <Window.Resources> <local:CustomerViewModel x:Key="TheDataProvider"/> <DataTemplate x:Key="DataTemplateCustomers"> <Border CornerRadius="5" Padding="5" Margin="3"> <Border.Background> <LinearGradientBrush EndPoint="1.007,0.463" StartPoint="-0.011,0.519"> <GradientStop Color="#FFF4EEEE" Offset="0"/> <GradientStop Color="#FFA1B0E2" Offset="1"/> </LinearGradientBrush> </Border.Background> <StackPanel Orientation="Horizontal"> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0} {1} (hired on {2:MMM dd, yyyy})"> <Binding Path="FirstName"/> <Binding Path="LastName"/> <Binding Path="HireDate"/> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel> </Border> </DataTemplate> </Window.Resources> <Grid > <ListBox ItemsSource="{Binding Path=GetAllCustomers, Source={StaticResource TheDataProvider}}" ItemTemplate="{StaticResource DataTemplateCustomers}" /> </Grid> </Window> ``` **Code Behind:** ``` using System.Windows; using System.Collections.ObjectModel; using System; namespace TestStringFormat234 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } } //view model public class CustomerViewModel { public ObservableCollection<Customer> GetAllCustomers { get { ObservableCollection<Customer> customers = new ObservableCollection<Customer>(); customers.Add(new Customer { FirstName = "Jim", LastName = "Smith", HireDate = DateTime.Parse("2007-12-31") }); customers.Add(new Customer { FirstName = "Jack", LastName = "Jones", HireDate = DateTime.Parse("2005-12-31") }); return customers; } } } //model public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime HireDate { get; set; } } } ```
I've got a blog post on this issue: <http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/> My post is all about showing data in blend *without* having to have that data displayed or even created at runtime.
How can I use Expression Blend to edit a DataTemplate created in Visual Studio?
[ "", "c#", "wpf", "expression-blend", "" ]
This is one of my most dreaded C/C++ compiler errors: > file.cpp(3124) : fatal error C1004: unexpected end-of-file found file.cpp includes almost a hundred header files, which in turn include other header files. It's over 3000 lines. The code should be modularized and structured, the source files smaller. We should refactor it. As a programmer there's always a wish list for improving things. But right now, the code is a mess and the deadline is around the corner. *Somewhere* among all these lines—quite possibly in one of the included header files, not in the source file itself—there's apparently an unmatched brace, unmatched #ifdef or similar. The problem is that when something is missing, the compiler can't really tell me *where* it is missing. It just knows that when it reached end of the file it wasn't in the right parser state. Can you offer some tools or other hints / methodologies to help me find the cause for the error?
If the #includes are all in one place in the source file, you could try putting a stray closing brace in between the #includes. If you get an 'unmatched closing brace' error when you compile, you know it all balances up to that point. It's a slow method, but it might help you pinpoint the problem.
One approach: if you have Notepad++, open all of the files (no problem opening 100 files), search for { and } (Search -> Find -> Find in All Open Documents), note the difference in count (should be 1). Randomly close 10 files and see if the difference in count is still 1, if so continue, else the problem is in one of those files. Repeat.
Hints and tools for finding unmatched braces / preprocessor directives
[ "", "c++", "c", "" ]
In Visual Studio when you add a new class, it always created with no modifiers and that makes class internal. ``` class MyClass { } ``` I would prefer that my class by default is created as public one. Why is it internal by default? What would you prefer?
Making class `internal` by default makes perfect sense to me: keep your privates to yourself and only explicitly expose parts which really need to be exposed: everything else is just implementation details and should not be visible to the outside world. In case you want to test your `internal` classes, .NET 2.0 onwards introduces a new attribute called [InternalsVisibleToAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx), which > Specifies that types that are ordinarily visible only within the current assembly are visible to another assembly. If this really annoys you, see `%ProgramFiles%\Microsoft Visual Studio 8\Common7 IDE\ItemTemplates\CSharp\1033\Class.zip`. This is a template which you can change to suit your needs. ReSharper has similar capability, but it's directly accessible from within th UI.
To create a Public class by default for Visual Studio 2012: Edit this file: `C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.cs` (Visual Studio 2022: `C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class`) To look like this: ``` using System; using System.Collections.Generic; $if$ ($targetframeworkversion$ >= 3.5)using System.Linq; $endif$using System.Text; $if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks; $endif$ namespace $rootnamespace$ { public class $safeitemrootname$ { } } ``` More info: <http://aaron-hoffman.blogspot.com/2013/05/edit-default-visual-studio-2012-item.html>
Why Visual Studio doesn't create a public class by default?
[ "", "c#", "visual-studio", "" ]
I have some jquery/php interaction set up on a page. It submits some data to the server and gets back records of data which are then to be aligned on the page for comparison and possible action beyond that. My question is what is the best practice for returning the info and then displaying it? * Return JSON object and then create html on the fly with js and display the data? * Return JSON object and then put that data in already created containers for the data on the page? * Return pure html from the server and just put that on the page? I was rolling these through my head last night and couldn't really figure out if one way would be better for any particular reason. I'm not a js guru so wasn't really sure the pros/cons and caveats to these different methods.
I think it ends up depending on your app. Pure HTML is the easiest, you just drop in in place and viola. JQuery makes it a breeze to add the proper events and what not. However, whenever I've used AJAX it's always evolved into returning JSON and building elements on the fly. If you are populating a tree for example, it may become messy to get the proper nesting. This forces you to have to do client side code anyway at which point simply using JSON from the start is cleaner. Also, If you plan to use the data calls from other pages then using JSON is the way to go because the HTML will bee fixed.
This completely depends on the way you have things set up in your application. I, for one, prefer to return JSON (second approach in your list), because I have an 'error code' parameter that I check in onSuccess function before updating the content on the page, and if it's not zero then I notify the user of the error, including the error message that came back from the server (server-side validation, database timeout, etc.).
Best practices for returning and displaying data from AJAX calls
[ "", "javascript", "jquery", "ajax", "json", "" ]
How can I set a column value at a specified row?
Not sure if you are trying to insert a new row or update a row that meets certain criteria. If the second is true, you need: ``` UPDATE table_name SET column1 = value, column2 = value2 WHERE some_column = some_value ```
To learn more about SQL: <http://www.w3schools.com/sql/default.asp> More info about INSERT: <http://www.w3schools.com/sql/sql_insert.asp> More info about UPDATE: <http://www.w3schools.com/sql/sql_update.asp>
Set a column value at a specified row
[ "", "sql", "" ]
What happens when you call notifyAll method on an object that is not waiting? Should there be exception or is it normal situation?
It is completely normal. You can only notify all that waiting on one single monitor. Everybody else is not interested. The object on which you call notifyAll is just the monitor on which others are waiting. If nobody is waiting nobody has to be notified
As you can see here, calling notifyAll() on an not waiting object does not have any effect. ![alt text](https://www.fh-wedel.de/%7Esi/vorlesungen/java/OOPMitJava/Multithreading/threadStates.png)
Java - wait and notifyAll
[ "", "java", "wait", "" ]