Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a unique situation where I'm building a site that will call data via AJAX and load it into "containers" (basically just divs styled and arranged according to elements retrieved from the AJAX callback). I'm not sure how many of these unique *container types* will be created (styled and rendered) when all is said and done, so I'm looking for a solution that will allow me to store containers in a separate file(s), load them dynamically as they are needed, populate the content, and rendered them on page. I'm not sure if I should write my own loading/template solution or use an existing JavaScript template engine (e.g.: Pure). The reason I'm hesitant to use an existing JavaScript template solution is they all seem focused on binding and looping on existing page elements, whereas I'm more concerned with the ability to load-up and binding to dynamic content.
After starting with JST, we moved to EJS: <http://embeddedjs.com/> It's more powerful, syntactically simpler, and you can put your templates in different files. The website is pretty nice too.
You might want to give **jQote** a try, it's the most powerful jQuery templating engine as it let's you use scripting inside your templates. Go check it out, it'll suit your needs, I promise. [<http://aefxx.com/jquery-plugins/jqote>](http://aefxx.com/jquery-plugins/jqote)
jQuery: Templating data
[ "", "javascript", "jquery", "ajax", "template-engine", "pure-js", "" ]
I am dynamically displaying array of labels on a form and am getting a new set of labels to be displayed on the form when a function is called again. But instead, the previous labels are still on the screen with the new labels. How do I clear the previous set of labels on the form? Thanks
You need to remove the old labels from the Form's "Controls" collection. Is this a good idea/design? Not so sure, but without seeing any code this is the best advice I can offer.
Check out this [article](http://msdn.microsoft.com/en-us/library/aa289500(VS.71).aspx) on "Implementing a Remove Method". You need Controls.Remove.
C# System.Forms.label
[ "", "c#", "winforms", "" ]
If I invoke the `run()` method on a Thread and the `run()` method throws an **uncaught Exception** what would be the outcome ? Who catches this *Exception*? Does the *Exception* even get caught?
If there is an exception handler installed for the ThreadGroup, the JVM passes the exception to it. If it's an AWT thread, you can install an event handler for otherwise unhandled exceptions. Otherwise the JVM handles it. Example of a thread group with a custom handler and how to use it: ``` public class MyThreadGroup extends ThreadGroup { public MyThreadGroup() { super("My Thread Group"); } public void uncaughtException(Thread t, Throwable ex) { // Handle exception } } Thread t = new Thread(new MyThreadGroup(), "My Thread") { ... }; t.start(); ``` Example of using an AWT exception handler: ``` public class MyExceptionHandler { public void handle(Throwable ex) { // Handle exception } public void handle(Thread t, Throwable ex) { // Handle exception } } System.setProperty("sun.awt.exception.handler", MyExceptionHandler.class.getName()); ```
If you've submitted the Runnable to an [ExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html) you can catch the Exception as wrapped inside a [ExecutionException](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutionException.html). (Highly recommended over simply calling run())
what happens when a Thread throws an Exception?
[ "", "java", "multithreading", "" ]
I am writing a simple web service using .NET, one method is used to send a chunk of a file from the client to the server, the server opens a temp file and appends this chunk. The files are quite large 80Mb, the net work IO seems fine, but the append write to the local file is slowing down progressively as the file gets larger. The follow is the code that slows down, running on the server, where aFile is a string, and aData is a byte[] ``` using (StreamWriter lStream = new StreamWriter(aFile, true)) { BinaryWriter lWriter = new BinaryWriter(lStream.BaseStream); lWriter.Write(aData); } ``` Debugging this process I can see that exiting the using statement is slower and slower. If I run this code in a simple standalone test application the writes are the same speed every time about 3 ms, note the buffer (aData) is always the same side, about 0.5 Mb. I have tried all sorts of experiments with different writers, system copies to append scratch files, all slow down when running under the web service. Why is this happening? I suspect the web service is trying to cache access to local file system objects, how can I turn this off for specific files? More information - If I hard code the path the speed is fine, like so ``` using (StreamWriter lStream = new StreamWriter("c:\\test.dat", true)) { BinaryWriter lWriter = new BinaryWriter(lStream.BaseStream); lWriter.Write(aData); } ``` But then it slow copying this scratch file to the final file destination later on - ``` File.Copy("c:\\test.dat", aFile); ``` If I use any varibale in the path it gets slow agin so for example - ``` using (StreamWriter lStream = new StreamWriter("c:\\test" + someVariable, true)) { BinaryWriter lWriter = new BinaryWriter(lStream.BaseStream); lWriter.Write(aData); } ``` It has been commented that I should not use StreamWriter, note I tried many ways to open the file using FileStream, none of which made any change when the code is running under the web service, I tried WriteThrough etc. Its the strangest thing I even tried this - ``` Write the data to file a.dat Spawn system "cmd" "copy /b b.dat + a.dat b.dat" Delete a.dat ``` This slows down the same way???? Makes me think the web server is running in some protected file IO environment catching all file operations in this process and child process, I can understand this if I was generating a file that might be later served to a client, but I am not, what I am doing is storing large binary blobs on disk, with a index/pointer to them stored in a database, if I comment out the write to the file the whole process fly's no performance issues at all. I started reading about web server caching strategies, makes me think is there a web.config setting to mark a folder as uncached? Or am I completely barking up the wrong tree.
Well I found the root cause, "Microsoft Forefront Security", group policy has this running real time scanning, I could see the process goto 30% CPU usage when I close the file, killing this process and everything works the same speed, outside and inside the web service! Next task find a way to add an exclusion to MFS!
A long shot: is it possible that you need close some resources when you have finished?
File IO slow or cached in a web service?
[ "", "c#", ".net", "web-services", "" ]
Simple Question: ``` list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ] ``` I want to create a `list_2` such that it only contains the numbers: ``` list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ] ``` Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?
This should be the most efficient and shortest in Python 2: ``` import operator filter(operator.isNumberType, list_1) ``` This in Python 3: ``` import numbers [x for x in list_1 if isinstance(x, numbers.Number)] ```
List comprehensions. ``` list_2 = [num for num in list_1 if isinstance(num, (int,float))] ```
Is there a way to output the numbers only from a python list?
[ "", "python", "" ]
I'm creating 3 events with the following function: ``` HANDLE WINAPI CreateEvent(...); ``` I'm waiting on **all** (**`bWaitAll` is set to `TRUE`**) event objects or a timeout with: ``` DWORD WINAPI WaitForMultipleObjects(...); ``` The return value is: ``` WAIT_TIMEOUT ``` Is there an easy way to check each event to find the one(s) that was(where) not set? As an example : ``` HANDLE evt1 = .... HANDLE evt2 = .... HANDLE evt3 = .... HANDLE evts[3] = .... DWORD ret = ::WaitForMultipleObjects(3, evts, TRUE, 10000); ``` After 10 sec : * 'ret' is WAIT\_TIMEOUT. * evt1 is set * evt2 is NOT set * evt3 is set The return value tells me "The time-out interval elapsed and the conditions specified by the bWaitAll parameter are not satisfied.", but not which one were signaled and which one were not. Thanks,
Yes, after WaitForMultipleObjects() returned call WaitForSingleObject() for each event specifying zero timeout. It will return WAIT\_TIMEOUT for events that are not signalled and WAIT\_OBJECT\_0 for signalled events. Don't forget to check for WAIT\_FAILED. Surely each event state might have been changed compared to the states they had at the moment WaitFormultipleObjects() returned.
OK. Total rewrite after having the question explained to me better in the comments. So if I'm understanding this right now, you are calling WaitForMultipleObjects with bWaitAll set to true, and when you get WAIT\_TIMEOUT back from it, want to figure out which objects are holding up the works. In that case, I'm with sharptooth, sort of. You can call WaitForSingleObject with a 0 timeout for each object. The problem with doing this is that it has side-effects for some objects. For example, if you do this on a mutex and it succeeds, you not only know it wasn't the culprit, but you now own the mutex. If that isn't what you want, you'll have to know to immediately release it. Any apporach you take is going to be subject to race conditions. Since you are outside of the "atomic" wait call, you could go through the process and discover that now they are all ready. You could get back a set of ready/unready that isn't what you actually had inside the wait call. Ick.
win32 : Get the state of an event object
[ "", "c++", "winapi", "" ]
I have a set of commands like: ``` C: cd Project testproj.exe ``` My system gets these commands one by one from a remote system. I need to execute each command in cmd.exe on receiving the command from the remote system. How to execute these using .NET? I also need to return the result of testproj.exe to the remote machine. How to take the result after running command?
`Process.Start` cmd.exe, and hook StandardIn, StandardOut, and StandardError. Then, when a command comes in, just write it to StandardIn and read StandardOut/Error for the return. The whole thing shouldn't be more than 15 LOC. That being said, just installing the Telnet Server would probably be easier - as it sounds like that's what you're essentially replicating....
``` var process = System.Diagnostics.Process.Start( "testproj.exe" ); process.WaitForExit(); var result = process.ExitCode; ``` This won't really honor things like "C:" or "CD path". Instead you'd want to create a batch file in a temporary folder then call the batch file.
Run a DOS command in .NET
[ "", "c#", ".net", "dos", "" ]
I have a string which looks like: ``` <html><head><title>example</title></head><body>some example text</body></html> ``` I get this string returned as a result to an AJAX request. I would like the browser to render and display that string. The idea would be to do something like: ``` $('html').parent().html(myString); ``` Well, that doesn't work. I've attempted to use an IFRAME but I haven't figured out how to get that to work either. **Note:** It is impossible for me to change this string. It is also impossible for me to regenerate this string in a subsequent call to the server (otherwise I could just redirect the browser to that url).
The document.open/write/close methods will do what you want: ``` var newDoc = document.open("text/html", "replace"); newDoc.write(myString); newDoc.close(); ``` Unless you pass in the replace parameter, the document.open call adds page history. So users would have to click back twice to go to the previous page.
You could just strip out the html tags, and then put everything inside the html element: ``` $('html').html(myString.replace(/<html>(.*)<\/html>/, "$1")); ```
How do I replace the entire HTML node using jQuery
[ "", "javascript", "jquery", "" ]
[Recently](https://stackoverflow.com/questions/1248971/db-design-for-multiple-types-of-entities/) I've asked a question about the best way to go to design a DB schema to support multiple types of users and interactions between them, [one of the answers](https://stackoverflow.com/questions/1248971/db-design-for-multiple-types-of-entities/1252446#1252446) suggested that I use one table for each user type and [Distributed Keys](http://blogs.conchango.com/davidportas/archive/2007/01/08/Distributed-Keys-and-Disjoint-Subtypes.aspx). The thing is the only databases I actively work with are MySQL and SQLite and I've always done this kinda of work of maintaining the integrity of the DB on the programming side and never directly in the database, can someone point me to a detailed yet easy to understand guide on foreign keys, references and related subjects? Thanks in advance! **EDIT**: I'm interested specifically in MySQL usage examples and documentation, I've [already searched in the MySQL manual](http://search.mysql.com/search?site=refman-50&q=references&lr=lang_en) but nothing useful comes up.
This isn't MySQL-specific, but there is some good stuff in here <http://www.simple-talk.com/sql/database-administration/ten-common-database-design-mistakes/> I don't agree with him about the use of natural keys versus surrogate keys. I have found surrogate keys in general work better for primary keys, but if you have a natural key you should put a unique index on it to prevent duplication of data. Pay particular attention to the sections on: **- Not using SQL facilities to protect data integrity** **- Trying to code generic T-SQL objects** **- One table to hold all domain values** Another good starting place is: <http://www.deeptraining.com/litwin/dbdesign/FundamentalsOfRelationalDatabaseDesign.aspx> [dead link Feb 17, 2015]
Try this one: [Relational Database Design Basics](http://www.databasedev.co.uk/design_basics.html) or the [Wiki](http://en.wikipedia.org/wiki/Relational_database). Give [this](http://blog.sqlauthority.com/2008/06/27/sql-server-difference-between-dbms-and-rdbms/) a read too. Specifically related to MySQL: * [Referential Integrity in MySQL](http://www.databasejournal.com/features/mysql/article.php/2248101/Referential-Integrity-in-MySQL.htm) * [Foreign Keys and Referential Integrity](http://sql-info.de/mysql/referential-integrity.html) Also this stackoverflow question: [MYSQL and RDBMS](https://stackoverflow.com/questions/362839/mysql-and-rdbms)
Where to learn SQL REFERENCES and foreign keys for schema design?
[ "", "sql", "mysql", "database", "database-design", "schema", "" ]
What is the actual difference between `session.gc_maxlifetime` and `session_cache_expire()` ? Suppose I want the users session to be invalid after 15 minutes of non-activity (and not 15 after it was first opened). Which one of these will help me there? I also know I can do `session_set_cookie_params()` which can set the user's cookie to expire in some amount of time. However, the cookie expiring and the actual session expiring on the server side are not the same; does this also delete the session when the cookie has expired? Another solution I have though of is simple `$_SESSION['last_time'] = time()` on every request, and comparing the session to the current time, deleting the session based on that. I was hoping there was a more "built-in" mechanism for handling this though. Thanks.
Each time [session\_start](http://php.net/session_start) is called the session files timestamp (if it exists) gets updated, which is used to calculated if session.gc\_maxlifetime has been exceeded. More importantly you can't depend on a session to expire after session.gc\_maxlifetime time has been exceeded. PHP runs garbage collection on expired sessions after the current session is loaded and by using [session.gc\_probability](http://php.net/manual/en/session.configuration.php#ini.session.gc-probability) and [session.gc\_divisor](http://php.net/manual/en/session.configuration.php#ini.session.gc-divisor) it calculates the probability that garbage collection will run. By default its a 1% probability. If you have a low number of visitors there is a probability that an inactive user could access a session that should have expired and been deleted. If this is important to you will need to store a timestamp in the session and calculate how log a user has been inactive. This example replaces [session\_start](http://php.net/session_start) and enforces a timeout: ``` function my_session_start($timeout = 1440) { ini_set('session.gc_maxlifetime', $timeout); session_start(); if (isset($_SESSION['timeout_idle']) && $_SESSION['timeout_idle'] < time()) { session_destroy(); session_start(); session_regenerate_id(); $_SESSION = array(); } $_SESSION['timeout_idle'] = time() + $timeout; } ```
I spent some time looking for a good answer to how the php.ini server settings make sessions expire. I found a lot of info but it took a while to figure out why the settings work the way they do. If you're like me, this might be helpful to you: Sessions are stored as cookies (files on the client's pc) or server side as files on the server. Both methods have advantages and disadvantages. For the sessions stored on the server, three variables are used. session.gc\_probability session.gc\_divisor session.gc\_maxlifetime (session.gc\_probability/session.gc\_divisor) produces the probability that the garbage collection routine will run. When the garbage collector runs, it checks for session files that haven't been accessed for at least session.gc\_maxlifetime and deletes them. This is all explained pretty well in forum posts (this one especially!) - But the following questions do come up: 1.) How is that probability applied? When does the server roll the dice? A: The server rolls the dice every time session\_start() is called during any active session on the server. So this means you should see the garbage collector run roughly once for every 100 times that session\_start() is called if you have the default of session.gc\_probability = 1 and session.gc\_divisor = 100 2.) What happens on low volume servers? A: When session\_start() is called it FIRST refreshes the session and makes the session values available to you. This updates the time on your session file on the server. It THEN rolls the dice and if it wins (1 out of 100 chance) it calls the garbage collector. The garbage collector then checks all session id files and sees if there are any that are eligible for deletion. So this means that if you are the only person on the server, your session will never go inactive and it will appear as though changing the settings have no effect. Let's say you change session.gc\_maxlifetime to 10 and session.gc\_probability to 100. This means there is a 100% chance the garbage collector will run and it will clear out any session files that haven't been accessed in the last 10 seconds. If you're the only one on the server, your session will not be deleted. You need at least 1 other active session running for yours to go inactive. So basically, on a low volume server or at a low volume time - it could be MUCH longer than session.gc\_maxlifetime before the garbage collector actually runs and the sessions are actually deleted. And without knowing how this works, it may appear completely random to you. 3.) Why do they use the probability? A: Performance. On a higher volume server you don't want the garbage collector running on every request of session\_start(). It will slow down the server needlessly. So depending on your server volume, you may want to increase or decrease the probability that the garbage collector runs. I hope that this ties things together for you. If you're like me and you tried session.gc\_maxlifetime and it didn't seem to work (because you tried it out on a development server so as not to disturb anyone), then this post hopefully saved you some head scratching. Good luck!
Session timeouts in PHP: best practices
[ "", "php", "security", "cookies", "session-timeout", "" ]
I am using `file_put_contents` to create a file. My php process is running in a group with permissions to write to the directory. When `file_put_contents` is called, however, the resulting file does not have group write permissions (it creates just fine the first time). This means that if I try to overwrite the file it fails because of a lack of permissions. Is there a way to create the file with group write permissions?
You might what to try setting the [`umask`](http://php.net/umask) before calling `file_put_contents` : it will change the default permissions that will be given to the file when it's created. The other way (better, according to the documentation) is to use [`chmod`](http://php.net/chmod) to change the permissions, just after the file has been created. *Well, after re-reading the question, I hope I understood it well...*
Example 1 (set file-permissions to read-write for owner and group, and read for others): ``` file_put_contents($filename, $data); chmod($filename, 0664); ``` Example 2 (make file writable by group without changing other permissions): ``` file_put_contents($filename, $data); chmod($filename, fileperms($filename) | 16); ``` Example 3 (make file writable by everyone without changing other permissions): ``` file_put_contents($filename, $data); chmod($filename, fileperms($filename) | 128 + 16 + 2); ``` 128, 16, 2 are for writable for owner, group and other respectively.
how can I create a file with file_put_contents that has group write permissions?
[ "", "php", "linux", "nginx", "" ]
I'm working with a legacy code that someone had left, and it happens to be my task to re-deploy the code. I'm using Windows Server 2003, Apache 2.0.63 and PHP 5.2.10. It doesn't work. At least, not in the way I had expected it to work. Call it bugs, if you will. Upon inspecting, I had a suspicion that this code (which appears numerous times in the application) is the culprit. ``` &$this-> ``` To illustrate the problem, I reproduce this code: ``` <?php phpinfo(); //$variable = &$this->request; ?> ``` The code above executed beautifully and as expected. However, if I change the code to: ``` <? phpinfo(); //$variable = &$this->request; ?> ``` The code misbehaves, and produce this result on the screen instead, which of course, totally unwanted and unexpected. ``` request; ?> ``` Now, the code is littered with the similar code as above, and as such, the application now produce output on the screen similar to this one: ``` request; $user = &$this->user; // This is comment return false; ?> ``` for a code that reads as: ``` <? $request = &$this->request; $user = &$this->user; // This is comment return false; ?> ``` I had tried to change every <? with <?php whenever &$this-> rears its ugly head, but most of the time, it introduces a new error instead. I reinstalled PHP and Apache, even using another version of PHP (5.2.6) and it still won't work. I deployed the code in my localhost (Mac OS X, PHP 5.2.8 and Apache 2.0.63) and it worked without a hassle. Please, anyone, *any* enlightenment will more than suffice.
In your php.ini, you need to set the following directive: ``` short_open_tag = On ``` From the [manual](http://www.php.net/manual/en/ini.core.php): > Tells whether the short form (`<? ?>`) > of PHP's open tag should be allowed... If you have time on your hands, you may want to consider replacing all those short tags '`<?`' with the full-form ones `<?php`, for better portability (see what just happened to you? :)
my recommendation is not to use open tags, because it can interfere with `<?xml` codes. I also had that problem before, just go and replace all `<?php` to `<?` , and then again all `<?` to `<?php`. In this way you won't get any ``` <? <-- one space after the '?' ``` and ``` <?php <-- one space after the 'p' ``` hope this will help...
Tag <? Misbehaving in PHP
[ "", "php", "" ]
Hi I'm new to SQL and I'm trying to figure out how I'm going to get the top 5 "bands" with most friends (userId) and this is what i have; a usertbl with userId as PK then a bandsTbl with bandId as PK then I have a table bandfriends with FK userId and bandId. ``` bandfriends userid | bandId --------------- 1 | 1 1 | 2 1 | 3 ``` Thanks!
Read up on COUNT and GROUP BY at mysql.org You'll want something like this (I haven't tested it): ``` SELECT bandId, COUNT(*) as fans FROM bandfriends ORDER BY fans DESC GROUP BY bandId LIMIT 5; ```
``` SELECT TOP 5 bandId, fanCount FROM (SELECT bandId, COUNT(*) as fanCount FROM bandfriends GROUP BY bandId ORDER BY COUNT(*) DESC) ``` You can also optionally specify WITH TIES in the select statement. See [this](http://msdn.microsoft.com/en-us/library/ms189463.aspx) and [this](http://www.devx.com/vb2themax/Tip/18477).
Top 5 with most friends
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have a repeating table, and I want one of the fields to be a hyperlink. There doesn't seem to be any way to set the address of the hyperlink based on a formula, though. I want to be able to make the address equal to some base URL concatenated with one of the other fields in the table. Is there any way to do this?
``` private string ChangeXmlContent(Uri url, XmlDocument xdoc, string description) { XmlNode group91 = xdoc.SelectSingleNode("//my:group91", NamespaceManager); group91.SelectSingleNode("//my:Url1", NamespaceManager).InnerText = url.ToString(); } ``` Fast & easy
I have used the xpath function concat(my:field2,my:field3) with the hyperlink field. you will have to type in the xpath expression yourself as the designer for some reason will not allow it.
Customizing InfoPath Hyperlink Addresses
[ "", "c#", ".net", "hyperlink", "infopath", "" ]
Say I have the following array: ``` var arr = new[] { "A", "B", "C" }; ``` How can I produce all the possible combinations that contain only two characters and no two the same (e.g. `AB` would be the same as `BA`). For example, using the above array it would produce: ``` AB AC BC ``` Please note that this example has been simplified. The array and the length of the string required will be greater. I'd really appreciate if someone could help.
These should give you a starting point: <http://www.interact-sw.co.uk/iangblog/2004/09/16/permuterate> <http://www.codeproject.com/KB/recipes/Combinatorics.aspx>
Lets extend it, so maybe we can see the pattern: ``` string[] arr = new string[] { "A", "B", "C", "D", "E" }; //arr[0] + arr[1] = AB //arr[0] + arr[2] = AC //arr[0] + arr[3] = AD //arr[0] + arr[4] = AE //arr[1] + arr[2] = BC //arr[1] + arr[3] = BD //arr[1] + arr[4] = BE //arr[2] + arr[3] = CD //arr[2] + arr[4] = CE //arr[3] + arr[4] = DE ``` I see two loops here. * The first (outer) loop goes from 0 to 4 (arr.Length - 1) * The second (inner) loop goes from the outer loops counter + 1 to 4 (arr.Length) Now it should be easy to translate that to code!
Getting all the combinations in an array
[ "", "c#", "" ]
I would like to print out the number of votes that each choice got. I have this code in a template: ``` {% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} <br /> {% endfor %} ``` `votes` is just a dictionary while `choices` is a model object. It raises an exception with this message: ``` "Could not parse the remainder" ```
To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object: ``` class Choice(models.Model): text = models.CharField(max_length=200) def calculateVotes(self): return Vote.objects.filter(choice=self).count() votes = property(calculateVotes) ``` And then in your template, you can do: ``` {% for choice in choices %} {{choice.choice}} - {{choice.votes}} <br /> {% endfor %} ``` The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa. I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.
``` choices = {'key1':'val1', 'key2':'val2'} ``` Here's the template: ``` <ul> {% for key, value in choices.items %} <li>{{key}} - {{value}}</li> {% endfor %} </ul> ``` Basically, `.items` is a Django keyword that splits a dictionary into a list of `(key, value)` pairs, much like the Python method `.items()`. This enables iteration over a dictionary in a Django template.
How to access a dictionary element in a Django template?
[ "", "python", "django", "django-templates", "" ]
Are the two statements below equivalent? ``` SELECT [...] FROM [...] WHERE some_col in (1,2,3,4,5) AND some_other_expr ``` and ``` SELECT [...] FROM [...] WHERE some_col in (1,2,3) or some_col in (4,5) AND some_other_expr ``` Is there some sort of truth table I could use to verify this?
`And` has precedence over `Or`, so, even if `a <=> a1 Or a2` ``` Where a And b ``` is not the same as ``` Where a1 Or a2 And b, ``` because that would be Executed as ``` Where a1 Or (a2 And b) ``` and what you want, to make them the same, is the following (using parentheses to override rules of precedence): ``` Where (a1 Or a2) And b ``` Here's an example to illustrate: ``` Declare @x tinyInt = 1 Declare @y tinyInt = 0 Declare @z tinyInt = 0 Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F ``` For those who like to consult references (in alphabetic order): * [Microsoft Transact-SQL operator precedence](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/operator-precedence-transact-sql?view=sql-server-2017) * [Oracle MySQL 9 operator precedence](https://dev.mysql.com/doc/refman/8.0/en/operator-precedence.html) * [Oracle 10g condition precedence](https://docs.oracle.com/cd/B19306_01/server.102/b14200/conditions001.htm#i1034834) * [PostgreSQL operator Precedence](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-PRECEDENCE) * [SQL as understood by SQLite](https://www.sqlite.org/lang_expr.html)
I'll add 2 points: * "IN" is effectively serial ORs with parentheses around them * AND has precedence over OR in every language I know So, the 2 expressions are simply not equal. ``` WHERE some_col in (1,2,3,4,5) AND some_other_expr --to the optimiser is this WHERE ( some_col = 1 OR some_col = 2 OR some_col = 3 OR some_col = 4 OR some_col = 5 ) AND some_other_expr ``` So, when you break the IN clause up, you split the serial ORs up, and changed precedence.
SQL Logic Operator Precedence: And and Or
[ "", "sql", "logical-operators", "operator-precedence", "" ]
I'm writing a basic GUI application that essentially invokes other processes given some parameters, while the output of those applications is displayed to the user via a richtext box in real-time. So basically I have a seperate process thread running the child processes. Most of the processes work fine on that thread, except for xdiscbld.exe (an Xbox ISO image creator tool) which crashes saying: ``` Unhandled Exception: System.IO.IOException: The handle is invalid. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded) at System.Console.get_BufferWidth() at XDiscBld.XDiscBldProgram.ProcessDisc() at XDiscBld.XDiscBldProgram.Run(String[] args) at XDiscBld.XDiscBldProgram.Main(String[] args) ``` (BTW, xDiscBld runs fine via a command prompt, or single threaded Process call) I wouldn't normally post such a specific error, but I'm really stumped and I think it could be something generic pertaining to a common issue with threads and holding onto some sort of IO handle. If anyone has had any experiance with a similar problem or has any insight on this, it would be appriciated.
I believe the actual issue doesn't have to do with threads, but rather XDiscBld wants to write to a console window that doesn't exist. This is because I'm starting the process like this. ``` process = new Process(); process.StartInfo.UseShellExecute = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = false; process.StartInfo.FileName = FileName; process.StartInfo.Arguments = Arguments; process.StartInfo.WorkingDirectory = WorkingDirectory; process.Start(); ``` If I run with just ``` process.StartInfo.FileName = FileName; process.StartInfo.Arguments = Arguments; process.StartInfo.WorkingDirectory = WorkingDirectory; process.Start(); ``` it works. So it's not liking how I'm redirecting the output. With that said, I still don't know how to make this work with the current system in place. Because this topic has derailed horribly I guess I should either delete it and start over, or leave it up for others' reference.
You must set process.StartInfo.UseShellExecute to **false** if you redirect input/output;
Executing a process on separate thread results in System.IO.__Error.WinIOError
[ "", "c#", "multithreading", "process", "" ]
I have a anonymous class: ``` var someAnonymousClass = new { SomeInt = 25, SomeString = "Hello anonymous Classes!", SomeDate = DateTime.Now }; ``` Is there anyway to attach Attributes to this class? Reflection, other? I was really hoping for something like this: ``` var someAnonymousClass = new { [MyAttribute()] SomeInt = 25, SomeString = "Hello anonymous Classes!", SomeDate = DateTime.Now }; ```
You're actually creating what is called an anonymous type here, not a dynamic one. Unfortunately no there is no way to achieve what you are trying to do. Anonymous types are meant to be a very simple immutable type consisting of name / value pairs. The C# version of anonymous type only allows you to customize the set of name / value pairs on the underlying type. Nothing else. VB.Net allows slightly more customization in that the pairs can be mutable or immutable. Neither allow you to augment the type with attributes though. If you want to add attributes you'll need to create a full type. **EDIT** OP asked if the attributes could be added via reflection. No this cannot be done. Reflection is a way of inspecting metadata not mutating it. Hence it cannot be used to add attributes. Additionally, type definitions in an assembly, and in general, are immutable and cannot be mutated at runtime [1]. This includes the adding of attributes to a method. So other reflection like technologies cannot be used here either. [1] The one exception to this is ENC operation
First of all, this is an anonymous type. The word "dynamic" might lead people to think you're talking about a C# 4.0 class implementing dynamic semantics, which you aren't. Secondly, no, you're not able to do what you ask. If you need to specify attributes for your properties, you're back to a named type, ie. a normal class or struct.
Can I use Attributes with Anonymous classes?
[ "", "c#", "attributes", "anonymous-types", "" ]
I have a pretty high traffic social network site, I would like to get into the habit of unsetting large array and mysql object and even some string variables. So is it possible to unset more then 1 item in PHP example: ``` <?PHP unset($var1); // could be like unset($var1,$var2,$var3); ?> ```
Yes. Your example will work just as you imagine. The method signature for [`unset()`](http://php.net/manual/en/function.unset.php) is as follows: ``` void unset ( mixed $var [, mixed $var [, mixed $... ]] ) ```
[The PHP manual](https://www.php.net/manual/en/function.unset.php) can be very handy. You can search for any built-in function and get a pretty detailed description of what that function does, etc. And the answer is yes, you can supply `unset` with as many variables as you want.
Can you unset() many variables at once in PHP?
[ "", "php", "unset", "" ]
I'm currently writing a small server application, and my problem is, that when I close my app (or better, press the terminate button in eclipse), the socket sometimes stays open, so when I execute my app the next time, bind() will fail with "Address already in use". How can I properly close my sockets when the program exits? I already put ``` close(mySocket); ``` in the class destructors, but that doesn't seem to change anything.
<http://hea-www.harvard.edu/~fine/Tech/addrinuse.html> should answer a lot of your questions. I tend to use SO\_REUSEADDR to work around that problem.
[Use SO\_REUSEADDR.](https://stackoverflow.com/questions/548879/releasing-bound-ports-on-process-exit/548912#548912)
Socket remains open after program has closed (C++)
[ "", "c++", "sockets", "bind", "" ]
Is there a copy constructor in python ? If not what would I do to achieve something similar ? The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.
I think you want the [copy module](http://docs.python.org/library/copy.html) ``` import copy x = copy.copy(y) # make a shallow copy of y x = copy.deepcopy(y) # make a deep copy of y ``` you can control copying in much the same way as you control [pickle](http://docs.python.org/library/pickle.html#module-pickle).
In python the copy constructor can be defined using default arguments. Lets say you want the normal constructor to run the function `non_copy_constructor(self)` and the copy constructor should run `copy_constructor(self, orig)`. Then you can do the following: ``` class Foo: def __init__(self, orig=None): if orig is None: self.non_copy_constructor() else: self.copy_constructor(orig) def non_copy_constructor(self): # do the non-copy constructor stuff def copy_constructor(self, orig): # do the copy constructor a=Foo() # this will call the non-copy constructor b=Foo(a) # this will call the copy constructor ```
Copy constructor in python?
[ "", "python", "constructor", "copy", "" ]
``` "abc def" "abcd efgh" ``` If I have a large string with a space that separates two substrings of varying length, what's the best way to extract each of the substrings from the larger string? Because this is a string rather than an array, array syntax `s[0]` will only retrieve the first letter of the string ('a'), rather than the first substring.
Use the [`split`](http://www.w3schools.com/jsref/jsref_split.asp) method of the `String` object: ``` "abc def".split(' ')[0] // Returns "abc" ``` Works like this: ``` "string".split('separator') // Returns array ```
``` var arr = "abc def".split(" "); document.write(arr[0]); ``` should work
How to get abc from "abc def"?
[ "", "javascript", "string", "substring", "" ]
How do I form an `if/else` statement for a PHP function failing? I want it to define `$results` one way if it works and another if it doesn't. I don't want to simply show an error or kill the error message if it fails. Currently, I have: ``` if(file_get_contents("http://www.address.com")){ $results = "it worked";} else { $results = "it didnt";} return $results ```
``` if(@file_get_contents("http://www.address.com");){ $results = "it worked";} else { $results = "it didnt";} return $results ``` By prepending an @ to a function, you can surpress its error message.
you want PHP's [try/catch functions](http://us.php.net/manual/en/language.exceptions.php). it goes something like: ``` try { // your functions } catch (Exception e){ //fail gracefully } ```
How to handle PHP function error?
[ "", "php", "exception", "conditional-statements", "" ]
im trying to recreate a very simple example of a C# project i WPF, its a simple image viewer.. from the sam's teach yourself C#, ive managed to get the open file dialog to open, but how do i set the image path to the image.source control in WPF? ``` private void SearchBtn_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog openfile = new Microsoft.Win32.OpenFileDialog(); openfile.DefaultExt = "*.jpg"; openfile.Filter = "Image Files|*.jpg"; Nullable<bool> result = openfile.ShowDialog(); if (result == true) { //imagebox.Source = openfile.FileName; } } ```
``` imagebox.Source = new BitmapImage(new Uri(openfile.FileName)); ```
you'll need to change the File Name into a URI and then create a bitmapimage : ``` if (File.Exists(openfile.FileName)) { // Create image element to set as icon on the menu element BitmapImage bmImage = new BitmapImage(); bmImage.BeginInit(); bmImage.UriSource = new Uri(openfile.FileName, UriKind.Absolute); bmImage.EndInit(); // imagebox.Source = bmImage; } ```
WPF image control source
[ "", "c#", "image", "wpf-controls", "" ]
I have some questions regarding the usage and significance of the `synchronized` keyword. * What is the significance of the `synchronized` keyword? * When should methods be `synchronized`? * What does it mean programmatically and logically?
The `synchronized` keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun: > `synchronized` methods enable a simple > strategy for preventing thread > interference and memory consistency > errors: if an object is visible to > more than one thread, all reads or > writes to that object's variables are > done through synchronized methods. *In a very, very small nutshell:* When you have two threads that are reading and writing to the same 'resource', say a variable named `foo`, you need to ensure that these threads access the variable in an atomic way. Without the `synchronized` keyword, your thread 1 may not see the change thread 2 made to `foo`, or worse, it may only be half changed. This would not be what you logically expect. Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about: * [Concurrency](https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html) * [Java Memory Model](http://en.wikipedia.org/wiki/Java_Memory_Model) Keep exploring these topics until the name *"Brian Goetz"* becomes permanently associated with the term *"concurrency"* in your brain.
Well, I think we had enough of theoretical explanations, so consider this code ``` public class TestThread extends Thread { String name; TheDemo theDemo; public TestThread(String name, TheDemo theDemo) { this.theDemo = theDemo; this.name = name; start(); } @Override public void run() { theDemo.test(name); } public static class TheDemo { public synchronized void test(String name) { for (int i = 0; i < 10; i++) { System.out.println(name + " :: " + i); try { Thread.sleep(500); } catch (Exception e) { System.out.println(e.getMessage()); } } } } public static void main(String[] args) { TheDemo theDemo = new TheDemo(); new TestThread("THREAD 1", theDemo); new TestThread("THREAD 2", theDemo); new TestThread("THREAD 3", theDemo); } } ``` Note: `synchronized` blocks the next thread's call to method test() as long as the previous thread's execution is not finished. Threads can access this method one at a time. Without `synchronized` all threads can access this method simultaneously. When a thread calls the synchronized method 'test' of the object (here object is an instance of 'TheDemo' class) it acquires the lock of that object, any new thread cannot call ANY synchronized method of the same object as long as previous thread which had acquired the lock does not release the lock. Similar thing happens when any static synchronized method of the class is called. The thread acquires the lock associated with the class(in this case any non static synchronized method of an instance of that class can be called by any thread because that object level lock is still available). Any other thread will not be able to call any static synchronized method of the class as long as the class level lock is not released by the thread which currently holds the lock. **Output with synchronised** ``` THREAD 1 :: 0 THREAD 1 :: 1 THREAD 1 :: 2 THREAD 1 :: 3 THREAD 1 :: 4 THREAD 1 :: 5 THREAD 1 :: 6 THREAD 1 :: 7 THREAD 1 :: 8 THREAD 1 :: 9 THREAD 3 :: 0 THREAD 3 :: 1 THREAD 3 :: 2 THREAD 3 :: 3 THREAD 3 :: 4 THREAD 3 :: 5 THREAD 3 :: 6 THREAD 3 :: 7 THREAD 3 :: 8 THREAD 3 :: 9 THREAD 2 :: 0 THREAD 2 :: 1 THREAD 2 :: 2 THREAD 2 :: 3 THREAD 2 :: 4 THREAD 2 :: 5 THREAD 2 :: 6 THREAD 2 :: 7 THREAD 2 :: 8 THREAD 2 :: 9 ``` **Output without synchronized** ``` THREAD 1 :: 0 THREAD 2 :: 0 THREAD 3 :: 0 THREAD 1 :: 1 THREAD 2 :: 1 THREAD 3 :: 1 THREAD 1 :: 2 THREAD 2 :: 2 THREAD 3 :: 2 THREAD 1 :: 3 THREAD 2 :: 3 THREAD 3 :: 3 THREAD 1 :: 4 THREAD 2 :: 4 THREAD 3 :: 4 THREAD 1 :: 5 THREAD 2 :: 5 THREAD 3 :: 5 THREAD 1 :: 6 THREAD 2 :: 6 THREAD 3 :: 6 THREAD 1 :: 7 THREAD 2 :: 7 THREAD 3 :: 7 THREAD 1 :: 8 THREAD 2 :: 8 THREAD 3 :: 8 THREAD 1 :: 9 THREAD 2 :: 9 THREAD 3 :: 9 ```
What does 'synchronized' mean?
[ "", "java", "multithreading", "keyword", "synchronized", "" ]
How do you initialize an array in C#?
Like this: ``` int[] values = new int[] { 1, 2, 3 }; ``` or this: ``` int[] values = new int[3]; values[0] = 1; values[1] = 2; values[2] = 3; ```
``` var array = new[] { item1, item2 }; // C# 3.0 and above. ```
How do you initialize an array in C#?
[ "", "c#", "arrays", "" ]
I use jquery to post data to mysql. ``` **In settings.php i have this short JS code:** $("form#submit").submit(function() { var fname = $('#fname').attr('value'); var lname = $('#lname').attr('value'); $.ajax({ type: "POST", url: "settings.php", data: "fname="+ fname +"& lname="+ lname, success: function(){ $('form#submit').hide(); $('div.success').fadeIn(); } }); return false; }); **And this short php:** if (isset($_POST['fname'])){ $fname = htmlspecialchars(trim($_POST['fname'])); DO SOMETHING.... } ``` This is the code where the FNAME comes from: (after hit ADD image-button then posted the fname value..) ``` echo "...... <form id='submit$i' method='post'><input type='hidden' name='fname' id='fname' class='text' value='$fm_linkaz'></div><input name='add'type='image' id='add' value='$fm_linkaz' src='s.png'/></form>.........."; ``` This is work well. But i need a SELECT element, so i changed the code to: ``` ...... echo "<select name=dropdown_list id='**ONAME**'><option value''>test</option>"; for($i=0; $i < count($myarray); $i++){ echo "<option value='$myarray[$i]'>$myarray[$i]</option>";}echo "</select>"; ......</form>"; ``` This is work well, but i dont know how can i modify the JS code, to post the selected value too. Thank u for your help.
First of all the javascript code needs a few updates: `$('#fname').val()` is better than `$('#fname').attr('value')` -- `.val()` will work on selects/checkboxes as well - where `.attr('value')` won't be reliable. Second: the data parameter to your $.ajax() call can take a json object (which it will convert to the form string) ``` $.ajax({ type: "POST", url: "settings.php", data: { 'fname': $('#fname').val(), 'lname': $('#lname').val(), 'oname': $('#oname').val() }, success: function(){ $('form#submit').hide(); $('div.success').fadeIn(); } }); ``` There is a [plugin](http://malsup.com/jquery/form/) that makes this much easier: ``` $("form").ajaxForm({ success: function(){ $('form#submit').hide(); $('div.success').fadeIn(); } }); ``` **UPDATED:** Also - the `<select>` element was named "dropdown\_list" - perhaps you wanted it to be submitting data as "oname" instead. Form elements use the "name" property to submit, the id property only makes css/js selectors easier to code.
To get a selected value for use ``` jQuery('#**ONAME**').val(); ``` Although I'm not sure if `**ONAME**` is valid ID, try removing the \*\*
Post SELECT element value
[ "", "php", "jquery", "mysql", "" ]
I have had a number of requests from clients wanting to take a customer's credit card number online and then process the payment in store at a POS of terminal. I'm wondering what the best method of doing this is. I don't want to store the credit card number on the server in plain text and I don't want to send an email with the number in plain text. The clients don't want to sign up for an online payment accounts because of the higher and additional cost of an online payment processor. Also both customers can't charge online because the total will likely change because of out of stock products or problems with customers request. What other options do I have? I'll be using PHP. I am also in Canada if the rules have any effect on which method I should use.
I solved this problem by building a frontend to GPG and allowing the website owner to generate their own GPG keys. Then, all credit card data is GPG encrypted and can only be decrypted with the website owner's private key, which for additional security could be kept off the server if desired.
I recommend using Authorize.net (only because that's what I have used). You can post the credit card information to Authorize.net to capture (AUTH\_CAPTURE I believe) the credit card information to be charged. Then your client can log in to the Authorize.net virtual terminal and charge or void each payment depending on available inventory. **DO NOT** store credit card information, even if it's encrypted, in a database that is accessible via the internet. I do not know where PCI compliance begins and ends, but I do know that if your client is storing credit card information, then they are required to be PCI compliant by the credit providers they accept. PCI compliance is a pain, and the approach I recommend is the easiest way around it that I have found. And with minimal headaches for the client.
Taking credit card information online without processing -- how best to do so?
[ "", "php", "encryption", "e-commerce", "credit-card", "pci-dss", "" ]
I have a project in which my client is asking me to use portlets 1.0 spec and Websphere Portal Server 6.0. I haven't worked with portlets before but what I've heard of them always have been bad critiques. What are the reasons besides the obvious of using them? If not reasons, what arguments could I use to avoid them?
The problems I have with portlets remind me of the same problems as EJBs- * portlets require you to write special code that can only be hosted and run in a special server; * every portlet server vendor has custom extensions/configurations/additional abilities so it's not trivial to change server vendors; * portlets seem to be overly complex to cover functionality that 90% of people wanting to use it don't need I'd suggest something like [Google Gadgets](http://code.google.com/apis/gadgets/index.html) as the Hibernate to portlet's EJB - * Javascript framework - server-side pieces can be written in any language, hosted on any server. * simpler to use * lots of portal servers support it, and it's more portable across vendors because it's not as complex, and it's not a spec for vendors to implement (and extend)
As someone who has had several jobs (including my current one) developing Java portlets, I'd say don't use them. Here's the problem: If you just wanted to use the pre-existing functionality of the portal you are choosing, then use a portal. If your use of portlets is just to construct a small, light, primarily read-only web-based dashboard where you can quickly look at disparate information, then that's fine. But if you (or more likely someone higher up on the org chart) thinks of portlets as a way to put a bunch of different web apps on a page and have it all "just work", then you are headed for a world of hurt. Portlets are highly-restricted, self-contained islands of functionality, not web apps in tiny squares on a page. Every one of my portlet-based jobs has made this mistake, and there's no light at the end of the tunnel. As a portlet developer, here's a small list of things you're used to doing in regular web apps, that you can't reliably do in portlets: * Generate URLs to other pages. You'll need a vendor-specific way to do that, since the Portlet API only allows you to generate URLs that target the portlet that generated them. * Read and set HTTP headers or set the HTTP response code (so no redirects or HTTP caching, since you don't own the page your portlet will be placed on) * Having to namespace all identifiers in the generated page. This means HTML id attributes and JavaScript function names. Since the namespace has to be determined at runtime to ensure uniqueness, you can't have these Javascript functions reside in a separate browser-cachable file they have to be in the response body for your portlet. Portlets feel as if they were designed for the state of web development as it was in the mid to late 90s (pre-AJAX). But they are ill-suited for today's web development environments (AJAX, single-page rich web apps, etc.) that assume you have complete control of the request/response cycle.
Pros and cons of Java Portlets?
[ "", "java", "evaluation", "portlet", "" ]
I'm using python to interface a hardware usb sniffer device with the python API provided by the vendor and I'm trying to read (usb packets) from the device in a separate thread in an infinite loop (which works fine). The problem is that my main loop does not seem to ever get scheduled again (my read loop gets all the attention). The code looks much like this: ``` from threading import Thread import time usb_device = 0 def usb_dump(usb_device): while True: #time.sleep(0.001) packet = ReadUSBDevice(usb_device) print "packet pid: %s" % packet.pid class DumpThread(Thread): def run(self): usb_dump() usb_device = OpenUSBDevice() t = DumpThread() t.start() print "Sleep 1" time.sleep(1) print "End" CloseUSBDevice(usb_device) sys.exit(0) ``` (I could paste actual code, but since you need the hardware device I figure it won't help much). I'm expecting this code to start dumping usb packets for about a second before the main thread terminates the entire program. However, all I see is "Sleep 1" and then the `usb_dump()` procedure runs forever. If I uncomment the "time.sleep(0.001)" statement in the inner loop of the `usb_dump()` procedure things start working the way I expect, but then the python code becomes unable to keep up with all the packets coming in :-( The vendor tells me that this is an python scheduler problem and not their api's fault and therefor won't help me: > «However, it seems like you are experiencing some nuances when using threading in Python. By putting the time.sleep in the DumpThread thread, you are explicitly signaling to the Python threading system to give up control. Otherwise, it is up the Python interpreter to determine when to switch threads and it usually does that after a certain number of byte code instructions have been executed.» Can somebody confirm that python is the problem here? Is there another way to make the DumpThread release control? Any other ideas?
Your vendor would be right if yours was **pure python** code; however, C extensions may release the [GIL](http://effbot.org/pyfaq/what-is-the-global-interpreter-lock.htm), and therefore allows for actual multithreading. In particular, time.sleep **does** release the GIL (you can check it directly from the source code, [here](http://svn.python.org/view/python/trunk/Modules/timemodule.c?view=markup) - look at `floatsleep` implementation); so your code should not have any problem. As a further proof, I have made also a simple test, just removing the calls to USB, and it actually works as expected: ``` from threading import Thread import time import sys usb_device = 0 def usb_dump(): for i in range(100): time.sleep(0.001) print "dumping usb" class DumpThread(Thread): def run(self): usb_dump() t = DumpThread() t.start() print "Sleep 1" time.sleep(1) print "End" sys.exit(0) ``` Finally, just a couple of notes on the code you posted: * usb\_device is not being passed to the thread. You need to pass it as a parameter or (argh!) tell the thread to get it from the global namespace. * Instead of forcing sys.exit(), it could be better to just signal the thread to stop, and then closing USB device. I suspect your code could get some multithreading issue, as it is now. * If you need just a periodic poll, threading.Timer class may be a better solution for you. [*Update*] About the latest point: as told in the comment, I think a `Timer` would better fit the semantic of your function (a periodic poll) and would automatically avoid issues with the GIL not being released by the vendor code.
I'm assuming you wrote a Python C module that exposes the ReadUSBDevice function, and that it's intended to block until a USB packet is received, then return it. The native ReadUSBDevice implementation needs to release the Python GIL while it's waiting for a USB packet, and then reacquire it when it receives one. This allows other Python threads to run while you're executing native code. <http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock> While you've unlocked the GIL, you can't access Python. Release the GIL, run the blocking function, then when you know you have something to return back to Python, re-acquire it. If you don't do this, then no other Python threads can execute while your native blocking is going on. If this is a vendor-supplied Python module, failing to release the GIL during native blocking activity is a bug. Note that if you're receiving many packets, and actually processing them in Python, then other threads should still run. Multiple threads which are actually running Python code won't run in parallel, but it'll frequently switch between threads, giving them all a chance to run. This doesn't work if native code is blocking without releasing the GIL. edit: I see you mentioned this is a vendor-supplied library. If you don't have source, a quick way to see if they're releasing the GIL: start the ReadUSBDevice thread while no USB activity is happening, so ReadUSBDevice simply sits around waiting for data. If they're releasing the GIL, the other threads should run unimpeded. If they're not, it'll block the whole interpreter. That would be a serious bug.
Scheduling issues in python
[ "", "python", "multithreading", "scheduling", "" ]
> **Possible Duplicates:** > [What to use: var or object name type?](https://stackoverflow.com/questions/236878/what-to-use-var-or-object-name-type) > [Use of var keyword in C#](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c) > [What’s the point of the var keyword?](https://stackoverflow.com/questions/209199/whats-the-point-of-the-var-keyword) > [Should I *always* favour implictly typed local variables in C# 3.0?](https://stackoverflow.com/questions/17032/should-i-always-favour-implictly-typed-local-variables-in-c-3-0) I have just installed a trial version of ReSharper to evaluate it for my company. One thing that I have noticed is it is suggesting that I change the following (made up example): ``` string s = ""; ``` to ``` var s = ""; ``` Is it best practice to use the var keyword rather than using the Object Type when declaring variables? What advantages does it give. For context I am a former Java developer who has just transitioned to the .Net works.
I think it's fine to use `var` where it makes the code easier to read, which for me would mean that the type that `var` is replacing must be completely obvious. For example, this would be a good use of `var` (contrived example): ``` var thing = new Dictionary<int, KeyValuePair<string, int>>(); ``` However this would be a bad use of `var`: ``` var thing = GetThingFromDatabase(); ```
I find it helpful in some cases where the type declaration is very long, for example: ``` Dictionary<int, string> item = new Dictionary<int, string>(); ``` becomes ``` var item = new Dictionary<int, string>(); ```
C# var keyword usage
[ "", "c#", "styles", "" ]
``` x=True def stupid(): x=False stupid() print x ```
You don't need to declare a function-local variable in Python. The "x=False" is referring to an x local to stupid(). If you really want to modify the global x inside stupid: ``` def stupid(): global x x=False ```
To answer your next question, use `global`: ``` x=True def stupid(): global x x=False stupid() print x ```
why does this python program print True
[ "", "python", "" ]
I have written this code having not used PHP for 2 years now to loop through a folder of photos and write them to the page in alphabetical order. It is a fairly simple request but it took me the best part of 15 minutes to write. ``` if ($handle = opendir('photos')) { $count = 0; $list[] = array(); while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $list[$count] = $file; $count ++; } } closedir($handle); asort($list); $sorted_list = array(); $sorted_list = array_values($list); foreach ($sorted_list as $i => $value) { echo "<li><img src=\"photos/$sorted_list[$i]\" alt=\"$sorted_list[$i]\" title=\"\"></li>\n"; } } ``` Have I written it totally the wrong way? Are there ways I can improve the code? Any constructive feedback gladly received.
You could take advantage of the [scandir()](http://php.net/scandir) function, which will handle reading the directory as well as sorting the results. ``` $files = scandir('photos'); if ($files !== false) { foreach($files as $f) { if ($f == '..' || $f == '.') continue; echo '<li><img src="photos/'.$f.'" alt="'.$f.'" title=""></li>'."\n"; } } ``` I edited it a bit for readability.
Try this: ``` $photos = glob('photos/*'); foreach($photos as $photo) { echo "<li><img src=\"{$photo}" alt=\"{$photo}\" title=\"\"></li>\n"; } ``` <http://us.php.net/manual/en/function.glob.php>
Can this code to loop through photos in a folder be optimised?
[ "", "php", "arrays", "file", "loops", "directory", "" ]
I have a multi-threaded C# application. There is one dictionary that is accessed from N different threads at the same time. 99% of the calls are from thread A and the rest are from B, C, ... Right now, I'm just locking the dictionary on each access. But it seems wasteful because 99% of the time that I'm calling lock, thread A already has the lock. What would a more efficient way of doing this be? Maybe some type of .Begin and .End calls could be required for threads B, C, ... and then Thread A would only have to check one bit on each call to see if any of the other threads are using the dictionary. Does anyone have a code sample of something like this implemented in a thread safe way?
You need to carefully examine your profiler data. Both Monitor and RWLSlim won't actually "hard-lock" (as in drop down to the OS primitives) unless there's an actual contention; the will use Interlocked in all other cases, and perf implications of that are relatively minimal (aside from the cache flushes). Performance wise, RWLockSlim is relatively expensive to create and a little more expensive than Monitor to enter. Its virtue is to allow muliple readers and a single writer. If you are seeing hard locks showing up, then you have actual contention, in which case the 99%/1%/1%/1%/... ratio you stated probably doesn't reflect reality. As previous posters noted, you should exmaine tha patten of use - in most cases you have occasional writes and massive reads, otherwise the system's consistency a somewhat difficult to enforfce. If that is the case, the RWlockSlim should remove unnecessary contention. Bottomline : it all depends on what you are trying to do - as in what this dictionary is for and how is accessed. Sometimes it make sense to widen locks to prevent taking too many of those, and in some - very rare - cases you might want to play with lock-free-style primitives like Interlocked before you even try to hit the "real" lock. Perhaps if you told us more about the scenario, we'd be able to help better.
How do you perform the lock. For reading you don't need to lock out the other threads in the same "hard" way as if you are also updating. Either way you can be a bit more loose around the read operations. I would suggest looking into the [`ReaderWriterLockSlim`](http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx) (unless you are already using it): ``` class DictionaryHolder { private IDictionary<int, string> _data = new Dictionary<int, string>(); private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); public void Update(int key, string value) { _lock.EnterWriteLock(); try { _data[key] = value; } finally { _lock.ExitWriteLock(); } } public string GetValue(int key) { _lock.EnterReadLock(); try { if (_data.ContainsKey(key)) { return _data[key]; } finally { _lock.ExitReadLock(); } } } ``` This will allow several threads to read from the dictionary "at the same time", while blocking access from other threads when updating it.
C# Threading Performance, One Thread 99% Of The Time
[ "", "c#", "multithreading", "" ]
I want to let users test out a PHP class of mine, that among other things crops and resizes images. I want them to write PHP code in a text field, send the form, and then their code will be run. How can I do this? Or is it other safe ways to let users (anyone) demo a PHP class?
Yes. You can use the eval statement in php (linked earlier by John <https://www.php.net/manual/en/function.eval.php>), however be very careful. You really don't want users to be able to run code on your machine freely. My recommendation would try to come up with a different approach to do demos - perhaps a flexible few examples... but don't let them run code directly
I would spawn the PHP process using a user account with next-to-no permissions. Give the read-write access to a single directory, but that's it. You're still opening yourself to DoS attacks with infinite loops and such, but if you absolutely must do it, then run the code in this very-low-permissions sandbox like IE and Chrome do. Using EVAL is probably the worst idea.
Interpret text input as PHP
[ "", "php", "class", "interpreter", "demo", "" ]
Can anyone suggest me where to download a GNU c++ compiler, which I can use in Ubuntu and also on Windows with Netbeans IDE, and also GNU tools.
If you are using any Linux/Unix/Solaris OS it is available unless you have explicitly not installed. That said, if you still wish to install GNU C++ compiler, use this command ``` sudo aptitude install build-essential ``` and if you wish to download it on your windows, steps are [here](http://www.mingw.org/) on Minimalist GNU for Windows
Getting everything you need on Debian/Ubuntu is very easy: ``` sudo apt-get install build-essential ```
Where to download GNU C++ compiler
[ "", "c++", "gnu", "" ]
I'm rephrasing this question because it was either too uninteresting or too incomprehensible. :) The original question came about because I'm making the transation from Java to Groovy, but the example could apply equally when transitioning to any of the higher-level languages (Ruby, Python, Groovy). Java is easy to debug because there is a clear relationship between lines of code, and fairly fine-grained behaviour, e.g. manipulate an array using a for loop: ``` for ( int i=0; i < array1.size(); i++ ) { if ( meetsSomeCriterion(array1.elementAt(i) ) { array2.add( array1.elementAt(i) ); } } ``` so you can set a breakpoint on the test in the loop and see what happens next. (I know there are better ways to write this; it's just to illustrate the point.) In languages like Ruby the idiomatic style seems to favour higher-level one-liner coding, e.g. from <http://rubyquiz.com/quiz113.html> ``` quiz.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse ``` I'm wondering if you can suggest any effective techniques for debugging this, for example if you changed the regular expression ... would you still use the traditional debugger, and step into/over the chained methods? Or is there a better way? Thanks!
If I were to debug your example, the first thing I would do is break it down into multiple steps. I don't care if it's "pythonic" or "the ruby way" or "tclish" or whatever, code like that can be difficult to debug. That's not to say I don't write code like that. Once it's been debugged it is sometimes OK to join it all into a single line but I find myself leaning more toward readability and maintainability and less toward writing concise code. If the one-liner approach is genuinely more readable I'll go with it, but if it's not, I don't.
Combining multiple actions into a single line is all well and good, when you can still look at the line in question and know that it's going to do exactly what you want it to do. The minute you get to the point where you can't look at the code and go "yeah, ok, it does xyz, there's no way it couldn't" is when you should consider breaking it into individual pieces. I give the same advice to people with long procs/methods. If you can't look at the code and know exactly what it's doing in all situations, then break it up. You can break up each of the "non-obvious" bits of code into it's own method and write tests for that piece alone. Then, you can use that method in your original method and know it's going to work... plus your original method is now easier to understand. Along the same lines, you can break your "scan(/(?:\d\*.)?\d{1,3}-?/)" code off into another method and test that by itself. The original code can then use that method, and it should be much easier to understand and know it's working.
Debugging Ruby/Python/Groovy
[ "", "python", "ruby", "debugging", "groovy", "dynamic-languages", "" ]
Is it possible to override the listview detault selection paint? The one that looks semi-transparent blue overlayed over the items, like in the explorer windows. I want to draw an outline around the selection to indicate selection. Any way to do this? Examples are appreciated.
Here is a quick working example, i was messing around with. First helper structs and enums. ``` [StructLayout(LayoutKind.Sequential)] public struct DRAWITEMSTRUCT { public int CtlType; public int CtlID; public int itemID; public int itemAction; public int itemState; public IntPtr hwndItem; public IntPtr hDC; public RECT rcItem; public IntPtr itemData; } [StructLayout(LayoutKind.Sequential)] public struct RECT { public int left; public int top; public int right; public int bottom; public int Width { get { return right - left; } } public int Height { get { return bottom - top; } } } public enum ListViewDefaults { LVS_OWNERDRAWFIXED = 0x0400 } public enum WMDefaults { WM_DRAWITEM = 0x002B, WM_REFLECT = 0x2000 } ``` Now create a custom ListView and Override **CreateParams** and **WndProc** ``` public class CustomListView : ListView { protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; //add OwnerDraw style...i took this idea from Reflecting against ListView // bit OR is very important, otherwise you'll get an exception cp.Style |= (int)ListViewDefaults.LVS_OWNERDRAWFIXED; return cp; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); //if we are drawing an item then call our custom Draw. if (m.Msg == (int)(WMDefaults.WM_REFLECT | WMDefaults.WM_DRAWITEM)) ProcessDrawItem(ref m); } ``` Now for the most important part..the drawing. I am pretty amateur at drawing but this should get you an idea of what to do. ``` private void ProcessDrawItem(ref Message m) { DRAWITEMSTRUCT dis = (DRAWITEMSTRUCT)Marshal.PtrToStructure(m.LParam, typeof(DRAWITEMSTRUCT)); Graphics g = Graphics.FromHdc(dis.hDC); ListViewItem i = this.Items[dis.itemID]; Rectangle rcItem = new Rectangle(dis.rcItem.left, dis.rcItem.top, this.ClientSize.Width, dis.rcItem.Height); //we have our rectangle. //draw whatever you want if (dis.itemState == 17) { //item is selected g.FillRectangle(new SolidBrush(Color.Red), rcItem); g.DrawString(i.Text, new Font("Arial", 8), new SolidBrush(Color.Black), new PointF(rcItem.X, rcItem.Y+1)); } else { //regular item g.FillRectangle(new SolidBrush(Color.White), rcItem); g.DrawString(i.Text, new Font("Arial", 8), new SolidBrush(Color.Black), new PointF(rcItem.X, rcItem.Y+1)); } //we have handled the message m.Result = (IntPtr)1; } ``` This is the result. [![alt text](https://i.stack.imgur.com/g828J.jpg)](https://i.stack.imgur.com/g828J.jpg)
.NET ListView supports owner drawing much more directly than the other answers suggest. You don't even need to subclass. Set OwnerDraw to true, listen for DrawSubItem event, and then in that event you can draw what you like. As always, [ObjectListView](http://www.codeproject.com/KB/list/ObjectListView.aspx) makes this process easier. There is [this page](http://objectlistview.sourceforge.net/cs/ownerDraw.html) documenting exacting how to do this. You can garish things like this if you are feeling mean to your users: [![alt text](https://i.stack.imgur.com/yHLUK.png)](https://i.stack.imgur.com/yHLUK.png) HOWEVER, none of these techniques will work if you want to draw something outside the bounds of the cell itself. So, if you were hoping to draw a selection outline around the whole row that overlapped the previous and subsequent rows, you cannot do this through owner drawing. Each cell is drawn individually and "owns" its part of the screen, wiping out anything that was already there. To do something like you are asking, you would have to intercept the postpaint stage of the custom draw (not owner draw. Michael Dunn [wrote a great introduction](http://www.codeproject.com/KB/list/lvcustomdraw.aspx) to custom drawing for CodeProject). You can read what is required [here](http://objectlistview.sourceforge.net/cs/blog1.html#custom-draw). I hate to say it, but the simplest answer to use an ObjectListView, create a Decoration and install it: ``` public void InitializeSelectionOverlay() { this.olv1.HighlightForegroundColor = Color.Black; this.olv1.HighlightBackgroundColor = Color.White; this.olv1.AddDecoration(new SelectedRowDecoration()); } public class SelectedRowDecoration : IOverlay { public void Draw(ObjectListView olv, Graphics g, Rectangle r) { if (olv.SelectedIndices.Count != 1) return; Rectangle rowBounds = olv.GetItem(olv.SelectedIndices[0]).Bounds; rowBounds.Inflate(0, 2); GraphicsPath path = this.GetRoundedRect(rowBounds, 15); g.DrawPath(new Pen(Color.Red, 2.0f), path); } private GraphicsPath GetRoundedRect(RectangleF rect, float diameter) { GraphicsPath path = new GraphicsPath(); RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); path.AddArc(arc, 180, 90); arc.X = rect.Right - diameter; path.AddArc(arc, 270, 90); arc.Y = rect.Bottom - diameter; path.AddArc(arc, 0, 90); arc.X = rect.Left; path.AddArc(arc, 90, 90); path.CloseFigure(); return path; } } ``` This gives something that looks like this:[![alt text](https://i.stack.imgur.com/EcJOK.png)](https://i.stack.imgur.com/EcJOK.png)
Winforms ListView Selection Drawing?
[ "", "c#", ".net", "winforms", "listview", "gdi+", "" ]
Is there a means to prevent a subclass from exposing public methods other than those defined in the base class, at compile-time? For example: ``` abstract public class AClass { abstract public void anAllowedMethod(); } public class BClass extends Aclass { public void anAllowedMethod() { } public void anAdditionalNonAllowedMethod() { } private void thisMethodIsAllowedBecauseItsNotPublic() { } } ``` Perhaps there is some keyword I can use in AClass to declare the subclass can only implemented the methods defined in AClass (ie. "anAllowedMethod()")?
At this stage of the game it is probably too late, but what you could do is create a final class with the relevant methods that takes a delegate in its constructor of a different type that has actual implementation, and have the methods of the final class call the delegate. That way whatever they add to the delegate won't be callable at all.
Not really. When you define a class and say that it extends/implements another class it must adhere to the contract of the class it extends/implements. There is no restriction on containing the said class' behaviour further. > In a project I'm working on, some developers are adding extra methods to the subclass which are not necessary As I see, this effectively means that your *design* is going to pieces due to developers doing what they please (by adding new public behaviour to objects). Unfortunately, if you don't manage your *design* once it is in the implementation phase (coding) bad things are bound to happen. Please consider a process of review (automated/manual)
Java: Prevent subclass from providing a different interface than base class
[ "", "java", "" ]
I am designing a server in java which would be used to trade bonds. This server will act as a mediator between the client UI and the analytical server. The analytical server is the brain, my server will simply interact with it (using tcp sockets) and forward the responses to the client. The server is expected to handle ~500 clients concurrently. And it has to be scalable and efficient to handle ~500 messages per second. The flow of messages between the client UI and the analytical server is this: ``` 1. Client through the UI requests for price. 2. My server accepts the message, formats it and then asynchronously sends to the analytical server. 3. When the response from the analytical server arrives, format and send the response to the client UI. 4. If the client likes the price, he/she will request to trade. 5. Repeat steps 2 & 3. ``` There is an existing framework that I leverage to handle authentication and to send messages between my server and the client UI. I have already coded the messaging bit between my server and the analytical server. So as far as designing the remainder of my server, I am thinking of having 4 blocking queues. When the request for price comes, I immediately insert the request in a queue (Queue1). I then have a processor which takes messages out of Queue1, formats it and puts it in another queue (Queue2). The processor class internally contains a thread pool (Executors.fixedThreadpool) and formatting of each message occurs in a separate thread. I then have a dispatcher class which contains another thread pool. This dispatcher class is responsible for taking messages from Queue2 and writing it to the Analytical server. When I receive the message from the analytical server, I insert it into another queue (Queue3). I have another thread pool which dequeues and formats the message and puts it into another (Queue4). And finally I have another thread pool with pops messages out of Queue4 and publishes to the client. I reason I chose 4 different queues is because if I want, I can write a tool to observe the size of these queues. The information about the size of these queues will ``` 1. Allow me to tune the size of the thread pools. 2. Further, if needed, I can publish the messages contained in these queues thus allowing me to monitor all the messages that flows through my server. ``` So what do you guys think? Any ideas, tips are most welcome. Cheers
First of all, when you say your server must "handle" ~500 messages per second, what exactly do you mean by "handle"? Accept? Because if you mean anything else, I'm not sure how that jibes with analytical server being asynchronous. Secondly, I think you have 3 queues too many :-) You need a queue to act as sync-to-async buffers between your server and the analytical server. Beyond that, there's little point in queueing anything else (well, that depends on how exactly you're getting a response back from the analytical server; if for some reason you're polling it instead of being notified then you *may* need the queue there as well).
So it sounds like you'll end up with 500 threads, if it takes longer than 1 second to process the message?
Critique my server design please
[ "", "java", "" ]
I am working through some code done by a previous developer. I'm pretty new to PHP so I am wondering if there is any well known pattern or solution to this problem. Basically the original author does not check any array indexes before he tries to use them. I know I can use `isset()` to check each before it is used, but right now there are hundreds of lines where these errors are appearing. Before I put on some music and start slamming my head into my keyboard I want to make sure there is not some nice shortcut for handling this. Here is a typical section of code I'm looking at: ``` /* snip */ "text" => $link . $top_pick_marker . $output['author'] . "&nbsp;" . "&nbsp;" . $output['new_icon'] . $output['rec_labels'] . " &nbsp; " . $output['admin_link'] . $output['alternate_title'] . $output['access_info'] . $output['description'] . $output['url'] . $output['subject_terms'] . $output['form_subdivisions'] . $output['dates_of_coverage'] . $output['update_frequency'] . $output['place_terms'], /* snip */ ``` I know I can use `isset()` here for each item. I would have to rearrange things a bit and remove all the concatenation as it is now. Is there any other easy way to do this or am I just stuck with it?
Figure out what keys are in the $output array, and fill the missing ones in with empty strings. ``` $keys = array_keys($output); $desired_keys = array('author', 'new_icon', 'admin_link', 'etc.'); foreach($desired_keys as $desired_key){ if(in_array($desired_key, $keys)) continue; // already set $output[$desired_key] = ''; } ```
You can use isset() without losing the concatenation: ``` //snip $str = 'something' . ( isset($output['alternate_title']) ? $output['alternate_title'] : '' ) . ( isset($output['access_info']) ? $output['access_info'] : '' ) . //etc. ``` You could also write a function to return the string if it is set - this probably isn't very efficient: ``` function getIfSet(& $var) { if (isset($var)) { return $var; } return null; } $str = getIfSet($output['alternate_title']) . getIfSet($output['access_info']) //etc ``` You won't get a notice because the variable is passed by reference.
How to avoid 'undefined index' errors?
[ "", "php", "arrays", "" ]
I just can't find an up-to-date chart about which mobile devices support which Java Micro Edition version. I'm especially interested in **Nokia smartphones** and their support for the new **JME 3.0**. *(I wonder that Sun doesn't seems to provide such information.)* Please, provide me some links, if you know any! **EDIT:** I'm probably mixing things up: **MIDP** seems to be the **mobile Java platform**, while **J2ME 3.0** is a **SDK** for it, right?
Nokia device specs, including supported JSRs: <http://www.forum.nokia.com/devices/>
You can also have a look at benchmark results as they sometime give a good indication of what is supported on a given phone: [www.jbenchmark.com](http://www.jbenchmark.com/) One fairly large curent issue is whether the phones you want to target support MIDP 2.1 (easy to test with a 2.1 helloworld application), like the recent Sony-Ericsson and Nokia handsets. That version is associated with Mobile Service Architecture (JSR-248), an improvement over Java Technology for the Wireless Industry (JSR-185) which specifies APIs that a handset should support.
Which phones support which J2ME (Java Micro Edition) spec?
[ "", "java", "java-me", "nokia", "smartphone", "" ]
Our company builds websites and web applications. We are a small firm and our team of developers are always building the javascript functions from scratch or copying from other websites built by us. Every time I bring to the table the word standardization and using a JS framework like JQuery, Prototype or any other, I am told Frameworks have the three points below as arguments against them: * Mainly for people that don't know enough JS * Frameworks limit Javascript developers * Frameworks bloat the actual development code with a lot of things that are not used. * We don't use enough Javascript in our applications for us to need JS framework In my mind it seems that Frameworks, give our team a good starting point, documentation, a community and always the option to grow on top of the framework. Could some Framework users elaborate further? EDIT 1: Thanks to all of you for your great responses. I really did not think that this was going to be such a hot topic. I am glad I asked the question. I posted another similar question in the following link in case you might think you want to add something. The topic of the new question is [CSS](https://stackoverflow.com/questions/1245893/what-are-the-arguments-against-using-a-css-framework) related. Thanks.
Arguments against: * Frameworks prevent you from re-inventing the wheel * Frameworks generally contain well tested code * Frameworks are well supported by the community * Frameworks force you to focus on the business problem you're trying to solve </sarcasm> * Frameworks may have a license you don't agree/can't work with
By your coworkers point of view, .NET and JAVA are for people who don't know enough assembly. Frameworks exist for a reason. They allow you go focus on the problem instead of dealing with repetitive code. They allow you to be confident (assuming you use well tested frameworks) that certain pieces of your code are reliable and well tested. If your coworkers are against frameworks, I would seriously consider moving on.
What are the arguments against using a JavaScript Framework for a Web site development company?
[ "", "javascript", "jquery", "frameworks", "yui", "" ]
Consider the following code: ``` if (IsDebuggingEnabled) { instance.Log(GetDetailedDebugInfo()); } ``` `GetDetailedDebugInfo()` may be an expensive method, so we only want to call it if we're running in debug mode. Now, the cleaner alternative is to code something like this: ``` instance.Log(() => GetDetailedDebugInfo()); ``` Where .Log() is defined such as: ``` public void Log(Func<string> getMessage) { if (IsDebuggingEnabled) { LogInternal(getMessage.Invoke()); } } ``` My concern is with performance, preliminary testing doesn't show the second case to be particularly more expensive, but I don't want to run into any surprises if load increases. Oh, and please don't suggest conditional compilation because it doesn't apply to this case. (P.S.: I wrote the code directly in the StackOverflow Ask a Question textarea so don't blame me if there are subtle bugs and it doesn't compile, you get the point :)
I was hoping for some documentation regarding performance in such cases, but it seems that all I got were suggestions on how to improve my code... No one seems to have read my P.S. - no points for you. So I wrote a simple test case: ``` public static bool IsDebuggingEnabled { get; set; } static void Main(string[] args) { for (int j = 0; j <= 10; j++) { Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i <= 15000; i++) { Log(GetDebugMessage); if (i % 1000 == 0) IsDebuggingEnabled = !IsDebuggingEnabled; } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } Console.ReadLine(); for (int j = 0; j <= 10; j++) { Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i <= 15000; i++) { if (IsDebuggingEnabled) GetDebugMessage(); if (i % 1000 == 0) IsDebuggingEnabled = !IsDebuggingEnabled; } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } Console.ReadLine(); } public static string GetDebugMessage() { StringBuilder sb = new StringBuilder(100); Random rnd = new Random(); for (int i = 0; i < 100; i++) { sb.Append(rnd.Next(100, 150)); } return sb.ToString(); } public static void Log(Func<string> getMessage) { if (IsDebuggingEnabled) { getMessage(); } } ``` **Timings seem to be exactly the same between the two versions. I get 145 ms in the first case, and 145 ms in the second case** Looks like I answered my own question.
No, it shouldn't have a bad performance. After all, you'll be calling it only in debug mode where performance is not at the forefront. Actually, you could **remove the lambda and just pass the method name** to remove the overhead of an unnecessary intermediate anonymous method. Note that if you want to do this in Debug builds, you can add a [`[Conditional("DEBUG")]`](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx) attribute to the log method.
Is using delegates excessively a bad idea for performance?
[ "", "c#", ".net", "performance", "delegates", "lambda", "" ]
When I display a WPF window with `WindowStyle="None"`, it looks great when using areo. However, when I use luna or classic, it displays an ugly gray border about 5 pixels wide. Of course, if I set `ResizeMode="NoResize"`, this border disappears, but I would like the window to be resizable (`ResizeMode="CanResize"`). Other non WPF applications (live mail, ie, firefox, etc.) do not display this gray border, but are still resizable. Is there a way to remove this border while still being resizable?
I'm using the WPF Customizable Window's Essential Window. Here's my window declaration (abbreviated): ``` <CustomWindow:EssentialWindow xmlns:aero="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" xmlns:CustomWindow="clr-namespace:CustomWindow;assembly=CustomWindow" AllowsTransparency="True" Background="Transparent" ResizeMode="CanResizeWithGrip" WindowStyle="None" ShowInTaskbar="True" > ```
Try setting [AllowsTransparency](http://msdn.microsoft.com/en-us/library/system.windows.window.allowstransparency.aspx) to True on the Window.
How can I remove the border of a WPF window when using luna or classic?
[ "", "c#", ".net", "wpf", "windows", "" ]
I'm recently working on a tree structure, multiple nodes, multiple and increasable levels, and a print() method. At first, i thought it should be a Composite, i then wrote down some possible design and codes: ![alt text](https://farm3.static.flickr.com/2596/3807730874_4d6d5ed7ee_o_d.gif) ``` $struc = new Node(‘name0’, ‘id0’, ‘desc0’); $node1 = new Node(‘node1’, ‘id1’, ‘desc1’); $node2 = new Node(‘node2’, ‘id2’, ‘desc2’); $node3 = new Node(‘node3’, ‘id3’, ‘desc3’); $leaf1 = new Leaf(‘leaf1’, ‘ld1’, ‘lesc1’); $leaf2 = new Leaf(‘leaf2’, ‘ld2’, ‘lesc2’); $leaf3 = new Leaf(‘leaf3’, ‘ld3’, ‘lesc3’); $leaf4 = new Leaf(‘leaf4’, ‘ld4’, ‘lesc4’); $struc.add($node1); $struc.add($node3); $node1.add($leaf1); $node1.add($leaf2); $node1.add($node2); $node2.add($leaf3); $node3.add($leaf4); ``` Looks good, i think and begin coding, print() method may follow Iterator pattern later. But during coding, i feel is it too complex for these simple nodes? And i have to instantiate a lot of concrete classes (more than 50+, and increasing). I then stopped and thinking a simple similar way by using array: ``` -- Structure Class -- //To be more readable and clear, array here could be //divided to 3 arrays(root/nodes/leafs), then connect //in a similar way Composite does. $struc = array('name0', 'id0', 'desc0', 'children'=>array( array('node1', 'id1', 'desc1', 'children' => array( array('leaf1', 'ld1', 'lesc1'), array('leaf2', 'ld2', 'lesc2'), array('node2', 'id2', 'desc2', 'children'=>array(array('leaf3', 'ld3', 'lesc3')) ) ) ), array('node3', 'id3', 'desc3', 'children' => array(array('leaf4', 'ld4', 'lesc4')) ) ) ); function print($node = $this->struct) { ... if(isset($node['children'])) $this->print($node['children']); ... } ``` The two designs look very similar, now i'm a little confused, what's the value of Composite pattern, am i missed something important of this pattern?
The point of the [composite pattern](http://en.wikipedia.org/wiki/Composite_pattern) is to be able to treat a collection of objects as if it were a single object (e.g. for displaying it or writing it to a file). As you write yourself "print() method may follow Iterator pattern later" - well, the point of the composite pattern would be that you could call print() without having to worry about whether you're printing a single Component or have to iterate through an entire Tree. But it looks as though you're unclear about object-oriented programming in general, since you're considering using nested arrays instead. The value of using objects instead of hashes (which PHP arrays are) for everything is [type safety](http://en.wikipedia.org/wiki/Type_safety), which makes it much easier to debug and maintain programs.
the value of composite is that you trade some complexity **for being able to not break encapsulation**. In your array version you are breaking encapsulation since you are testing if the node is not a leaf: ``` if(isset($node['children'])) $this->print($node['children']); ``` with composite you can say: ``` print(); ``` then run-time polymorphism will call the right method. In this case (I'm not a PHP programmer so let me to use a Java-like syntax): ``` class Node { void print() { for (child in children) { child.print(); } } ... } class Leaf { void print() { // print it! } } ``` another advantage over plain array is that you are **hiding your implementation details** (data structure, etc)
What advantage will Composite pattern bring me over just Array?
[ "", "php", "design-patterns", "" ]
Although I have experience with SQL and generating HTML reports with PHP, I'm a relative beginner with Microsoft Access. I'm currently using Microsoft Access 2007 to connect to MSSQL Server 2005. I have a table of Reports that looks something like this: ``` ReportID DateCreated Author ... ``` I'd like to create a form that allows the user to specify a start date and an end date, which would then show the number of reports by each author within the specified date range. I've already done this in a form by first retrieving a list of unique authors into a combo box, and then allowing the user to select the author, start date, and end date, and displaying the count in a text box. However, I was wondering if there was an easier or better way, or if there was a way to display all of the authors and their totals simultaneously. Thanks in advance :)
You can have multiple fields associated with a combobox, so first have them pick the dates, then initialize the combobox with both author and total field.
Make 2 unbound text controls for StartDate and EndDate. Put those in the header of a continuous form. Use a button or an AfterUpdate event to change the recordsource of your form. Something like: ``` me.recordsource = "SELECT author, count(*) from myTable GROUP BY author WHERE DateCreated BETWEEN #" & format(startDate, "mm/dd/yyyy") & "# AND #" & format(startDate, "mm/dd/yyyy") & "#" ```
Displaying totals within a specified date range in Microsoft Access
[ "", "sql", "sql-server", "sql-server-2005", "ms-access", "ms-access-2007", "" ]
How do I reimport a module? I want to reimport a module after making changes to its .py file.
For **Python 3.4+**: ``` import importlib importlib.reload(nameOfModule) ``` For **Python < 3.4**: ``` reload(my.module) ``` From the [Python docs](http://docs.python.org/2.7/library/functions.html#reload) > Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. Don't forget the caveats of using this method: * When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed. * If a module imports objects from another module using `from ... import ...`, calling `reload()` for the other module does not redefine the objects imported from it — one way around this is to re-execute the `from` statement, another is to use `import` and qualified names (`module.*name*`) instead. * If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.
In python 3, `reload` is no longer a built in function. If you are using python 3.4+ you should use [`reload`](https://docs.python.org/3/library/importlib.html#importlib.reload) from the [`importlib`](https://docs.python.org/3/library/importlib.html) library instead: ``` import importlib importlib.reload(some_module) ``` If you are using python 3.2 or 3.3 you should: ``` import imp imp.reload(module) ``` instead. See <http://docs.python.org/3.0/library/imp.html#imp.reload> If you are using [`ipython`](https://ipython.org), definitely consider using the [`autoreload`](https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html) extension: ``` %load_ext autoreload %autoreload 2 ```
Reimport a module while interactive
[ "", "python", "" ]
(This is a probably a very beginner question and I may be missing something obvious) I've just moved from my mac back to windows, and I'm trying to get set up with C++. I have visual studio 2008 C++: how do I compile "normal" non .net/clr C++? I want a command line application, and the only project that seemed fit was "CLR console application." My stuff works and compiles fine with Xcode or dev C++, but VS gives me 57 errors, and seems to only want me to do .net stuff. I have to include "stdafx.h" before it will even do anything. Can I just use plain old C++, with std::string and vectors, without the .net stuff? Or do I need dev c++? thanks guys!
Select General->Empty project project type.
Create a Win32 Console Application. The Win32 part might be a bit confusing, but what it means is basically just a native C++ project (from which you *can* use the Win32 should you so desire - but you don't have to) stdafx.h is the default precompiled header (which you probably don't want. I have no idea why they enable that as default, since it is completely pointless in small projects). In the project creation wizard, be sure to select "empty project", or it'll create the precompiled header plus a couple of other files you don't want or need. It can also be turned off in the project properties.
compiling "standard" C++ in visual studio (non .net)
[ "", "c++", "visual-studio", "visual-studio-2008", "winapi", "" ]
I seem to be running around in circles and have been doing so in the last hours. I want to populate a datagridview from an array of strings. I've read its not possible directly, and that I need to create a custom type that holds the string as a public property. So I made a class: ``` public class FileName { private string _value; public FileName(string pValue) { _value = pValue; } public string Value { get { return _value; } set { _value = value; } } } ``` this is the container class, and it simply has a property with the value of the string. All I want now is that string to appear in the datagridview, when I bind its datasource to a List. Also I have this method, BindGrid() which I want to fill the datagridview with. Here it is: ``` private void BindGrid() { gvFilesOnServer.AutoGenerateColumns = false; //create the column programatically DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn(); DataGridViewCell cell = new DataGridViewTextBoxCell(); colFileName.CellTemplate = cell; colFileName.Name = "Value"; colFileName.HeaderText = "File Name"; colFileName.ValueType = typeof(FileName); //add the column to the datagridview gvFilesOnServer.Columns.Add(colFileName); //fill the string array string[] filelist = GetFileListOnWebServer(); //try making a List<FileName> from that array List<FileName> filenamesList = new List<FileName>(filelist.Length); for (int i = 0; i < filelist.Length; i++) { filenamesList.Add(new FileName(filelist[i].ToString())); } //try making a bindingsource BindingSource bs = new BindingSource(); bs.DataSource = typeof(FileName); foreach (FileName fn in filenamesList) { bs.Add(fn); } gvFilesOnServer.DataSource = bs; } ``` Finally, the problem: the string array fills ok, the list is created ok, but I get an empty column in the datagridview. I also tried datasource= list<> directly, instead of = bindingsource, still nothing. I would really appreciate an advice, this has been driving me crazy.
Use a [BindingList](http://msdn.microsoft.com/en-us/library/ms132679.aspx) and set the [DataPropertyName](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspx)-Property of the column. Try the following: ``` ... private void BindGrid() { gvFilesOnServer.AutoGenerateColumns = false; //create the column programatically DataGridViewCell cell = new DataGridViewTextBoxCell(); DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn() { CellTemplate = cell, Name = "Value", HeaderText = "File Name", DataPropertyName = "Value" // Tell the column which property of FileName it should use }; gvFilesOnServer.Columns.Add(colFileName); var filelist = GetFileListOnWebServer().ToList(); var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList //Bind BindingList directly to the DataGrid, no need of BindingSource gvFilesOnServer.DataSource = filenamesList } ```
may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you ``` public class FileName { [DisplayName("File Name")] public string FileName {get;set;} [DisplayName("Value")] public string Value {get;set;} } ``` and then you can bind List as datasource as ``` private void BindGrid() { var filelist = GetFileListOnWebServer().ToList(); gvFilesOnServer.DataSource = filelist.ToArray(); } ``` for further information you can visit this page [Bind List of Class objects as Datasource to DataGridView](http://www.ilmlinks.com/Pages/bindclasslistdgv) hope this will help you.
How to bind list to dataGridView?
[ "", "c#", ".net", "binding", "datagridview", "" ]
I want to learn [STL](http://en.wikipedia.org/wiki/Standard_Template_Library) by quick browsing of real project source. Where can I find a high quality project that uses STL?
**[Notepad++:](http://notepad-plus.sourceforge.net/uk/site.htm)** pure Win32 + STL only! > Based on a powerful editing component > Scintilla, Notepad++ is written in C++ > and uses pure Win32 API and STL which > ensures a higher execution speed and > smaller program size. By optimizing as > many routines as possible without > losing user friendliness, Notepad++ is > trying to reduce the world carbon > dioxide emissions. When using less CPU > power, the PC can throttle down and > reduce power consumption, resulting in > a greener environment.
Note that STL is partly included in the C++ standard itself. That makes most of the products listed at <http://www.research.att.com/~bs/applications.html> interesting. The list is a mix of proprietary and open source projects.
Is there any cool project written in STL?
[ "", "c++", "stl", "" ]
These are the tables: ``` threads: id, date, title, text comments: id, thread_id, date, comment ``` How would I do to list the last commented thread on top? This is currently how it looks: ``` $threads = mysql_query("SELECT id, title FROM threads ORDER BY date ASC"); while ($thread = mysql_fetch_assoc($threads)) { echo $thread['title']; } ``` I can't figure this one out folks. So if someone could give me an hand that would be great! Cheers!
Try this: ``` SELECT DISTINCT t.id, t.title FROM threads t LEFT JOIN comments c ON t.id = c.thread_id ORDER BY c.date DESC ``` Left join is needed in case you have threads with no comments.
This one should get it done: ``` SELECT threads.id, threads.title, max(comments.date) FROM threads LEFT OUTER JOIN comments ON threads.id = comments.thread_id GROUP BY threads.id, threads.title ORDER BY max(comments.date) DESC ```
How should I join these tables?
[ "", "sql", "mysql", "join", "" ]
I am looking for pointers towards APIs in c# that will allow me to control my Internet connection by turning the connection on and off. I want to write a little console app that will allow me to turn my access on and off , allowing for productivity to skyrocket :) (as well as learning something in the process) Thanks !!
If you're using Windows Vista you can use the built-in firewall to block any internet access. The following code creates a firewall rule that blocks any outgoing connections on all of your network adapters: ``` using NetFwTypeLib; // Located in FirewallAPI.dll ... INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FWRule")); firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; firewallRule.Description = "Used to block all internet access."; firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT; firewallRule.Enabled = true; firewallRule.InterfaceTypes = "All"; firewallRule.Name = "Block Internet"; INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Add(firewallRule); ``` Then remove the rule when you want to allow internet access again: ``` INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Remove("Block Internet"); ``` This is a slight modification of some other code that I’ve used, so I can’t make any guarantees that it’ll work. Once again, keep in mind that you'll need Windows Vista (or later) and administrative privileges for this to work. Link to the [firewall API](http://msdn.microsoft.com/en-us/library/aa366458(VS.85).aspx) documentation.
This is what I am currently using (my idea, not an api): ``` System.Diagnostics; void InternetConnection(string str) { ProcessStartInfo internet = new ProcessStartInfo() { FileName = "cmd.exe", Arguments = "/C ipconfig /" + str, WindowStyle = ProcessWindowStyle.Hidden }; Process.Start(internet); } ``` **Disconnect from internet:** `InternetConnection("release");` **Connect to internet:** `InternetConnection("renew");` Disconnecting will just remove the access to internet (it will show a caution icon in the wifi icon). Connecting might take five seconds or more. **Out of topic**: In any cases you might want to check if you're connected or not (when you use the code above), I better suggest this: ``` System.Net.NetworkInformation; public static bool CheckInternetConnection() { try { Ping myPing = new Ping(); String host = "google.com"; byte[] buffer = new byte[32]; int timeout = 1000; PingOptions pingOptions = new PingOptions(); PingReply reply = myPing.Send(host, timeout, buffer, pingOptions); return (reply.Status == IPStatus.Success); } catch (Exception) { return false; } } ```
Any way to turn the "internet off" in windows using c#?
[ "", "c#", "" ]
I have a trivial example: ``` def func1(): local_var = None def func(args): print args, print "local_var:", local_var local_var = "local" func("first") func("second") func1() ``` I expect the output to be: ``` first local_var: None second local_var: local ``` However, my actual output is: ``` first local_var: Traceback (most recent call last): File "test.py", line 13, in func1() File "test.py", line 10, in func1 func("first") File "test.py", line 6, in func print "local_var:", local_var UnboundLocalError: local variable 'local_var' referenced before assignment ``` My understanding of python scoping rules dictate that this should work as expected. I have other code where this works as expected, but reducing one non-working code fragment to it's trivial case above also doesn't work. So I'm stumped.
The assignment to `local_var` in `func` makes it local **to `func`** -- so the `print` statement references that "very very local" variable before it's ever assigned to, as the exception says. As jtb says, in Python 3 you can solve this with `nonlocal`, but it's clear from your code, using `print` statements, that you're working in Python 2. The traditional solution in Python 2 is to make sure that the assignment is not to a barename and thus does not make the variable more local than you wish, e.g.: ``` def func1(): local_var = [None] def func(args): print args, print "local_var:", local_var[0] local_var[0] = "local" func("first") func("second") func1() ``` the assignment to the indexing is not to a barename and therefore doesn't affect locality, and since Python 2.2 it's perfectly acceptable for nested inner functions to *refer* to variables that are locals in outer containing functions, which is all this version does (*assigning* to barenames is a different issue than *referring* to variables).
Before Python 3.0, functions couldn't write to non-global variables in outer scopes. Python3 has introduced the `nonlocal` keyword that lets this work. You'd add `nonlocal local_var` at the top of `func()`'s definition to get the output you expected. See [PEP 3104](http://www.python.org/dev/peps/pep-3104/ "Access to Names in Outer Scopes"). If you're not working in Python 3 you'll have to make the variable global, or pass it into the function somehow.
Python scoping problem
[ "", "python", "scoping", "" ]
I'm writing a Multiplayer C++ based game. I need a flexible file format to store information about the game charactors. The game charactors will often not share the same attributes, or use a basew For example: A format that would allow me to do something like this: ``` #include "standardsettings.config" //include other files which this file //then changes FastSpaceship: Speed: 10 //pixels/sec Rotation: 5 //deg/sec MotherShip : FastSpaceship //inherits all the settings of the Spaceship ship ShieldRecharge: 4 WeaponA [ power:10, range:20, style:fireball] SlowMotherShip : MotherShip //inherits all the settings of the monther ship Speed: 4 // override speed ``` I've been searching for a pre-existing format that does all this, or is similar, but with no luck. I'm keen not to reinvent the wheel unless I have to, so i was wondering if anyone knows any good configuration file formats that support these features
After alot of searching i've found a pretty good solution using [Lua](http://www.lua.org) Lua I found out was originally designed as a configuration file language, but then evolved into a complete programming language. Example util.lua ``` -- helper function needed for inheritance function inherit(t) -- return a deep copy (incudes all subtables) of the table t local new = {} -- create a new table local i, v = next(t, nil) -- i is an index of t, v = t[i] while i do if type(v)=="table" then v=inherit(v) end -- deep copy new[i] = v i, v = next(t, i) -- get next index end return new end ``` globalsettings.lua ``` require "util" SpaceShip = { speed = 1, rotation =1 } ``` myspaceship.lua ``` require "globalsettings" -- include file FastSpaceship = inherits(SpaceShip) FastSpaceship.Speed = 10 FastSpaceship.Rotation = 5 MotherShip = inherits(FastSpaceship) MotherShip.ShieldRecharge = 4 ShieldRecharge.WeaponA = { Power = 10, Range = 20, Style = "fireball" SlowMotherShip = inherits(MotherShip) SlowMotherShip.Speed = 4 ``` Using the print function in Lua its also easy to test the settings if they are correct. Syntax isn't quite as nice as I would like it, but its so close to what I want, i'm not gonna mind writing out a bit more. The using the code here <http://windrealm.com/tutorials/reading-a-lua-configuration-file-from-c.php> I can read the settings into my C++ program
JSON is about the simplest file format around, has mature libraries, and you can interpret it to do anything you want. ``` { "FastSpaceship" : { "Speed" : 10, "Rotation" : 5 }, "MotherShip" : { "Inherits" : "FastSpaceship", "ShieldRecharge" : 4, "WeaponA": { "Power": 10, "Range": 20, "style": "fireball" } }, "SlowMotherShip": { "Inherits": "MotherShip", "Speed": 4 } } ```
What configuration file format allows the inclusions of otherfiles and the inheritance of settings?
[ "", "c++", "configuration-files", "file-format", "" ]
I am building a English/french website and was wondering if there is a best practice for such a job. 1. Duplicating the site and making a french and english folder with the appropriate site inside. 2. Using PHP to swap the content with html tags. eg. if($lang=='en'): 3. Use php to swap only the content leaving the html tags the same for both. eg. if statements all over the place. Would this be bad for efficiency? Any other suggestions would be appreciated
We have a framework in place for when (if) our site goes international that works like this... Folder structure; ``` / lang/ english/ images/ text/ dutch/ images/ text/ ``` Any text or images that are language specific are removed from the page directly and replaced by constants. eg On the login screen, we drop in; ``` echo TEXT_LOGIN_WELCOME; ``` which is defined in /lang/english/text/login.php as; ``` define('TEXT_LOGIN_WELCOME', 'Welcome, please login:'); ``` but in /lang/dutch/text/login.php it's defined as; ``` define('TEXT_LOGIN_WELCOME', 'Welcome, please login (in dutch):'); ``` ;-) Each language define file is named exactly the same as the page it is used for, so when we load a public-facing page, we only need to figure out which language the user speaks and we can include the relevant language define file. The good thing about this system is that all the language info is centralised. When you need to add a new language, simply copy the main (english?) folder, rename it, zip the whole thing up and send it to a translation service to work their magic. Of course, the downside of this system is the maintenance as both languages and content grow... If anyone has any bright ideas with regard to this then I'd love to hear them! Btw, if you end up needing to guess a user's location by IP, you might want to check out [geoIP](http://www.maxmind.com/app/ip-location).
Use a templating system. [Smarty Template Engine](http://www.smarty.net/) is probably one of the most well-known PHP ones. Not only does a templating system serve the exact purpose you're trying to accomplish, it also makes maintaining pages far easier by separating the display code from the content (which also allows you to use the same template for lots of different content pages of a similar nature).
Most effient way to template a multi lingual site
[ "", "php", "templates", "multilingual", "" ]
Often I have a class as such: ``` public class Foo { private String field1; private String field2; // etc etc etc } ``` This makes the initial values of field1 and field2 equal to null. Would it be better to have all my String class fields as follows? ``` public class Foo { private String field1 = ""; private String field2 = ""; // etc etc etc } ``` Then, if I'm consistent with class definition I'd avoid a lot of null pointer problems. What are the problems with this approach?
I disagree with the other posters. Using the empty string is acceptable. I prefer to use it whenever possible. In the great majority of cases, a null String and an empty String represent the exact same thing - unknown data. Whether you represent that with a null or an empty String is a matter of choice.
That way lies madness (usually). If you're running into a lot of null pointer problems, that's because you're trying to use them before actually populating them. Those null pointer problems are loud obnoxious warning sirens telling you where that use is, allowing you to then go in and fix the problem. If you just initially set them to empty, then you'll be risking using them instead of what you were actually expecting there.
Should I set the initial java String values from null to ""?
[ "", "java", "null", "initialization", "string", "" ]
Is there a *smooth* way to glob in C or C++ in Windows? E.g., myprogram.exe \*.txt sends my program an ARGV list that has...ARGV[1]=`*.txt` in it. I would like to be able to have a function (let's call it readglob) that takes a string and returns a vector of strings, each containing a filename. This way, if I have files `a.txt b.txt c.txt` in my directory and readglob gets an argument `*.txt`, it returns the above filelist. ``` //Prototype of this hypothetical function. vector<string> readglob(string); ``` Does such exist?
Link with `setargv.obj` (or `wsetargv.obj`) and argv[] will be globbed for you similar to how the Unix shells do it: * <http://msdn.microsoft.com/en-us/library/8bch7bkk.aspx> I can't vouch for how well it does it though.
This is very Windows-specific. I don't know how you'd write this to be cross-platform. But I've used this in Windows programs and it works well for me. ``` // Change to the specified working directory string path; cout << "Enter the path to report: "; cin >> path; _chdir(path.c_str()); // Get the file description string desc; cout << "Enter the file description: "; cin >> desc; // List the files in the directory intptr_t file; _finddata_t filedata; file = _findfirst(desc.c_str(),&filedata); if (file != -1) { do { cout << filedata.name << endl; // Or put the file name in a vector here } while (_findnext(file,&filedata) == 0); } else { cout << "No described files found" << endl; } _findclose(file); ```
Globbing in C++/C, on Windows
[ "", "c++", "c", "windows", "glob", "" ]
What would be the most appropriate image type to display a jpg image (loaded from a local folder) on a JPanel? Cheers.
``` ImageIcon image = new ImageIcon("image/pic1.jpg"); JLabel label = new JLabel("", image, JLabel.CENTER); JPanel panel = new JPanel(new BorderLayout()); panel.add( label, BorderLayout.CENTER ); ```
You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.
Display a jpg image on a JPanel
[ "", "java", "image", "jpanel", "" ]
I know this is a dumb question and I guess it must have been asked before. However I am unable to find an answer to my question. Here is some sample code (which of course does not compile) to outline my problem: ``` class test { int[] val1; string val2; static bool somefunction(test x, test y) { dosomestuff() test result; while(result is nothing) { if(somecondition){result=new test(something);} } } } ``` The problem which I have is in the following line: ``` while(result is nothing) ``` This is the syntax from VB, which of course is not what the C# compiler accepts. Could somebody tell me how to resolve the problem?
The syntax you are looking for is: ``` while (result == null) ``` You also have to set `result = null;` to start with also
* **TL;DR:** `if (Object.Equals(`*`myVariable`*`, default(`*`MyVariableType`*`)))` + Replace *`myVariable`* and *`MyVariableType`*. There are other solutions. --- `if (myVariable == null)` will **not work**[1] **with *[value](http://www.albahari.com/valuevsreftypes.aspx) [types](http://msdn.microsoft.com/en-us/library/3ewxz6et.aspx)***. (See further below for short intros to  *reference types* vs. *value types*   and `struct`s.) The value types mainly are `struct`s (e.g. `DateTime`), including[2] the [simple types](http://msdn.microsoft.com/en-us/library/aa691144%28v=vs.71%29.aspx) like `int`, and `enum`erations. Value types don't support a `null` value (intrinsically). The exception and the fix to this are [nullable](http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx) types: Essentially these add `null` to the possible values of a struct type. They are structurally the same as the `Maybe<T>` you might know from other languages[3]. You create them with `ValueType?` (e.g. `int?`) which is syntactic sugar for `Nullable<ValueType>`. Alternatively, instead of using a nullable type, you could compare your variable to its type's default value: ``` if (Object.Equals(myVariable, default(MyVariableType))) ``` (This will work both for reference types (objects) and value types.) Note that you have to replace *`MyVariableType`* manually – unfortunately you can **not** do ``` if (Object.Equals(myVariable, default(myVariable.GetType()))) ``` because `default()` only accepts a type name directly. (I suppose it evaluates at compile-time.) ## *structs* in a nutshell > Put simply, structs are cut-down classes. Imagine classes that don’t > support inheritance or finalizers, and you have the cut-down version: > the struct. Structs are defined in the same way as classes (except > with the `struct` keyword), and apart from the limitations just > described, structs can have the same rich members, including fields, > methods, properties and operators. > > [Cited from: http://www.albahari.com/valuevsreftypes.aspx ] Classes are *reference types*: A class variable (or more specifically, its memory area) only contains a pointer to an other memory area, where the actual object instance data is stored. *Value type* variables directly contain the data. This may yield a speed benefit due to [cache locality](http://en.wikipedia.org/wiki/Locality_of_reference) and saving the lookup. But it may also be detrimental to performance in the case of more complex structs. --- Footnotes: [1] It does not even throw an error. `myVariable == null` will always just yield `false`, because your `myVariable` will be initialized with the non-`null` [default](http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx) value (zero ([equivalent](http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx)) or a struct of zeros and `null`s). This default value is available with `default(Type)`. [2] Technically the simple types (all [built-in types](http://msdn.microsoft.com/en-us/library/cs7y5x0x%28v=vs.90%29.aspx) except `string` and `object`) [are](http://msdn.microsoft.com/en-us/library/aa691144%28v=vs.71%29.aspx) structs. Side note: The built-in types are [aliases](http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx) for types from the [System](http://msdn.microsoft.com/en-us/library/system.aspx) namespace. [3] E.g. [in Haskell](http://www.haskell.org/ghc/docs/6.10.2/html/libraries/base/Data-Maybe.html). In C# `Maybe<T>` is not built-in, but can be implemented. It provides `Nothing` as a more explicit/self-documenting version of `null` both for classes and structs. [4] There is no [4]. No really, you can go and check.
How to tell whether a variable has been initialized in C#?
[ "", "c#", "class", "isset", "" ]
I am new at C, and I am debugging with source code. However, I am confused with this code snippet. When the values are assigned to the structure value, I think it is some masking. But not sure, and if it is masking. How does masking work in this concept? Many thanks, ``` #define MSGINFO_ENABLE 0x01 #define MIME_ENABLE 0x02 #define FASTSTART_CODERS_IN_OFFERED 0x04 #define TRANSADDR_ENABLE 0x08 typedef struct { unsigned int msginfo_mask; /* added in version 0x0101 */ } VIRTBOARD; VIRTBOARD VirtBoard; /* Not sure I understand what is happening here. */ VirtBoard.msginfo_mask = MSGINFO_ENABLE | MIME_ENABLE | FASTSTART_CODERS_IN_OFFERED | TRANSADDR_ENABLE; ```
Ok in plain English: The Hexdecimal numbers 0x01,0x02,0x04,0x08 were each selected BECAUSE they are each encoded as different single bits being set in binary. None of the bit maps overlap so each one can be read and set without being effected by the other bits. Adding the following comments to your code makes it clearer what's happening: ``` #define MSGINFO_ENABLE 0x01 // => 0001 #define MIME_ENABLE 0x02 // => 0010 #define FASTSTART_CODERS_IN_OFFERED 0x04 // => 0100 #define TRANSADDR_ENABLE 0x08 // => 1000 ``` Now adding a comment before the other line shows the result: ``` // VirtBoard.msginfo_mask |= 0001 // VirtBoard.msginfo_mask |= 0010 // VirtBoard.msginfo_mask |= 0100 // VirtBoard.msginfo_mask |= 1000 // ---- // VirtBoard.msginfo_mask == 1111 VirtBoard.msginfo_mask = MSGINFO_ENABLE | MIME_ENABLE | FASTSTART_CODERS_IN_OFFERED | TRANSADDR_ENABLE; ``` While the comments on the assignment make it clear what's going on, once you understand what's happening, the comments kinda defeat the purpose of symbolically defining constants.
It might help to think of it this way (values shown in binary): ``` MSGINFO_ENABLE = 0001 MIME_ENABLE = 0010 FASTSTART_CODERS_IN_OFFERED = 0100 TRANSADDR_ENABLE = 1000 ``` So... 1001 is `TRANSADDR_ENABLE` and `MSGINFO_ENABLE` or 1101 is eveything but `FASTSTART_CODERS_IN_OFFERED` Does that help at all? The `|` notation is C syntax to set the correct bit: ``` int something = 0; something = MSGINFO_ENABLE | TRANSADDR_ENABLE; ``` is the a syntax to set only those 2 bits.
How masking works
[ "", "c++", "c", "" ]
Basically I want to have access to all standard python int operators, eg `__and__` and `__xor__` etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode) ``` class Hex(int): def __repr__(self): return "0x%x"%self __str__=__repr__ # this certainly helps with printing if __name__=="__main__": print Hex(0x1abe11ed) ^ Hex(440720179) print Hex(Hex(0x1abe11ed) ^ Hex(440720179)) ``` Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934 Any ideas?
In response to your comment: You could write a Mixin by yourself: ``` class IntMathMixin: def __add__(self, other): return type(self)(int(self).__add__(int(other))) # ... analog for the others ``` Then use it like this: ``` class Hex(IntMathMixin, int): def __repr__(self): return "0x%x"%self __str__=__repr__ ```
You should define `__repr__` and `__str__` separately: ``` class Hex(int): def __repr__(self): return "Hex(0x%x)" % self def __str__(self): return "0x%x" % self ``` The `__repr__` function should (if possible) provide Python text that can be `eval()`uated to reconstruct the original object. On the other hand, `__str__` can just return a human readable representation of the object.
subclassing int to attain a Hex representation
[ "", "python", "hex", "subclassing", "representation", "" ]
I'm trying to parse results from the YouTube API. I'm getting the results correctly as a string, but am unable to parse it correctly. I followed suggestions on a previous thread, but am not getting any results. My sample code is: ``` string response = youtubeService.GetSearchResults(search.Term, "published", 1, 50); XDocument xDoc = XDocument.Parse(response, LoadOptions.SetLineInfo); var list = xDoc.Descendants("entry").ToList(); var entries = from entry in xDoc.Descendants("entry") select new { Id = entry.Element("id").Value, Categories = entry.Elements("category").Select(c => c.Value) //Published = entry.Element("published").Value, //Title = entry.Element("title").Value, //AuthorName = entry.Element("author").Element("name").Value, //Thumnail = entry.Element("media:group").Elements("media:thumnail").ToList().ElementAt(0) }; foreach (var entry in entries) { // entry.Id and entry.Categories available here } ``` The problem is that entries has a count of 0 even though the XDocument clearly has the valid values. The value of the response variable (Sample XML) can be seen here: <http://snipt.org/lWm> (FYI: The youTube schema is listed here: <http://code.google.com/apis/youtube/2.0/developers_guide_protocol_understanding_video_feeds.html>) Can anyone tell me what I'm doing wrong here?
All the data is in the "<http://www.w3.org/2005/Atom>" namespace; you need to use this throughout: ``` XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom"); ``` ... ``` from entry in xDoc.Descendants(ns + "entry") select new { Id = entry.Element(ns + "id").Value, Categories = entry.Elements(ns + "category").Select(c => c.Value) ... }; ``` etc (untested)
When you see `prefix:name`, it means that `name` is in the namespace whose prefix has been declared as `prefix`. If you look at the top of the document, you'll see an `xmlns:media=something`. The `something` is the namespace used for anything with the prefix `media`. This means you need to create an XNamespace for each of the namespaces you need to reference: ``` XNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/"); ``` and then use `media` for the names in that namespace: ``` media + "group" ``` The namespaces in this document are: ``` xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:media="http://search.yahoo.com/mrss/" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:gml="http://www.opengis.net/gml" xmlns:yt="http://gdata.youtube.com/schemas/2007" xmlns:georss="http://www.georss.org/georss" ```
Using LINQ to XML to Process XML in Multiple Namespaces
[ "", "c#", "xml", "linq-to-xml", "" ]
I have two string that i want to limit to lets say the first 25 characters for example. Is there a way to cut off text after the 25th character and add a ... to the end of the string? So '12345678901234567890abcdefg' would turn into '12345678901234567890abcde...' where 'fg' is cut off.
May I make a modification to pallan's code? ``` $truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string; ``` This doesn't add the '...' if it is shorter.
Really quickly, ``` $truncated = substr('12345678901234567890abcdefg', 0, 20) . '...' ```
How do you cut off text after a certain amount of characters in PHP?
[ "", "php", "string", "strip", "" ]
Currently I'm able to send some form data from an HTML page to a Servlet, process it, and return the result by forwarding/redirecting to a displayresults.jsp page; However I'm wondering if there's a way to process a form submission in this fashion and then return the results to the initial page? So that whatever I wish to return shows up below the form. The idea in the end will be to have a search function up top, then have the search results appear below on the same page.
Yes 1. Stick the results into the request object from within the servlet 2. Get the servlet to **forward** back to the request page 3. Add some code into the JSP to pull out the results from the request object and display them See this for a simple example <http://www.tek-tips.com/viewthread.cfm?qid=1189624&page=11> If your usecase means that you'll be jumping from the search results elsewhere and back you may wish to maintain the search results in the session.
``` <c:choose> <c:when test="${empty param.search}"> <form method="post"><input type="text" name="search" /></form> </c:when> <c:otherwise> <%-- show search result here. --%> </c:otherwise> </c:choose> ```
Display form-processing results on current page in JSP
[ "", "java", "jsp", "servlets", "" ]
Given a DLL with the following classes : ``` #define DLLAPI __declspec(...) class DLLAPI Base { public: virtual void B(); }; class Derived : public Base { public: virtual void B(); virtual void D(); }; ``` Will my "Derived" class be visible outside of the dll even if the "DLLAPI" keyword is not applied to the class definition (at least, not directly)? Is the "D()" function visible to? Thanks
class Derived won't be exported by your DLL. Classes don't inherit exporting. Add DLLAPI to that too. Note too that class members default to private accessibility, so none of your methods should be accessible. However, I do see Base::B() being exported in my test. The C++ header in the DLL-using code would flag the error, but I wonder if you tweaked the header there, if you could fool it. Anyway, if you did instantiate a Derived inside your DLL (via another entry point), the virtual table should still work, so if you did: ``` Base* b = getTheDerived(); b->B(); ``` you'd invoke Derived::B().
You can find out from a Visual Studio command shell by typing ``` link /dump /exports <yourdll> ``` If they are exported, you will see "decorated names" for the functions. To see what they are in human readable format, copy-paste one and do ``` undname <decorated name> ```
__declspec(dllimport/dllexport) and inheritance
[ "", "c++", "windows", "dll", "dllimport", "dllexport", "" ]
I have a developed a Restlet application. I would like to return a JSP file on a URL request through Restlet. How can I achieve this without using a redirect? i.e. Let's say I have the file "contact.jsp" on mydomain.com and I want people to be able to access contact.jsp at <http://mydomain.com/contact> Thus, in Restlet, I would have: ``` router.attach("/contact", MyResource.class); ``` But how can I return the "contact.jsp" page? I know that a redirect would work, but I don't want users to see the ".jsp" in "<http://mydomain.com/contact.jsp>"... or is there another strategy that would work without even using restlet? Maybe some modification of my web.xml file? Edit (2009-08-14): My answer posted below doesn't work on App-Engine and Restlet. It does work however, if I don't include Restlet, or allow Restlet to have a url-pattern of "/\*" What would be ideal is to have a subclass of the Router that allows me to do this: ``` router.attach("/contact", "/contact.jsp"); ``` Thanks! Edit (2009-08-17): I'm surprised I haven't had any responses since I posted a bounty. Will someone comment and let me know if my question/problem isn't clear? Edit (2009-08-17): Interesting observation. When using the method described by "Rich Seller" below, it works when deployed on Google App-Engine and not locally. Additionally, If I call <http://mydomain.com/contact.jsp> on Google App-Engine it bypasses Restlet and goes straight to the JSP. But, locally, Restlet takes over. That is, <http://localhost:8080/contact.jsp> does not go to the JSP and goes to Restlet. Do deployed app-engine applications respond differently to URLs as their local counterpart?
"I would like to return a JSP file on a URL request through Restlet" - My understanding is JSP's are converted to servlets. Since Servlets are orthogonol to Restlets not sure how you can return JSP file through Restlet. Assuming you are asking for a way to use JSP in addition to Restlet, This is best achieved by mapping your restlets to a rootpath such as /rest instead of /\* and using the .jsp as usual.
Restlet doesn't currently support JSPs directly. They're difficult to handle outside of the servlet container. There's a [discussion on Nabble](http://n2.nabble.com/JSP-Servlet-Representation-td2384688.html) about this issue that you may find useful, at the moment it looks like you need to either return a redirect to the JSP mapped as normal in the web.xml, or hack it to process the JSP and return the stream as the representation. The response dated "Apr 23, 2009; 03:02pm" in the thread describes how you could do the hack: ``` if (request instanceof HttpRequest && ((HttpRequest) request).getHttpCall() instanceof ServletCall) { ServletCall httpCall = (ServletCall) ((HttpRequest) request).getHttpCall(); // fetch the HTTP dispatcher RequestDispatcher dispatcher = httpCall.getRequest().getRequestDispatcher("representation.jsp"); HttpServletRequest proxyReq = new HttpServletRequestWrapper(httpCall.getRequest()); // Overload the http response stream to grab the JSP output into a dedicated proxy buffer // The BufferedServletResponseWrapper is a custom response wrapper that 'hijacks' the // output of the JSP engine and stores it on the side instead of forwarding it to the original // HTTP response. // This is needed to avoid having the JSP engine mess with the actual HTTP stream of the // current request, which must stay under the control of the restlet engine. BufferedServletResponseWrapper proxyResp = new BufferedServletResponseWrapper(httpCall.getResponse()); // Add any objects to be encoded in the http request scope proxyReq.setAttribute("myobjects", someObjects); // Actual JSP encoding dispatcher.include(proxyReq, proxyResp); // Return the content of the proxy buffer Representation rep = new InputRepresentation(proxyResp.toInputStream(),someMediaType); ``` The source for the BufferedServletResponseWrapper is posted a couple of entries later.
Configure Restlet to Return JSPs on Google App Engine?
[ "", "java", "google-app-engine", "jsp", "restlet", "" ]
Say I have 50 rows in a MySQL table. I want to select the first ten (`LIMIT 10`), but then I want to be able to select the next 10 on a different page. So how do I start my selection, after row 10? Updated query: ``` mysql_query(" SELECT * FROM `picdb` WHERE `username` = '$username' ORDER BY `picid` DESC LIMIT '$start','$count' ") ```
I recommend working by obtaining the first page using: ``` LIMIT 0, 10 ``` then for the second page ``` LIMIT 10, 10 ``` then ``` LIMIT 20, 10 ``` for the third page, and so on.
``` LIMIT 10 LIMIT 10 OFFSET 10 ``` From the [MySQL 5.1 docs on `SELECT` syntax](http://dev.mysql.com/doc/refman/5.1/en/select.html): > For compatibility with PostgreSQL, > MySQL also supports the LIMIT > row\_count OFFSET offset syntax.
How can I select rows in MySQL starting at a given row number?
[ "", "php", "mysql", "pagination", "limit", "" ]
We're mostly doing C++ developing in Visual Studio 2005, and some C# coding. We're considering upgrading to Visual Studio 2008, but we're wondering if it will be worth the trouble. From what I've seen, and that is not much, VS2008 doesn't have any big advantages over VS2005. So is it worth switching to VS2008 from VS2005, or is it better to wait for VS2010? What are your experiences switching from VS2005 to VS2008? Thanks in advance! Regards, Sebastiaan
No, not really. There were only minor improvements to the C++ IDE, and the major improvements coming from the C++ team at MSFT are in Visual Studio 2010 (including an intellisense overhaul). It would not be beneficial to C++ developers in anyway really, you're not missing out.
I haven't seen much improvements in VS2008 comparing to 2005 for C++. Once VS2010 is released, it would be worth moving to it as it's C++ support is incredible.
For C++ developers, is it worth to switch from VS2005 to VS2008?
[ "", "c++", "visual-studio-2008", "visual-studio-2005", "" ]
I'm experiencing big problems using ExcelPackage, because sometimes the formulas are not updated (even if I remove the value). I've tried using ExcelInterop to save xlsx as xls, thinking that this could resolve the issue, but it didn't. The way I've found to resolve it is by pressing CTRL + ALT + F9. The user will not like doing it everytime, so, I want to do it programatically. Do you know any effective way to ensure all xlsx formulas are updated?
Call **Application.CalculateFull** from a VBA macro (or over the COM object)
I have found this to work for me before: ``` for (int iWorksheet = 1; iWorksheet <= workbook.Worksheets.Count; iWorksheet++) { Worksheet ws = ((Worksheet)workbook.Worksheets[iWorksheet]); ws.UsedRange.Formula = ws.UsedRange.Formula; ws.Calculate(); } ```
How to automatically refresh excel formulas?
[ "", "c#", ".net", "excel", "" ]
I was initially going to implement an observer pattern in C# 3.0 to solve my problem although it wouldn't be implement exactly in the same way. My problem is that I have a web application with users who can post messages. Notifications do not go directly to other users but to a distributed cache where a statistics objects are updated and users can check the statistics a decide if they want the updates or not. I currently have a IObserver interface that would need to implement multiple Update() methods based on who is posting a message and how they do it. I have also looked at the mediator pattern but I don't think it is a correct fit because instances of a mediator would not have a list of who is currently logged in. I am now wondering if there is another established design pattern that would be more suitable or if I should just fuinish building out my current Observer pattern to fit my needs. Thanks
Can't you implement it via events/delegates? This is the standard way to implement the Observer pattern in C# and other .Net languages.
Aren't .Net events just observer-patterns in disguise? :) You could have a class, say, Statistic, and have that class expose an OnUpdate() event.
Alternative design pattern to Observer for .Net
[ "", "c#", "design-patterns", "observer-pattern", "" ]
I used to be using visual studio 2005. Sad news is, I am using VS2008 and I need to call a web service. can someone paste same code snippets? **Why did I get a negative -1?**
What type of web-service are you trying to consume? If it's a 2.0 style ASMX service then there's an extra click or two to get to it. [Here's](http://devlicio.us/blogs/derik_whittaker/archive/2008/07/21/referencing-2-0-web-services-asmx-in-visual-studio-2008.aspx) some instuctions.
My VS2008 SP1 has an "Add Web Reference" option, but you can also use ***Add Service Reference - Advanced - Add Web Reference***. Those last two are buttons on the bottom of the dialog boxes that will appear. If you want to learn WCF, [that tutorial John Saunders linked](http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!790.entry) should get you started. There are tons of resources about it on the internet.
Visual Studio 2008: how to consume or call Web Service?
[ "", "c#", "visual-studio-2008", "web-services", "" ]
We're having some trouble with including javascript in masterpages. The "~/" root shortcut doesn't seem to work, and so we're having to manually enter in the path to the javascript from where it will be used, for example: "../../tooltip.js" However, the problem is that if the nested page is in a different path, this approach does not work as the path stays the same despite the nested page being in a different location - any solutions on how to get the path automatically working like it does for the css files? Thanks!
The `~/` is a special entity in ASP.NET which represents the "application root". The translation only happens when you pass that URL through an ASP.NET server control, such as `<asp:Image runat="server" ImageUrl="~/path..." />`. Trying to use it in something that is passed as literal text directly to the client, such as ` will be rendered exactly that in the browser. There are a few solutions to this: 1. Put your scripts in a predictable place relative to the domain root, such as `domain.com/scripts/script.js`, and you can refer to it as `/scripts/script.js`. The preceding `/` tells the client (browser) it is an absolute path from the domain root. 2. Use [Page.ResolveClientUrl](http://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveclienturl.aspx) to render the correct path (`<%=Page.ResolveClientUrl("~/script./js")%>`) 3. Create your own server control which handles the `~/` resolution. 4. Embed the script as an [assembly resource](http://msdn.microsoft.com/en-us/library/bb398930.aspx).
Cory Larson [recommends](https://stackoverflow.com/questions/697660/asp-net-master-page-and-file-path-issues/697674#697674): ``` <script type="text/javascript" src="<%= Page.ResolveClientUrl("~/tooltip.js") %>"></script> ```
How to insert javascript in asp.net master pages
[ "", "asp.net", "javascript", "" ]
I have a web service that receives data from various clients. Some of them sends the data encoded using escape(), while the others instead use encodeURIComponent(). Is there a way to detect the encoding used to escape the data?
Encourage your clients to use encodeURIComponent(). See this page for an explanation: [Comparing escape(), encodeURI(), and encodeURIComponent()](http://xkr.us/articles/javascript/encode-compare/). If you really want to try to figure out exactly how something was encoded, you can try to look for some of the characters that escape() and encodeURI() do not encode.
This won't help in the server-side, but in the client-side I have used javascript exceptions to detect if the url encoding has produced ISO Latin or UTF8 encoding. `decodeURIComponent` throws an exception on invalid UTF8 sequences. ``` try { result = decodeURIComponent(string); } catch (e) { result = unescape(string); } ``` For example, ISO Latin encoded umlaut 'ä' `%E4` will throw an exception in Firefox, but UTF8-encoded 'ä' `%C3%A4` will not. ### See Also * [decodeURIComponent vs unescape, what is wrong with unescape?](https://stackoverflow.com/questions/619323/decodeuricomponent-vs-unescape-what-is-wrong-with-unescape) * [Comparing escape(), encodeURI(), and encodeURIComponent()](http://xkr.us/articles/javascript/encode-compare/)
How to detect if a string is encoded with escape() or encodeURIComponent()
[ "", "javascript", "encoding", "escaping", "" ]
I wanted to hide some business logic and make the variables inaccessible. Maybe I am missing something but if somebody can read the javascript they can also add their own and read my variables. Is there a way to hide this stuff?
That's one of the downsides of using a scripting language - if you don't distribute the source, nobody can run your scripts! You can run your JS through an [obfuscator](http://www.google.com/search?q=javascript+obfuscator) first, but if anyone really wants to figure out exactly what your code is doing, it won't be that much work to reverse-engineer, especially since the *effects* of the code are directly observable in the first place.
Any code which executes on a client machine is available to the client. Some forms of code are *harder* to access, but if someone really wants to know what's going on, there's no way you have to stop them. If you don't want someone to find out what code is being run, do it on a server. Period.
Method to 'compile' javascript to hide the source during page execution?
[ "", "javascript", "" ]
I build a huge graph in JVM (Scala) which I want to use repeatedly, tweaking algorithms. I'd rather not reload it each time from disk. Is there a way to have it sit in one JVM while connecting from another, where the algorithms are being developed?
Save your graph to disk, then map it into memory with [MappedByteBuffer](http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html). Both processes should use the same memory, which will be shared with the page cache.
Two JVMs sounds more complicated than it needs to be. Have you considered doing a kind of "hot deploy" setup, where your main program loads up the graph, displays the UI, and then asks for (or automatically looks for) a jar/class file to load that contains your actual algorithm code? That way your algorithm code would be running in the same jvm as your graph, but you wouldn't have to reload the graph just to reload a new algorithm implementation. UPDATE to address OP's question in comment: Here's how you could structure your code so that your algorithms would be swappable. It doesn't matter what the various algorithms do, so long as they are operating on the same input data. Just define an interface like the following, and have your graph algorithms implement it. ``` public interface GraphAlgorithm { public void doStuff(Map<whatever> myBigGraph) } ``` If your algorithms are displaying results to some kind of widget, you could pass that in as well, or have doStuff() return some kind of results object.
How can I share memory between two JVM instances?
[ "", "java", "scala", "jvm", "" ]
Is it possible to filter a Django queryset by model property? i have a method in my model: ``` @property def myproperty(self): [..] ``` and now i want to filter by this property like: ``` MyModel.objects.filter(myproperty=[..]) ``` is this somehow possible?
Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.
I might be misunderstanding your original question, but there is a [filter](http://docs.python.org/library/functions.html#filter) builtin in python. ``` filtered = filter(myproperty, MyModel.objects) ``` But it's better to use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` filtered = [x for x in MyModel.objects if x.myproperty()] ``` or even better, a [generator expression](http://docs.python.org/tutorial/classes.html#generator-expressions): ``` filtered = (x for x in MyModel.objects if x.myproperty()) ```
Filter by property
[ "", "python", "django", "orm", "" ]
Can someone kindly provide a code to create an array from a CSV file using fgetcsv? I've used the following code to create an array from a simple CSV file, but it doesn't work right when one of my fields has multiple commas - such as addresses. ``` $lines =file('CSV Address.csv'); foreach($lines as $data) { list($name[],$address[],$status[]) = explode(',',$data); } ``` \*Also, str\_getcsv is not supported by my hosting service. The above code doesn't work with the following CSV file example. First column is name, second column is address, third column is marital status. ``` Scott L. Aranda,"123 Main Street, Bethesda, Maryland 20816",Single Todd D. Smith,"987 Elm Street, Alexandria, Virginia 22301",Single Edward M. Grass,"123 Main Street, Bethesda, Maryland 20816",Married Aaron G. Frantz,"987 Elm Street, Alexandria, Virginia 22301",Married Ryan V. Turner,"123 Main Street, Bethesda, Maryland 20816",Single ```
Like you said in your title, [fgetcsv](http://www.php.net/manual/en/function.fgetcsv.php) is the way to go. It's pretty darn easy to use. ``` $file = fopen('myCSVFile.csv', 'r'); while (($line = fgetcsv($file)) !== FALSE) { //$line is an array of the csv elements print_r($line); } fclose($file); ``` You'll want to put more error checking in there in case `fopen()` fails, but this works to read a CSV file line by line and parse the line into an array.
I think the [str\_getcsv](http://php.net/manual/en/function.str-getcsv.php)() syntax is much cleaner, it also doesn't require the CSV to be stored in the file system. ``` $csv = str_getcsv(file_get_contents('myCSVFile.csv')); echo '<pre>'; print_r($csv); echo '</pre>'; ``` Or for a line by line solution: ``` $csv = array(); $lines = file('myCSVFile.csv', FILE_IGNORE_NEW_LINES); foreach ($lines as $key => $value) { $csv[$key] = str_getcsv($value); } echo '<pre>'; print_r($csv); echo '</pre>'; ``` Or for a line by line solution with no str\_getcsv(): ``` $csv = array(); $file = fopen('myCSVFile.csv', 'r'); while (($result = fgetcsv($file)) !== false) { $csv[] = $result; } fclose($file); echo '<pre>'; print_r($csv); echo '</pre>'; ```
How to create an array from a CSV file using PHP and the fgetcsv function
[ "", "php", "arrays", "csv", "" ]
I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attempting to use a package structure based on my domain name for both the project and the app, and that's where I'm running into problems. Here's my file structure (with \_\_init\_\_.py files where appropriate): ``` $HOME/django-sites/mydomain $HOME/django-apps/mydomain/cms ``` And my PYTHONPATH: ``` $HOME/django-sites:$HOME/django-apps ``` If I fire up a Python interpreter (from any directory on the filesystem) I can import classes from the site, but not the application. If I reverse the order of the two entries in the PYTHONPATH (apps first, then sites) I can import from the app but not the site. It looks like Python's only attempting to import from the first entry in the PYTHONPATH that contains the first portion of the package name. Is that correct? Is this expected behavior? If so, I can only stick modules in package structures like domain/app1, domain/app2 if they live in the same directory structure - regardless of the PYTHONPATH. It's not show-stopper because I can rename the site, but it's much different than I was expecting. The Python tutorial mentions \_\_path\_\_, but I have no idea how to use it: > Packages support one more special attribute, \_\_path\_\_. This is initialized to be a list containing the name of the directory holding the package’s \_\_init\_\_.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package. > > While this feature is not often needed, it can be used to extend the set of modules found in a package. Has anyone else come across this? Is there something I can do with \_\_path\_\_ to make this function as expected?
Your analysis seems about right. The python path is used to locate modules to import; python imports the first one it finds. I'm not sure what you could do to work around this other than name your modules different things or put them in the same location in the search path.
Here's how `__path__` in a package's `__init__.py` is intended to be used: ``` $ export PYTHONPATH=$HOME/django-sites $ ls -d $HOME/django* django-apps/ django-sites/ $ cat /tmp/django-sites/mydomain/__init__.py import os _components = __path__[0].split(os.path.sep) if _components[-2] == 'django-sites': _components[-2] = 'django-apps' __path__.append(os.path.sep.join(_components)) $ python -c'import mydomain; import mydomain.foo' foo here /tmp/django-apps/mydomain/foo.pyc $ ``` as you see, this makes the contents of `django-apps/mydomain` part of the `mydomain` package (whose `__init__.py` resides under `django-sites/mydomain`) -- you don't need `django-apps` on `sys.path` for this purpose, either, if you use this approach. Whether this is a better arrangement than the one @defrex's answer suggests may be moot, but since a package's enriching its `__path__` is a pretty important bit of a python programmer's bag of tools, I thought I had better illustrate it anyway;-).
Creating multiple Python modules in different directories that share a portion of the package structure
[ "", "python", "django", "" ]
Using Javascript, is there an equivalent function or functionality so VBScript's IsEmpty function? The VBScript function returns whether the given variable is "empty", e.g. since all the variables are actually VARIANTs, whether or not the VARIANT has a vt of VT\_EMPTY, whereas most of what I've found for Javascript is string-specific or not generalizable.
``` function IsEmpty( theValue ) { if ( theValue === undefined ) { return true; } return false; } ```
JavaScript has a number of different values which could be considered "empty" and a number of different ways to test for empty. First things that are empty: 1. `undefined`: values that have been not been assigned. if you create a variable but don't assign anything to it, this is what it will contain. 2. `null`: this is an object value that can be assigned to any `var`. Next how to test for them. JavaScript is loosely typed with a lot of implicit type conversion. This means that when two values are of different types, the standard equals operator `==` performs type coersion. The triple-equals operator does **not** perform type coersion which makes it the best operator for testing against very specific values. 1. you can test the type of a value which returns a string that can be tested (*note the triple-equals operator*): ``` if ("undefined" === typeof myFoo) { /* this would be considered empty */ } ``` 2. you can test against the keyword `undefined` (*note the triple-equals operator*): ``` if (undefined === myFoo) { /* this would be considered empty */ } ``` 3. you can test against the keyword `null` (*note the triple-equals operator*): ``` if (null === myFoo) { /* this would be considered empty */ } ``` 4. you can test against the empty string `""` (*note the triple-equals operator*): ``` if ("" === myFoo) { /* this would be the empty string */ } ``` 5. if you are expecting a value which would not normally be coerced to the boolean value `false`, then you can test for its existence by just testing it directly within the if statement: ``` if (!myFoo) { /* this would be any falsy value, including false, null, 0, undefined */ } else { /* this would be any truthy value, including objects, numbers other than zero, Dates, etc. */ } ``` Most of the time, if you're expecting something "truthy", you can just test it directly and it will be coerced to a boolean value. So in short, you could probably get away with defining it as this: ``` function isEmpty(value) { return !value; } ``` But it often makes more sense just to put a `!` or `!!` before the object to get its value. Just be careful if you are expecting `false` or `0` (zero) as valid values. In those cases it is better to test the `typeof` the object and make choices accordingly.
Does VBScript's IsEmpty have an equivalent in JavaScript?
[ "", "javascript", "vbscript", "" ]
If I have a prototype that looks like this: ``` function(float,float,float,float) ``` I can pass values like this: ``` function(1,2,3,4); ``` So if my prototype is this: ``` function(float*); ``` Is there any way I can achieve something like this? ``` function( {1,2,3,4} ); ``` Just looking for a lazy way to do this without creating a temporary variable, but I can't seem to nail the syntax.
You can do it in C99 (but *not* ANSI C (C90) or any current variant of C++) with *compound literals*. See section 6.5.2.5 of the C99 standard for the gory details. Here's an example: ``` // f is a static array of at least 4 floats void foo(float f[static 4]) { ... } int main(void) { foo((float[4]){1.0f, 2.0f, 3.0f, 4.0f}); // OK foo((float[5]){1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); // also OK, fifth element is ignored foo((float[3]){1.0f, 2.0f, 3.0f}); // error, although the GCC doesn't complain return 0; } ``` GCC also provides this as an extension to C90. If you compile with `-std=gnu90` (the default), `-std=c99`, or `-std=gnu99`, it will compile; if you compile with `-std=c90`, it will not.
This is marked both C and C++, so you're gonna get radically different answers. If you are expecting four parameters, you can do this: ``` void foo(float f[]) { float f0 = f[0]; float f1 = f[1]; float f2 = f[2]; float f3 = f[3]; } int main(void) { float f[] = {1, 2, 3, 4}; foo(f); } ``` But that is rather unsafe, as you could do this by accident: ``` void foo(float f[]) { float f0 = f[0]; float f1 = f[1]; float f2 = f[2]; float f3 = f[3]; } int main(void) { float f[] = {1, 2}; // uh-oh foo(f); } ``` It is usually best to leave them as individual parameters. Since you shouldn't be using raw arrays anyway, you can do this: ``` #include <cassert> #include <vector> void foo(std::vector<float> f) { assert(f.size() == 4); float f0 = f[0]; float f1 = f[1]; float f2 = f[2]; float f3 = f[3]; } int main(void) { float f[] = {1, 2, 3, 4}; foo(std::vector<float>(f, f + 4)); // be explicit about size // assert says you cannot do this: foo(std::vector<float>(f, f + 2)); } ``` An improvement, but not much of one. You could use [`boost::array`](http://www.boost.org/doc/libs/1_39_0/doc/html/array.html), but rather than an error for mismatched size, they are initialized to 0: ``` #include <boost/array.hpp> void foo(boost::array<float, 4> f) { float f0 = f[0]; float f1 = f[1]; float f2 = f[2]; float f3 = f[3]; } int main(void) { boost::array<float, 4> f = {1, 2, 3, 4}; foo(f); boost::array<float, 4> f2 = {1, 2}; // same as = {1, 2, 0, 0} foo(f2); } ``` This will all be fixed in C++0x, when initializer list constructors are added: ``` #include <cassert> #include <vector> void foo(std::vector<float> f) { assert(f.size() == 4); float f0 = f[0]; float f1 = f[1]; float f2 = f[2]; float f3 = f[3]; } int main(void) { foo({1, 2, 3, 4}); // yay, construct vector from this // assert says you cannot do this: foo({1, 2}); } ``` And probably `boost::array` as well: ``` #include <boost/array.hpp> void foo(boost::array<float, 4> f) { float f0 = f[0]; float f1 = f[1]; float f2 = f[2]; float f3 = f[3]; } int main(void) { foo({1, 2, 3, 4}); foo({1, 2}); // same as = {1, 2, 0, 0} ..? I'm not sure, // I don't know if they will do the check, if possible. } ```
How to pass a constant array literal to a function that takes a pointer without using a variable C/C++?
[ "", "c++", "c", "function", "" ]
Using the Maven javadoc plugin you can exclude certain packages - but I have lots of packages and only a handful of classes I want to produce Javadoc for. Is there a way to include rather than exclude? I would also like to do things on a class level rather than a package level as I have some classes in a package which need javadoc and some which don't.
In the end I used the `sourcepath` configuration option to specify two packages containing the classes I wanted to Javadoc and gave classes in those packages that I didn't want to Javadoc default access. Setting the `show` configuration option to public allowed me to choose which classes Javadoc was produced for by setting there access to public. Full configuration below: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <links> <link>http://java.sun.com/j2se/1.5.0/docs/api/</link> </links> <source>1.5</source> <show>public</show> <doctitle>Foo API</doctitle> <title>Foo API</title> <bottom><![CDATA[Copyright notice]]></bottom> <sourcepath>${basedir}/src/main/java/com/foo/api;${basedir}/src/main/java/com/bar/api</sourcepath> </configuration> </plugin> ``` However, this is essentially a workaround and I strongly agree with shek's comment that this should be an enchancement against the maven-javadoc-plugin as it is supported by the javadoc utility. <http://jira.codehaus.org/browse/MJAVADOC>
Since maven-javadoc-plugin version 2.9, you can do this in your configuration: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.9</version> <configuration> .... <sourceFileIncludes> <include>Foo.java</include> <include>Bar.java</include> </sourceFileIncludes> <sourcepath>${basedir}/src/main/java/path/to/foo-and-bar</sourcepath> .... </configuration> .... ``` ... which would build a Javadoc site only including the mentioned classes.
Maven javadoc plugin - how can I include only certain classes?
[ "", "java", "maven-2", "javadoc", "maven-plugin", "" ]
How can I say which class of many (which all do the same job) execute faster? is there a software to measure that?
You have *(at least)* two solutions : The quite "naïve" one is using microtime(true) tobefore and after a portion of code, to get how much time has passed during its execution ; other answers said that and gave examples already, so I won"t say much more. This is a nice solution if you want to benchmark a couple of instructions ; like compare two types of functions, for instance -- it's better if done thousands of times, to make sure any "perturbating element" is averaged. Something like this, so, if you want to know how long it take to serialize an array : ``` $before = microtime(true); for ($i=0 ; $i<100000 ; $i++) { serialize($list); } $after = microtime(true); echo ($after-$before)/$i . " sec/serialize\n"; ``` Not perfect, but useful, and it doesn't take much time to set up. --- The other solution, that works quite nice if you want to identify which function takes lots of time in an entire script, is to use : * The [Xdebug](http://xdebug.org/) extension, to generate profiling data for the script * Software that read the profiling data, and presents you something readable. I know three of those : + [Webgrind](https://github.com/jokkedk/webgrind) ; web interface ; should work on any Apache+PHP server + [WinCacheGrind](http://sourceforge.net/projects/wincachegrind/) ; only on windows + [KCacheGrind](https://kcachegrind.github.io/html/Home.html) ; probably only Linux and linux-like ; That's the one I prefer, btw To get profiling files, you have to install and configure Xdebug ; take a look at the [Profiling PHP Scripts](http://xdebug.org/docs/profiler) page of the documentation. What I generally do is not enable the profiler by default *(it generates quite big files, and slows things down)*, but use the possibility to send a parameter called `XDEBUG_PROFILE` as GET data, to activate profiling just for the page I need. The profiling-related part of my php.ini looks like this : ``` xdebug.profiler_enable = 0 ; Profiling not activated by default xdebug.profiler_enable_trigger = 1 ; Profiling activated when requested by the GET parameter xdebug.profiler_output_dir = /tmp/ouput_directory xdebug.profiler_output_name = files_names ``` *(Read the documentation for more informations)* This screenshot is from a C++ program in KcacheGrind : [![http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif](https://i.stack.imgur.com/lB2NU.gif)](https://i.stack.imgur.com/lB2NU.gif) (source: [sourceforge.net](http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif)) You'll get exactly the same kind of thing with PHP scripts ;-) *(With KCacheGrind, I mean ; WinCacheGrind is not as good as KCacheGrind...)* This allows you to get a nice view of what takes time in your application -- and it sometimes definitly helps to locate **the** function that is slowing everything down ^^ Note that Xdebug counts the CPU time spent by PHP ; when PHP is waiting for an answer from a Database (for instance), it is not working ; only waiting. So Xdebug will think the DB request doesn't take much time ! This should be profiled on the SQL server, not PHP, so... Hope this is helpful :-) Have fun !
For quick stuff I do this (in PHP): ``` $startTime = microtime(true); doTask(); // whatever you want to time echo "Time: " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n"; ``` You can also use a profiler like [http://xdebug.org/](http://xdebug.org/ "xdebug").
How can I measure the speed of code written in PHP?
[ "", "php", "testing", "performance", "measurement", "" ]
C# has no printform method. Is it possible to reference Vb.net PrintForm instead of starting from scratch which would be a waste of time ?
Yes. Just add a reference to Microsoft.VisualBasic to your C# project.
Anything you can do from VB.Net you can do from C# by checking the Microsoft.VisualBasic namespace.
Is it possible to reference Vb.net PrintForm method in C#?
[ "", "c#", "" ]
I'm writing a console tool to generate some C# code for objects in a class library. The best/easiest way I can actual generate the code is to use reflection after the library has been built. It works great, but this seems like a haphazard approch at best. Since the generated code will be compiled with the library, after making a change I'll need to build the solution twice to get the final result, etc. Some of these issues could be mitigated with a build script, but it still feels like a bit too much of a hack to me. My question is, are there any high-level best practices for this sort of thing?
Have you considered using T4 templates for performing the code generation? It looks like it's getting much more publicity and attention now and more support in VS2010. This tutorial seems database centric but it may give you some pointers: <http://www.olegsych.com/2008/09/t4-tutorial-creatating-your-first-code-generator/> in addition there was a recent Hanselminutes on T4 here: <http://www.hanselminutes.com/default.aspx?showID=170>. Edit: Another great place is the T4 tag here on StackOverflow: <https://stackoverflow.com/questions/tagged/t4> EDIT: (By asker, new developments) As of VS2012, T4 now supports reflection over an active project in a single step. This means you can make a change to your code, and the compiled output of the T4 template will reflect the newest version, without requiring you to perform a second reflect/build step. With this capability, I'm marking this as the accepted answer.
Its pretty unclear what you are doing, but what does seem clear is that you have some base line code, and based on some its properties, you want to generate more code. So the key issue here are, given the base line code, how do you extract interesting properties, and how do you generate code from those properties? Reflection is a way to extract properties of code running (well, at least loaded) into the same execution enviroment as the reflection user code. The problem with reflection is it only provides a very limited set of properties, typically lists of classes, methods, or perhaps names of arguments. IF all the code generation you want to do can be done with just that, well, then reflection seems just fine. But if you want more detailed properties about the code, reflection won't cut it. In fact, the only artifact from which truly arbitrary code properties can be extracted is the the source code as a character string (how else could you answer, is the number of characters between the add operator and T in middle of the variable name is a prime number?). As a practical matter, properties you can get from character strings are generally not very helpful (see the example I just gave :). The compiler guys have spent the last 60 years figuring out how to extract interesting program properties and you'd be a complete idiot to ignore what they've learned in that half century. They have settled on a number of relatively standard "compiler data structures": abstract syntax trees (ASTs), symbol tables (STs), control flow graphs (CFGs), data flow facts (DFFs), program triples, ponter analyses, etc. If you want to analyze or generate code, your best bet is to process it first into such standard compiler data structures and then do the job. If you have ASTs, you can answer all kinds of question about what operators and operands are used. If you have STs, you can answer questions about where-defined, where-visible and what-type. If you have CFGs, you can answer questions about "this-before-that", "what conditions does statement X depend upon". If you have DFFs, you can determine which assignments affect the actions at a point in the code. Reflection will never provide this IMHO, because it will always be limited to what the runtime system developers are willing to keep around when running a program. (Maybe someday they'll keep all the compiler data structures around, but then it won't be reflection; it will just finally be compiler support). Now, after you have determined the properties of interest, what do you do for code generation? Here the compiler guys have been so focused on generation of machine code that they don't offer standard answers. The guys that do are the program transformation community (<http://en.wikipedia.org/wiki/Program_transformation>). Here the idea is to keep at least one representation of your program as ASTs, and to provide special support for matching source code syntax (by constructing pattern-match ASTs from the code fragments of interest), and provide "rewrite" rules that say in effect, "when you see this pattern, then replace it by that pattern under this condition". By connecting the condition to various property-extracting mechanisms from the compiler guys, you get relatively easy way to say what you want backed up by that 50 years of experience. Such program transformation systems have the ability to read in source code, carry out analysis and transformations, and generally to regenerate code after transformation. For your code generation task, you'd read in the base line code into ASTs, apply analyses to determine properties of interesting, use transformations to generate new ASTs, and then spit out the answer. For such a system to be useful, it also has to be able to parse and prettyprint a wide variety of source code langauges, so that folks other than C# lovers can also have the benefits of code analysis and generation. These ideas are all reified in the [DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html). DMS handles C, C++, C#, Java, COBOL, JavaScript, PHP, Verilog, ... and a lot of other langauges. (I'm the architect of DMS, so I have a rather biased view. YMMV).
Using reflection for code gen?
[ "", "c#", "reflection", "code-generation", "" ]
I have a java.net.URL object that uses the HTTPS protocol, e.g.: ``` https://www.bla.com ``` And I have to change only the protocol part of this URL object so that when I call its toString() method I get this: ``` http://www.bla.com ``` What is the best way to do that?
You'll have the use the methods available to you: ``` URL oldUrl = new URL("https://www.bla.com"); URL newUrl = new URL("http", oldUrl.getHost(), oldUrl.getPort(), oldUrl.getFile(), oldUrl.getRef()); ``` There's an even more expansive set() method that takes 8 items, you might need that for more elaborate URLs. Edit: As was just pointed out to me, I wasn't paying attention, and set() is protected. So URL is technically mutable, but to us mortals, it's immutable. So you'll just have to construct a new URL object.
You can also use string replacement: ``` URL oldUrl = new URL("https://www.bla.com"); String newUrlString = oldUrl.toString().replaceFirst("^https", "http"); URL newUrl = new URL(newUrlString); ```
How to change only the protocol part of a java.net.URL object?
[ "", "java", "http", "" ]
I have to maintain code from a contractor. It has this "interesting" snippet: ``` String webServicesValue = webResponse.substring(webResponse.indexOf("<" + fieldName + ">") + fieldName.length() + 2, webResponse.indexOf("</" + fieldName + ">")); ``` It took me a few minutes to understand what he's trying to do. It seems to be a WTF code, but my colleague suggested, "If it ain't broken, don't fix it." I'm wondering if this code will ever fail. It seems to be working so far, and I honestly can't think of a test case to fail this. Thanks,
Yes. It will throw an Exception if "<fieldname>" is not present in the response. Specifically it will try to call webResponse.substring(fieldName.length() + 1, -1); "<fieldname/>" will cause similar problems, as will any attributes on the element. And if you get "<fieldname> ... <fieldname> ... </fieldName> ... </fieldName>", you'll get the wrong answer. EDIT: in the light of followup discussions, I'd say that this code should be rewritten to use a proper XML parser ... unless you / your team can guarantee that the code will *never* have to deal with problematic XML. XML simply allows too many valid (and invalid) variations to deal with by ad-hoc string manipulation.
What happens if you receive **`<fieldname/>`** ?
Test case to fail this code?
[ "", "java", "unit-testing", "testing", "" ]
I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant... Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction, etc) which takes a lot of time (from seconds to several minutes). I use this module from a GUI written in wxpython and a console script. When I looked at how to implement progress dialogs in wxpython, I saw that I must get somehow a progress value to update my dialog, which is pure logic you'll admit... So I decided to use the number of frame processed in my engine functions, yield the current frame number every 33 frames and yield None when the processing is finished. by doing that here's what it looks like: ``` dlg = wx.ProgressDialog("Movie processing", "Movie is being written...", maximum = self.engine.endProcessingFrame,self.engine.startProcessingFrame, parent=self, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_SMOOTH | wx.PD_CAN_ABORT) state = self.engine.processMovie() f = state.next() while f != None: c, s = dlg.Update(f, "Processing frame %d"%f) if not c:break f = state.next() dlg.Destroy() ``` That works very well, there is absolutely no noticeable speed loss, but I would like to be able to call processMovie() function without having to deal with generators if I don't want to. For instance my console script which uses the engine module doesn't care of the progress, I could use it but it is destined to be executed in an environment where there is no display so I really don't care about the progress... Anyone with another design that the one I came up with? (using threads, globals, processes, etc) There must be a design somewhere that does this job cleany I think :-)
Using a generator is fine for this, but the whole point of using generators is so you can builtin syntax: ``` for f in self.engine.processMovie(): c, s = dlg.Update(f, "Processing frame %d"%f) if not c: break ``` If you don't care about that, then you can either say: ``` for f in self.engine.processMovie(): pass ``` or expose a function (eg. engine.processMovieFull) to do that for you. You could also use a plain callback: ``` def update_state(f): c, s = dlg.Update(f, "Processing frame %d"%f) return c self.engine.processMovie(progress=update_state) ``` ... but that's not as nice if you want to process the data piecemeal; callback models prefer to do all the work at once--that's the real benefit of generators.
This sounds like a perfect case for events. The process sends a "status update event", and anyone who wants to know (in this case the dialog) listens to that event.
usage of generators as a progression notifier
[ "", "python", "progress-bar", "generator", "" ]
For educational purposes, I am using cstrings in some test programs. I would like to shorten strings with a placeholder such as "...". That is, `"Quite a long string"` will become `"Quite a lo..."` if my maximum length is set to 13. Further, I do not want to destroy the original string - the shortened string therefore has to be a copy. The (static) method below is what I come up with. My question is: **Should the class allocating memory for my shortened string also be responsible for freeing it?** What I do now is to store the returned string in a separate "user class" and defer freeing the memory to that user class. ``` const char* TextHelper::shortenWithPlaceholder(const char* text, size_t newSize) { char* shortened = new char[newSize+1]; if (newSize <= 3) { strncpy_s(shortened, newSize+1, ".", newSize); } else { strncpy_s(shortened, newSize+1, text, newSize-3); strncat_s(shortened, newSize+1, "...", 3); } return shortened; } ```
The standard approach of functions like this is to have the user pass in a char[] buffer. You see this in functions like `sprintf()`, for example, which take a destination buffer as a parameter. This allows the caller to be responsible for both allocating and freeing the memory, keeping the whole memory management issue in a single place.
In order to avoid buffer overflows and memory leaks, you should **always use C++ classes** such as `std::string` in this case. Only the very last instance should convert the class into something low level such as `char*`. This will make your code simple and safe. Just change your code to: ``` std::string TextHelper::shortenWithPlaceholder(const std::string& text, size_t newSize) { return text.substr(0, newSize-3) + "..."; } ``` When using that function in a C context, you simply use the `cstr()` method: ``` some_c_function(shortenWithPlaceholder("abcde", 4).c_str()); ``` That's all! In general, you should not program in C++ the same way you program in C. It's more appropriate to treat C++ as a really different language.
Avoiding memory leaks while mutating c-strings
[ "", "c++", "memory-management", "connection-string", "cstring", "" ]
I want to use partially transparent images in drag/drop operations. This is all set up and works fine, but the actual transformation to transparency has a weird side effect. For some reason, the pixels seem to be blended against a black background. The following image describes the problem: ![Transparency problem](https://i.stack.imgur.com/AEPKZ.png) Figure a) is the original bitmap. Figure b) is what is produced after alpha blending has been performed. Obviously this is a lot darker than the intended 50% alpha filter intended. Figure c) is the desired effect, image a) with 50% transparency (added to the composition with a drawing program). The code I use to produce the trasparent image is the following: ``` Bitmap bmpNew = new Bitmap(bmpOriginal.Width, bmpOriginal.Height); Graphics g = Graphics.FromImage(bmpNew); // Making the bitmap 50% transparent: float[][] ptsArray ={ new float[] {1, 0, 0, 0, 0}, // Red new float[] {0, 1, 0, 0, 0}, // Green new float[] {0, 0, 1, 0, 0}, // Blue new float[] {0, 0, 0, 0.5f, 0}, // Alpha new float[] {0, 0, 0, 0, 1} // Brightness }; ColorMatrix clrMatrix = new ColorMatrix(ptsArray); ImageAttributes imgAttributes = new ImageAttributes(); imgAttributes.SetColorMatrix(clrMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage(bmpOriginal, new Rectangle(0, 0, bmpOriginal.Width, bmpOriginal.Height), 0, 0, bmpOriginal.Width, bmpOriginal.Height, GraphicsUnit.Pixel, imgAttributes); Cursors.Default.Draw(g, new Rectangle(bmpOriginal.Width / 2 - 8, bmpOriginal.Height / 2 - 8, 32, 32)); g.Dispose(); imgAttributes.Dispose(); return bmpNew; ``` Does anyone know why the alpha blending does not work? **Update I:** For clarity, the code does work if I'm alphablending on top of a drawn surface. The problem is that I want to create a completely semitransparent image from an existing image and use this as a dynamic cursor during drag/drop operations. Even skipping the above and only painting a filled rectangle of color 88ffffff yields a dark grey color. Something fishy is going on with the icon. **Update II:** Since I've reseached a whole lot and believe this has got something to do with the Cursor creation, I'm gonna include that code below too. If I GetPixel-sample the bitmap just before the CreateIconIndirect call, the four color values seem to be intact. Thus I have a feeling the culprits might be the hbmColor or the hbmMask members of the IconInfo structure. Here's the IconInfo structure: ``` public struct IconInfo { // http://msdn.microsoft.com/en-us/library/ms648052(VS.85).aspx public bool fIcon; // Icon or cursor. True = Icon, False = Cursor public int xHotspot; public int yHotspot; public IntPtr hbmMask; // Specifies the icon bitmask bitmap. If this structure defines a black and white icon, // this bitmask is formatted so that the upper half is the icon AND bitmask and the lower // half is the icon XOR bitmask. Under this condition, the height should be an even multiple of two. // If this structure defines a color icon, this mask only defines the AND bitmask of the icon. public IntPtr hbmColor; // Handle to the icon color bitmap. This member can be optional if this structure defines a black // and white icon. The AND bitmask of hbmMask is applied with the SRCAND flag to the destination; // subsequently, the color bitmap is applied (using XOR) to the destination by using the SRCINVERT flag. } ``` And here is the code that actually creates the Cursor: ``` public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot) { IconInfo iconInfo = new IconInfo(); GetIconInfo(bmp.GetHicon(), ref iconInfo); iconInfo.hbmColor = (IntPtr)0; iconInfo.hbmMask = bmp.GetHbitmap(); iconInfo.xHotspot = xHotSpot; iconInfo.yHotspot = yHotSpot; iconInfo.fIcon = false; return new Cursor(CreateIconIndirect(ref iconInfo)); } ``` The two external functions are defined as follows: ``` [DllImport("user32.dll", EntryPoint = "CreateIconIndirect")] public static extern IntPtr CreateIconIndirect(ref IconInfo icon); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo); ```
GDI+ has a number of problems related to alpha blending when doing interop with GDI (and Win32). In this case, the call to bmp.GetHbitmap() will blend your image with a black background. An [article on CodeProject](http://www.codeproject.com/KB/miscctrl/AlphaImageImagelist.aspx) gives more detail on the problem, and a solution that was used for adding images to an image list. You should be able to use similar code to get the HBITMAP to use for the mask: ``` [DllImport("kernel32.dll")] public static extern bool RtlMoveMemory(IntPtr dest, IntPtr source, int dwcount); [DllImport("gdi32.dll")] public static extern IntPtr CreateDIBSection(IntPtr hdc, [In, MarshalAs(UnmanagedType.LPStruct)]BITMAPINFO pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset); public static IntPtr GetBlendedHBitmap(Bitmap bitmap) { BITMAPINFO bitmapInfo = new BITMAPINFO(); bitmapInfo.biSize = 40; bitmapInfo.biBitCount = 32; bitmapInfo.biPlanes = 1; bitmapInfo.biWidth = bitmap.Width; bitmapInfo.biHeight = -bitmap.Height; IntPtr pixelData; IntPtr hBitmap = CreateDIBSection( IntPtr.Zero, bitmapInfo, 0, out pixelData, IntPtr.Zero, 0); Rectangle bounds = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bitmapData = bitmap.LockBits( bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb ); RtlMoveMemory( pixelData, bitmapData.Scan0, bitmap.Height * bitmapData.Stride); bitmap.UnlockBits(bitmapData); return hBitmap; } ```
A while ago, I read this problem arises out of a requirement for pre-multiplied alpha channels in the bitmaps. I'm not sure if this was an issue with Windows cursors or GDI, and for the life of me, I cannot find documentation regarding this. So, while this explanation may or may not be correct, the following code does indeed do what you want, using a pre-multiplied alpha channel in the cursor bitmap. ``` public class CustomCursor { // alphaLevel is a value between 0 and 255. For 50% transparency, use 128. public Cursor CreateCursorFromBitmap(Bitmap bitmap, byte alphaLevel, Point hotSpot) { Bitmap cursorBitmap = null; External.ICONINFO iconInfo = new External.ICONINFO(); Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); try { // Here, the premultiplied alpha channel is specified cursorBitmap = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppPArgb); // I'm assuming the source bitmap can be locked in a 24 bits per pixel format BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); BitmapData cursorBitmapData = cursorBitmap.LockBits(rectangle, ImageLockMode.WriteOnly, cursorBitmap.PixelFormat); // Use either SafeCopy() or UnsafeCopy() to set the bitmap contents SafeCopy(bitmapData, cursorBitmapData, alphaLevel); //UnsafeCopy(bitmapData, cursorBitmapData, alphaLevel); cursorBitmap.UnlockBits(cursorBitmapData); bitmap.UnlockBits(bitmapData); if (!External.GetIconInfo(cursorBitmap.GetHicon(), out iconInfo)) throw new Exception("GetIconInfo() failed."); iconInfo.xHotspot = hotSpot.X; iconInfo.yHotspot = hotSpot.Y; iconInfo.IsIcon = false; IntPtr cursorPtr = External.CreateIconIndirect(ref iconInfo); if (cursorPtr == IntPtr.Zero) throw new Exception("CreateIconIndirect() failed."); return (new Cursor(cursorPtr)); } finally { if (cursorBitmap != null) cursorBitmap.Dispose(); if (iconInfo.ColorBitmap != IntPtr.Zero) External.DeleteObject(iconInfo.ColorBitmap); if (iconInfo.MaskBitmap != IntPtr.Zero) External.DeleteObject(iconInfo.MaskBitmap); } } private void SafeCopy(BitmapData srcData, BitmapData dstData, byte alphaLevel) { for (int y = 0; y < srcData.Height; y++) for (int x = 0; x < srcData.Width; x++) { byte b = Marshal.ReadByte(srcData.Scan0, y * srcData.Stride + x * 3); byte g = Marshal.ReadByte(srcData.Scan0, y * srcData.Stride + x * 3 + 1); byte r = Marshal.ReadByte(srcData.Scan0, y * srcData.Stride + x * 3 + 2); Marshal.WriteByte(dstData.Scan0, y * dstData.Stride + x * 4, b); Marshal.WriteByte(dstData.Scan0, y * dstData.Stride + x * 4 + 1, g); Marshal.WriteByte(dstData.Scan0, y * dstData.Stride + x * 4 + 2, r); Marshal.WriteByte(dstData.Scan0, y * dstData.Stride + x * 4 + 3, alphaLevel); } } private unsafe void UnsafeCopy(BitmapData srcData, BitmapData dstData, byte alphaLevel) { for (int y = 0; y < srcData.Height; y++) { byte* srcRow = (byte*)srcData.Scan0 + (y * srcData.Stride); byte* dstRow = (byte*)dstData.Scan0 + (y * dstData.Stride); for (int x = 0; x < srcData.Width; x++) { dstRow[x * 4] = srcRow[x * 3]; dstRow[x * 4 + 1] = srcRow[x * 3 + 1]; dstRow[x * 4 + 2] = srcRow[x * 3 + 2]; dstRow[x * 4 + 3] = alphaLevel; } } } } ``` The pinvoke declarations are found in the External class, shown here: ``` public class External { [StructLayout(LayoutKind.Sequential)] public struct ICONINFO { public bool IsIcon; public int xHotspot; public int yHotspot; public IntPtr MaskBitmap; public IntPtr ColorBitmap; }; [DllImport("user32.dll")] public static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO piconinfo); [DllImport("user32.dll")] public static extern IntPtr CreateIconIndirect([In] ref ICONINFO piconinfo); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern IntPtr CreateBitmap(int nWidth, int nHeight, uint cPlanes, uint cBitsPerPel, IntPtr lpvBits); } ``` A few notes on the code: 1. To use the unsafe method, UnsafeCopy(), you must compile with the /unsafe flag. 2. The bitmap copying methods are ugly, especially the safe method, which uses Marshal.ReadByte()/Marshal.WriteByte() calls. There must be a faster way to copy bitmap data while also inserting alpha bytes. 3. I do assume that the source bitmap is able to be locked in a 24 bits per pixel format. This should not be a problem, though.
Windows Forms: Making a cursor bitmap partially transparent
[ "", "c#", "winforms", "gdi+", "alphablending", "mouse-cursor", "" ]
Can someone help me understand variable/function inheritance in PHP classes. My parent class has a function which is used by all the child classes. However each child classes needs to use it's own variable in this function. I want to call the function in the child classes statically. In the example below, the 'world' is displayed, as opposed to the values in the child classes. Can anyone explain how I can get the function to echo the values in the child classes. Should I be using interfaces? Is this something to do with late static binding (which is unavailable to me due to using a pre 5.3.0 version of PHP)? ``` class myParent { static $myVar = 'world'; static function hello() { echo self::$myVar; } } class myFirstChild extends myParent { static $myVar = 'earth'; } class mySecondChild extends myParent { static $myVar = 'planet'; } myFirstChild::hello(); mySecondChild::hello(); ```
Yeah, you can't do that. The declarations of `static $myVar` do not interact with each other in any way, precisely because they are static, and yeah, if you had 5.3.0 you could get around it, but you don't so you can't. My advice is to just use a non-static variable and method.
You could do it like this: ``` class myParent { var $myVar = "world"; function hello() { echo $this->myVar."\n"; } } class myFirstChild extends myParent { var $myVar = "earth"; } class mySecondChild extends myParent { var $myVar = "planet"; } $first = new myFirstChild(); $first->hello(); $second = new mySecondChild(); $second->hello(); ``` This code prints ``` earth planet ```
PHP function and variable inheritance
[ "", "php", "" ]
How to update value for a specific key in a dictionary `Dictionary<string, int>`?
Just point to the dictionary at given key and assign a new value: ``` myDictionary[myKey] = myNewValue; ```
It's possible by accessing the key as index **for example:** ``` Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary["test"] = 1; dictionary["test"] += 1; Console.WriteLine (dictionary["test"]); // will print 2 ```
How to update the value stored in Dictionary in C#?
[ "", "c#", "dictionary", "" ]
I am writing a webservice that allows users to post files and then retrieve them at a URL (basically think of it as the RESTful Amazon S3). The issue I came across was rather then return a byte[] from my Oracle query (Spring JDBC) I am returning an InputStream and then streaming the data back to the client in chunks. This (IMO) is a much better idea since I put no size restriction on the file and I don't want 2GB byte arrays in memory. At first it seemed to work fine, but I ran into a case during heavy load that sometimes a Connection would get reused before the previous servlet could send the file. It seems after the JDBC call that returned the InputStream, the Connection would be returned to the pool (Spring would call conn.close(), but not clear the associated ResultSet). So if no other request was given that Connection then the InputStream would still be valid and could be read from, but if the Connection was given to a new request then the InputStream would be null and the previous request would fail. My solution was to create a subclass of InputStream that also takes a Connection as a constructor arg, and in the overridden **public close()** method also close the Connection. I had to ditch the Spring JDBC and just make a normal PreparedStatement call, otherwise Spring would always return the connection to the pool. ``` public class ConnectionInputStream extends InputStream { private Connection conn; private InputStream stream; public ConnectionInputStream(InputStream s, Connection c) { conn = c; stream = s; } // all InputStream methods call the same method on the variable stream @Override public void close() throws IOException { try { stream.close(); } catch (IOException ioex) { //do something } finally { try { conn.close(); } catch (SQLException sqlex) { //ignore } } } } ``` Does anyone have a more elegant solution, or see any glaring problems with my solution? Also this code wasn't cut/paste from my actual code so if there is a typo just ignore it.
Unfortunately, my imagination went wild when you asked this question. I don't know if this solution is considered more elegant. However, these classes are simple and easily re-usable so you may find a use for them if they are not satisfactory. You will see everything coming together at the end... ``` public class BinaryCloseable implements Closeable { private Closeable first; private Closeable last; public BinaryCloseable(Closeable first, Closeable last) { this.first = first; this.last = last; } @Override public void close() throws IOException { try { first.close(); } finally { last.close(); } } } ``` `BinaryCloseable` is used by `CompositeCloseable`: ``` public class CompositeCloseable implements Closeable { private Closeable target; public CompositeCloseable(Closeable... closeables) { target = new Closeable() { public void close(){} }; for (Closeable closeable : closeables) { target = new BinaryCloseable(target, closeable); } } @Override public void close() throws IOException { target.close(); } } ``` The `ResultSetCloser` closes `ResultSet` objects: ``` public class ResultSetCloser implements Closeable { private ResultSet resultSet; public ResultSetCloser(ResultSet resultSet) { this.resultSet = resultSet; } @Override public void close() throws IOException { try { resultSet.close(); } catch (SQLException e) { throw new IOException("Exception encountered while closing result set", e); } } } ``` The `PreparedStatementCloser` closes `PreparedStatement` objects: ``` public class PreparedStatementCloser implements Closeable { private PreparedStatement preparedStatement; public PreparedStatementCloser(PreparedStatement preparedStatement) { this.preparedStatement = preparedStatement; } @Override public void close() throws IOException { try { preparedStatement.close(); } catch (SQLException e) { throw new IOException("Exception encountered while closing prepared statement", e); } } } ``` The `ConnectionCloser` closes `Connection` objects: ``` public class ConnectionCloser implements Closeable { private Connection connection; public ConnectionCloser(Connection connection) { this.connection = connection; } @Override public void close() throws IOException { try { connection.close(); } catch (SQLException e) { throw new IOException("Exception encountered while closing connection", e); } } } ``` We now refactor your original `InputStream` idea into: ``` public class ClosingInputStream extends InputStream { private InputStream stream; private Closeable closer; public ClosingInputStream(InputStream stream, Closeable closer) { this.stream = stream; this.closer = closer; } // The other InputStream methods... @Override public void close() throws IOException { closer.close(); } } ``` Finally, it all comes together as: ``` new ClosingInputStream( stream, new CompositeCloseable( stream, new ResultSetCloser(resultSet), new PreparedStatementCloser(statement), new ConnectionCloser(connection) ) ); ``` When this `ClosingInputStream`'s `close()` method is called, this is effectively what happens (with exception handling omitted for clarity's sake): ``` public void close() { try { try { try { try { // This is empty due to the first line in `CompositeCloseable`'s constructor } finally { stream.close(); } } finally { resultSet.close(); } } finally { preparedStatement.close(); } } finally { connection.close(); } } ``` You're now free to close as many `Closeable` objects as you like.
Why not read the entire `InputStream`/`byte[]`/whatever from the query before releasing the query yourself? It sounds like you are trying to return data from the query after your code has told Spring / the pool that you are done with the connection.
Spring JDBC connection pool and InputStream results
[ "", "java", "oracle", "spring", "jdbc", "" ]
Is there an easy method to extract only one field. For instance: ``` $sql = "SELECT field1 FROM table"; $res = mysql_query($sql) or die(mysql_error()); $arr = mysql_fetch_assoc($res); $field1 = $arr['field1']; ``` My feeling says this could be done much easier.
You can use [mysql\_result()](http://uk.php.net/mysql_result). > string mysql\_result ( resource $result , int $row [, mixed $field= 0 ] ) > Retrieves the contents of one cell from a MySQL result set.
Maybe ``` $sql = "SELECT field1 FROM table"; $result = mysql_query($sql) or die(mysql_error()); $field1 = mysql_fetch_object($result)->field1; ```
mysql fetching only one field
[ "", "php", "mysql", "" ]
Just started learning active record and am wondering how to best retrieve data from multiple tables where an SQL aggregate query is involved. In the following example (from a medical app) I'm looking for the most recent events of various types for each patient (e.g. last visit, last labtest etc). As you can see from the sql query below I'm looking for the max(date) value from a grouped query. I resorted to find\_by\_sql to do this - however I'd like to see how to do this without using find\_by\_sql. IOW - how would you get the required data here using a pure ActiveRecord approach. Below are the Table and Class defs I'm testing with: Find by Sql to retrieve most recent entries for each type - note the 'max(event\_date)' here ``` strsql = "select p.lname, e.patient_id, e.event_type, max(e.event_date) as event_date from events e inner join patients p on e.patient_id = p.id group by p.lname, e.patient_id, e.event_type" ``` Here's the sample sql query result: ``` lname, patient_id, event_type, latest 'Hunt', 3, 'Labtest', '2003-05-01 00:00:00' 'Hunt', 3, 'Visit', '2003-03-01 00:00:00' 'Seifer', 2, 'Labtest', '2002-05-01 00:00:00' 'Seifer', 2, 'Visit', '2002-03-01 00:00:00' Table Relationships are: Tables ---> Patients --> Events --> visits --> labtests --> ... other patients t.string :lname t.date :dob events t.column :patient_id, :integer t.column :event_date, :datetime t.column :event_type, :string visits t.column :event_id, :integer t.column :visittype, :string labtests t.column :event_id, :integer t.column :testtype, :string t.column :testvalue, :string ``` Classes ``` class Patient < ActiveRecord::Base has_many :events has_many :visits, :through =>:events has_many :labtests, :through => :events end class Event < ActiveRecord::Base has_many :visits has_many :labtests belongs_to :patient end class Visit < ActiveRecord::Base belongs_to :event end class Labtest < ActiveRecord::Base belongs_to :event end ```
As Pallan pointed out, the `:select` option cannot be used with the `:include` option. However the `:joins` option can. And this is what you want here. In fact, it can take the same arguments as `:include` or use your own SQL. Here's some rough, untested code, may need some minor fiddling. ``` Event.all(:select => "events.id, patients.lname, events.patient_id, events.event_type, max(events.event_date) as max_date", :joins => :patient, :group => "patients.lname, events.patient_id, events.event_type") ``` Note I modified things slightly. I renamed the `event_date` alias to `max_date` so there's no confusion over which attribute you are referring to. The attributes used in your `:select` query are available in the models returned. For example, in this you can call `event.max_date`. I also added the event `id` column because you can sometimes get some nasty errors without an `id` attribute (depending on how you use the returned models). The primary difference between `:include` and `:joins` is that the former performs eager loading of the associated models. In other words, it will automatically fetch the associated patient object for each event. This requires control of the `select` statement because it needs to select the patient attributes at the same time. With `:joins` the patient objects are not instantiated.
An include is just a clever left join, you can use that in conjuction with select and group\_by in your .find
Can Rails' Active Record handle SQL aggregate queries?
[ "", "sql", "ruby-on-rails", "activerecord", "aggregate", "" ]
Simple question but difficult to formulate for a search engine: if I make a pointer to a map object, how do I access and set its elements? The following code does not work. ``` map<string, int> *myFruit; myFruit["apple"] = 1; myFruit["pear"] = 2; ```
You can do this: ``` (*myFruit)["apple"] = 1; ``` or ``` myFruit->operator[]("apple") = 1; ``` or ``` map<string, int> &tFruit = *myFruit; tFruit["apple"] = 1; ``` or (C++ 11) ``` myFruit->at("apple") = 1; ```
`myFruit` is a pointer to a map. If you remove the asterisk, then you'll have a map and your syntax following will work. Alternatively, you can use the dereferencing operator (`*`) to access the map using the pointer, but you'll have to create your map first: ``` map<string, int>* myFruit = new map<string, int>() ; ```
How to access elements of a C++ map from a pointer?
[ "", "c++", "" ]
Is it possible to know the location of ***const*** variables within an exe? We were thinking of watermarking our program so that each user that downloads the program from our server will have some unique key embedded in the code. Is there another way to do this?
**Key consideration #1: Assembly signing** Since you are distributing your application, clearly you are signing it. As such, since you're modifying the binary contents, you'll have to integrate the signing process directly in the downloading process. **Key consideration #2: `const` or `readonly`** There is a key difference between `const` and `readonly` variables that many people do not know about. In particular, if I do the following: ``` private readonly int SomeValue = 3; ... if (SomeValue > 0) ... ``` Then it will compile to byte code like the following: ``` ldsfld [SomeValue] ldc.i4.0 ble.s ``` If you make the following: ``` private const int SomeValue = 3; ... if (SomeValue > 0) ... ``` Then it will compile to byte code like the following: ``` {contents of if block here} ``` `const` variables are [allowed to be] substituted and evaluated by the compiler instead of at run time, where `readonly` variables are always evaluated at run time. This makes a **big** difference when you expose fields to other assemblies, as a change to a `const` variable is a breaking change that forces a recompile of all dependent assemblies. **My recommendation** I see two reasonably easy options for watermarking, though I'm not an expert in the area so don't know how "good" they are overall. 1. Watermark the embedded splash screen or About box logo image. 2. Watermark the symmetric key for loading your string resources. Keep a cache so only have to decode them once and it won't be a performance problem - this is a variable applied to a commonly used obfuscation technique. The strings are stored in the binary as UTF-8 encoded strings, and can be replaced in-line as long as the new string's null-terminated length is less than or equal to the length of the string currently found in the binary. Finally, Google reported the following [article on watermarking software](http://www.preemptive.com/watermarking.html) that you might want to take a look at.
You could build a binary with a watermark that is a string representation of a GUID in a .net type as a constant. After you build, perform a search for the GUID string in the binary file to check its location. You can change this GUID value to another GUID value and then run the binary and actually see the changed value in code output. Note: The formatting is important as the length would be very important since you're messing with a compiled binary. For example, you'll want to keep the leading zeros of a GUID so that all instances have the same char length when converted to a string. i have actually done this sort of thing with Win32 DLLs and even the Sql Server 2000 Desktop exe. (There was a hack where you could switch the desktop edition into a full blown SQL server by flipping a switch in the binary.) This process could then be automated and a new copy of a DLL would be programmatically altered by a small, server-side utility for each client download. Also take a look at this: [link](http://moebiusit.com/blog/pabloromano/2009/07/13/changing-dll-settings-without-re-compiling/) It discusses the use of storing settings in a .Net DLL and uses a class-based approach and embeds the app settings file and is configurable after compilation.
C#: Location of const variable in a binary
[ "", "c#", ".net", "security", "compiler-construction", "watermark", "" ]
I am creating a non-blocking IO system for the server side of my project. The actual implementation isn't important (it is Java NIO if you care), but I feel very intimidated by the subtle issues you have to pay close attention to when programming socket communications. My knowledge is lacking in a lot of areas, so I can't even conceive of all the ways things can "go wrong"... "half-closed" connections, connections that send much more data than I would anticipate, etc. What I am looking for is some sort of client-side tool to help test the robustness of my system by automating the process of connecting and testing for a specific behavior. Some sort of tool with different sorts of options to simulate the different ways in which connections could be open, used, and closed. Perhaps it would let me send a megabyte of gibberish at once, or try to do things that don't "make sense", all for the purposes of me being able to test random, rare things that might cause my code to break, or to fail to recognize a "broken" connection and close it. Does a sort of tool exist? Another approach might be some Java code/unit test. Any thoughts? Thanks so much!
you can leverage your knowledge in Java writing simple unit tests that emulates random client behaviour: * too many data * too many connections * open and close * other corner cases Pure Java tests, without native code and other tricky configuration are a huge win. As starting point I recommend [JMeter](http://jakarta.apache.org/jmeter/): > Apache JMeter may be used to test performance both on static and dynamic resources (files, Servlets, Perl scripts, Java Objects, Data Bases and Queries, FTP Servers and more). It can be used to simulate a heavy load on a server, network or object to test its strength or to analyze overall performance under different load types. You can use it to make a graphical analysis of performance or to test your server/script/object behavior under heavy concurrent load. Take also a look at [JUnitPerf](http://clarkware.com/software/JUnitPerf.html) website.
I'd suggest looking at [netcat](http://netcat.sourceforge.net/). It gives you a very flexible way of pushing all kinds of data to a running server.
Testing/troubleshooting tool for network connections?
[ "", "java", "unit-testing", "testing", "sockets", "nio", "" ]
I need to use an `std::string` to store data retrieved by `fgets()`. To do this I need to convert the `char*` return value from `fgets()` into an `std::string` to store in an array. How can this be done?
`std::string` has a constructor for this: ``` const char *s = "Hello, World!"; std::string str(s); ``` Note that this construct deep copies the character list at `s` and `s` should not be `nullptr`, or else behavior is undefined.
If you already know size of the char\*, use this instead ``` char* data = ...; int size = ...; std::string myString(data, size); ``` This doesn't use strlen. EDIT: If string variable already exists, use assign(): ``` std::string myString; char* data = ...; int size = ...; myString.assign(data, size); ```
convert a char* to std::string
[ "", "c++", "stdstring", "" ]