Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Syntactic sugar for properties for example in C#: ``` private int x; public int X{ get { return x; } set { x = value; } } ``` or simply ``` public int X{ get; set; } ``` I am missing verbatim strings in java... @"C:\My Documents\" instead of "C:\\My Documents\\" Do you agree Java needs more "sugar"? Any one knows is there is sugar coming in next Java versions?
While I don't necessarily agree with Java's philosophy, I think that adding lots of **syntactic sugar** to Java would go against its philosophy. Java is supposed to be a very simple, easy to reason about language with few constructs, kind of a lowest common denominator *lingua franca* in the programming community. It was largely a reaction to the complexity of C++. There is supposed to be very little "magic" in it, beyond what is needed (garbage collection, mostly) to make it a memory-safe language. If you want more sugar, etc. in a reasonably high-performance, statically typed language, I would say that Java is just the wrong language for you. You're probably better off just using C#, or maybe D.
"Syntactic sugar causes cancer of the semicolon." -- Alan Perlis. Epigrams on Programming.
I want more syntactic sugar in my Java!
[ "", "java", "syntactic-sugar", "" ]
I have a business user who tried his hand at writing his own SQL query for a report of project statistics (e.g. number of tasks, milestones, etc.). The query starts off declaring a temp table of 80+ columns. There are then almost 70 UPDATE statements to the temp table over almost 500 lines of code that each contain their own little set of business rules. It finishes with a SELECT \* from the temp table. Due to time constraints and 'other factors', this was rushed into production and now my team is stuck with supporting it. Performance is appalling, although thanks to some tidy up it's fairly easy to read and understand (although the code smell is nasty). What are some key areas we should be looking at to make this faster and follow good practice?
First off, if this is not causing a business problem, then leave it until it becomes a problem. Wait until it becomes a problem, then fix everything. When you do decide to fix it, check if there is one statement causing most of your speed issues ... issolate and fix it. If the speed issue is over all the statements, and you can combine it all into a single SELECT, this will probably save you time. I once converted a proc like this (not as many updates) to a SELECT and the time to run it went from over 3 minutes to under 3 seconds (no shit ... I couldn't believe it). By the way, don't attempt this if some of the data is coming from a linked server. If you don't want to or can't do that for whatever reason, then you might want to adjust the existing proc. Here are some of the things I would look at: 1. If you are creating indexes on the temp table, wait until after your initial INSERT to populate it. 2. Adjust your initial INSERT to insert as many of the columns as possible. There are probably some update's you can eliminate by doing this. 3. Index the temp table before running your updates. Do not create indexes on any of the columns targetted by the update statements until after their updated. 4. Group your updates if your table(s) and groupings allow for it. 70 updates is quite a few for only 80 columns, and sounds like there may be an opportunity to do this. Good luck
First thing I would do is check to make sure there is an active index maintenance job being run periodically. If not, get all existing indexes rebuilt or if not possible at least get statistics updated. Second thing I would do is set up a trace (as described [here](https://stackoverflow.com/questions/257906/ms-sql-server-2008-how-can-i-log-and-find-the-most-expensive-queries#257944)) and find out which statements are causing the highest number of reads. Then I would run in SSMS with 'show actual execution plan' and tally the results with the trace. From this you should be able to work out whether there are missing indexes that could improve performance. EDIT: If you are going to downvote, please leave a comment as to why.
Refactoring "extreme" SQL queries
[ "", "sql", "sql-server-2005", "refactoring", "" ]
The question has been asked: [No PHP for large projects? Why not?](https://stackoverflow.com/questions/385203/no-php-for-large-projects-why-not) It's a recurring theme and PHP developers--with some cause--are forced to [defend PHP](https://stackoverflow.com/questions/309300/defend-php-convince-me-it-isnt-horrible). All of these questions are valid and there have been some responses but this got me thinking. Based on the principle that you can write good code in any language and bad code in any language, I thought it worth asking a positive rather than negative question. Rather than **why you can't**, I wanted to ask **how you can** use PHP for large projects. So, how do you write a large, complex, scalable, secure and robust PHP application? EDIT: While I appreciate that the organizational aspects are important, they apply to **any** large project. What I'm primarily aiming for here is technical guidance and how to deal with common issues of scalability. Using an opcode cache like APC is an obvious starter. Cluster-aware sessions would be another. That's the sort of thing I'm getting at.
For the most part, the problems with php are not so much with the language. The problems come from the coupling of a low barrier of entry and the lack of any infrastructure to avoid common programming problems or security problems. Its a language that, by itself, is pretty quick-and-dirty. Nevertheless, it still has many advantages for large-scale web apps. You'll just need to know how to add in some level of infrastructure to avoid a lot of the common web programming blunders. See - [What should a developer know *before* building a public web site](https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site) for help with this. You need to learn about the reasons php can make your web app to be insecure or problematic and learn to mitigate those problems. You should learn about how to use php to securely access your database. You should learn about avoiding SQL injection. You should learn about evil things like register\_globals and why you should never ever use them. In short, you should **do your homework** about your tool before just diving in for a real-world, large-scale, web app. Once you are educated, it comes down to you'll probably want to build a framework or use a preexisting framework that will mitigate these problems. Popular frameworks include PEAR and Zend. Also, useful questions that might help: * [What should every php programmer know?](https://stackoverflow.com/questions/306497/what-should-every-php-programmer-know) * [What should a developer know *before* building a public web site](https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site)
Using PHP for large projects isn't different than with any other language. You need experience and knowledge in writing [maintainable](http://www.php.net/zend-engine-2.php) and [extendable](http://framework.zend.com/) source code. You need to be aware of [security pitfalls](http://phpsec.org/projects/guide/) and [performance concerns](http://ilia.ws/files/phptek2007_performance.pdf). You need to have researched your [problem domain](http://en.wikipedia.org/wiki/Problem_domain) and be well familiar with it. In the end, same as any other language - what you need are [high-quality](http://www.joelonsoftware.com/items/2005/01/27.html) and [well-motivated](http://www.google.com/intl/en/jobs/) developers.
How to use PHP for large projects?
[ "", "php", "" ]
How would you access the cache from a jQuery ajax call? I'm using jquery to do some data verification and quick data access. I have a static web-method that jquery is calling via json to return a value. I don't want to call to the database everytime so I'd like to cache the data I'm hitting, but I can't determine how to call the asp.net cache from within javascript, or a static method. I'd like to send the page object through to the static method, which would allow me to access page.cache, but don't know how. Barring that, maybe a way to access the cache from javascript itself?
`System.Web.HttpContext.Current.Cache` Cache is shared per app domain - not per Page. Page just has a [convenience property of Page.Cache](http://msdn.microsoft.com/en-us/library/system.web.ui.page.cache.aspx) to get the current Cache, which means you can just do Cache["key"] from a method in a page. As you've noticed, if you're in a static method - then you have no Page instance, and you have no Page.Cache property. So, you need to use [HttpContext.Cache](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.cache.aspx). But, wait - you have no HttpContext instance either! That's ok, the currently executing instance is stored at the static property of [HttpContext.Current](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.current.aspx). So - to answer your question - in a static method, use HttpContext.Current.Cache. BTW, you can also access the [Request](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.request.aspx) and [Response](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.response.aspx) properties from there.
I think calling a PageMethod may be the best you can really do, if you really want to do this: <http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/>
Is there a way to access a cache or session from a static method?
[ "", "c#", "asp.net", "jquery", "ajax", "dynamic", "" ]
Edit: Warning - I now realize that the following technique is generally regarded as a bad idea because it creates hidden dependencies for the sake of looking neat. --- I recently discovered that you can use the StackTrace to infer information about the caller of a method. This enables you to create a seemingly "cool" API whereby you simply invoke a method without bothering to pass any explicit parameters to it, and the method works out what to do based on the StackTrace. Is this a bad thing to do, and if so, why? Example: ``` public class Cache { public Object CheckCache() { Object valueToReturn = null; string key = GenerateCacheKeyFromMethodPrototype(new StackTrace().GetFrame(1).GetMethod()); //frame 1 contains caller if(key is in cache) valueToReturn = itemFromCache; return valueToReturn; } } public class Foo { private static Cache cache = new Cache(); public Blah MethodFoo(param1, param2...) { Blah valueToReturn = cache.CheckCache(); //seems cool! if(valueToReturn == null) { valueToReturn = result of some calculation; //populate cache } return valueToReturn; } } ``` I'm sure there are errors in the above pseudocode, but you get my drift. --- Edit: thanks for everyone's responses.
There's two reasons why not to do this: * It's slow * It's creates a brittle solution. If you wanted to do this, you'd better off using a tool that supports Aspect Oriented Programming, such as Castle's Dynamic Proxy.
Another problem is that the compiler may "inline" your method in the optimisation process, e.g. ``` void MethodA() { MethodB(); } void MethodB() { foo(); } ``` becomes: ``` void MethodA() { foo(); } ``` This is obviously a problem because the immediately caller for foo is nolonger MethodB, but instead MethodA. There is an attribute you can place on your method to prevent it being inlined though: ``` [MethodImpl( ... NoInline )] ``` (I can't remember the exact parameter) -Oisin
Using The StackTrace To Infer The Caller Of A Method
[ "", "c#", "stack-trace", "" ]
Say a class ``` Person +Name: string +Contacts: List<Person> ``` I want to be able to check if a person has a contact with a certain name without having to create a dummy Person instance. ``` person.Contacts.Contains<string>("aPersonName"); ``` This should check all persons in the Contacts list if their Name.Equals("aPersonName"); I see that there is a Contains already available, but I don't know where I should implement it's logic.
It's probably easiest to use [Enumerable.Any](http://msdn.microsoft.com/en-us/library/bb534972.aspx): ``` return person.Contacts.Any(person => person.Name=="aPersonName"); ``` Alternatively, project and then contain: ``` return person.Select(person => person.Name).Contains("aPersonName"); ```
I'm assuming the Contacts is the Contacts for the person in question (person in your code snippit) List has a contains method that takes an object of type T as a parameter and returns true or false if that object exists in the list. What your wanting is IList.Exists method, Which takes a predicate. example (c# 3.0) ``` bool hasContact = person.Contacts.Exists(p => p.Name == "aPersonName"); ``` or (c# 2.0) ``` bool hasContact = person.Contacts.Exists(delegate(Person p){ return p.Name == "aPersonName"; }); ```
Contains<T>() and how to implement it
[ "", "c#", "linq", "" ]
## Background I have an application written in native C++ over the course of several years that is around 60 KLOC. There are many many functions and classes that are dead (probably 10-15% like the similar Unix based question below asked). We recently began doing unit testing on all new code and applying it to modified code whenever possible. However, I would make a SWAG that we have less than 5% test coverage at the present moment. ## Assumptions/Constraints The method and/or tools must support: * Native (i.e. unmanaged) C++ * Windows XP * Visual Studio 2005 * Must not require user supplied test cases for coverage. (e.g. can't depend on unit tests to generate code coverage) If the methods support more than these requirements, then great. **NOTE:** We currently use the Professional edition of Visual Studio 2005, not the Team System. Therefore, using Team System might be a *valid* suggestion (I don't know, I've never used it) however I'm hoping it is not the *only* solution. ## Why using unit tests for code coverage is problematic I believe that it is impossible for a generic tool to find all the dead (e.g. unreachable code) in any arbitrary application with zero false positives (I think this would be equivalent to the Halting problem). However, I also believe it is possible for a generic tool to find many types of dead code that are highly probable to in fact be dead, like classes or functions which are never reference in the code by anything else. By using unit tests to provide this coverage, you no longer using a generic algorithm and are thus increasing both the percentage of dead code you can detect and the probability that any hits are not false positives. Conversely, using unit tests could result in false negatives since the unit tests themselves might be the only thing exercising a given piece of code. Ideally, I would have regression testing that exercises all externally available methods, APIs, user controls, etc. which would serve as a baseline measurement of code coverage analysis to rule out certain methods from being false positives. Sadly however, I do not have this automated testing at the present time. Since I have such a large code base with such a low test case coverage percentage however, I'm looking for something that could help without requiring huge amounts of time invested in writing test cases. ## Question **How do you go about detecting dead code in an automated or semi-automated fashion in a native C++ application on the Windows platform with the Visual Studio 2005 development environment?** ## See Also [Dead code detection in legacy C/C++ project](https://stackoverflow.com/questions/229069/dead-code-detection-in-legacy-cc-project) [I want tell the VC++ Compiler to compile all code. Can it be done?](https://stackoverflow.com/questions/104952/i-want-tell-the-vc-compiler-to-compile-all-code-can-it-be-done)
Ask the linker to remove unreferenced objects (/OPT:REF). If you use function-level linking, and verbose linker output, the linker output will list every function it can prove is unused. This list may be far from complete, but you already have the tools needed.
We use [Bullseye](http://www.bullseye.com/coverage.html), and I can recommend it. It doesn't need to be run from a unit test environment, although that's what we do.
Automated Dead code detection in native C++ application on Windows?
[ "", "c++", "windows", "visual-studio-2005", "code-coverage", "dead-code", "" ]
I have a model that looks like this: ``` class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) ``` I want select count (just the count) of items for each category, so in SQL it would be as simple as this: ``` select category_id, count(id) from item group by category_id ``` Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the *count( )* method in Django, however I don't see how *group by* would fit there.
Here, as I just discovered, is how to do this with the Django 1.1 aggregation API: ``` from django.db.models import Count theanswer = Item.objects.values('category').annotate(Count('category')) ```
(**Update**: Full ORM aggregation support is now included in [Django 1.1](http://docs.djangoproject.com/en/dev/releases/1.1/#aggregate-support). True to the below warning about using private APIs, the method documented here no longer works in post-1.1 versions of Django. I haven't dug in to figure out why; if you're on 1.1 or later you should use the real [aggregation API](http://docs.djangoproject.com/en/dev/topics/db/aggregation/) anyway.) The core aggregation support was already there in 1.0; it's just undocumented, unsupported, and doesn't have a friendly API on top of it yet. But here's how you can use it anyway until 1.1 arrives (at your own risk, and in full knowledge that the query.group\_by attribute is not part of a public API and could change): ``` query_set = Item.objects.extra(select={'count': 'count(1)'}, order_by=['-count']).values('count', 'category') query_set.query.group_by = ['category_id'] ``` If you then iterate over query\_set, each returned value will be a dictionary with a "category" key and a "count" key. You don't have to order by -count here, that's just included to demonstrate how it's done (it has to be done in the .extra() call, not elsewhere in the queryset construction chain). Also, you could just as well say count(id) instead of count(1), but the latter may be more efficient. Note also that when setting .query.group\_by, the values must be actual DB column names ('category\_id') not Django field names ('category'). This is because you're tweaking the query internals at a level where everything's in DB terms, not Django terms.
Django equivalent for count and group by
[ "", "python", "django", "" ]
I'm building a fairly simple PHP script that will need to send some emails with attachments. I've found these 2 libraries to do this. Does either one have significant advantages over the other? Or should I just pick one at random and be done with it?
I was going to say that PHPMailer is no longer developed, and Swift Mailer is. But when I googled ... <https://github.com/PHPMailer/PHPMailer> That suggests its being worked on again. I've used PHPMailer a lot, and its always been solid and reliable. I had recently started using Swift Mailer, for the above reason, and it too has given me no trouble. Now that PHPMailer is developed again, I think I'll probably give the new version a try. So, my answer is that both are capable, and that it doesn't matter that much – choose one, learn it, use it. Both offer massive advantages over mail() and abstract away the nuances of email so that you can get on with whatever you are really trying to develop.
Whatever the features are, they have variety in their applicable licenses: PHPMailer - LGPL 2.1 (<https://github.com/PHPMailer/PHPMailer>) SwiftMailer - MIT license (<https://github.com/swiftmailer/swiftmailer>)
PhpMailer vs. SwiftMailer?
[ "", "php", "email", "attachment", "phpmailer", "swiftmailer", "" ]
Can someone explain to me why my code: ``` string messageBody = "abc\n" + stringFromDatabaseProcedure; ``` where valueFromDatabaseProcedure is not a value from the SQL database entered as ``` 'line1\nline2' ``` results in the string: ``` "abc\nline1\\nline2" ``` This has resulted in me scratching my head somewhat. I am using ASP.NET 1.1. **To clarify,** I am creating string that I need to go into the body of an email on form submit. I mention ASP.NET 1.1 as I do not get the same result using .NET 2.0 in a console app. All I am doing is adding the strings and when I view the messageBody string I can see that it has escaped the value string. **Update** What is not helping me at all is that Outlook is not showing the \n in a text email correctly (unless you reply of forward it). An online mail viewer (even the Exchange webmail) shows \n as a new line as it should.
I just did a quick test on a test NorthwindDb and put in some junk data with a \n in middle. I then queried the data back using straight up ADO.NET and what do you know, it does in fact escape the backslash for you automatically. It has nothing to do with the n it just sees the backslash and escapes it for you. In fact, I also put this into the db: foo"bar and when it came back in C# it was foo\"bar, it escaped that for me as well. My point is, it's trying to preserve the data as is on the SQL side, so it's escaping what it thinks it needs to escape. I haven't found a setting yet to turn that off, but if I do I'll let you know...
ASP.NET would use `<br />` to make linebreaks. `\n` would work with Console Applications or Windows Forms applications. Are you outputting it to a webpage? **Method #1** ``` string value = "line1<br />line2"; string messageBody = "abc<br />" + value; ``` If that doesn't work, try: ``` string value = "line1<br>line2"; string messageBody = "abc<br>" + value; ``` **Method #2** Use [System.Environment.NewLine](http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx): ``` string value = "line1"+ System.Environment.NewLine + "line2"; string messageBody = "abc" System.Environment.NewLine + value; ``` One of these ways is guaranteed to work. If you're outputting a string to a Webpage (or an email, or a form submit), you'd *have* to use one of the ways I mentioned. The `\n` will never work there.
Newlines escaped unexpectedly in C#/ASP.NET 1.1 code
[ "", "c#", "asp.net", "" ]
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python. How can I do this?
See the [locale](https://docs.python.org/3/library/locale.html) module. This does currency (and date) formatting. ``` >>> import locale >>> locale.setlocale( locale.LC_ALL, '' ) 'English_United States.1252' >>> locale.currency( 188518982.18 ) '$188518982.18' >>> locale.currency( 188518982.18, grouping=True ) '$188,518,982.18' ```
## New in 2.7 ``` >>> '{:20,.2f}'.format(18446744073709551616.0) '18,446,744,073,709,551,616.00' ``` <http://docs.python.org/dev/whatsnew/2.7.html#pep-0378>
Currency formatting in Python
[ "", "python", "formatting", "currency", "" ]
What would you suggest as a replacement to the Maven Java build toolset? Just plain Ant scripts? SCons?
While I like the **idea** of Maven, I always find myself fighting it for anything but the simplest configurations. Its architecture is plugin-based, and the quality of the plugins varies widely. Documentation is sketchy at best; half the time I can't figure out if the doc I'm reading is for Maven 1 or 2. And how often have you had to resort to using the `maven-ant-plugin` to do something basic? I've been using [Apache Ivy](http://ant.apache.org/ivy/) for about a year now, and I'm pretty happy with it. There is a bit of a learning curve though. But there's an active mailing list, and the author is very responsive. What I ended up doing was writing a "library" of a few simple Ant targets such as "resolve", "compile", "install", etc. that expect things to be in standard Maven places (such as `src/main/java`) and then `<import>` the targets into my various projects. This way you get the best of both worlds- Maven-style configuration, and all the power of Ant.
It depends on what you use anyway. Maven 1? Maven 2? I find Maven 2 decently documented, and quite powerful, when used in combination with Ant tasks and some home baked Java plugins. There are Ant tasks to use Maven features from Ant: <http://maven.apache.org/ant-tasks/index.html> . So you don't really need to write your own "library". And you can call Ant from Maven: <http://maven.apache.org/plugins/maven-antrun-plugin/> . You can also script things using Groovy for example: <http://groovy.codehaus.org/GMaven+-+Executing+Groovy+Code> . Or just write Java code for the custom bits you need: <http://maven.apache.org/guides/plugin/guide-java-plugin-development.html> . There's no reason not to mix and match, when you can do it ;)
Maven replacement?
[ "", "java", "maven-2", "build", "continuous-integration", "" ]
This is a sql newbie question. Basically, I want an extra column to return with my select statement to number the rows. I'm using mysql. Eg: ``` select * from friends David Steve Joe ``` What is the syntax to get: ``` 1 David 2 Steve 3 Joe ```
From: <http://markmal.blogspot.com/2006/04/oracle-like-rownum-in-mysql.html> ``` SELECT @rownum:=@rownum+1 rownum, t.*FROM (SELECT @rownum:=0) r, mytable t; ```
In SQL Server 2005 and higher you can use the [Row\_Number](http://msdn.microsoft.com/en-us/library/ms186734.aspx) function.
SQL a numbering column - MySQL
[ "", "sql", "mysql", "" ]
I want to create a unique id but `uniqid()` is giving something like `'492607b0ee414'`. What i would like is something similar to what tinyurl gives: `'64k8ra'`. The shorter, the better. The only requirements are that it should not have an obvious order and that it should look prettier than a seemingly random sequence of numbers. Letters are preferred over numbers and ideally it would not be mixed case. As the number of entries will not be that many (up to 10000 or so) the risk of collision isn't a huge factor. Any suggestions appreciated.
Make a small function that returns random letters for a given length: ``` <?php function generate_random_letters($length) { $random = ''; for ($i = 0; $i < $length; $i++) { $random .= chr(rand(ord('a'), ord('z'))); } return $random; } ``` Then you'll want to call that until it's unique, in pseudo-code depending on where you'd store that information: ``` do { $unique = generate_random_letters(6); } while (is_in_table($unique)); add_to_table($unique); ``` You might also want to make sure the letters do not form a word in a dictionnary. May it be the whole english dictionnary or just a bad-word dictionnary to avoid things a customer would find of bad-taste. EDIT: I would also add this only make sense if, as you intend to use it, it's not for a big amount of items because this could get pretty slow the more collisions you get (getting an ID already in the table). Of course, you'll want an indexed table and you'll want to tweak the number of letters in the ID to avoid collision. In this case, with 6 letters, you'd have 26^6 = 308915776 possible unique IDs (minus bad words) which should be enough for your need of 10000. EDIT: If you want a combinations of letters and numbers you can use the following code: ``` $random .= rand(0, 1) ? rand(0, 9) : chr(rand(ord('a'), ord('z'))); ```
@[gen\_uuid()](https://stackoverflow.com/a/1516430/4061501) by gord. preg\_replace got some nasty utf-8 problems, which causes the uid somtimes to contain "+" or "/". To get around this, you have to explicitly make the pattern utf-8 ``` function gen_uuid($len=8) { $hex = md5("yourSaltHere" . uniqid("", true)); $pack = pack('H*', $hex); $tmp = base64_encode($pack); $uid = preg_replace("#(*UTF8)[^A-Za-z0-9]#", "", $tmp); $len = max(4, min(128, $len)); while (strlen($uid) < $len) $uid .= gen_uuid(22); return substr($uid, 0, $len); } ``` Took me quite a while to find that, perhaps it's saves somebody else a headache
Short unique id in php
[ "", "php", "uniqueidentifier", "unique-index", "" ]
After tinkering around to solve [this][1] problem, I think the core of the problem is the following: When you use the Html.RadioButton() html helper with an Enum as value field, you can only choose your option once. AFter reposting the page, the helpers will ignore the value set in the call and set all radio buttons to the same value, being the value you selected the previous post back. Am I doing something wrong? *Example (watch the **value** of the buttons)* ``` <fieldset> <legend>Test</legend> <div> <label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel"> Any </label> <%=Html.RadioButton("SearchBag.EffectIndicator", "Any" , ViewData.Model.SearchBag.EffectIndicatorIsAny, new { @id = "SearchBag.EffectIndicatorAny" })%> </div> <div> <label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel"> Solid </label> <%=Html.RadioButton("SearchBag.EffectIndicator", "Solid", ViewData.Model.SearchBag.EffectIndicatorIsSolid, new { @id = "SearchBag.EffectIndicatorSolid" })%> </div> <div> <label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel"> Effect </label> <%=Html.RadioButton("SearchBag.EffectIndicator", "Effect", ViewData.Model.SearchBag.EffectIndicatorIsEffect, new { @id = "SearchBag.EffectIndicatorEffect" })%> </div> </fieldset> ``` Will generate ``` <fieldset> <legend>Effect</legend> <div class="horizontalRadio"> <label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel"> Any </label> <input checked="checked" id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Any" /> </div> <div class="horizontalRadio"> <label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel"> Solid </label> <input id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" /> </div> <div class="horizontalRadio"> <label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel"> Effect </label> <input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Effect" /> </div> </fieldset> ``` And will generate the second time: ``` <fieldset> <legend>Effect</legend> <div class="horizontalRadio"> <label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel"> Any </label> <input id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Solid" /> </div> <div class="horizontalRadio"> <label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel"> Solid </label> <input checked="checked" id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" /> </div> <div class="horizontalRadio"> <label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel"> Effect </label> <input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Solid" /> </div> </fieldset> ```
This is due to a bug in the ASP.NET MVC Beta code. I wrote a full explanation of the issue at asp.net MVC forum. Refer to this [link](http://forums.asp.net/t/1338576.aspx)
In case anybody cares here is a real quick and dirty work around in anticipation for the next update of the framework. It only regexreplaces the value with your value. It's not unit tested, not guaranteed not whatever. Put it in your HtmlHelper class library or wherever you put HtmlHelper extentions. add the following usings: * System.Text.RegularExpressions; * System.Web.Mvc.Html; ``` /*ToDo: remove when patched in framework*/ public static string MonkeyPatchedRadio(this HtmlHelper htmlHelper, string name, object value, bool isChecked, object htmlAttributes){ string monkeyString = htmlHelper.RadioButton(name, value, isChecked, htmlAttributes); monkeyString = Regex.Replace(monkeyString, "(?<=value=\").*(?=\".*)", value.ToString()); return monkeyString; } ``` I know it can be done better and whatnot, but I really hope it will be fixed soon anyway. If you feel like making it better, it's community wiki, so go ahead
Html.RadioButton sets all values to selected value
[ "", "c#", "html-helper", "asp.net-mvc-beta1", "" ]
Sometimes it seems natural to have a default parameter which is an empty list. However, [Python produces unexpected behavior in these situations](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). For example, consider this function: ``` def my_func(working_list=[]): working_list.append("a") print(working_list) ``` The first time it is called, the default will work, but calls after that will update the existing list (with one `"a"` each call) and print the updated version. How can I fix the function so that, if it is called repeatedly without an explicit argument, a new empty list is used each time?
``` def my_func(working_list=None): if working_list is None: working_list = [] # alternative: # working_list = [] if working_list is None else working_list working_list.append("a") print(working_list) ``` [The docs](https://docs.python.org/reference/compound_stmts.html#function-definitions) say you should use `None` as the default and explicitly [test for it](https://stackoverflow.com/questions/3257919/what-is-the-difference-between-is-none-and-none) in the body of the function.
Other answers have already already provided the direct solutions as asked for, however, since this is a very common pitfall for new Python programmers, it's worth adding the explanation of why Python behaves this way, which is nicely summarized in [*The Hitchhikers Guide to Python*](https://docs.python-guide.org/writing/gotchas/) under [*Mutable Default Arguments*](https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments): > Python's default arguments are evaluated *once* when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you *will* and have mutated that object for all future calls to the function as well.
How can I avoid issues caused by Python's early-bound default parameters (e.g. mutable default arguments "remembering" old data)?
[ "", "python", "default-parameters", "" ]
I need to use lists for my program and needed to decide if I use std::vector or std::list. The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator. My code looks like this: ``` #include <list> template <class T > class myList : public std::list<T> { public: T operator[](int index); T operator[](int & index); myList(void); ~myList(void); }; #include "myList.h" template<class T> myList<T>::myList(void): std::list<T>() {} template<class T> myList<T>::~myList(void) { std::list<T>::~list(); } template<class T> T myList<T>::operator[](int index) { int count = 0; std::list<T>::iterator itr = this->begin(); while(count != index)itr++; return *itr; } template<class T> T myList<T>::operator[](int & index) { int count = 0; std::list<T>::iterator itr = this->begin(); while(count != index)itr++; return *itr; } ``` I can compile it but I get a linker error if I try to use it. Any ideas?
All template code should be put in header file. This fill fix linking problems (that's the simplest way). The reason it happens is because compilers compiles every source (.cc) file separately from other files. On the other hand it needs to know what code exactly it needs to create (i.e. what is the T in template is substituted with), and it has no other way to know it unless the programmer tells it explicitly or includes all the code when template instantiation happens. I.e. when mylist.cc is compiled, it knows nothing about mylist users and what code needs to be created. On the other hand if listuser.cc is compiled, and all the mylist code is present, the compiler creates needed mylist code. You can read more about it in [here](http://www.iis.sinica.edu.tw/~kathy/vcstl/templates.htm) or in Stroustrup. Your code has problems, what if user requests negative or too large (more than amount of elements in the list). And i didn't look too much. Besides, i don't know how u plan to use it, but your operator[] is O(N) time, which will probably easily lead to O(N\*N) loops...
Depending on your needs, you should use `std::vector` (if you need often appends/removes at the end, and random access), or `std::deque` (if you need often appends/removes at the end or at the beginning, and your dataset is huge, and still want random access). Here is a good picture showing you how to make the decision: [![Container Choice](https://i.stack.imgur.com/qWf2C.png)](https://i.stack.imgur.com/qWf2C.png) (source: [adrinael.net](http://adrinael.net/containerchoice.png))
Extending std::list
[ "", "c++", "templates", "list", "linker", "" ]
Is it possible to set the DataContext property of a usercontrol after the user control has been loaded, and force the usercontrol to rebind?
I'm pretty sure that if you just set the datacontext again, it will rebind
If you need to do extra work when the DataContext changes you can use a custom DependencyProperty and bind it to the DataContext property. Use the DependencyPropertyChangedEventHandler to know when the DP changed. For a more complete explanation see my blog post at <http://msmvps.com/blogs/theproblemsolver/archive/2008/12/29/how-to-know-when-the-datacontext-changed-in-your-control.aspx>.
Silverlight: How to force binding after setting the DataContext property
[ "", "c#", ".net", "silverlight", "data-binding", "" ]
I have several functions that I wrote and I use regularly on my servers, is there a way I can add them to the core so I don't have to include them from external files? I am running PHP5
You could add your libraries as a [PEAR](http://pear.php.net/) extension. Then you could add it to your [local PEAR repository](http://kuziel.info/log/archives/2006/04/01/Installation-of-local-PEAR-repository). Pear is added to the default include path in php.ini. Then you can just use "pear install myextension" on your machines. If these are C functions you interface with in php (php extensions) then you can do something similar with [PECL](http://pecl.php.net/).
I've done this before.. it's a fairly involved process, but not too bad. This article at zend.com should tell you everything you need to know: <http://devzone.zend.com/303/extension-writing-part-i-introduction-to-php-and-zend/> edit: I should add that there are better ways to achieve the essence of what you're trying to do. Remember that doing this will further clutter up PHP's (already very cluttered) namespace. You're probably better off just making a global include file that has all of your most commonly used functions that you include wherever you need it. edit2: Upon rereading your original question, you said you don't want to do that, but I still think it's probably the best way. But best of luck to you with the extension route.
Adding functions to PHP core
[ "", "php", "deployment", "pear", "pecl", "" ]
I would like to do something like the following: ``` def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) ``` In python, is it possible to assign something like a function pointer?
Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python.
Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value. You can use this to implement a Strategy pattern, for example: ``` def the_simple_way(a, b): # blah blah def the_complicated_way(a, b): # blah blah def foo(way): if way == 'complicated': doit = the_complicated_way else: doit = the_simple_way doit(a, b) ``` Or a lookup table: ``` def do_add(a, b): return a+b def do_sub(a, b): return a-b handlers = { 'add': do_add, 'sub': do_sub, } print handlers[op](a, b) ``` You can even grab a method bound to an object: ``` o = MyObject() f = o.method f(1, 2) # same as o.method(1, 2) ```
function pointers in python
[ "", "python", "function-pointers", "" ]
I have a table structure that looks like: ``` <table> <tr id="row1"> <td> <div>row 1 content1</div> </td> <td> <div>row 1 content2</div> </td> <td> <div>row 1 content3</div> </td> </tr> <tr id="row2"> <td> <div>row 2 content1</div> </td> <td> <div>row 2 content2</div> </td> <td> <div>row 2 content3</div> </td> </tr> <tr id="row3"> <td> <div>row 3 content1</div> </td> <td> <div>row 3 content2</div> </td> <td> <div>row 3 content3</div> </td> </tr> </table> ``` Using jQuery I am trying to select the DIV in the second cell of the third row. I tried the following (amongst other things): ``` var d = $('#row3').children(':eq(1)').children(':eq(0)'); ``` What I get back is an array with a single element (the DIV I'm after) and I have to then access using d[0]. Why is jQuery returning a single element array, I thought using the selector above would return the DIV element directly? --- **[@Shog9](https://stackoverflow.com/questions/307500/how-do-i-select-an-element-in-jquery#307509)** - Duh...Ok a light just switched on in my brain, I get it now. Cheers.
jQuery always returns a set of elements. Sometimes, the set is empty. Sometimes, it contains only one element. The beauty of this is that you can write code to work the same way regardless of how many elements are matched: ``` $("selector").each(function() { this.style.backgroundColor = "red"; }); ``` Fun!
If you prefer keeping a jQuery object, you may write instead: ``` $("selector").first().val() ```
How do I select a single element in jQuery?
[ "", "javascript", "jquery", "" ]
This is a purely theoretical question. Given three simple classes: ``` class Base { } class Sub extends Base { } class SubSub extends Sub { } ``` And a function meant to operate on these classes: ``` public static void doSomething(Base b) { System.out.println("BASE CALLED"); } public static void doSomething(Sub b) { System.out.println("SUB CALLED"); } ``` It seems that the followign code: ``` SubSub ss = new SubSub(); doSomething(ss); ``` could legitimately result in printing either BASE CALLED, or SUB CALLED, since SubSub can be casted to both of those. In fact, removing the Sub version of the function causes BASE CALLED to be printed. What actually happens is that "SUB CALLED" is printed. This seems to mean that which function is called doesn't depend on the order the functions are defined in, as the Base version was called first. Does Java just look at all the different versions of the function and pick the one which requires the smallest traversal up the inheritance stack? Is this standardized? Is it written out in any documentation?
The formal specification can be found in [part 15.12.2.5 of the Java Language Specification (JLS)](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#301183). Thanks to generics this is pretty complicated, so you might want to look at [same section of the first edition of the JLS](http://java.sun.com/docs/books/jls/first_edition/html/15.doc.html#18428). It basically says that the compiler tries to find a version of the method where all parameters including the object the method is called upon are most specific. If no such method exists (e.g. since you have `method(Base, Sub)` and `method(Sub, Base)` but not `method(Sub, Sub)`), then the compilation fails. Note that the actual choice of method depends on the dynamic type of the target object for instance methods, but not for the parameters. Your example would still work the same on the instance level. You should be able to give the compiler a helping hand by casting or redeclaring the type of `ss`. If the declared type of the variable matches a signature exactly then everything is clear for the compiler and maintenance programmers as well. It doesn't matter if you then assign a more specific type as long as the declared type matches.
As far as I know, Java and C++ make this decision at compilation time (since these are static functions that are not dynamically dispatchable) based on the most specific matching that they can make. If your static type is SubSub and you have an overload that takes SubSub, this is the one that will be invoked. I'm fairly sure it's in both standards. If you have a reference or pointer to Base, even if it contains a Sub or a SubSub, you will match the version that takes a Base because at compile time, that is the only assurance that the compiler has.
How does Java pick which overloaded function to call?
[ "", "java", "inheritance", "programming-languages", "function", "" ]
The GUI for managing plugins in Eclipse got a bit of an overhaul in version 3.4.0. This GUI is accessed via the "Software Updates..." option in the Help menu. The option to remove the selected Mylyn plugin is greyed out. In fact, this is true of virtually every installed plugin. I know that the Mylyn plugins are optional, so why amn't I provided with an option to remove them?
**The following text is quoted from the Eclipse help docs:** The Uninstall wizard allows you to review and uninstall items in your configuration. This wizard is shown when you select items and press Uninstall... from the Installed Software page. To uninstall software from your system: 1. Click *Help > About and then click Installation Details...* to open a dialog showing pages that provide more detail about your installation. 2. Click the *Installed Software* tab to see a list of the software items that you have installed into your system. 3. Select the items that you wish to uninstall. Click *Uninstall...* The *Uninstall Details* page will show you a list of the items that will be uninstalled. Expanding each item will show what additional items (if any) will be uninstalled as a result of your choice. If you change your mind about which items should be uninstalled, you may click *Back* to see a checkmark list of the items you selected before. You may check and uncheck different items in the list, and click *Next* when you are ready to continue. 5. Click *Finish* to start the uninstall. Once all of the software is uninstalled successfully, you will be prompted to restart for the Workbench. Click *Yes* when asked to exit and restart the Workbench for the changes to take effect.
And just to update it for Helios - Eclipse 3.6 `Help->Install New Software` at the bottom of dialog there is link `What is already installed` once you click on that you will get list of installed plugins and `Uninstal...` button
How to uninstall plugins in Eclipse 3.4.X or higher
[ "", "java", "eclipse", "ide", "plugins", "eclipse-plugin", "" ]
Say I have three classes: ``` class X{}; class Y{}; class Both : public X, public Y {}; ``` I mean to say I have two classes, and then a third class which extends both (multiple-inheritance). Now say I have a function defined in another class: ``` void doIt(X *arg) { } void doIt(Y *arg) { } ``` and I call this function with an instance of both: ``` doIt(new Both()); ``` This causes a compile-time error, stating that the function call is ambiguous. What are the cases, besides this one, where the C++ compiler decides the call is ambiguous and throws an error, if any? How does the compiler determine what these cases are?
Simple: if it's ambiguous, then the compiler gives you an error, forcing you to choose. In your snippet, you'll get a different error, because the type of `new Both()` is a pointer to `Both`, whereas both overloads of `doIt()` accept their parameters by value (i.e. they do not accept pointers). If you changed `doIt()` to take arguments of types `X*` and `Y*` respectively, the compiler would give you an error about the ambiguous function call. If you want to explicitly call one or the other, you cast the arguments appropriately: ``` void doIt(X *arg) { } void doIt(Y *arg) { } Both *both = new Both; doIt((X*)both); // calls doIt(X*) doIt((Y*)both); // calls doIt(Y*) delete both; ```
I get this error with gcc: ``` jeremy@jeremy-desktop:~/Desktop$ g++ -o test test.cpp test.cpp: In function ‘int main(int, char**)’: test.cpp:18: error: call of overloaded ‘doIt(Both&)’ is ambiguous test.cpp:7: note: candidates are: void doIt(X) test.cpp:11: note: void doIt(Y) ```
How does C++ pick which overloaded function to call?
[ "", "c++", "inheritance", "programming-languages", "function", "multiple-inheritance", "" ]
How do I extract a double value from a string using regex. ``` import re pattr = re.compile(???) x = pattr.match("4.5") ```
Here's the easy way. Don't use regex's for built-in types. ``` try: x = float( someString ) except ValueError, e: # someString was NOT floating-point, what now? ```
A regexp from the [`perldoc perlretut`](http://perldoc.perl.org/perlretut.html#Building-a-regexp): ``` import re re_float = re.compile("""(?x) ^ [+-]?\ * # first, match an optional sign *and space* ( # then match integers or f.p. mantissas: \d+ # start out with a ... ( \.\d* # mantissa of the form a.b or a. )? # ? takes care of integers of the form a |\.\d+ # mantissa of the form .b ) ([eE][+-]?\d+)? # finally, optionally match an exponent $""") m = re_float.match("4.5") print m.group(0) # -> 4.5 ``` To extract numbers from a bigger string: ``` s = """4.5 abc -4.5 abc - 4.5 abc + .1e10 abc . abc 1.01e-2 abc 1.01e-.2 abc 123 abc .123""" print re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s) # -> ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2', # ' 1.01', '-.2', ' 123', ' .123'] ```
Extract float/double value
[ "", "python", "regex", "" ]
I have a goal to build an application with UI that would run on both Windows Mobile and "normal" desktop Windows. The priority is for it to "look good" under Windows Mobile, and for desktop Windows it is OK if it distorted. Before I invest days trying, I would like to hear if that is possible to begin with. There are several parts to this question: 1. Is .NET Compact Framework a subset of "normal" (please, edit) .NET Framework? If not, does MSDN have any information anywhere on classes that are in .NET Compact Framework, but not in "normal" (again, please, edit) framework? 2. Is behavior of shared classes same in both frameworks? 3. Is it possible to have a single Visual Studio 2005 solution / project for both platforms? If yes, how do to set it up? 4. Any other comments and advice? Any relevant links?
1. The CF **contains** a subset of the full framework (FFx), but it is not a pure subset. There are actually several things available in the CF that aren't in the FFx, which makes it a bit more difficult. CF apps also, except in the most rudimentary cases, use P/Invoke. Those calls are never the same from the desktop to the device, so they are not directly portable (though with a little abstraction you can have a platform-agnostic interface). 2. For the most part, behavior is the same. I've seen some cases [where it's not](http://blog.opennetcf.com/ctacke/2008/10/02/BehavioralDifferencesBetweenTheCFAndFFx.aspx), and I recall some event ordering not always being identical though, so trust but verify. 3. It's possible through very careful massaging of the configurations, but I certainly don't recommend it. It's difficult to maintain and very fragile. Instead have two project files, one for CF and one for FFx. You're likely to have code file differences anyway. Add the code files as links to each project so they both use the same physical source file. I'd recommend using some form of [CI](http://www.martinfowler.com/articles/continuousIntegration.html) to help ensure they both build at all times. 4. Take a look at [Dan Moth's MSDN article](http://msdn.microsoft.com/en-us/magazine/cc163387.aspx) and [blog entries](http://www.danielmoth.com/Blog/2006/10/mobile-cross-platform-development.html) on sharing code assets.
P.S. I found the poster online - it'll show you all the classes that are CF. I ordered it fro Microsoft because Kinkos wanted $65 to print it out in color for me! Microsoft sent me a couple of copies free - all I had to do was ask: <http://www.microsoft.com/downloads/details.aspx?familyid=7B645F3A-6D22-4548-A0D8-C2A27E1917F8&displaylang=en> I have it hanging in my cubicle and it's a godsend when trying to remember which namespaces classes can be found in.
Common C# source code for Windows and Windows Mobile
[ "", "c#", ".net", "winapi", "windows-mobile", "compact-framework", "" ]
I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings. How can I do this?
You can convert a string to a 32-bit signed integer with the `int` function: ``` string = "1234" i = int(string) # i is a 32-bit integer ``` If the string does not represent an integer, you'll get a `ValueError` exception. Note, however, that if the string does represent an integer, but that integer does not fit into a 32-bit signed int, then you'll actually get an object of type `long` instead. You can then convert it to other widths and signednesses with some simple math: ``` s8 = (i + 2**7) % 2**8 - 2**7 # convert to signed 8-bit u8 = i % 2**8 # convert to unsigned 8-bit s16 = (i + 2**15) % 2**16 - 2**15 # convert to signed 16-bit u16 = i % 2**16 # convert to unsigned 16-bit s32 = (i + 2**31) % 2**32 - 2**31 # convert to signed 32-bit u32 = i % 2**32 # convert to unsigned 32-bit s64 = (i + 2**63) % 2**64 - 2**63 # convert to signed 64-bit u64 = i % 2**64 # convert to unsigned 64-bit ``` You can convert strings to floating point with the `float` function: ``` f = float("3.14159") ``` Python floats are what other languages refer to as `double`, i.e. they are 64-bits. There are no 32-bit floats in Python.
Python only has a single `int` type. To convert a string to an `int`, use `int()` like this: ``` >>> str = '123' >>> num = int(str) >>> num 123 ``` **Edit:** Also to convert to float, use `float()` in the exact same way.
Typecasting in Python
[ "", "python", "string", "int", "bit", "casting", "" ]
I have a base class in which I want to specify the methods a child class must have, but not implement them itself. However, the methods in a child class may have a different number of paramaters to the definition in the base class. Having tried this with an abstract method, php doesn't allow this. Is it possible?
Short of specifying the abstract method with no parameters and requiring the subclassed method to access the args through func\_get\_args, I don't see how this would be possible.
The child class's function can add extra, optional arguments to the signature without it causing errors: ``` abstract class Foo { abstract function bar($a); } class NewFoo extends Foo { function bar($a, $b = null) { //do something } } ```
Can I specify a non strict method requirement for child classes?
[ "", "php", "oop", "abstract-class", "" ]
I have simple regex ``` "\".*\"" ``` for me its says select everything between " and ", but it also catches ``` "text") != -1 || file.indexOf(".exe" ``` for me its two strings, for regex its one. how can i make regex to see that its two strings? P.S. I'm using Java.
That's the non-greedy form: ``` ".*?" ``` The `*?` means: "Match as little as possible", while the `*` alone means "Match as much as possible". The latter basically goes on until the end of the string, giving characters back one by one so the final `"` can match. That's why you get everything between the first and the very last quote in your string. ``` // for the sake of completeness: Java would need this pattern string "\".*?\"" ```
Regular expressions are "greedy". What you want to do is exclude quotes from the middle of the match, like ``` "\"[^\"]*\"" ```
Error in Regex for String
[ "", "java", "regex", "" ]
I have a ListBox and I want to add a context menu to each item in the list. I've seen the "solution" to have the right click select an item and suppress the context menu if on white space, but this solution feels dirty. Does anyone know a better way?
This way the menu will pop up next to the mouse ``` private string _selectedMenuItem; private readonly ContextMenuStrip collectionRoundMenuStrip; public Form1() { var toolStripMenuItem1 = new ToolStripMenuItem {Text = "Copy CR Name"}; toolStripMenuItem1.Click += toolStripMenuItem1_Click; var toolStripMenuItem2 = new ToolStripMenuItem {Text = "Get information on CR"}; toolStripMenuItem2.Click += toolStripMenuItem2_Click; collectionRoundMenuStrip = new ContextMenuStrip(); collectionRoundMenuStrip.Items.AddRange(new ToolStripItem[] {toolStripMenuItem1, toolStripMenuItem2 }); listBoxCollectionRounds.MouseDown += listBoxCollectionRounds_MouseDown; } private void toolStripMenuItem2_Click(object sender, EventArgs e) { var info = GetInfoByName(_selectedMenuItem); MessageBox.Show(info.Name + Environment.NewLine + info.Date); } private void toolStripMenuItem1_Click(object sender, EventArgs e) { Clipboard.SetText(_selectedMenuItem); } private void myListBox_MouseDown(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) return; var index = myListBox.IndexFromPoint(e.Location); if (index != ListBox.NoMatches) { _selectedMenuItem = listBoxCollectionRounds.Items[index].ToString(); collectionRoundMenuStrip.Show(Cursor.Position); collectionRoundMenuStrip.Visible = true; } else { collectionRoundMenuStrip.Visible = false; } } ```
Just to elaborate a little further to what Frans has said...Even though the ListBox owns the ContextMenuStrip, you can still customize the items in the menu strip at the time it's opening. Thus customizing it's contents based on the mouse position within the listbox. The example below selects the item in the listbox based on a right mouse click and then customizes a context menu strip based on the item the user right-clicked on. This is a simple example but should get you going: Add a listbox to a form and add this code: ``` #region Private Members private ContextMenuStrip listboxContextMenu; #endregion private void Form1_Load( object sender, EventArgs e ) { //assign a contextmenustrip listboxContextMenu = new ContextMenuStrip(); listboxContextMenu.Opening +=new CancelEventHandler(listboxContextMenu_Opening); listBox1.ContextMenuStrip = listboxContextMenu; //load a listbox for ( int i = 0; i < 100; i++ ) { listBox1.Items.Add( "Item: " + i ); } } private void listBox1_MouseDown( object sender, MouseEventArgs e ) { if ( e.Button == MouseButtons.Right ) { //select the item under the mouse pointer listBox1.SelectedIndex = listBox1.IndexFromPoint( e.Location ); if ( listBox1.SelectedIndex != -1) { listboxContextMenu.Show(); } } } private void listboxContextMenu_Opening( object sender, CancelEventArgs e ) { //clear the menu and add custom items listboxContextMenu.Items.Clear(); listboxContextMenu.Items.Add( string.Format( "Edit - {0}", listBox1.SelectedItem.ToString() ) ); } ``` Hope that help.
How can I add a context menu to a ListBoxItem?
[ "", "c#", "winforms", "listbox", "contextmenu", "" ]
I recently took my Db initiating code out of the \_\_construct of my Page class and placed it just after I initiate the Page class. I removed it from within the Page class because I want to be able to access it from anywhere (other classes for example). It also takes server, username, password and database arguments to it when initiated, and I don't wish to enter these every time. Is there a way I can access it from under the Page class now? I've tried a few methods, even global (which I have been told is an awful way to do things) and so far no avail. I am still new to OO, but I am teaching myself as best as I can. Should I make it a static class? Will this affect the lazy connector to the Db I have setup? Any help would be much appreciated. Thank you **[EDIT]** Similar Question: [Global or Singleton for database connection?](https://stackoverflow.com/questions/130878/global-or-singleton-for-database-connection)
A global of some sort (Be that global variables, singleton or some other variant) is an improvement over your previous approach, and as such you're on the right track. Generally speaking though, you should try to minimise the scope of program state (For a number of reasons, which I won't get into here). Having a global variable is in conflict with this principle. There are different solutions to this problem, but the most powerful and often overlooked approach, is to use inversion of control; Instead of obtaining a dependency, your class should receive it. For example, let's say you currently have this ``` class EditUserController { function saveUser() { $db = Database::GetInstance(); $db->execute("update users set ...", ...); } } ``` You could change this into: ``` class EditUserController { function saveUser($db) { $db->execute("update users set ...", ...); } } ``` Passing dependencies on the function-parameter level can be a bit unwieldy though, so a compromise could be to pass it on a per-object level: ``` class EditUserController { protected $db; function __construct($db) { $this->db = $db; } function saveUser() { $this->db->execute("update users set ...", ...); } } ``` This is a fairly common pattern in OO programming. In addition to being more practical than passing in function parameters, it has the additional benefit of separating construction (Where shared dependencies are wired up to each other), from runtime (Where they are used). This makes a lot of things simpler.
Global variables do have a use, and this would be one of them. Unless it's likely that you're going to be needing multiple database connections, (or even still), then I don't see a problem with setting up a global $db object. An alternative way is to have a static "Factory" class which you can use to get the object. In Joomla 1.5, the way you access the DB object is like this: ``` $db =& JFactory::getDBO(); ``` the getDBO function checks if the DB object has been created: if it has, return a reference to it, otherwise connect and initialise, and then return it. This could equally apply to other "could-be-made-global" objects, like the current User object.
PHP - Where is the best place to initiate a database class?
[ "", "php", "oop", "" ]
In python, is there a difference between calling `clear()` and assigning `{}` to a dictionary? If yes, what is it? Example: ``` d = {"stuff":"things"} d.clear() #this way d = {} #vs this way ```
If you have another variable also referring to the same dictionary, there is a big difference: ``` >>> d = {"stuff": "things"} >>> d2 = d >>> d = {} >>> d2 {'stuff': 'things'} >>> d = {"stuff": "things"} >>> d2 = d >>> d.clear() >>> d2 {} ``` This is because assigning `d = {}` creates a new, empty dictionary and assigns it to the `d` variable. This leaves `d2` pointing at the old dictionary with items still in it. However, `d.clear()` clears the same dictionary that `d` and `d2` both point at.
`d = {}` will create a new instance for `d` but all other references will still point to the old contents. `d.clear()` will reset the contents, but all references to the same instance will still be correct.
Difference between dict.clear() and assigning {} in Python
[ "", "python", "dictionary", "" ]
I'm programming in PHP and would like to create web pages which have email addresses that are easily read by humans but not easily harvested by spammers. The email addresses are coming from user input, and I think I can identify an address by using a regular expression, but I'm not clear exactly how I should replace the email addresses or with what, in order to keep most automated spam bots from harvesting them. Here's one idea: (pseudo code) ``` (email)@(domain.com) $1<span class="remove">DELETE</span>$2 .remove { display: none; } ``` Hopefully the bot will trip up on the span tag. Finally, I'm looking for a solution that will not disturb email addresses that are inside of `mailto:` tags. **Duplicate of** [How can I prevent prevent bots from collecting e-mail addresses?](https://stackoverflow.com/questions/311555/how-can-i-prevent-prevent-bots-from-collecting-e-mail-addresses#311629 "How can I prevent prevent bots from collecting e-mail addresses?") which is duplicate of [What are some ways to protect emails on websites from spambots?](https://stackoverflow.com/questions/308772/what-are-some-ways-to-protect-emails-on-websites-from-spambots#309147 "What are some ways to protect emails on websites from spambots?") and maybe some others...
You can obfuscate it using CSS as well... ``` <span class="email-encrypt">moc.liamelgoog@avynnib<span class="email-decrypt-message">(Reverse this text to get my Email address)</span></span> /*Decrypt Email */ .email-encrypt { unicode-bidi:bidi-override; direction: rtl; } .email-encrypt .email-decrypt-message { display:none; } ``` Edit: Here, the email address in the source is in reverse - what the CSS statements does is that it reverts the email address to its original form. I hope that makes sense. But I am not sure how effective this is - there are many bots who simulate a browser environment. I think I am better of saying something like - my email is binnyva, googlemail.
## Use [GD](https://www.php.net/gd) and create image of your Email ID You can use the [PHP GD library](https://www.php.net/gd) to easily create an image of any given text. A sample code will look like, ``` <?php header("Content-type: image/png"); $im = @imagecreate(110, 20)or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 0, 0, 0); $text_color = imagecolorallocate($im, 255, 255, 255); imagestring($im, 1, 5, 5, "anything@domain.com", $text_color); imagepng($im); imagedestroy($im); ?> ``` **Advantages:** * Spammers can't just capture it, unless they use an OCR :p * Very low overhead, using PNG/GIF format * Can be created on the fly for any text **Disadvantages:** * Cannot click on the mail, as a link * Won't work with TTS engines, a -ve for the visually challenged.
How can I use PHP to obfuscate email addresses so they are not easily harvested by spammers?
[ "", "php", "regex", "spam-prevention", "email-spam", "" ]
I have a class Agent with a property Id Given a collection of Agents I need to check if any of them have duplicate Ids. I am currently doing this with a hash table but am trying to get Linq-ified, what's a good way of doing this?
Similar to Y Low's approach, **Edited:** ``` var duplicates = agents.GroupBy(a => a.ID).Where(a=>a.Count() > 1); foreach (var agent in duplicates) { Console.WriteLine(agent.Key.ToString()); } ```
For what it's worth, I just compared the two methods we've struck upon in this thread. First I defined a helper class: ``` public class Foo { public int ID; } ``` ... and then made a big list of instances with a random ID: ``` var list = new List<Foo>(); var r = new Random(); for (int i = 0; i < 10000; i++) list.Add(new Foo { ID = r.Next() }); ``` ... and lastly, timed the code: ``` var sw = new Stopwatch(); sw.Start(); bool b = list.Any(i => list.Where(j => i != j).Any(j => j.ID == i.ID)); Console.WriteLine(b); Console.WriteLine(sw.ElapsedTicks); sw.Reset(); sw.Start(); b = (list.GroupBy(i => i.ID).Count() != list.Count); Console.WriteLine(b); Console.WriteLine(sw.ElapsedTicks); ``` Here's one output: > False > > 59392129 > > False > > 168151 So I think it's safe to say that grouping and then comparing the count of groups to the count of items is way, *way* faster than doing a brute-force "nested Any" comparison.
LINQy way to check if any objects in a collection have the same property value
[ "", "c#", "linq", "" ]
I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty. ``` import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): result = "" last_match_index = 0 for match in PHONE_RE.finditer(s): raw_number = match.group() number = ''.join(d for d in raw_number if d in digits) call = '<a href="tel:%s">%s</a>' % (number, raw_number) result += s[last_match_index:match.start()] + call last_match_index = match.end() result += s[last_match_index:] return result >>> numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") 'Ghost Busters at <a href="tel:5554232368">(555) 423-2368</a>! How about this one: <a href="tel:5554567890">555 456 7890</a>! <a href="tel:5554567893">555-456-7893</a> is where its at.' ``` Is there anyway I could restructure the regex or the the regex method I'm using to make this cleaner? **Update** To clarify, my question is not about the correctness of my regex - I realize that it's limited. Instead I'm wondering if anyone had any comments on the method of substiting in links for the phone numbers - is there anyway I could use `re.replace` or something like that instead of the string hackery that I have?
Nice first take :) I think this version is a bit more readable (and probably a teensy bit faster). The key thing to note here is the use of [re.sub](http://docs.python.org/library/re.html#module-contents). Keeps us away from the nasty match indexes... ``` import re PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') NON_NUMERIC = re.compile('\D') def numbers2links(s): def makelink(mo): raw_number = mo.group() number = NON_NUMERIC.sub("", raw_number) return '<a href="tel:%s">%s</a>' % (number, raw_number) return PHONE_RE.sub(makelink, s) print numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") ``` A note: In my practice, I've not noticed much of a speedup pre-compiling simple regular expressions like the two I'm using, even if you're using them thousands of times. The re module may have some sort of internal caching - didn't bother to read the source and check. Also, I replaced your method of checking each character to see if it's in `string.digits` with another `re.sub()` because I think my version is more readable, not because I'm certain it performs better (although it might).
Why not re-use the work of others - for example, from [RegExpLib.com](http://regexlib.com/REDetails.aspx?regexp_id=458)? My second suggestion is to remember there are other countries besides the USA, and quite a few of them have telephones ;-) Please don't forget us during your software development. Also, there is a standard for the formatting of telephone numbers; the ITU's [E.123](http://en.wikipedia.org/wiki/E.123). My recollection of the standard was that what it describes doesn't match well with popular usage. Edit: I mixed up G.123 and E.123. Oops. Props [Bortzmeyer](https://stackoverflow.com/users/15625/bortzmeyer)
US-format phone numbers to links in Python
[ "", "python", "regex", "mobile-website", "phone-number", "" ]
I am working through some of the exercises in The C++ Programming Language by Bjarne Stroustrup. I am confused by problem 11 at the end of Chapter 12: > (\*5) Design and implement a library for writing event-driven simulations. Hint: <task.h>. ... An object of class task should be able to save its state and to have that state restored so that it can operate as a coroutine. Specific tasks can be defined as objects of classes derived from task. The program to be executed by a task might be defined as a virtual function. ... There should be a scheduler implementing a concept of virtual time. ... The tasks will need to communicate. Design a class queue for that. ... I am not sure exactly what this is asking for. Is a task a separate thread? (As far as I know it is not possible to create a new thread without system calls, and since this is a book about C++ I do not believe that is the intent.) Without interrupts, how is it possible to start and stop a running function? I assume this would involve busy waiting (which is to say, continually loop and check a condition) although I cannot see how that could be applied to a function that might not terminate for some time (if it contains an infinite loop, for example). **EDIT:** Please see my post below with more information.
> Hint: <task.h>. is a reference to an old cooperative multi-tasking library that shipped with [early versions of CFront](http://www.softwarepreservation.org/projects/c_plus_plus#release_e) (you can also download at that page). If you read the paper "[A Set of C++ Classes for Co-routine Style Programming](http://www.softwarepreservation.org/projects/c_plus_plus/cfront/release_e/doc/ClassesForCouroutines.pdf)" things will make a lot more sense. --- Adding a bit: I'm not an old enough programmer to have used the task library. However, I know that C++ was designed after Stroustrup wrote a simulation in Simula that had many of the same properties as the task library, so I've always been curious about it. If I were to implement the exercise from the book, I would probably do it like this (please note, I haven't tested this code or even tried to compile it): ``` class Scheduler { std::list<*ITask> tasks; public: void run() { while (1) // or at least until some message is sent to stop running for (std::list<*ITask>::iterator itor = tasks.begin() , std::list<*ITask>::iterator end = tasks.end() ; itor != end ; ++itor) (*itor)->run(); // yes, two dereferences } void add_task(ITask* task) { tasks.push_back(task); } }; struct ITask { virtual ~ITask() { } virtual void run() = 0; }; ``` I know people will disagree with some of my choices. For instance, using a struct for the interface; but structs have the behavior that inheriting from them is public by default (where inheriting from classes is private by default), and I don't see any value in inheriting privately from an interface, so why not make public inheritance the default? The idea is that calls to ITask::run() will block the scheduler until the task arrives at a point where it can be interrupted, at which point the task will return from the run method, and wait until the scheduler calls run again to continue. The "cooperative" in "cooperative multitasking" means "tasks say when they can be interrupted" ("coroutine" usually means "cooperative multitasking"). A simple task may only do one thing in its run() method, a more complex task may implement a state machine, and may use its run() method to figure out what state the object is currently in and make calls to other methods based on that state. The tasks **must** relinquish control once in a while for this to work, because that is the definition of "cooperative multitasking." It's also the reason why all modern operating systems don't use cooperative multitasking. This implementation does not (1) follow fair scheduling (maybe keeping a running total of clock ticks spent in in task's run() method, and skipping tasks that have used too much time relative to the others until the other tasks "catch up"), (2) allow for tasks to be removed, or even (3) allow for the scheduler to be stopped. As for communicating between tasks, you may consider looking at [Plan 9's libtask](http://swtch.com/libtask/) or [Rob Pike's newsqueak](http://herpolhode.com/rob/) for inspiration (the "UNIX implementation of Newsqueak" download includes a paper, "The Implementation of Newsqueak" that discusses message passing in an interesting virtual machine). But I believe this is the basic skeleton Stroustrup had in mind.
Here's my understanding of an "event-driven simulation": * A controller handles an event queue, scheduling events to occur at certain times, then executing the top event on the queue. * Events ocur instantaneously at the scheduled time. For example, a "move" event would update the position and state of an entity in the simulation such that the state vector is valid at the current simulation time. A "sense" event would have to make sure all entities' states are at the current time, then use some mathematical model to evaluate how well the current entity can sense the other entities. (Think robots moving around on a board.) * Thus time progresses discontinuously, jumping from event to event. Contrast this with a time-driven simulation, where time moves in discrete steps and all entities' states are updated every time step (a la most Simulink models). * Events can then occur at their natural rate. It usually doesn't make sense to recompute all data at the finest rate in the simulation. Most production event-driven simulations run in a single thread. They can be complex by their very nature, so trying to synchronize a multi-threaded simulation tends to add exponential layers of complexity. With that said, there's a standard for multi-process military simulations called [Distributive Interactive Simulation](http://en.wikipedia.org/wiki/Distributed_Interactive_Simulation) (DIS) that uses predefined TCP messages to transmit data between processes. EDIT: It's important to define a difference between modeling and simulation. A model is a mathematical representation of a system or process. A simulation is built from one or more models that are executed over a period of time. Again, an event driven simulation hops from event to event, while a time driven simulation proceeds at a constant time step.
Event-driven simulation class
[ "", "c++", "simulation", "event-driven", "" ]
I would like to be able to refactor out the **OrderBy** clause in a linq expression. Here is an example of a refactor of the **where** clause before: ``` results = ctx.ActiveUsers .Where(u => u.CompanyID != 1 && (u.LastName.ToLower().Contains(searchString) || u.Email.ToLower().Contains(searchString) || u.Company.Name.ToLower().Contains(searchString))) .OrderBy(u => u.LastName ).ThenBy(u => u.FirstName) .Select(u => new Employee { ID = u.ID , FirstName = u.FirstName , LastName = u.LastName , Email = u.Email , CompanyName = u.Company.Name , CompanyID = u.CompanyID.ToString() }); ``` --- after: ``` results = ctx.ActiveUsers .Where(Employee.GetExpression(searchString)) .OrderBy(u => u.LastName ).ThenBy(u => u.FirstName) .Select(u => new Employee { ID = u.ID , FirstName = u.FirstName , LastName = u.LastName , Email = u.Email , CompanyName = u.Company.Name , CompanyID = u.CompanyID.ToString() }); ``` --- ``` private static Expression<Func<User, bool>> GetExpression(string searchString) { Expression<Func<User, bool>> p = (u => u.CompanyID != 1 && (u.LastName.ToLower().Contains(searchString) || u.Email.ToLower().Contains(searchString) || u.Company.Name.ToLower().Contains(searchString))); return p; } ``` I was wondering if the same type of thing would be possible except I would like to refactor the **Orderby** expression. Thank you in advance
Assuming you want to actually take a string such as "LastName", "FirstName" etc, I'd do something like: ``` var unordered = ctx.ActiveUsers .Where(Employee.GetExpression(searchString)) .OrderBy(ordering) .Select(u => new Employee { ID = u.ID, FirstName = u.FirstName, LastName = u.LastName, Email = u.Email, CompanyName = u.Company.Name, CompanyID = u.CompanyID.ToString() }); ``` and add a new OrderBy extension method: ``` public static class UserQueryableExtensions { public static IOrderedQueryable<User> OrderBy(this IQueryable<User> source, string ordering) { switch (ordering) { case "LastName": return source.OrderBy(x => x.LastName); case "FirstName": return source.OrderBy(x => x.FirstName); case "Email": return source.OrderBy(x => x.Email); case "Company": return source.OrderBy(x => x.Company); default: throw new ArgumentException("Unknown ordering"); } } } ``` You certainly *could* do this using reflection, but unless you have a significant set of properties (or you want to use the same routine for different entity types) a switch statement is easier.
thanks jon, that answer put me on the right path for now... However, I need to preserve the **ThenBy** clause in my order. so while the solution below is not dynamic it still preserves the **ThenBy** ``` var unordered = ctx.ActiveUsers .Where(Employee.GetExpression(searchString)) .MyOrder() .Select(u => new Employee { ID = u.ID, FirstName = u.FirstName, LastName = u.LastName, Email = u.Email, CompanyName = u.Company.Name, CompanyID = u.CompanyID.ToString() }); ``` --- ``` public static class UserQueryableExtensions { public static IOrderedQueryable<User> MyOrder(this IQueryable<User> source ) { return source.OrderBy(x => x.LastName).ThenBy(x => x.FirstName).ThenBy(x => x.Email); } } ```
refactoring the OrderBy expression
[ "", "c#", "linq", "lambda", "" ]
A recent [question came up](https://stackoverflow.com/questions/349659/stringformat-or-not) about using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was a bad example and proposed using a combination of AppendLine and AppendFormat. It occurred to me I've never really settled myself into a "preferred" approach for using these methods. I think I might start using something like the following but am interested to know what other people use as a "best practice": ``` sbuilder.AppendFormat("{0} line", "First").AppendLine(); sbuilder.AppendFormat("{0} line", "Second").AppendLine(); // as opposed to: sbuilder.AppendLine( String.Format( "{0} line", "First")); sbuilder.AppendLine( String.Format( "{0} line", "Second")); ```
I view `AppendFormat` followed by `AppendLine` as not only more readable, but also more performant than calling `AppendLine(string.Format(...))`. The latter creates a whole new string and then appends it wholesale into the existing builder. I'm not going to go as far as saying "Why bother using StringBuilder then?" but it does seem a bit against the spirit of StringBuilder.
Just create an extension method. ``` public static StringBuilder AppendLine(this StringBuilder builder, string format, params object[] args) { builder.AppendFormat(format, args).AppendLine(); return builder; } ``` Reasons I prefer this: * Doesn't suffer as much overhead as `AppendLine(string.Format(...))`, as stated above. * Prevents me from forgetting to add the `.AppendLine()` part at the end (happens frequently enough). * Is more readable (but that is more of an opinion). If you don't like it being called 'AppendLine,' you could change it to 'AppendFormattedLine' or whatever you want. I enjoy everything lining up with other calls to 'AppendLine' though: ``` var builder = new StringBuilder(); builder .AppendLine("This is a test.") .AppendLine("This is a {0}.", "test"); ``` Just add one of these for each overload you use of the AppendFormat method on StringBuilder.
When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat?
[ "", "c#", ".net", "formatting", "stringbuilder", "" ]
I've been doing quite a bit of debugging of managed applications lately using both Visual Studio and WinDbg, and as such I'm often ask to assist colleagues in debugging situations. On several occasions I have found people aho just insert break points here and there and hope for the best. In my experience that is rarely a useful technique. My approach goes something like this. * Reproduce the problem. Ideally reduce the input as much as possible. * Examine what goes wrong and list theories for where the bug may be. * Examine one theory at a time by debugging that specific area of the code. Repeat steps as necessary. For complex debugging problems I often work with a colleague. For WinDbg this is especially useful. Any other useful tips or best practices for debugging?
One very best practice is not diving into debugger immediately but look at the code and *think hard* for some time.
If there was one tip I could give to everyone about debugging it would be to break it again. That is, when you think you've found the fix and the system seems to work. Back the fix out and see if the system breaks again. Sometimes you can get lost in the sequence of what you've tried as potential solutions and you finish up in a totally different area of the system while you're debugging the problem. Then you forget what you've changed back in the original area where you were working. Backing the fix out and then reproducing the problem ensures that the candidate fix isn't relying on something else that you've changed in another part of the system. That your patch for the fix is a correct standalone solution. HTH. cheers, Rob
Best practices for debugging
[ "", "c#", ".net", "debugging", "" ]
I have two computers. Both running WinXP SP2 (I don't really know ho similar they are beyond that). I am running MS Visual C# 2008 express edition on both and that's what I'm currently using to program. I made an application that loads in an XML file and displays the contents in a DataGridView. The first line of my xml file is: ``` <?xml version="1.0" encoding="utf-8"?> ``` ...and really... it's utf-8 (at least according to MS VS C# when I just open the file there). I compile the code and run it on one computer, and the contents of my DataGridView appears normal. No funny characters. I compile the code and run it on the other computer (or just take the published version from computer #1 and install it on computer #2 - I tried this both ways) and in the datagridview, where there are line breaks/new lines in the xml file, I see funny square characters. I'm a novice to encoding... so the only thing I really tried to troubleshoot was to use that same program to write the contents of my xml to a new xml file (but I'm actually writing it to a text file, with the xml tags in it) since the default writing to a text file seems to be utf-8. Then I read this new file back in to my program. I get the same results. I don't know what else to do or how to troubleshoot this or what I might fundamentally be doing wrong in the first place. -Adeena
I'm not sure of the cause of your problem, but one solution would be to to just strip out the carriage returns from your strings. For every string you add, just call `TrimEnd(null)` on it to remove trailing whitespace: ``` newrow["topic"] = att1.ToString().TrimEnd(null); ``` If your strings might end in other whitespace (i.e. spaces or tabs) and you want to keep those, then just pass an array containing only the carriage return character to `TrimEnd`: ``` newrow["topic" = att1.ToString().TrimEnd(new Char[]{'\r'}); ``` Disclaimer: I am not a C# programmer; the second statement may be syntactically incorrect
This doesn't have to do with UTF-8 or character encodings - this problem has to do with [line endings](http://en.wikipedia.org/wiki/Line_ending). In Windows, each line of a text file ends in the two characters carriage-return (CR) and newline (LF, for line feed), which are code points U+000D and U+000A respectively. In ASCII and UTF-8, these are encoded as the two bytes `0D 0A`. Most non-Windows systems, including Linux and Mac OS X, on the other hand, uses just a newline character to signal end-of-line, so it's not uncommon to see line ending problems when transferring text files between Windows and non-Windows systems. However, since you're using just Windows on both systems, this is more of a mystery. One application is correctly interpreting the CRLF combination as a newline, but the other application is confused by the CR. Carriage returns are not printable characters, so it replaces the CR with a placeholder box, which is what you see; it then correctly interprets the line feed as the end-of-line.
I think this is some kind of encoding problem
[ "", "c#", "xml", "encoding", "datagridview", "" ]
# Background In a C# command-line app I'm writing, several of the parameters have "yes" and "no" as the possible values. I am storing their input using the Enum type shown below. ``` enum YesNo { Yes, No } ``` Which is fine - the code works. No problem there. NOTE: Yes, I could store these as bool (that's how it used to work). My design choice is to be explicit about the Yes/No choice made by the user because they will see this printed in other contexts and I'd like it to be more obvious what the choice was. # My Question * It just seems odd to have an enum called "YesNo" - what are some suggestions for better names for an enum for "yes" and "no" values. # So Finally I asked this question relatively early in StackOverflow's life. It wasn't fake question - I really did have this situation. I just thought it would be nice to use it see what the community would do. Because it is, I admit a somewhat odd question. First, thanks to all who spent the time replying. I'm trying to pay that back with a thoughtful conclusion. Comments on the answers **switching to bool**. I understand your motivation, but I feel I need to point out that having a **binary** choice (and by that I mean a choice between any two values - alive/dead, married/unmarried, etc.) is not the same as **boolean** choice between true and false. We find as programmers switching between yes/no and true/false easy - fair enough. Had my choice in this case been for example "Democrat" or "Replication"" (contrived example, I know) then you can see possibilities for confusion or at least awkwardness. I do think the bool option is valid in this case, but less so in other binary choices. **localization** - great point. In my specific case it didn't matter - this was not and is never going to be localized, but for other situations it is something to consider. **more than three options** - In fact, later on I had to add a third value called to represent the valid (in my application) condition of a user specifically *not* making the choice. There were a lot of good comments, thank you all!
I'd suggest you use a name that indicates the Value which is set to Yes or No. E.G. ``` public enum Married { YES, NO } ```
You say you don't want to use bool because it will be printed out for the user to see amongst other contents. That suggests the problem isn't in *storage* but in *display*. By all means present true/false as Yes/No, but there's no need to create a whole new type for it IMO. EDIT: In addition to suggesting you don't use an enum in the first place, I'd strongly recommend that if you *do* use an enum, you change the order or use explicit values. Having Yes=0, No=1 will be really confusing if you ever end up seeing the values as integers.
What's a good name for an Enum for Yes & No values
[ "", "c#", "coding-style", "naming-conventions", "naming", "" ]
With jQuery, how do I find out which key was pressed when I bind to the keypress event? ``` $('#searchbox input').bind('keypress', function(e) {}); ``` I want to trigger a submit when `ENTER` is pressed. **[Update]** Even though I found the (or better: one) answer myself, there seems to be some room for variation ;) Is there a difference between `keyCode` and `which` - especially if I'm just looking for `ENTER`, which will never be a unicode key? Do some browsers provide one property and others provide the other one?
Actually this is better: ``` var code = e.keyCode || e.which; if(code == 13) { //Enter keycode //Do something } ```
Try this ``` $('#searchbox input').bind('keypress', function(e) { if(e.keyCode==13){ // Enter pressed... do anything here... } }); ```
jQuery Event Keypress: Which key was pressed?
[ "", "javascript", "jquery", "events", "bind", "keypress", "" ]
I'm writing a java app using eclipse which references a few external jars and requires some config files to be user accessable. 1. What is the best way to package it up for deployment? 2. My understanding is that you cant put Jars inside another jar file, is this correct? 3. Can I keep my config files out of the jars and still reference them in the code? Or should the path to the config file be a command line argument? 4. Are there any third party plugins for eclipse to help make this easier? I'm using an ant build file at the moment but I'm not sure I know what I'm doing. 5. Is there an equivelent of the deployment projects in Visual studio, that will figure out everything you need and just make an installer? I've used install4j before, and it was powerful if no where near as automated as .Net deployment projects. Cheers.
There is no one 'best way'. It depends on whether you are deploying a swing application, webstart, applet, library or web application. Each is different. On point 2, you are correct. Jar files cannot contain other jar files. (Well, technically they can, its just that the inner jar file won't be on your classpath, effectively meaning that jar files do not contain jar files). On point 3, you certainly can reference config files outside the jar file. You can typically reference a config file as a file or a resource. If you use the resource approach, it typically comes from the classpath (can be in a jar). If you use a file, then you specify the filename (not in a jar). In general, most Java developers would use [Apache Ant](http://ant.apache.org) to achieve deployment. Its well documented, so take a look.
(1) An alternative to ant that you may wish to consider is [maven](http://maven.apache.org/). A brief intro to maven can be found [here](http://maven.apache.org/run-maven/index.html). For building a JAR, maven has the [jar](http://maven.apache.org/maven-1.x/plugins/jar/properties.html) plugin, which can automate the process of ensuring all dependent jars are listed in your jar's manifest. If you're using eclipse, then download the [maven integration](http://m2eclipse.codehaus.org/) as well. (2) Another alternative is to use [OneJar](http://one-jar.sourceforge.net/) (disclaimer: haven't tried this myself).
Whats best way to package a Java Application with lots of dependencies?
[ "", "java", "eclipse", "deployment", "" ]
``` Type.GetType("System.String") ``` Is there a lookup for the aliases available somewhere? ``` Type.GetType("string") ``` returns `null`.
This is not possible programmatically, since the 'aliases' are in fact keywords introduced in C#, and `Type.GetType` (like every other framework method) is part of the language-independent framework. You could create a dictionary with the following values: ``` bool System.Boolean byte System.Byte sbyte System.SByte char System.Char decimal System.Decimal double System.Double float System.Single int System.Int32 uint System.UInt32 long System.Int64 ulong System.UInt64 object System.Object short System.Int16 ushort System.UInt16 string System.String ```
The "aliases" are part of the language definition. You need to look them up in the [language spec](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx) in question. They are compiled away, and don't exist at runtime - string becomes System.String, int becomes System.Int32, etc.
Possible to get type of an aliased type in c#?
[ "", "c#", "c#-3.0", "" ]
I read somewhere that one should never use error conditions as normal program flow. Makes excellent sense to me... But C# application sitting on top of a MySQL db. I need to parse a string value into two parts, an ID, and a value. (The original data come from a Devonian database), then validate the value against a lookup table. So, a couple of original strings might look like this: "6776 Purple People Eater" "BIK Yellow Polka-Dot Bikini (currently in use)" "DCP Deuce Coup" So, my little utility parses each string into the ID and the description based on the index of the first space (fortunately, consistent). I then pass the ID to the lookup, get the new value and away we go. Unfortunately, TPTB also decided that we no longer need no stinkin' Yellow Polka-Dot Bikinis (currently in use). So, BIK does not return a row. Here's a code snippet: ``` foreach (string product in productTokens) { tempProduct = product.Trim(); if (tempProduct.Length > 0) { if (tempProduct.Length < 10) { product_id = tempProduct; } else { int charPosition = tempProduct.IndexOf(" "); product_id = tempProduct.Substring(0, charPosition); } try { s_product = productAdapter.GetProductName(product_id).ToString(); } catch (Exception e) { if (e.Message.ToString() == "Object reference not set to an instance of an object.") { s_product = ""; } else { errLog.WriteLine("Invalid product ID " + e.Message.ToString()); Console.WriteLine("Invalid product ID " + e.Message.ToString()); throw; } //else } //catch if (s_product.Length > 0) { sTemp = sTemp + s_product + "; "; } } //if product.length > 0 } //foreach product in productTokens ``` Really, really ugly! Particularly the part where I test for an invalid IDin the catch block. There simply must be a better way to handle this. If anyone can help me out, I'd really appreciate it. Thanks.
You shouldn't be calling ToString() at that point, first you should check if the value returned is null; ``` object productName = productAdapter.GetProductName(product_id); if ( productName != null ) { s_product = productName.ToString(); } else { s_product = String.Empty; } ```
In addition to the recommendations of Rob and Marc, and based on your code above, I'd suggest another tweak; I'd be really surprised if `productAdapter.GetProductName()` doesn't *already* return a `String`, in which case calling ToString() on it is utterly redundant. If it does indeed already return a `String`, then your whole try/catch block becomes one line: ``` s_product = productAdapter.GetProductName(product_id) ?? string.Empty; ``` Also, I think it might be useful to mention something else that *already* returns a `String` - `Exception.Message`. So all of the different places where you're calling ToString() in your code are also utterly redundant. Also, I would suggest using the instance method `String.Split()` rather than the combination of `IndexOf` and `SubString`: ``` product_id = tempProduct.Split(" ", 2)[1]; ``` Finally, deciding what kind of `Exception` you've caught by examining the `Message` property should be a totally last-ditch scenario. Even if you really did *need* to catch `NullReferenceException` here, you should do so *explicitly*: ``` catch (NullReferenceException) { s_product = ""; } catch (Exception e) { // Log your invalid ID error condition here } ``` *P.S.: I'm also not really sure what at all this question has to do with MySQL, since there's no evidence of any DB API in your code.*
How to Avoid Throwing An Error When SQL Select Returns Nothing
[ "", "c#", "mysql", "null", "catch-block", "" ]
I frequently make use of `Request.QueryString[]` variables. In my `Page_load` I often do things like: ``` int id = -1; if (Request.QueryString["id"] != null) { try { id = int.Parse(Request.QueryString["id"]); } catch { // deal with it } } DoSomethingSpectacularNow(id); ``` It all seems a bit clunky and rubbish. How do you deal with your `Request.QueryString[]`s?
Below is an extension method that will allow you to write code like this: ``` int id = request.QueryString.GetValue<int>("id"); DateTime date = request.QueryString.GetValue<DateTime>("date"); ``` It makes use of `TypeDescriptor` to perform the conversion. Based on your needs, you could add an overload which takes a default value instead of throwing an exception: ``` public static T GetValue<T>(this NameValueCollection collection, string key) { if(collection == null) { throw new ArgumentNullException("collection"); } var value = collection[key]; if(value == null) { throw new ArgumentOutOfRangeException("key"); } var converter = TypeDescriptor.GetConverter(typeof(T)); if(!converter.CanConvertFrom(typeof(string))) { throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T))); } return (T) converter.ConvertFrom(value); } ```
Use int.TryParse instead to get rid of the try-catch block: ``` if (!int.TryParse(Request.QueryString["id"], out id)) { // error case } ```
How do you test your Request.QueryString[] variables?
[ "", "c#", "coding-style", "tryparse", "isnumeric", "request.querystring", "" ]
Is it possible to have a C static library API, which uses C++ internally and hide this from users of the library? I have writen a portable C++ library I wish to statically link to an iPhone application. I have created an Xcode project using the Max OS X 'static library' template, and copied the source across, as well as writing a C wapper (to deal with exceptions) using (extern "C"). I am trying to use the generated library (.a file) in another Cocoa iPhone application. Everything works well if the I use (.mm) extentions on the calling ObjectiveC file and (.cpp) on the implementation class in the library. But I get unresolved symbols on linking when I try and change the wrapper file to a (.c) extention, even though all the wrapper function files are only C functions. Just becuase C++ is used internally in a library, does it mean that externally it still must be treated as a C++ program. Is there not anyway to enforce this abstraction? **Edit:** Thanks for the replies, I had been using extern "C", I was just unsure about what configurations where needed in the calling project. ie. if the calling projected would require to know if it used C++ or could be ignorant and think its a purely C library. It would seem I cannot, and I must use (.mm) files on my ObjectiveC classes.
It's too hard to do this in comments, so I'm just going to demonstrate for you quickly what the linking issues are that you're having. When Xcode encounters files, it uses build rules based on the suffix to decide which compiler to use. By default, gcc links the files to the standard C library, but does not link with the standard C++ library. Archive files (static libraries) have no linking resolution done at all. They are basically an archive of object files which *need to be linked*. Since you have no .mm or .cpp files in your project, g++ is never called and your files are never linked to the standard libraries. To correct this, just add the standard C++ libraries to your other linker flags in your Xcode project, or just simply add them to the pre-defined other flags option as -l (e.g., -lstdc++). Here is a quick demonstration: stw.h: ``` #ifdef __cplusplus extern "C" #endif void show_the_world(void); ``` stw.cpp: ``` #include <iostream> #include "stw.h" using namespace std; extern "C" void show_the_world() { cout << "Hello, world!\n"; } ``` Build the library: ``` $ g++ -c stw.cpp -o stw.cpp -O0 -g $ ar rcs stw.a stw.o ``` Using the library from a C application: myapp.c: ``` #include "stw.h" int main() { show_the_world(); return 0; } ``` Building the C application: ``` $ gcc -o myapp myapp.c stw.a -lstdc++ -g -O0 $ ./myapp Hello, world! $ ``` If you try to compile without the -lstdc++ you will get all the unresolved issues because the C compiler has absolutely NO idea that it should link to the C++ runtime (and why would it, right!?!?) so you have to add this manually. The other option you have is to change the build rule for your project... instead of having Xcode use gcc to build .c and .m files, tell it to use g++ and your issues will be resolved.
You should declare the functions you want to be visible `extern "C"`. Their signatures need to be C-compatible, but the contents do not (you may access C++ objects, for instance, but you cannot pass them directly; pointers are okay). The symbols will then be visible to any C-compatible environment. EDIT: And compile it as a C++ source file, C doesn't have the notion of language linkage. There are a couple other gotchas with language linkage (like the fact that all `extern "C"` functions with the same name are the same function, regardless of namespace). EDIT2: In the header, you can check for the macro `__cplusplus`, and use that to set for C++ and other languages, respectively (because C++ will require `extern "C"` declarations, and other languages will probably complain about them).
Using C/C++ static libraries from iPhone ObjectiveC Apps
[ "", "c++", "c", "" ]
I remember reading in some Java book about any operator other than 'instanceof' for comparing the type hierarchy between two objects. instanceof is the most used and common. I am not able to recall clearly whether there is indeed another way of doing that or not.
Yes, there is. Is not an operator but a method on the Class class. Here it is: [isIntance(Object o )](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance(java.lang.Object)) Quote from the doc: > *...This method is the dynamic equivalent of the Java language instanceof operator* ``` public class Some { public static void main( String [] args ) { if ( Some.class.isInstance( new SubClass() ) ) { System.out.println( "ieap" ); } else { System.out.println( "noup" ); } } } class SubClass extends Some{} ```
You can also, for reflection mostly, use `Class.isInstance`. ``` Class<?> stringClass = Class.forName("java.lang.String"); assert stringClass.isInstance("Some string"); ``` Obviously, if the type of the class is known at compile-time, then `instanceof` is still the best option.
Is there any way other than instanceof operator for object type comparison in java?
[ "", "java", "" ]
In Python, is there a portable and simple way to test if an executable program exists? By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but imagine it's `launchmissiles`)
Easiest way I can think of: ``` def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ.get("PATH", "").split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None ``` **Edit**: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command. **Edit**: Updated to use os.path.isfile() instead of os.path.exists() per comments. **Edit**: `path.strip('"')` seems like the wrong thing to do here. Neither Windows nor POSIX appear to encourage quoted PATH items.
I know this is an ancient question, but you can use `distutils.spawn.find_executable`. This has been [documented since python 2.4](http://docs.python.org/release/2.4/dist/module-distutils.spawn.html) and has existed since python 1.6. ``` import distutils.spawn distutils.spawn.find_executable("notepad.exe") ``` Also, Python 3.3 now offers [`shutil.which()`](https://docs.python.org/library/shutil.html#shutil.which).
Test if executable exists in Python?
[ "", "python", "path", "" ]
Does anyone know the query the last synchronization date from sql server (2008). It is the same information displayed in replication monitor, but I want to be able to get that date from a query.
You can see a lot of info about merge sessions by using the system table msMerge\_sessions: ``` select * from msMerge_sessions ``` Depending on the info you need, use the other system tables available in your database.
I created a view like this to get last date by the subscriber ``` select subscriber_name, max(start_time) as last_sync from msMerge_sessions inner join msMerge_agents on msmerge_agents.id = msmerge_sessions.agent_id group by subscriber_name ``` I called the view 'LastSync' - I then joined that view like this to get a representation similar to what the replication monitor shows. ``` SELECT dbo.LastSync.id, dbo.LastSync.subscriber_name, dbo.LastSync.creation_date, dbo.LastSync.last_sync, distribution.dbo.MSmerge_sessions.estimated_upload_changes + distribution.dbo.MSmerge_sessions.estimated_download_changes AS estimate_rows, distribution.dbo.MSmerge_sessions.upload_inserts + distribution.dbo.MSmerge_sessions.upload_updates + distribution.dbo.MSmerge_sessions.upload_deletes + distribution.dbo.MSmerge_sessions.download_inserts + distribution.dbo.MSmerge_sessions.download_updates + distribution.dbo.MSmerge_sessions.download_deletes AS actual_rows, distribution.dbo.MSmerge_sessions.duration AS total_seconds, distribution.dbo.MSmerge_sessions.percent_complete, distribution.dbo.MSmerge_sessions.delivery_rate, CASE (runstatus) WHEN 1 THEN 'Start' WHEN 2 THEN 'Succeed' WHEN 3 THEN 'In Progress' WHEN 4 THEN 'Idle' WHEN 5 THEN 'Retry' WHEN 6 THEN 'Fail' END AS Status FROM distribution.dbo.MSmerge_sessions INNER JOIN dbo.LastSync ON dbo.LastSync.id = distribution.dbo.MSmerge_sessions.agent_id AND distribution.dbo.MSmerge_sessions.start_time = dbo.LastSync.last_sync ```
sql server replication - get last synchronization date from query
[ "", "sql", "sql-server", "synchronization", "replication", "" ]
I have a MS SQL table that I don't have any control over and I need to write to. This table has a int primary key that isn't automatically incremented. I can't use stored procs and I would like to use Linq to SQL since it makes other processing very easy. My current solution is to read the last value, increment it, try to use it, if I get a clash, increment it again and retry. Something along these lines: ``` var newEntity = new Log() { ID = dc.Logs.Max(l => l.ID) + 1, Note = "Test" }; dc.Logs.InsertOnSubmit(newEntity); const int maxRetries = 10; int retries = 0; bool success = false; while (!success && retries < maxRetries) { try { dc.SubmitChanges(); success = true; } catch (SqlException) { retries++; newEntity.ID = dc.Logs.Max(l => l.ID); } } if (retries >= maxRetries) { throw new Exception("Bummer..."); } ``` Does anyone have a better solution? EDIT: Thanks to [Jon](https://stackoverflow.com/questions/385809/correctly-incrementing-values-using-linq-to-sql#385814), I simplified the max ID calculation. I was still in SQL thinking mode.
That looks like an expensive way to get the maximum ID. Have you already tried ``` var maxId = dc.Logs.Max(s => s.ID); ``` ? Maybe it doesn't work for some reason, but I really *hope* it does... (Admittedly it's more than possible that SQL Server optimises this appropriately.) Other than that, it looks okay (smelly, but necessarily so) to me - but I'm not an expert on the matter...
You didn't indicate whether your app is the only one inserting into the table. If it is, then I'd fetch the max value once right after the start of the app/webapp and use Interlocked.Increment on it every time you need next ID (or simple addition if possible race conditions can be ruled out).
Correctly incrementing values using Linq to SQL
[ "", "c#", "linq-to-sql", "auto-increment", "" ]
I have some data. I want to go through that data and change cells (for example - Background color), if that data meets a certain condition. Somehow, I've not been able to figure it out how to do this seemingly easy thing in Silverlight.
This is slightly old code (from before RTM), but does something like what you're looking for. It checks some data on an object in a row and then sets the colour of the row accordingly. **XAML:** ``` <my:DataGrid x:Name="Grid" Grid.Row="1" Margin="5" GridlinesVisibility="None" PreparingRow="Grid_PreparingRow"> <my:DataGrid.Columns> <my:DataGridTextBoxColumn DisplayMemberBinding="{Binding Cheese}" Header="Cheese"></my:DataGridTextBoxColumn> <my:DataGridTextBoxColumn DisplayMemberBinding="{Binding Biscuit}" Header="Biscuit"></my:DataGridTextBoxColumn> </my:DataGrid.Columns> </my:DataGrid> ``` **Code:** ``` this.Grid.AlternatingRowBackground = null; private void Grid_PreparingRow(object sender, DataGridRowEventArgs e) { CheesyClass c = e.Row.DataContext as CheesyClass; if (c != null && c.Cheese == "cheddar") { e.Row.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 125, 125)); } } ```
Actually this won't work in all examples. See these links for the 'proper' way of achieving this <http://silverlight.net/forums/p/27465/93474.aspx#93474> <http://silverlight.net/forums/t/27467.aspx>
Silverlight Datagrid: Changing cell styles, based on values
[ "", "c#", "silverlight", "datagrid", "cells", "" ]
I am trying to help a small business that has an application that could benefit from occasional (or temporary) database expertise. The problem is, this company has all their IP in this database, so they are rightfully hesitant to give someone access it. They would typically meet and gain trust in person, but the talent pool within physical proximity to them is pretty limited. I would like to think that they could still somehow tap into the global DBA expertise though... Even the crappiest DBA will be able to dance SQL Circles around these guys - so exposing only pieces of the database doesn't sound feasible to me, but I am hoping I just don't know how. Anyone have any tips on how they could find a trustworthy company (or individual)? When I hire a programmer, I start them on basic stuff that if they mess up won't hurt too much. With a database, is there something that I can start with that can limit their exposure. Maybe Profiler output for analysis or something?
As the others have mentioned, NDA's are a good idea, that covers you from the standpoint of WHAT they see... However, I can feel that you are also concerned about any potential "damage" the person could do to your database if they make mistakes. To get around, and protect from this is a bit harder, but there a few good key items that I would recommend. 1. BACKUP EVERYTHING before starting, this is common sense, but cannot be overstated 2. Provide the consultant a test environment if you are able to replicate production issues. This gives an isolated environment where testing can be done. 3. DO NOT limit their database access. Database issues require digging into the system, limiting their access, could actually contribute to an error rather than preventing them. 4. Look for references, or evidence of the persons abilities. I provide this information as a consultant myself. I do .NET and SQL Server consulting, and I ensure that all of the above are true in my consulting cases, and I have not had a fault. Steven points out the biggest key in this all and that is **all a consultant has is his reputation**. Serious consultants fully understand this, and because of it will make sure that they do NOT put themselves into tricky situations.
The simplest thing is requiring all employees and contractors who see the database, or its design, to sign non-disclosure agreements. There are plenty of boilerplate ones there, and a good attorney can provide guidance on what you'd need in one with less than an hour of billing time. Everyone in the industry is used to them, and everybody understands why they have to sign them. Of course, that's not a programming question, it's just a legal problem.
How do I find trustworthy database help out on the interweb?
[ "", "sql", "database", "" ]
``` public static IQueryable<TResult> ApplySortFilter<T, TResult>(this IQueryable<T> query, string columnName) where T : EntityObject { var param = Expression.Parameter(typeof(T), "o"); var body = Expression.PropertyOrField(param,columnName); var sortExpression = Expression.Lambda(body, param); return query.OrderBy(sortExpression); } ``` Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time: ``` var sortExpression = Expression.Lambda<T, TSortColumn>(body, param); ``` Or ``` return query.OrderBy<T, TSortColumn>(sortExpression); ``` I don't think this is possible however as TSortColumn can only be determined during runtime. Is there a way around this?
We did something similar (not 100% the same, but similar) in a LINQ to SQL project. Here's the code: ``` public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) { var type = typeof(T); var property = type.GetProperty(ordering); var parameter = Expression.Parameter(type, "p"); var propertyAccess = Expression.MakeMemberAccess(parameter, property); var orderByExp = Expression.Lambda(propertyAccess, parameter); MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp)); return source.Provider.CreateQuery<T>(resultExp); } ``` We didn't actually use a generic, we had a known class, but it should work on a generic (I've put the generic placeholder where it should be). **Edit:** For descending order, pass in `OrderByDescending` instead of "OrderBy": ``` MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp)); ```
You can also use Dynamic Linq Info here <http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx> C# download here <http://msdn.microsoft.com/en-us/vcsharp/bb894665.aspx> Then just add the using Linq.Dynamic; and you automatically get 2 additional extension methods that can be used like this ``` return query.OrderBy("StringColumnName"); ```
How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?
[ "", "c#", ".net", "linq", "entity-framework", "expression-trees", "" ]
Is it possible to use a DB sequence for some column that **is not the identifier/is not part of a composite identifier**? I'm using hibernate as jpa provider, and I have a table that has some columns that are generated values (using a sequence), although they are not part of the identifier. What I want is to use a sequence to create a new value for an entity, where the column for the sequence is **NOT** (part of) the primary key: ``` @Entity @Table(name = "MyTable") public class MyEntity { //... @Id //... etc public Long getId() { return id; } //note NO @Id here! but this doesn't work... @GeneratedValue(strategy = GenerationType.AUTO, generator = "myGen") @SequenceGenerator(name = "myGen", sequenceName = "MY_SEQUENCE") @Column(name = "SEQ_VAL", unique = false, nullable = false, insertable = true, updatable = true) public Long getMySequencedValue(){ return myVal; } } ``` Then when I do this: ``` em.persist(new MyEntity()); ``` the id will be generated, but the `mySequenceVal` property will be also generated by my JPA provider. Just to make things clear: I want **Hibernate** to generate the value for the `mySequencedValue` property. I know Hibernate can handle database-generated values, but I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property. If Hibernate can generate values for primary keys, why can't it generate for a simple property?
Looking for answers to this problem, I stumbled upon [this link](http://forum.hibernate.org/viewtopic.php?p=2405140) It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The `@GeneratedValue` annotation is only used in conjunction with `@Id` to create auto-numbers. The `@GeneratedValue` annotation just tells Hibernate that the database is generating this value itself. The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this: ``` @Entity public class GeneralSequenceNumber { @Id @GeneratedValue(...) private Long number; } @Entity public class MyEntity { @Id .. private Long id; @OneToOne(...) private GeneralSequnceNumber myVal; } ```
I found that `@Column(columnDefinition="serial")` works perfect but only for PostgreSQL. For me this was perfect solution, because second entity is "ugly" option. A call to `saveAndFlush` on the entity is also necessary, and `save` won't be enough to populate the value from the DB.
Hibernate JPA Sequence (non-Id)
[ "", "java", "hibernate", "jpa", "sequence", "" ]
I have been working on a script with PHP4 that relies on NuSOAP. Now, I'm trying to move this to PHP5, and use the buildin support for SOAP there. ``` $wsdlPath = ""; // I have obviously set these variables to something meaningful, just hidden for the sake of security $apiPath = ""; $username = ""; $password = ""; // PHP5 style $client = new soapclient($wsdlPath, array('login'=>username, 'password'=> $password, 'soap_version'=> SOAP_1_2, 'location'=> $apiPath, 'trace'=> 1)); // PHP4/NuSOAP style $client = new soapclient($wsdlPath, true); client->setEndpoint($apiPath); $client->setCredentials($username, $password); $client ->loadWSD); ``` The PHP5-version throws the following exception stacktrace: ``` EXCEPTION=SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://external-nbb.napi.norwegian.no.stage.osl.basefarm.net/api/napi1300?wsdl' in /home/eisebfog/public_html/database/norwegian.php:31 Stack trace: #0 /home/eisebfog/public_html/database/norwegian.php(31): SoapClient->SoapClient('http://external...', Array) #1 /home/eisebfog/public_html/database/index.php(53): require_once('/home/eisebfog/...') #2 {main} ``` Now, as the NuSOAP version does work, and the pure PHP5 doesn't - it doesn't take a brain surgeon to figure out I'm doing something wrong. I have access to the .htaccess file, and through phpinfo() I have made sure that I'm running NuSOAP properly and running PHP5 when I should, and PHP4/Nusoap when I should. Basically, I'm not very good with web services and soap - but if anyone has any ideas, i'd appreciate any input on what I'm doing wrong and how I can move to the native soap in PHP5. Btw, the reson I want this move in the first place is the assumed resource savings in native soap. I'd appreciate any links to benchmarks between these two solutions too.
Make sure NuSoap and PHPv5-SOAP are running on the same server. If I'm not totally wrong, both libraries uses the same class-name. Maybe it will work better if you make sure none NuSopa-files are included? And also verify that the SOAP-library are loaded: ``` if(!extension_loaded('soap')){ dl('soap.so'); // Actually a deprecated method. See "notes" at http://no.php.net/dl } ``` I guess the version-field you refer to is defined as "SOAP 1.1" or similiar? Best wishes :) Btw: what are you working on? Exchange of delays from the pilot to the airport? Or perhaps a webservice which will decrease the waiting-time on luggage delivery at Osl? :p
Without testing it, I have two suggestions: First, put your error\_reporting to the highest possible (before creating the SoapClient): ``` error_reporting( E_ALL ); ``` If there's something wrong with the authentication on the server's side, PHP will throw warnings. In most of the cases, it will tell you, what has gone wrong. Second: I don't know if you can specifiy the 'location' option together with an URL to a wsdl. Theoretically, the wsdl tells your client, where the endpoint of the operations is, so you don't have to bother.
Moving from NuSOAP to PHP5 SOAP
[ "", "php", "soap", "wsdl", "port", "nusoap", "" ]
Assuming that writing nhibernate mapping files is not a big issue....or polluting your domain objects with attributes is not a big issue either.... what are the pros and cons? is there any fundamental technical issues? What tends to influence peoples choice? not quite sure what all the tradeoffs are.
The biggest pro of AR is that it gives you a ready-made repository and takes care of session management for you. Either of `ActiveRecordBase<T>` and `ActiveRecordMediator<T>` are a gift that you would have ended up assembling yourself under NHibernate. Avoiding the XML mapping is another plus. The AR mapping attributes are simple to use, yet flexible enough to map even fairly 'legacy' databases. The biggest con of AR is that it actively encourages you to think incorrectly about NHibernate. That is, because the default session management is session-per-call, you get used to the idea that persisted objects are disconnected and have to be `Save()`d when changes happen. This is not how NHibernate is supposed to work - normally you'd have session-per-unit-of-work or request or thread, and objects would remain connected for the lifecycle of the session, so changes get persisted automatically. If you start off using AR and then figure out you need to switch to session-per-request to make lazy loading work - which is not well explained in the docs - you'll get a nasty surprise when an object you weren't expecting to get saved does when the session flushes. Bear in mind that the Castle team wrote AR as a complementary product for Castle Monorail, which is a Rails-like framework for .NET. It was designed with this sort of use in mind. It doesn't adapt well to a more layered, decoupled design. Use it for what it is, but don't think about it as a shortcut to NHibernate. If you want to use NH but avoid mapping files, use NHibernate Attributes or better, Fluent NHibernate.
I found ActiveRecord to be a good piece of kit, and very suitable for the small/medium projects I've used it for. Like Rails, it makes many important decisions for you, which has the effect of keeping you focused you on the meat of the problem. In my opinion pro's and cons are: **Pros** * Lets you focus on problem in hand, because many decisions are made for you. * Includes mature, very usable infrastructure classes (Repository, Validations etc) * Writing AR attributes are faster than writing XML or NHibernate.Mapping.Attributes IMHO. * Good documentation and community support * It's fairly easy to use other NHibernate features with it. * A safe start. You have a get-out clause. You can slowly back into a bespoke NHibernate solution if you hit walls with AR. * Great for domain-first development (generating the db). * You might also want to look up the benefits and drawbacks of the [ActiveRecord pattern](http://martinfowler.com/eaaCatalog/activeRecord.html) **Cons** * You can't pretend NHibernate isn't there - you still need to learn it. * Might not be so productive if you already have a legacy database to work with. * Not transparent persistence. * In-built mappings are comprehensive, but for *some* projects you might need to revert to NHibernate mappings in places. I haven't had this problem, but just a thought. In general, I really like ActiveRecord and it's always been a time saver, mainly because I seem to happily *accept* the decisions and tools baked into the library, and subsequently spend more time focusing on the problem in hand. I'd give it a try on a few projects and see what you think.
Whats the pros and cons of using Castle Active Record vs Straight NHibernate?
[ "", "c#", "nhibernate", "castle-activerecord", "" ]
I am getting this linker error. > **mfcs80.lib(dllmodul.obj) : error LNK2005: \_DllMain@12 already defined in MSVCRT.lib(dllmain.obj)** Please tell me the correct way of eliminating this bug. I read solution on microsoft support site about this bug but it didnt helped much. I am using VS 2005 with Platform SDK
If you read the linker error thoroughly, and apply some knowledge, you may get there yourself: The linker links a number of compiled objects and libraries together to get a binary. Each object/library describes * what symbols it expects to be present in other objects * what symbols it defines If two objects define the same symbol, you get exactly this linker error. In your case, both mfcs80.lib and MSVCRT.lib define the \_DllMain@12 symbol. Getting rid of the error: 1. find out which of both libraries you actually need 2. find out how to tell the linker not to use the other one (using e.g. the [tip from James Hopkin](https://stackoverflow.com/questions/343368/error-lnk2005-dllmain12-already-defined-in-msvcrtlib#343413))
I had the same error message, but none of the answers here solved it for me. So if you Encounter that Problem when creating a DLL Project that uses MFC, it can be resolved by entering the following line: `extern "C" { int __afxForceUSRDLL; }` to the cpp file where `DllMain` is defined. Then your own `DllMain` implementation is used, rather than the one from dllmain.obj. > When we try to use MFC library, we surely will include afx.h directly > or indirectly, then MFC(afx.h) tell the linker to find the symbol of > \_\_afxForceUSRDLL and put that object which contains \_\_afxForceUSRDLL into the program, so linker searches and puts dllmodule.obj into our > program, because \_\_afxForceUSRDLL is defined in dllmodule.cpp. > > That’s the common scenario. When we want to use our own DllMain in a > mfc dll project, linker complains that there are two DllMain, one in > our code, one in Dllmodule.obj. > > So we need to tell the linker to add our dllmain.obj for > \_\_afxForceUSRDLL. So we need to define \_\_afxForceUSRDLL in our own cpp file where our own DllMain is defined, then the linker will ignore > mfc’s dllmodule.obj and see only one DllMain and never complains. Source: <http://social.msdn.microsoft.com/Forums/en-US/0d78aa6b-1e87-4c01-a4a7-691335b7351a/how-to-build-mfc-application-dll-in-visual-c-2010>
error LNK2005: _DllMain@12 already defined in MSVCRT.lib
[ "", "c++", "visual-c++", "linker", "" ]
I often find linq being problematic when working with custom collection object. They are often defened as The base collection ``` abstract class BaseCollection<T> : List<T> { ... } ``` the collections is defined as ``` class PruductCollection : BaseCollection<Product> { ... } ``` Is there a better way to add results from a linq expession to this collection than addrange or concat? ``` var products = from p in HugeProductCollection where p.Vendor = currentVendor select p; PruductCollection objVendorProducts = new PruductCollection(); objVendorProducts.AddRange(products); ``` It would be nice if the object returned form the linq query was of my custom collection type. As you seem to need to enumerate the collection two times to do this. **EDIT** : After reading the answers i think the best solution is to implementa a ToProduct() extention. Wonder if the covariance/contravariance in c#4.0 will help solve these kinds of problems.
The problem is that LINQ, through extension methods on `IEnumerable<T>`, knows how to build Arrays, Lists, and Dictionaries, it doesn't know how to build your custom collection. You could have your custom collection have a constructor that takes an `IEnumerable<T>` or you could write you. The former would allow you to use the LINQ result in your constructor directly, the latter would allow you to decorate the LINQ statement with your extension and get back the collection you desire. Either way you'll need to do some sort of conversion from the generic collection to your specialized collection -- either in the constructor or in the extension. Or you could do both... ``` public static class MyExtensions { public static ProductCollection ToProducts( this IEnumerable<Product> collection ) { return new ProductCollection( collection ); } } public class ProductCollection : BaseCollection<Product> { ... public ProductCollection( IEnumerable<Product> collection ) : base( collection ) { } ... } var products = (from p in HugeProductCollection where p.Vendor = currentVendor select p).ToProducts(); ```
I can suggest you a way in that you don't have to enumerate the collection 2 times: ``` abstract class BaseCollection<T> : List<T> { public BaseCollection(IEnumerable<T> collection) : base(collection) { } } class PruductCollection : BaseCollection<Product> { public PruductCollection(IEnumerable<Product> collection) : base(collection) { } } var products = from p in HugeProductCollection where p.Vendor = currentVendor select p; PruductCollection objVendorProducts = new PruductCollection(products); ```
Linq with custom base collection
[ "", "c#", "linq", "" ]
What is the best resource for learning the features and benefits of windbg? I want to be able to discuss investigate memory issues (handles, objects), performance issues, etc . . .
These are some I like: * [Maoni Stephens and Claudio Caldato's article on MSDN](http://msdn.microsoft.com/en-us/magazine/cc163528.) * [Maoni's blog](http://blogs.msdn.com/maoni/) (it is not updated recently but it contains a lot of useful material) * [Tess Fernandez](http://blogs.msdn.com/tess/) has a a LOT of info reguarding windbg check out her video from teched in Barcellona. She also has an article called "[Learning .NET Debugging](http://blogs.msdn.com/tess/archive/2008/01/30/learning-net-debugging.aspx)" which will certainly be helpful. I suggest you to subscribe to this blog it is allways full with fresh info about debugging. * [John Robbins from Wintellect](http://www.wintellect.com/CS/blogs/jrobbins/default.aspx) has a column on MSDN magazine called [BUGSLAYER](http://msdn.microsoft.com/en-us/magazine/cc163322.aspx) so check it out and allso his book [Debugging Microsoft .NET 2.0 Application](https://rads.stackoverflow.com/amzn/click/com/0735622027)s has few chapters dedicated just to winDbg * [Install WinDBG](http://blogs.msdn.com/johan/archive/2007/01/11/how-to-install-windbg-and-get-your-first-memory-dump.aspx) * Getting Started [Part 1](http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx) and [Part 2](http://blogs.msdn.com/johan/archive/2007/11/26/getting-started-with-windbg-part-ii.aspx)
Good resources here too! <http://bartdesmet.net/blogs/bart>
What is the best resource for learning the features and benefits of windbg?
[ "", "c#", "debugging", "windbg", "" ]
I need to access a mysql database from c# code but I would prefer not to use ODBC for the reasons below. I have to create a demo and I am using xampp on a USB drive. My code (database Read/Write code) is written in C#. So to keep the USB drive isolated from the computer that the demo runs on I am moving away from ODBC because of setup reasons.
<http://dev.mysql.com/downloads/connector/net/5.2.html> Last time I tried it it worked fine but if you need to connect to, for example, MySQL and SQL Server you'll need to duplicate the code once using SqlConnection and the other using MysqlConnection.
You'll probably want to use the [MySQL .Net connector](http://dev.mysql.com/downloads/connector/net/5.2.html)
what is the best way to use c# with mysql without using odbc
[ "", "c#", "mysql", "" ]
I was searching here about converting a string like "16:20" to a DateTime type without losing the format, I said I dont want to add dd/MM/yyy or seconds or AM/PM, because db just accept this format. I tried with Cultures yet Thanks in Advance
All DateTime objects must have a date and a time. If you want just the time, use TimeSpan: ``` TimeSpan span = TimeSpan.Parse("16:20"); ``` If you want a DateTime, add that time to the min value: ``` TimeSpan span = TimeSpan.Parse("16.20"); DateTime dt = DateTime.MinValue.Add(span); // will get you 1/1/1900 4:20 PM which can be formatted with .ToString("HH:mm") for 24 hour formatting ```
Just give a date format to your dateTime. `string DateFormat = "yyyy MM d "` this willl give you the **year month and day**. after continuing; `string DateFormat = "yyyy MM d HH:mm:ss "` in here the **Capital H** will give you the `24 hours time format` and lowerCase `"h" will give you the 12 hours time` format... when you give the Dateformat as a string you can do whatever you want with date and time. ``` string DateFormat = "yyyyMMdHHmmss"; string date = DateTime.Now.ToStrign(DateFormat); ``` OR ``` Console.writeline(DateTime.Now.ToStrign(DateFormat)); ``` **OUTPUT:** ``` 20120823132544 ```
DateTime Format like HH:mm 24 Hours without AM/PM
[ "", "c#", "datetime", "formatting", "" ]
I have a list of input words separated by comma. I want to sort these words by alphabetical and length. How can I do this without using the built-in sorting functions?
Good question!! Sorting is probably the most important concept to learn as an up-and-coming computer scientist. There are actually lots of different algorithms for sorting a list. When you break all of those algorithms down, the most fundamental operation is the comparison of two items in the list, defining their "natural order". For example, in order to sort a list of integers, I'd need a function that tells me, given any two integers X and Y whether X is less than, equal to, or greater than Y. For your strings, you'll need the same thing: a function that tells you which of the strings has the "lesser" or "greater" value, or whether they're equal. Traditionally, these "comparator" functions look something like this: ``` int CompareStrings(String a, String b) { if (a < b) return -1; else if (a > b) return 1; else return 0; } ``` I've left out some of the details (like, how do you compute whether a is less than or greater than b? clue: iterate through the characters), but that's the basic skeleton of any comparison function. It returns a value less than zero if the first element is smaller and a value greater than zero if the first element is greater, returning zero if the elements have equal value. But what does that have to do with sorting? A sort routing will call that function for pairs of elements in your list, using the result of the function to figure out how to rearrange the items into a sorted list. The comparison function defines the "natural order", and the "sorting algorithm" defines the logic for calling and responding to the results of the comparison function. Each algorithm is like a big-picture strategy for guaranteeing that ANY input will be correctly sorted. Here are a few of the algorithms that you'll probably want to know about: **Bubble Sort:** Iterate through the list, calling the comparison function for all adjacent pairs of elements. Whenever you get a result greater than zero (meaning that the first element is larger than the second one), swap the two values. Then move on to the next pair. When you get to the end of the list, if you didn't have to swap ANY pairs, then congratulations, the list is sorted! If you DID have to perform any swaps, go back to the beginning and start over. Repeat this process until there are no more swaps. NOTE: this is usually not a very efficient way to sort a list, because in the worst cases, it might require you to scan the whole list as many as N times, for a list with N elements. ***Merge Sort:*** This is one of the most popular divide-and-conquer algorithms for sorting a list. The basic idea is that, if you have two already-sorted lists, it's easy to merge them. Just start from the beginning of each list and remove the first element of whichever list has the smallest starting value. Repeat this process until you've consumed all the items from both lists, and then you're done! ``` 1 4 8 10 2 5 7 9 ------------ becomes ------------> 1 2 4 5 7 8 9 10 ``` But what if you don't have two sorted lists? What if you have just one list, and its elements are in random order? That's the clever thing about merge sort. You can break any single list into smaller pieces, each of which is either an unsorted list, a sorted list, or a single element (which, if you thing about it, is actually a sorted list, with length = 1). So the first step in a merge sort algorithm is to divide your overall list into smaller and smaller sub lists, At the tiniest levels (where each list only has one or two elements), they're very easy to sort. And once sorted, it's easy to merge any two adjacent sorted lists into a larger sorted list containing all the elements of the two sub lists. NOTE: This algorithm is ***much*** better than the bubble sort method, described above, in terms of its worst-case-scenario efficiency. I won't go into a detailed explanation (which involves some fairly trivial math, but would take some time to explain), but the quick reason for the increased efficiency is that this algorithm breaks its problem into ideal-sized chunks and then merges the results of those chunks. The bubble sort algorithm tackles the whole thing at once, so it doesn't get the benefit of "divide-and-conquer". --- Those are just two algorithms for sorting a list, but there are a lot of other interesting techniques, each with its own advantages and disadvantages: Quick Sort, Radix Sort, Selection Sort, Heap Sort, Shell Sort, and Bucket Sort. The internet is overflowing with interesting information about sorting. Here's a good place to start: <http://en.wikipedia.org/wiki/Sorting_algorithms>
Create a console application and paste this into the Program.cs as the body of the class. ``` public static void Main(string[] args) { string [] strList = "a,b,c,d,e,f,a,a,b".Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach(string s in strList.Sort()) Console.WriteLine(s); } public static string [] Sort(this string [] strList) { return strList.OrderBy(i => i).ToArray(); } ``` Notice that I do use a built in method, [`OrderBy`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.orderby.aspx). As other answers point out there are many different sort algorithms you could implement there and I think my code snippet does everything for you except the actual sort algorithm. [Some C# specific sorting tutorials](http://www.publicjoe.f9.co.uk/csharp/sort00.html)
How can I sort an array of strings?
[ "", "c#", "arrays", "" ]
I would need to create a temp table for paging purposes. I would be selecting all records into a temp table and then do further processing with it. I am wondering which of the following is a better approach: 1) Select all the columns of my Primary Table into the Temp Table and then being able to select the rows I would need OR 2) Select only the primary key of the Primary Table into the Temp Table and then joining with the Primary Table later on? Is there any size consideration when working with approach 1 versus approach 2? [EDIT] I am asking because I would have done the first approach but looking at PROCEDURE [dbo].[aspnet\_Membership\_FindUsersByName], that was included with ASP.NET Membership, they are doing Approach 2 [EDIT2] With people without access to the Stored procedure: ``` -- Insert into our temp table INSERT INTO #PageIndexForUsers (UserId) SELECT u.UserId FROM dbo.aspnet_Users u, dbo.aspnet_Membership m WHERE u.ApplicationId = @ApplicationId AND m.UserId = u.UserId AND u.LoweredUserName LIKE LOWER(@UserNameToMatch) ORDER BY u.UserName SELECT u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved, m.CreateDate, m.LastLoginDate, u.LastActivityDate, m.LastPasswordChangedDate, u.UserId, m.IsLockedOut, m.LastLockoutDate FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p WHERE u.UserId = p.UserId AND u.UserId = m.UserId AND p.IndexId >= @PageLowerBound AND p.IndexId <= @PageUpperBound ORDER BY u.UserName ```
If you have a non-trivial amount of rows (more than 100) than a table variable's performance is generally going to be worse than a temp table equivalent. But test it to make sure. Option 2 would use less resources, because there is less data duplication. Tony's points about this being a dirty read are really something you should be considering.
With approach 1, the data in the temp table may be out of step with the real data, i.e. if other sessions make changes to the real data. This may be OK if you are just viewing a snapshot of the data taken at a certain point, but would be dangerous if you were also updating the real table based on changes made to the temporary copy.
SQL - Temp Table: Storing all columns in temp table versus only Primary key
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I am currently reading "Beginning CakePHP:From Novice to Professional" by David Golding. At one point I have to use the CLI-command "cake bake", I get the welcome-screen but when I try to bake e.g. a Controller I get the following error messages: ``` Warning: mysql_connect(): Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2) in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 117 Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 122 Warning: mysql_get_server_info(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 130 Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 154 Error: Your database does not have any tables. ``` I suspect that the error-messages has to do with php trying to access the wrong mysql-socket, namely the default osx mysql-socket - instead of the one that MAMP uses. Hence I change my database configurations to connect to the UNIX mysql-socket (:/Applications/MAMP/tmp/mysql/mysql.sock): ``` class DATABASE_CONFIG { var $default = array( 'driver' => 'mysql', 'connect' => 'mysql_connect', 'persistent' => false, 'host' =>':/Applications/MAMP/tmp/mysql/mysql.sock', // UNIX MySQL-socket 'login' => 'my_user', 'password' => 'my_pass', 'database' => 'blog', 'prefix' => '', ); } ``` But I get the same error-messages with the new socket: ``` Warning: mysql_connect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock:3306' (2) in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 117 Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 122 Warning: mysql_get_server_info(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 130 Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 154 Error: Your database does not have any tables. ``` Also, even though I use the UNIX-socket that MAMP show on it's welcome-screen, CakePHP loses the database-connection, when using this socket instead of localhost. Any ideas on how I can get bake to work? **-- Edit 1 --** Thank you guys for helping me out! :) I have a problem figuring out where in my.cnf to edit to get MySQL to listen to TCP/IP request. The only paragraph I can find where TCP/IP is mentioned is the following: ``` # Don't listen on a TCP/IP port at all. This can be a security enhancement, # if all processes that need to connect to mysqld run on the same host. # All interaction with mysqld must be made via Unix sockets or named pipes. # Note that using this option without enabling named pipes on Windows # (via the "enable-named-pipe" option) will render mysqld useless! # #skip-networking ``` That allows me to turn off TCP/IP completely, which is the opposite of my intention. I don't know how to go about what you suggest, if you could be more elaborate it would be great. I am a total n00b on these matters :S Reg. connecting to a local socket: I removed the leading colon in the host-parameter, same result.
From the error, it looks like it's trying to connect to an actual IP address and not a UNIX socket, look: ``` '/Applications/MAMP/tmp/mysql/mysql.sock:3306' ``` It's appending a port to the socket, which is wrong. So, I'd first try to configure MySQL to listen to TCP/IP requests (edit the proper section in my.cnf) and try providing 127.0.0.1 instead of the socket. In case you [won't scroll down](https://stackoverflow.com/a/1318934/5190): To fix it at CakePHP level, change host on database.php to 'localhost' and add a port directive with its value set to the socket name '/Applications/MAMP/tmp/mysql/mysql.sock'
I find the solution to this problem : Add a socket config in the cakephp app/config/database.php file ``` class DATABASE_CONFIG { var $default = array( 'driver' => 'mysql', 'persistent' => false, 'host' => 'localhost', 'port' => '/Applications/MAMP/tmp/mysql/mysql.sock', // here is the key ! 'login' => 'you', 'password' => 'yourpass', 'database' => 'yourdb', 'prefix' => '', ); ```
How do I get CakePHP bake to find mysql.sock and recognize MySQL while using MAMP on Mac OSX?
[ "", "php", "mysql", "cakephp", "" ]
In the past I've written sites in ASP.NET just to get nice reusable templating via master pages (layouts) and user controls (partials). I'm talking about sites that have no more complicated code in them than simple variable substitution in templates - I'm just using it to keep my HTML organized. It's great to be able to define the basic layout of your page in one file, and then just fill in the holes for each individual page, re-using some common bits as user controls. However, I'd rather not continue using Windows hosting, so I'd like to write static pages in PHP, which runs everywhere. In the past I've written myself a poor-man's user control for PHP that just unpacks an array and includes a template, but that's clunky and still requires me to put PHP includes all over my pages. I feel like Smarty or one of the other big templating languages for PHP is overkill for just organizing some "static" pages. I've considered just doing the pages in Ruby on Rails because I really like HAML/SASS and the layout/partial model, but having a whole rails app for static content seems silly. But I haven't found anything that seems just right in PHP. Can any PHP gurus recommend anything? I want something more sophisticated than "include" but I don't really need much. That said, something that could give me layouts/partials AND HAML/SASS would be heaven. I've looked at [phammable](http://phammable.org/) but it doesn't look like it solves the layout/partial problem. Again, I'm not looking for something as complex as Smarty, and I don't want a full CMS. I just want something that will let me properly modularize the HTML of my site. We're talking one step beyond static HTML here.
> I just want something that will let me > properly modularize the HTML of my > site. Look at <http://code.google.com/p/hoduli/> With that simple tool you'll be able to write like this: ``` <h:define name="header"> some header contents </h:define> ... <h:header /> <h:include file="middle_part.php" /> <h:footer> some ... </h:footer> ```
[Zend\_View](http://framework.zend.com/manual/en/zend.view.html) supports layouts, partials and placeholders. Also checkout a new templating language called [Dwoo](http://dwoo.org) which is similar to Smarty but also takes some ideas from Django templating. And finally, [Calypso](http://www.beberlei.de/calypso/) which is a Django template language clone for PHP
Simple web page layout and templating in PHP
[ "", "php", "html", "templates", "" ]
I have a base class vehicle and some children classes like car, motorbike etc.. inheriting from vehicle. In each children class there is a function Go(); now I want to log information on every vehicle when the function Go() fires, and on that log I want to know which kind of vehicle did it. Example: ``` public class vehicle { public void Go() { Log("vehicle X fired"); } } public class car : vehicle { public void Go() : base() { // do something } } ``` --- How can I know in the function Log that car called me during the base()? Thanks, Omri
Calling [`GetType()`](http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx) from Vehicle.Go() would work - but only if Go() was actually called. One way of enforcing this is to use the [template method pattern](http://en.wikipedia.org/wiki/Template_method_pattern): ``` public abstract class Vehicle { public void Go() { Log("vehicle {0} fired", GetType().Name); GoImpl(); } protected abstract void GoImpl(); } public class Car : Vehicle { protected override void GoImpl() { // do something } } ```
this.GetType() will give you the type of the current instance
In C#, can I know in the base class what children inherited from me?
[ "", "c#", ".net", "inheritance", "" ]
Good morning, Apologies for the newbie question. I'm just getting started with ASP.NET internationalization settings. Background info: I have a website which displays a `<table>` HTML object. In that `<table>` HTML object, I have a column which displays dates. My server being in the US, those dates show up as `MM/DD/YYYY`. Many of my users plug into this webpage through Excel, via the Data --> Import External Data --> Import Web Query interface. My users, for the most part, are in the US, so those dates show up correctly in their Excel screens. Now I need to make the webpage work for UK users. As is, they are downloading the dates as `MM/DD/YYYY`, which makes their spreadsheets unusable since their regional settings are set to `DD/MM/YYYY`. My question is: How do I make it so the web server realizes that the incoming request has a `en-GB` culture setting? I could engineer my own little custom workaround, but I'm sure I'm not the first programmer to come across this. How do the pro's handle this? I'm looking for a solution that would be relatively simple and quick to put up, but I don't want to just put some crappy buggy piece of my own logic togethe that I'm going to dread 6 months from now. Thanks a lot in advance, -Alan.
A couple of points: * The <globalization> element also needs the attribute culture="auto". The uiCulture attribute affects the language used to retrieve resources. The culture attribute affects the culture used for formatting numbers an dates. * As noted in [this MSDN article](http://msdn.microsoft.com/en-us/library/bz9tc508.aspx), it is not a best practice to rely exclusively on browser settings to determine the UI culture for a page. Users frequently use browsers that are not set to their preferences (for example, in an Internet cafe). You should provide a method for users to explicitly choose a language or language and culture (CultureInfo name) for the page.
You can allow the browser to set your UI culture automatically if you wish, by opening up the web.config, like this: ``` <configuration> <system.web> <globalization uiCulture="auto" /> ... ``` And then the culture set by the browser will be automatically set in your app. This means that when you have the framework display date/time values, they will be formatted according to the current thread's UI Culture. This will also help if you are using currency and/or localized text (however you have to provide the localized resources for each culture you support).
ASP.NET Globalization -- Displaying dates
[ "", "c#", "asp.net", "internationalization", "globalization", "" ]
I have read a lot of popular standards manuals for open source PHP projects. A lot enforce underscores for variables spaces, and a lot enforce camelCase. Should global functions and variables be named differently to class methods/properties? I know the most important thing is consistency, but I'd like to hear some thoughts on this. What would you recommend?
I find camelCase a little more pleasant to type, because I find the underscore a bit awkward to type. Don't use global variables. I avoid procedural coding in PHP, I find OOP is easier to keep things organized. Besides, doesn't PHP have enough stuff in it's global namespace already? Generally I try to stick to: * Classes are StudlyCaps singular or plural nouns, as appropriate: `Item`, `Row`, `DB`, `Items`. * Variables are lowercase nouns, singular or plural depending on what they hold: `$column`, `$name` * Constants are singular upper-case nouns: `DEBUG`, `TYPE_FOO`. * Methods are camelCase, and begin with singular verbs (`get`, `perform`, `do`), followed by a noun (singular or plural) describing what it operates on or returns (`getThing()`, `getThings()`) It definitely depends on what you're coding for. If I'm coding PHP or PEAR, I use camelCase. If I'm doing Python/Django, I use under\_scores. If I'm writing ELisp, I use dashed-separators.
In PHP itself, almost every native function is underscore separated. Most of the PHP code examples in the documentation are underscore separated. In most languages I think Camel or Pascal Casing is more appropriate, but I think there's clear history for using underscore separation in PHP.
PHP - Function/variable naming
[ "", "php", "naming-conventions", "" ]
I'm thinking about how limiting it is for AJAX apps to have to poll for updates, when what would be ideal is for javascript to be able to set up a real two way connection to the server. I'm wondering if there is some method of integrating javascript with a browser plugin that can make a tcp connection so that I could pass data into and out of the browser plugin.
Here is an implementation with a similar approach: * [socketjs](http://sly.w3m.hu/socketjs) It uses a Java Applet and bridges its API to JavaScript, interesting... And here another one: * [jSocket](http://code.google.com/p/jsocket/) This one is a wrapper of the Actionscript 3 Socket API, bridged to JavaScript...
[WebSockets](http://en.wikipedia.org/wiki/WebSockets) is designed to solve this problem.
How can I communicate over TCP sockets from JavaScript?
[ "", "javascript", "ajax", "user-interface", "sockets", "" ]
I'm developing a PHP website that uses url routing. I'd like the site to be directory independent, so that it could be moved from <http://site.example.com/> to <http://example.com/site/> without having to change every path in the HTML. The problem comes up when I'm linking to files which are not subject to routing, like css files, images and so on. For example, let's assume that the view for the action `index` of the controller `welcome` contains the image `img/banner.jpg`. If the page is requested with the url <http://site.example.com/welcome>, the browser will request the image as <http://site.example.com/img/banner.jpg>, which is perfectly fine. But if the page is requested with the url <http://site.example.com/welcome/index>, the browser will think that `welcome` is a directory and will try to fetch the image as <http://site.example.com/welcome/img/banner.jpg>, which is obviously wrong. I've already considered some options, but they all seem imperfect to me: * Use url rewriting to redirect requests from (**\*.css**|**\*.js**|...) or (**css/\***|**js/\***|...) to the right path. *Problems*: Every extension would have to be named in the rewrite rules. If someone would add a new filetype (e.g. an mp3 file), it wouldn't be rewritten. * Prepend the base path to each relative path with a php function. For example: `<img src="<?php echo url::base(); ?>img/banner.jpg" />` *Problems*: Looks messy; **css**- and **js**-files containing paths would have to be processed by PHP. So, how do you keep a website directory independent? Is there a better/cleaner way than the ones I came up with?
You could put in the head ``` <base href="<?php echo url::base(); ?>" /> ``` This will mean the browser will request any non-absolute URLs relative to that path. However I am not sure how this would affect URLs embedded in CSS files etc. This does not affect paths defined in CSS files. (thanks mooware)
The `<base>` thing will work but you need to remember it's going to affect your `<a>` tags too. Consider this example.: ``` <!-- this page is http://oursite.com/index.html --> <html> <head> <base href="http://static.oursite.com/" /> </head> <body> <img src="logo.gif" alt="this is http://static.oursite.com/logo.gif" /> <a href="/login">this links to http://static.oursite.com/login which is not what we wanted. we wanted http://oursite.com/login</a> </body> </html> ``` If you use a PHP function call for creating your links, that won't be a problem as you can just make sure it spits out absolute URL. But if you (or your designers) hand-code the `<a>` tags then you're stuck with the same problem again, just now with `<a>` instead of `<img>`. EDIT: I should add the above paragraph is assuming you serve images from a different host name like we do. If you don't then obviously that won't be a problem.
How to keep a website with url routing directory independent
[ "", "php", "url-routing", "" ]
When you run a JUnit 4 ParameterizedTest with the Eclipse TestRunner, the graphical representation is rather dumb: for each test you have a node called `[0]`, `[1]`, etc. Is it possible give the tests `[0]`, `[1]`, etc. explicit names? Implementing a `toString` method for the tests does not seem to help. (This is a follow-up question to [JUnit test with dynamic number of tests](https://stackoverflow.com/questions/358802/junit-test-with-dynamic-number-of-tests).)
JUnit4 now [allows specifying a name attribute](https://github.com/junit-team/junit/wiki/Parameterized-tests) to the Parameterized annotation, such that you can specify a naming pattern from the index and toString methods of the arguments. E.g.: ``` @Parameters(name = "{index}: fib({0})={1}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } }); } ```
I think there's nothing *built in* in jUnit 4 to do this. I've implemented a solution. I've built my own `Parameterized` class based on the existing one: ``` public class MyParameterized extends TestClassRunner { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public static @interface Parameters { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public static @interface Name { } public static Collection<Object[]> eachOne(Object... params) { List<Object[]> results = new ArrayList<Object[]>(); for (Object param : params) results.add(new Object[] { param }); return results; } // TODO: single-class this extension private static class TestClassRunnerForParameters extends TestClassMethodsRunner { private final Object[] fParameters; private final Class<?> fTestClass; private Object instance; private final int fParameterSetNumber; private final Constructor<?> fConstructor; private TestClassRunnerForParameters(Class<?> klass, Object[] parameters, int i) throws Exception { super(klass); fTestClass = klass; fParameters = parameters; fParameterSetNumber = i; fConstructor = getOnlyConstructor(); instance = fConstructor.newInstance(fParameters); } @Override protected Object createTest() throws Exception { return instance; } @Override protected String getName() { String name = null; try { Method m = getNameMethod(); if (m != null) name = (String) m.invoke(instance); } catch (Exception e) { } return String.format("[%s]", (name == null ? fParameterSetNumber : name)); } @Override protected String testName(final Method method) { String name = null; try { Method m = getNameMethod(); if (m != null) name = (String) m.invoke(instance); } catch (Exception e) { } return String.format("%s[%s]", method.getName(), (name == null ? fParameterSetNumber : name)); } private Constructor<?> getOnlyConstructor() { Constructor<?>[] constructors = getTestClass().getConstructors(); assertEquals(1, constructors.length); return constructors[0]; } private Method getNameMethod() throws Exception { for (Method each : fTestClass.getMethods()) { if (Modifier.isPublic((each.getModifiers()))) { Annotation[] annotations = each.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType() == Name.class) { if (each.getReturnType().equals(String.class)) return each; else throw new Exception("Name annotated method doesn't return an object of type String."); } } } } return null; } } // TODO: I think this now eagerly reads parameters, which was never the // point. public static class RunAllParameterMethods extends CompositeRunner { private final Class<?> fKlass; public RunAllParameterMethods(Class<?> klass) throws Exception { super(klass.getName()); fKlass = klass; int i = 0; for (final Object each : getParametersList()) { if (each instanceof Object[]) super.add(new TestClassRunnerForParameters(klass, (Object[]) each, i++)); else throw new Exception(String.format("%s.%s() must return a Collection of arrays.", fKlass.getName(), getParametersMethod().getName())); } } private Collection<?> getParametersList() throws IllegalAccessException, InvocationTargetException, Exception { return (Collection<?>) getParametersMethod().invoke(null); } private Method getParametersMethod() throws Exception { for (Method each : fKlass.getMethods()) { if (Modifier.isStatic(each.getModifiers())) { Annotation[] annotations = each.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType() == Parameters.class) return each; } } } throw new Exception("No public static parameters method on class " + getName()); } } public MyParameterized(final Class<?> klass) throws Exception { super(klass, new RunAllParameterMethods(klass)); } @Override protected void validate(MethodValidator methodValidator) { methodValidator.validateStaticMethods(); methodValidator.validateInstanceMethods(); } } ``` **To be used like:** ``` @RunWith(MyParameterized.class) public class ParameterizedTest { private File file; public ParameterizedTest(File file) { this.file = file; } @Test public void test1() throws Exception {} @Test public void test2() throws Exception {} @Name public String getName() { return "coolFile:" + file.getName(); } @Parameters public static Collection<Object[]> data() { // load the files as you want Object[] fileArg1 = new Object[] { new File("path1") }; Object[] fileArg2 = new Object[] { new File("path2") }; Collection<Object[]> data = new ArrayList<Object[]>(); data.add(fileArg1); data.add(fileArg2); return data; } } ``` This implies that I instantiate the test class earlier. I hope this won't cause any errors ... I guess I should test the tests :)
ParameterizedTest with a name in Eclipse Testrunner
[ "", "java", "eclipse", "unit-testing", "junit", "parameterized-unit-test", "" ]
Right now we just use something like this ``` stopWatch.Start(); try { method(); } finally { stopWatch.Stop(); } ``` Which works fine for synchronous methods, but some are executing asynchronously, so the time is skewed when multiple threads are executing. Is there an equivalent to System.Diagnostics.Stopwatch that will measure only time spend in the current thread? We want to collect data over an extended period of time in our internal beta(alpha?) release, and running under a profiler full time isn't a feasible option. Edit: To clarify, we want to only measure the time spent executing method(), so if Method1() and Method2() both start at the same time and Method1 finishes at the 2 second mark and Method2 finishes at the 4 second mark, I want something that would tell me that Method1 spent about 1 second executing and Method2 spend about 3 seconds executing (Assuming during the first 2 seconds they shared the (assumed single core) processor equally.
Hmm, from Jon Skeet's answer to this question: [Timing a line of code accurately in a threaded application, C#](https://stackoverflow.com/questions/252793/timing-a-line-of-code-accurately-in-a-threaded-application-c) And also this article: <http://lyon-smith.org/blogs/code-o-rama/archive/2007/07/17/timing-code-on-windows-with-the-rdtsc-instruction.aspx> It seems like there's no simple way to do this.
The stopwatch should measure time spent only in one thread. You would need to run a separate instance on every thread. This would give you probably the closes results to what you want. Alternatively (preferred option if you want to monitor the whole application, and not just some methods), there are various performance counters you can use out of the box (they are updated by .Net runtime). There is lots of information on the web, you can start with msdn: <http://msdn.microsoft.com/en-us/library/w8f5kw2e(VS.71).aspx>
How do you measure code block (thread) execution time with multiple concurrent threads in .NET
[ "", "c#", ".net", "performance", "multithreading", "measurement", "" ]
The docs for [Dictionary.TryGetValue](http://msdn.microsoft.com/en-us/library/bb347013.aspx) say: > When this method returns, [the value argument] contains the value associated with the specified key, if the key is found; otherwise, the **default value for the type of the value parameter**. This parameter is passed uninitialized. I need to mimic this in my class. *How do I find the default value for type T?* --- How can this question be modified to make it show up in the search? Exact duplicate of [Returning a default value. (C#)](https://stackoverflow.com/questions/367378/returning-a-default-value-c)
You are looking for this: ``` default(T); ``` so: ``` public T Foo<T>(T Bar) { return default(T); } ```
``` default(T); ```
default value for generic type in c#
[ "", "c#", "generics", "default-value", "" ]
Say I have the following code: ``` function One() {} One.prototype.x = undefined; function Two() {} var o = new One(); var t = new Two(); ``` `o.x` and `t.x` will both evaluate to `undefined`. `o.hasOwnProperty('x')` and `t.hasOwnProperty('x')` will both return false; the same goes for `propertyIsEnumerable`. Two questions: * Is there any way to tell that o.x is defined and set to `undefined`? * Is there ever any reason to? (should the two be semantically equivalent?) A small caveat: doing (for propName in o) loop will yield 'x' as one of the strings, while doing it in t will not - so there IS a difference in how they're represented internally (at least in Chrome).
A slightly simpler way than your method is to use the [Javascript in operator](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator) ``` alert('x' in o); // true alert('x' in t); // false ```
object.hasOwnProperty(name) only returns true for objects that are in the same object, and false for everything else, including properties in the prototype. ``` function x() { this.another=undefined; }; x.prototype.something=1; x.prototype.nothing=undefined; y = new x; y.hasOwnProperty("something"); //false y.hasOwnProperty("nothing"); //false y.hasOwnProperty("another"); //true "someting" in y; //true "another" in y; //true ``` Additionally the only way do delete a property is to use delete. Setting it to undefined do NOT delete it. The proper way to do it is to use **in** like [roborg](https://stackoverflow.com/users/24181/) said. Update: **undefined** is a primitive value, see [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) section 4.3.2 and 4.3.9.
JavaScript - Identify whether a property is defined and set to 'undefined', or undefined
[ "", "javascript", "object", "properties", "undefined", "" ]
Hi I'm very new to sql but have been passed a job in which I need to query the db(MS SQL 2005) I need to return all workers where a HeadID is given.(tables below) So I need to get all the managers that match the HeadID and then all the workers that match those managers by ManagerID. How would I do this? Any help or any sql terminology that would help me better search for the solution would be much appreciated. Thanks tb\_Head: HeadID tb\_Manager: ManagerID, HeadID, tb\_Worker: WorkerID, ManagerID,
A simple way would be to do something like this: ``` select * from tb_Worker join tb_Manager on tb_Worker.ManagerID = tb_Manager.ManagerID join tb_Head on tb_Manager.HeadID = Head.HeadID where tb_Head.HeadID = <given value> ``` Tune your table names and select columns as appropriate.
Use common table expression ``` USE AdventureWorks; GO WITH DirectReports(ManagerID, EmployeeID, EmployeeLevel) AS ( SELECT ManagerID, EmployeeID, 0 AS EmployeeLevel FROM HumanResources.Employee WHERE ManagerID IS NULL UNION ALL SELECT e.ManagerID, e.EmployeeID, EmployeeLevel + 1 FROM HumanResources.Employee e INNER JOIN DirectReports d ON e.ManagerID = d.EmployeeID ) SELECT ManagerID, EmployeeID, EmployeeLevel FROM DirectReports ; GO ```
Nested Select statement?
[ "", "sql", "sql-server", "" ]
The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code. ``` var urls = new List<string>(); urls.Add("http://www.google.com"); foreach (string url in urls) { // Get all links from the url List<string> newUrls = GetLinks(url); urls.AddRange(newUrls); // <-- This is really the problematic row, adding values to the collection I'm looping } ``` How can I rewrite this in a better way? I'm guessing a recursive solution?
You can't, basically. What you really want here is a queue: ``` var urls = new Queue<string>(); urls.Enqueue("http://www.google.com"); while(urls.Count != 0) { String url = url.Dequeue(); // Get all links from the url List<string> newUrls = GetLinks(url); foreach (string newUrl in newUrls) { queue.Enqueue(newUrl); } } ``` It's slightly ugly due to there not being an `AddRange` method in `Queue<T>` but I think it's basically what you want.
There are three strategies you can use. 1. Copy the List<> to a second collection (list or array - perhaps use ToArray()). Loop through that second collection, adding urls to the first. 2. Create a second List<>, and loop through your urls List<> adding new values to the second list. Copy those to the original list when done looping. 3. Use a *for* loop instead of a *foreach* loop. Grab your count up front. List should leave things indexed correctly, so it you add things they will go to the end of the list. I prefer #3 as it doesn't have any of the overhead associated with #1 or #2. Here is an example: ``` var urls = new List<string>(); urls.Add("http://www.google.com"); int count = urls.Count; for (int index = 0; index < count; index++) { // Get all links from the url List<string> newUrls = GetLinks(urls[index]); urls.AddRange(newUrls); } ``` --- Edit: The last example (#3) assumes that you **don't** want to process additional URLs as they are found in the loop. If you **do** want to process additional URLs as they are found, just use urls.Count in the *for* loop instead of the local *count* variable as mentioned by [configurator](/users/9536/configurator) in the comments for this answer.
How to add items to a collection while consuming it?
[ "", "c#", ".net", "" ]
I'm trying to make some types in Django that map to standard Django types. The [custom model field documentation](http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields) goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods. For example, if I were storing playing cards, I want something like: ``` class Card(object): """ A playing card. """ def as_number(self): """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades).""" return self.number + self.suit_rank() * 13 def __unicode(self): ... def is_highest(self, other_cards, trump=None):... def __init__(self, number, suit): ... ... ``` I want my models to have something like: ``` class my_game(models.Model): ante = models.IntegerField() bonus_card = Card() # Really stored as an models.IntegerField() .... ``` I'm expecting the answer will look like inheriting from the correct type, adding some specially named get/store fields for card, and renaming **init**(). Does anyone have sample code or better documentation?
I'd do this with a subclass of Django's PositiveIntegerField: ``` from django.db import models class Card(object): """The ``Card`` class you described.""" ... class CardField(models.PositiveIntegerField): __metaclass__ = models.SubfieldBase def get_db_prep_value(self, value): """Return the ``int`` equivalent of ``value``.""" if value is None: return None try: int_value = value.as_number() except AttributeError: int_value = int(value) return int_value def to_python(self, value): """Return the ``Card`` equivalent of ``value``.""" if value is None or isinstance(value, Card): return value return Card(int(value)) ``` The `get_db_prep_value` method is responsible for converting `value` into something suitable for interacting with the database, in this case either an `int` or `None`. The `to_python` method does the reverse, converting `value` into a `Card`. Just like before, you'll need to handle the possibility of `None` as a value. Using the `SubfieldBase` ensures that `to_python` is called every time a value is assigned to the field.
Why can't you do something like the following? ``` class Card(models.Model): """ A playing card. """ self.suit = models.PositiveIntegerField() self.rank = models.PositiveIntegerField( choices=SUIT_CHOICES ) def as_number(self): """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades).""" return self.number + self.suit * 13 def __unicode__(self): return ... def is_highest(self, other_cards, trump=None):... ``` Certainly, this is quite simple, and fits comfortably with what Django does naturally.
How do I create trivial customized field types in Django models?
[ "", "python", "django", "django-models", "" ]
I want to display documents on my website. The server is hosted on a Debian machine. I was thinking I can allow the upload of support documents then use a Linux app or PHP app to convert the doc into PDF and display that in an HTML page. Are there any APIs or binaries that allow me to do this?
If it is an office document, one option would be to use openoffice in headless mode. See here for a python script that shows how: <http://www.oooninja.com/2008/02/batch-command-line-file-conversion-with.html> If it is any other kind of document (e.g. your own XML document), then you would need to do a bit more work. I have had some success using XSL to define a translation to docbook format, then using docbook tools to generate the PDF (and various other formats). You could also use XSL to go straight to PDF if you need more precise control over how things look.
You can create a PDF print-to-file printer and send any number of documents to the printer via lpr. ``` function lpr($STR,$PRN,$TITLE) { $prn=(isset($PRN) && strlen($PRN))?"$PRN":C_DEFAULTPRN ; $title=(isset($TITLE))?"$TITLE":"stdin" . rand() ; $CMDLINE="lpr -P $prn -T $title"; $pipe=popen("$CMDLINE" , 'w'); if (!$pipe) {print "pipe failed."; return ""; } fwrite($pipe,$STR); pclose($pipe); } // lpr() //open document... //read into $source lpr($source, "PDF", $title); //print to device exit(); ``` Also [HTMLDOC](http://www.easysw.com/htmldoc/) can convert your HTML into a PDF.
How to convert documents to PDF on a Linux/PHP stack?
[ "", "php", "linux", "pdf", "" ]
I have the table (Product\_Id, category priority, atribute1, atribute2...) in MS Access, and I am trying to make a query that orders the data grouped by Category and ordered by the highest priority. Priority can be Null, so it should be placed at the end. Example: Table ``` 1, 100, 2, atr1, atr2 2, 300, , atr1, atr2 3, 100, 5, atr1, atr2 4, 200, 9, atr1, atr2 5, 100, , atr1, atr2 6, 200, 1, atr1, atr2 ``` Result expected in Query: ``` 6, 200, 1, atr1, atr2 4, 200, 9, atr1, atr2 1, 100, 2, atr1, atr2 3, 100, 5, atr1, atr2 5, 100, , atr1, atr2 2, 300, , atr1, atr2 ```
In Jet SQL, this may suit: ``` SELECT t2.MinOfPriority, tn.Field2, Nz([tn.Field3],999) AS Priority, tn.Field4, tn.Field5 FROM tn INNER JOIN (SELECT Min(Nz(tn.Field3,999)) AS MinOfPriority, tn.Field2 FROM tn GROUP BY tn.Field2) AS t2 ON tn.Field2 = t2.Field2 ORDER BY t2.MinOfPriority, tn.Field2, Nz([Field3],999); ```
The easiest solution (not necessarily the best in some cases) is to use column numbers in your ordering expressions: ``` SELECT t2.MinOfPriority, tn.Field2, Nz([tn.Field3],999) AS Priority, tn.Field4, tn.Field5 ORDER BY 1,2,3 ```
How to Order a SQL Query with grouped rows
[ "", "sql", "ms-access", "sql-order-by", "" ]
Below is my table, a User could have multiple profiles in certain languages, non-English profiles have a higher priority. ``` +----------+--------+----------------+----------------+ |ProfileID |UserID |ProfileLanguage |ProfilePriority | +----------+--------+----------------+----------------+ |1 |1 |en-US |2 | +----------+--------+----------------+----------------+ |2 |1 |es-MX |1 | +----------+--------+----------------+----------------+ |3 |1 |ja-JP |1 | +----------+--------+----------------+----------------+ |4 |2 |es-MX |1 | +----------+--------+----------------+----------------+ |5 |2 |ja-JP |2 | +----------+--------+----------------+----------------+ |6 |2 |de-DE |1 | +----------+--------+----------------+----------------+ |7 |3 |en-US |2 | +----------+--------+----------------+----------------+ ``` For example: When a Spanish-speaking visitor requests my site (where ProfileLanguage = 'es-MX' or ProfilePriority = 2), I want the records like below: ``` +----------+--------+----------------+----------------+ |ProfileID |UserID |ProfileLanguage |ProfilePriority | +----------+--------+----------------+----------------+ |2 |1 |es-MX |1 | +----------+--------+----------------+----------------+ |5 |2 |ja-JP |2 | +----------+--------+----------------+----------------+ |7 |3 |en-US |2 | +----------+--------+----------------+----------------+ ``` Below, is the basic SQL to get the users: ``` SELECT UserID, MIN(ProfilePriority) AS ProfilePriority FROM Profile WHERE ProfileLanguage = 'es-MX' OR ProfilePriority = 2 GROUP BY UserID ``` But as you know, I can only get the UserID, but I also need other column information, like ProfileID etc.. So I hope experts here could tell me the correct SQL expression to get the right records.
This may work, if profilepriority and userid could be a composite unique key; ``` select p.* from Profile p join (SELECT UserID, MIN(ProfilePriority) AS ProfilePriority FROM Profile WHERE ProfileLanguage = 'en-US' OR ProfilePriority = 2 GROUP BY UserID) tt on p.userID = tt.UserID and p.ProfilePriority = tt.ProfilePriority ```
``` SELECT * FROM Profile as tb1 inner join (SELECT UserID, MIN(ProfilePriority) AS ProfilePriority FROM Profile WHERE ProfileLanguage = 'es-MX' OR ProfilePriority = 2 GROUP BY UserID) as tb2 on tb1.userid = tb2.userid and tb1.ProfilePriority = tb2.ProfilePriority ``` Enter all the columns you require in separated with a comma instead of \* in the above query.
SQL expression problem
[ "", "sql", "group-by", "expression", "" ]
I have the following method in my code: ``` private bool GenerateZipFile(List<FileInfo> filesToArchive, DateTime archiveDate) { try { using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(GetZipFileName(archiveDate)))) { zipStream.SetLevel(9); // maximum compression. byte[] buffer = new byte[4096]; foreach (FileInfo fi in filesToArchive) { string fileName = ZipEntry.CleanName(fi.Name); ZipEntry entry = new ZipEntry(fileName); entry.DateTime = fi.LastWriteTime; zipStream.PutNextEntry(entry); using (FileStream fs = File.OpenRead(fi.FullName)) { StreamUtils.Copy(fs, zipStream, buffer); } zipStream.CloseEntry(); } zipStream.Finish(); zipStream.Close(); } return true; } catch (Exception ex) { OutputMessage(ex.ToString()); return false; } } ``` This code generates a ZIP file with all the correct entries, but each file is listed as being 4 TB (both unpacked and packed) and creates the following error when I try to open it: ``` Extracting to "C:\winnt\profiles\jbladt\LOCALS~1\Temp\" Use Path: no Overlay Files: yes skipping: QPS_Inbound-20081113.txt: this file is not in the standard Zip 2.0 format Please see www.winzip.com/zip20.htm for more information error: no files were found - nothing to do ``` The code is practically taken from the samples, but I seem to be missing something. Does anyone have any pointers?
I used to use SharpZipLib until I switched to [DotNetZip](http://www.codeplex.com/DotNetZip) You may want to check it out as an alternative. Example: ``` try { using (ZipFile zip = new ZipFile("MyZipFile.zip") { zip.AddFile("c:\\photos\\personal\\7440-N49th.png"); zip.AddFile("c:\\Desktop\\2005_Annual_Report.pdf"); zip.AddFile("ReadMe.txt"); zip.Save(); } } catch (System.Exception ex1) { System.Console.Error.WriteLine("exception: " + ex1); } ```
See the post by [Tyler Holmes](http://blog.tylerholmes.com/2008/12/windows-xp-unzip-errors-with.html) The issue with Winzip 8.0 and others is with Zip64. Set the original file size when adding the ZipEntry and the error goes away. e.g. ``` string fileName = ZipEntry.CleanName(fi.Name); ZipEntry entry = new ZipEntry(fileName); entry.DateTime = fi.LastWriteTime; entry.Size = fi.Length; zipStream.PutNextEntry(entry); ``` Current release zip utilities don't have the problem.
Basics of SharpZipLib. What am I missing?
[ "", "c#", ".net", ".net-2.0", "compression", "sharpziplib", "" ]
JavaScript does funky automatic conversions with objects: ``` var o = {toString: function() {return "40"; }}; print(o + o); print((o+1)+o); print((o*2) + (+o)); ``` will print: ``` 4040 40140 120 ``` This is because +, if any of the arguments are objects/strings, will try to convert all the arguments to strings then concatenate them. If all arguments are numbers, it adds them together. \* and unary + convert objects to numbers using toString (as well as valueOf, not shown here). What does JavaScript do for the ++ operator?
From [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) > ## 11.3 Postfix Expressions > > **Syntax** > > PostfixExpression : > > * LeftHandSideExpression > * LeftHandSideExpression [no LineTerminator here] ++ > * LeftHandSideExpression [no LineTerminator here] -- > > **11.3.1 Postfix Increment Operator** > > The production *PostfixExpression : > LeftHandSideExpression [no > LineTerminator here] ++* is evaluated > as follows: > > 1. Evaluate LeftHandSideExpression. > 2. Call GetValue(Result(1)). > 3. Call ToNumber(Result(2)). > 4. Add the value 1 to Result(3), using the same rules as for the + operator > (section 11.6.3). > 5. Call PutValue(Result(1), Result(4)). > 6. Return Result(3). --- This is pseudo javascript code of how postInc works: ``` function postInc(a) { var x = +a; // Converts a to a number, Section 11.4.6 Unary + Operator a = x + 1; return x; } ``` Edit: As [mikesamuel](https://stackoverflow.com/users/20394/) said: it's not parseInt. Updated to reflect that.
The following code illustrates this well: ``` var a = {toString: function() {return "40"; }}; nl(typeof a); nl(typeof +a); nl(typeof a); nl(typeof (a++)); nl(a); nl(typeof a); ``` The output is: ``` object number object number 41 number ``` Unary plus converts the object to a number and doesn't modify it. a++ first converts the object to a number, **then returns that number**, and then increments the number, storing the value in a. This is opposed to another possible solution, where a++ would first return the object, and then do the conversion to a number and incrementation.
How does JavaScript treat the ++ operator?
[ "", "javascript", "operators", "type-conversion", "coercion", "" ]
I am writing a website with PHP. Since it will need to be accessed by anyone on the network to access the internet I have to create a mobile version. How do I best check if it's a mobile device? I don't want to have a switch statement with 50 devices at the end since I don't only want to support the iPhone. Is there a PHP class I could use?
You need to check several headers that the client sends, such as USER\_AGENT and HTTP\_ACCEPT. Check out [this article](http://mobiforge.com/developing/story/lightweight-device-detection-php) for a comprehensive detection script for mobile user-agents in PHP.
You should look at [Tera-WURFL](http://www.tera-wurfl.com), it is a PHP & MySQL-based software package that detects mobile devices and their capabilities. Here is the Tera-WURFL code that you would use to detect if the visiting device is mobile: ``` <?php require_once("TeraWurfl.php"); $wurflObj = new TeraWurfl(); $wurflObj->GetDeviceCapabilitiesFromAgent(); if($wurflObj->capabilities['product_info']['is_wireless_device']){ // this is a mobile device }else{ // this is a desktop device } ?> ```
How do I determine whether it's a mobile device with PHP?
[ "", "php", "mobile", "" ]
I have a XML with a structure similar to this: ``` <category> <subCategoryList> <category> </category> <category> <!--and so on --> </category> </subCategoryList> </category> ``` I have a Category class that has a `subcategory` list (`List<Category>`). I'm trying to parse this XML file with XPath, but I can't get the child categories of a category. How can I do this with XPath? Is there a better way to do this?
[This link](http://www.roseindia.net/tutorials/xPath/java-xpath.shtml) has everything you need. In shorts: ``` public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse("persons.xml"); XPath xpath = XPathFactory.newInstance().newXPath(); // XPath Query for showing all nodes value XPathExpression expr = xpath.compile("//person/*/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } } ```
I believe the XPath expression for this would be "`//category/subCategoryList/category`". If you just want the children of the root `category` node (assuming it is the document root node), try "`/category/subCategoryList/category`".
Parsing XML with XPath in Java
[ "", "java", "xml", "xpath", "" ]
What is the smartest way to get an entity with a field of type List persisted? ## Command.java ``` package persistlistofstring; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Persistence; @Entity public class Command implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Basic List<String> arguments = new ArrayList<String>(); public static void main(String[] args) { Command command = new Command(); EntityManager em = Persistence .createEntityManagerFactory("pu") .createEntityManager(); em.getTransaction().begin(); em.persist(command); em.getTransaction().commit(); em.close(); System.out.println("Persisted with id=" + command.id); } } ``` --- This code produces: ``` > Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named pu: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory: > oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException > Local Exception Stack: > Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException > Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7 > Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException > Exception Description: predeploy for PersistenceUnit [pu] failed. > Internal Exception: Exception [TOPLINK-7155] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException > Exception Description: The type [interface java.util.List] for the attribute [arguments] on the entity class [class persistlistofstring.Command] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface. > at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143) > at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169) > at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110) > at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) > at persistlistofstring.Command.main(Command.java:30) > Caused by: > ... ```
Use some JPA 2 implementation: it adds a @ElementCollection annotation, similar to the Hibernate one, that does exactly what you need. There's one example [here](http://jazzy.id.au/2008/03/24/jpa_2_0_new_features_part_1.html). **Edit** As mentioned in the comments below, the correct JPA 2 implementation is ``` javax.persistence.ElementCollection @ElementCollection Map<Key, Value> collection; ``` **See: <http://docs.oracle.com/javaee/6/api/javax/persistence/ElementCollection.html>**
Should anyone be looking for an alternative solution where you store your string lists as one field in your database, here's how I solved that. Create a Converter like this: ``` import java.util.Arrays; import java.util.List; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import static java.util.Collections.*; @Converter public class StringListConverter implements AttributeConverter<List<String>, String> { private static final String SPLIT_CHAR = ";"; @Override public String convertToDatabaseColumn(List<String> stringList) { return stringList != null ? String.join(SPLIT_CHAR, stringList) : ""; } @Override public List<String> convertToEntityAttribute(String string) { return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList(); } } ``` Now use it on your Entities like this: ``` @Convert(converter = StringListConverter.class) private List<String> yourList; ``` In the database, your list will be stored as `foo;bar;foobar`, and in your Java object you will get a list with those strings.
How to persist a property of type List<String> in JPA?
[ "", "java", "orm", "jpa", "" ]
I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. This all works great when I run the Python (command line) tool that comes with Python. However, if I run cygwin and then run Python from within, it cannot find the numpy package. What environment variable do I need to set? What value should it be set to?
Cygwin comes with its own version of Python, so it's likely that you have two Python installs on your system; one that installed under Windows and one which came with Cygwin. To test this, try opening a bash prompt in Cygwin and typing `which python` to see where the Python executable is located. If it says `/cygdrive/c/Python25/python.exe` or something similar then you'll know you're running the Windows executable. If you see `/usr/local/bin/python` or something like that, then you'll know that you're running the Cygwin version. I recommend opening a DOS prompt and running Python from there when you need interactive usage. This will keep your two Python installs nicely separate (it can be very useful to have both; I do this on my own machine). Also, you may have some problems running a program designed for Windows interactive console use from within a Cygwin shell.
You're running a separate copy of python provided by cygwin. You can run /cygdrive/c/python25/python (or wherever you installed it) to get your win32 one, or just install another copy of numpy.
Running numpy from cygwin
[ "", "python", "numpy", "" ]
Not many are aware of this feature, but Python's functions (and methods) can have [attributes](http://www.python.org/dev/peps/pep-0232/). Behold: ``` >>> def foo(x): ... pass ... >>> foo.score = 10 >>> dir(foo) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score'] >>> foo.score 10 >>> foo.score += 1 >>> foo.score 11 ``` What are the possible uses and abuses of this feature in Python ? One good use I'm aware of is [PLY](http://www.dabeaz.com/ply/)'s usage of the docstring to associate a syntax rule with a method. But what about custom attributes ? Are there good reasons to use them ?
I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface) ``` class Foo(WebService): @webmethod def bar(self, arg1, arg2): ... ``` then I can define ``` def webmethod(func): func.is_webmethod = True return func ``` Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is\_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.
I've used them as static variables for a function. For example, given the following C code: ``` int fn(int i) { static f = 1; f += i; return f; } ``` I can implement the function similarly in Python: ``` def fn(i): fn.f += i return fn.f fn.f = 1 ``` This would definitely fall into the "abuses" end of the spectrum.
Python function attributes - uses and abuses
[ "", "python", "function", "attributes", "" ]
Is it possible to read the data in the php $\_SESSION array in the .htaccess file in Apache? So say I have the following: ``` $_SESSION['foo'] = 'bar'; ``` could I then in .htaccess do something like: ``` RewriteRule bla.png folder/{the php session var foo}/file.png ``` Is that possible? I already have a working workaround but if this is possible it would be way nicer.
I'm not aware that its possible. But I can think of a few workarounds involving rewriting to a PHP script.
# Answer to the main question: **No,** at least not as you imagine. The file is called `.ht`***`access`*** because they are *"distributed configuration files"* and of course configuration && ***access*** handling must happen first - therefor you can't get "PHP session variable" because it simply comes after the processing of the `.htaccess` I will show you some workarounds below, but before - you should **pay attention to this:** # Is this really necessary? - suggested solutions: If you just want to redirect filepath **/** by logged-in user - **.htaccess is NOT the way** - use just `bla.php` as address and then in php file do the redirect - something like this: ``` <?php session_start(); header("Location: folder/".$_SESSION['foo']."/file.png"); exit(); ?> ``` However if you can't change the source URL, you will first have to redirect `bla.png` to `bla.php` but I guess you know how to do that :-) In frameworks using MPV/MVC model there are often scripts for "routing" for a reason - e.g. this one. Optionally you could make a "php-router" from this script adding some other PHP-relying redirects while using `if/elseif/else` or `case` to choose what will happen - where the redirect will go. ### OR You are probably using a session anyway - so why just don't generate the url straight in PHP like: `$url = "example.com/bla.png?foo=".$_SESSION['foo'];` + regexp in `.htaccess` or even: `$url = "example.com/folder/".$_SESSION['foo']."/file.png";` Anyway I guess you are redirecting because you can't (for some reason) do that. :-) # Workarounds If you are still persuaded that you have to do this in .htaccess file here are some workarounds ## 1) Use cookies In modern days cookies are often available, so if you "trust" your client's cookies, you could make a redirect rule based on a `HTTP_COOKIE` server-variable - assuming you've stored cookie called "`foo`" before: ``` RewriteCond %{HTTP_COOKIE} ^(.*)foo=([-_a-zA-Z0-9]+)(.*)$ [NC] RewriteRule ^bla.png$ /folder/%2/file.png [R=307,NC,L] #possibly use 302 if you like dinosaurs ``` As you can see the trick is to create condition checking `HTTP_COOKIE` server-variable for some condition. It basicly says: > Is there a COOKIE called "foo" which contains only "-, \_, lower or upper case letters or numbers"? > > If so - redirect *example.com/bla.png* to *example.com/folder/CURRENT\_FOO\_VALUE/file.png* > > > **[flags]**: [307 redirect](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) (R=307), don't mind letter-case (NC), don't apply other rules (L) Good point is that `HTTP_COOKIE` server-variable is structured in this way: ``` name=value; name2=value2 ``` ## 2) NOT recommended - other workarounds: ### a) read session to `HTTP_SESSION` environment variable using mod\_session See the [apache manual for mod\_session](http://httpd.apache.org/docs/current/mod/mod_session.html) for more info how to read session into the `HTTP_SESSION` env. variable. The approach then would be the same as for the "COOKIE-workaround". ### b) store needed info in a text file and read it with the `RewriteMap` directive as @Chris suggested But again you will somehow have to detect which 'foo' is it so maybe `SSL_SESSION_ID` or some other `$_GET/$_POST` parameters?
Get PHP session vars in .htaccess
[ "", "php", "apache", "session", ".htaccess", "" ]
I am using the following code to attempt to read a large file (280Mb) into a byte array from a UNC path ``` public void ReadWholeArray(string fileName, byte[] data) { int offset = 0; int remaining = data.Length; log.Debug("ReadWholeArray"); FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); while (remaining > 0) { int read = stream.Read(data, offset, remaining); if (read <= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; } } ``` This is blowing up with the following error. ``` System.IO.IOException: Insufficient system resources exist to complete the requested ``` If I run this using a local path it works fine, in my test case the UNC path is actually pointing to the local box. Any thoughts what is going on here ?
I suspect that something lower down is trying to read into another buffer, and reading all 280MB in one go is failing. There may be more buffers required in the network case than in the local case. I would read about 64K at a time instead of trying to read the whole lot in one go. That's enough to avoid too much overhead from chunking, but will avoid huge buffers being required. Personally I tend to just read to the end of the stream rather than assuming that the file size will stay constant. See [this question](https://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream) for more information.
Also, the code as written needs to put the `FileStream` into a `using` block. Failing to dispose of resources is a very possible reason for receiving "Insufficient system resources": ``` public void ReadWholeArray(string fileName, byte[] data) { int offset = 0; int remaining = data.Length; log.Debug("ReadWholeArray"); using(FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { while (remaining > 0) { int read = stream.Read(data, offset, remaining); if (read <= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; } } } ```
IOException reading a large file from a UNC path into a byte array using .NET
[ "", "c#", ".net", "arrays", "large-files", "unc", "" ]
the following js works fine in FF2 but in IE6 the dropdown always selects one option to early, IE -> testix2 vs. FF2 -> testix3 If we add an alertBox somewhere in the script, it also works fine in IE6. But how to solve this without an alertBox? tia ``` <script language="JavaScript" type="text/javascript"> <!-- function Entry(value, name, selected) { this.value = value; this.name = name; this.selected = selected; } //--> </script> <select id="selSeaShells"> </select> <script language="JavaScript" type="text/javascript"> <!-- var productCategoryLevel2 = new Array(); productCategoryLevel2.push(new Entry('Hallo1', 'testix1', false)); productCategoryLevel2.push(new Entry('Hallo2', 'testix2', false)); productCategoryLevel2.push(new Entry('Hallo3', 'testix3', true)); var i = 0; for (i in productCategoryLevel2) { var optL2 = document.createElement('option'); optL2.selected = true; optL2.text = productCategoryLevel2[i].name; optL2.value = productCategoryLevel2[i].value; if (productCategoryLevel2[i].selected == true) { productCategoryLevel2[i].selected = true; optL2.selected = true; } else { optL2.selected = false; } try { document.getElementById("selSeaShells").add(optL2, null); } catch(ex3) { document.getElementById("selSeaShells").add(optL2); } } //--> </script> ```
I'm not entirely sure why your example does not work, but it works if you do it like this (i.e. setting the selectedIndex on the <select> rather than setting the <option>'s selected propery). Tested FF3, IE6, Chrome. ``` var i = 0; for (i in productCategoryLevel2) { var optL2 = document.createElement('option'); optL2.text = productCategoryLevel2[i].name; optL2.value = productCategoryLevel2[i].value; try { document.getElementById("selSeaShells").add(optL2, null); } catch(ex3) { document.getElementById("selSeaShells").add(optL2); } if (productCategoryLevel2[i].selected == true) { document.getElementById("selSeaShells").selectedIndex = i; } } ```
I can't test this right now, but you may want to iterate over your array using a standard for(;;) loop rather than the for..in construct, which should only ever be used on objects in javascript.
javascript options selected IE6 vs. FF2
[ "", "javascript", "html", "internet-explorer-6", "html-select", "" ]
Should I start a Python program with: ``` if__name__ == '__main__': some code... ``` And if so, why? I saw it many times but don't have a clue about it.
If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, `__name__` evaluates to `'foo'`, but if you run "python foo.py" from the command line, `__name__` evaluates to `'__main__'`. Note that you do need to insert a space between if and \_, and indent the main program: ``` if __name__ == '__main__': main program here ```
A better pattern is this: ``` def main(): ... if __name__ == '__main__': main() ``` This allows your code to be invoked by someone who imported it, while also making programs such as [pychecker](http://pychecker.sourceforge.net/) and [pylint](http://www.logilab.org/projects/pylint) work.
Python program start
[ "", "python", "" ]
What are all the other things the `new` operator does other than allocating memory and calling a constructor?
The C++ standard has this to say about the single object form (the form usually used) of the new operator from the `<new>` header: > Required behavior: > > Return a nonnull pointer to suitably aligned storage (3.7.3), or else throw a > bad\_alloc exception. This requirement is binding on a replacement version of this function. > > Default behavior: > > — Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether > the attempt involves a call to the Standard C library function malloc is unspecified. > > — Returns a pointer to the allocated storage if the attempt is successful. Otherwise, if the last argument to > set\_new\_handler() was a null pointer, throw bad\_alloc. > > — Otherwise, the function calls the current new\_handler (18.4.2.2). If the called function returns, the loop > repeats. > > — The loop terminates when an attempt to allocate the requested storage is successful or when a called > new\_handler function does not return. The standard has a lot of other stuff to say about the new operator and dynamic memory allocation (an awful lot to say), but I think the "Default behavior" list sums up the basics of the new operator pretty well.
I've written a explanation of what it does in [this](https://stackoverflow.com/questions/365887/how-do-malloc-and-new-work-how-are-they-different-implementation-wise#365891) answer. It explains how * `new` gets the memory * `new` handles memory failure * `new` handles constructor exceptions * `new` handles special placement and nothrow versions Michael explained how the default allocator function (::operator new) gets memory nicely and how it handles failure. I've seen your question on where the size of an object is stored in his comments. The answer is, there isn't size stored if not necassary. Remember that C doesn't need the size for `free` (and ::operator new can just use `malloc`): ``` void * memory = malloc(x); free (memory); // no need to tell it the size ``` Here is an example where you see how storing the size has an impact on the size of allocation for the array form of a new expression (not covered by my other answer): ``` #include <cstddef> #include <iostream> struct f { // requests allocation of t bytes void * operator new[](std::size_t t) throw() { void *p = ::operator new[](t); std::cout << "new p: " << p << std::endl; std::cout << "new size: " << t << std::endl; return p; } // requests deleting of t bytes starting at p void operator delete[](void *p, std::size_t t) throw() { std::cout << "delete p: " << p << std::endl; std::cout << "size : " << t << std::endl; return ::operator delete[](p); } }; int main() { std::cout << "sizeof f: " << sizeof (f) << std::endl; f * f_ = new f[1]; std::cout << "&f_ : " << f_ << std::endl; delete[] f_; } ``` It will print out something like this: ``` sizeof f: 1 new p: 0x93fe008 new size: 5 &f_ : 0x93fe00c delete p: 0x93fe008 size : 5 ``` One byte for the object itself and 4 bytes for the count which is stored just before the allocated area of the object. Now if we use the deallocation function without a size parameter (just removing it from the operator delete), we get this output: ``` sizeof f: 1 new p: 0x9451008 new size: 1 &f_ : 0x9451008 delete p: 0x9451008 ``` The C++ runtime here doesn't care about the size, so it doesn't store it anymore. Note that this is highly implementation specific, and that's what gcc does here to be able to tell you the size in the member operator delete. Other implementations may still store the size, and will most likely if there is a destructor to invoke for the class. For example just adding `~f() { }` above makes gcc to store the size, regardless on what deallocation function we write.
What does the C++ new operator do other than allocation and a ctor call?
[ "", "c++", "new-operator", "" ]
I have some code which I did not originally create that uses \_beginthreadex and \_endthreadex. For some reason, when it calls \_endthreadex(0), the call just hangs and never returns. Any ideas as to what would normally cause this call to hang?
\_endthreadex ends the thread, so it can't return. That's the whole point of calling it. EDIT: It's a bit unusual to call \_endthreadex, normally you just let the thread start procedure return and the runtime calls \_endthreadex for you. You may need to explain a bit more, what you are trying to do before we can help.
My answer is too far late, but still someone will use it. In my case \_endthreadex hanged when I unload dll and deleted some global objects. One of global objects had another thread inside and that thread also performed thread exit. This caused deadlock since DLLMain already locked crt memory map. Read DLLMain help and find that you are not allowed do any other action on another threads or processes during DLLMain call.
_endthreadex(0) hangs
[ "", "c++", "multithreading", "" ]
I'm using ASP.NET MVC and I have a partial control that needs a particular CSS & JS file included. Is there a way to make the parent page render the `script` and `link` tags in the 'head' section of the page, rather than just rendering them inline in the partial contol? To clarify the control that I want to include the files from is being rendered from a View with `Html.RenderPartial` and so cannot have server-side content controls on it. I want to be able to include the files in the html `head` section so as to avoid validation issues.
<http://www.codeproject.com/Articles/38542/Include-Stylesheets-and-Scripts-From-A-WebControl-.aspx> This article contains information about overriding HttpContext.Response.Filter which worked great for me.
If I have requirements for CSS/Javascript in a partial view, I simply make sure that any page that may include the partial view, either directly or as content retrieved from AJAX, has the CSS/Javascript included in it's headers. If the page has a master page, I add a content placeholder in the master page header and populate it in the child page. To get intellisense in the partial view, I add the CSS/Javascript includes in the partial view but wrapped with an `if (false)` code block so they are not included at runtime. ``` <% if (false) { %> <link href=... <script type=... <% } %> ```
How can I include css files from an MVC partial control?
[ "", "javascript", "asp.net-mvc", "css", "" ]
I'm doing some research in code generation from xsd schema files. My requirements: * Must generate C# 2.0 code (or above), using generic collections where needed. * Must generate comments from the xsd comments * Must generate fully serializable code. * Should be able to generate resuable basetypes when generating from multiple xsd's with the same includes. (see also my other questions: [How can I generate multiple classes from xsd’s with common includes?](https://stackoverflow.com/questions/374600/how-can-i-generate-multiple-classes-from-xsds-with-common-includes) and [How can I generate comments from xs:documentation tags in a wsdl?](https://stackoverflow.com/questions/374086/how-can-i-generate-comments-from-xsdocumentation-tags-in-a-wsdl) I have found the following options: 1. Use xsd.exe (supplied with the SDK and Visual Studio) 2. XSDCodeGen from [Daniel Cazzulino](http://www.clariusconsulting.net/blogs/kzu/archive/2004/05/14/XsdCodeGenTool.aspx) 3. [Xsd2Code](http://www.codeplex.com/Xsd2Code) 4. [CodeXS](http://www.bware.biz/CodeXS/) 5. [XsdObjectGen](http://www.microsoft.com/downloads/details.aspx?familyid=89e6b1e5-f66c-4a4d-933b-46222bb01eb0&displaylang=en) by Microsoft 6. [XSDClassGen](http://www.dotnetjunkies.com/WebLog/ram-marappan/default.aspx) (Seems to be missing in action) Did I miss any? Because (1), (2) and (5) do not generate 2.0 code, and I have problems with serializing code from (3). What do you use when generating code?
I believe [XSD2Code](http://xsd2code.codeplex.com/) is the best tool currently available (in 2011). I recently went through the same process at work of analysing the available tools out there so i thought i would provide an updated answer that relates to **VS2010**. Our main driver was that **xsd.exe** does not generate XML doc from the XSD annotations, which we wanted as we have hundreds of type definitions. I tried all the tools listed above as well as others and most were either deprecated, unmaintained or unable to match the current functionality of xsd.exe available in VS2010. **Xsd2Code** however is a superb tool and seems to be actively maintained. It provides all the functionality that was listed above and a lot more - the CodePlex page also has great examples of how the various options affect output. It also has tight VS integration, including context menu integration and a custom build tool (which means that if you reference the XSDs in your project and specify the custom tool, it will automatically update the code as you update the XSD). All in all saved us a lot of work. A quick summary of the other tools i looked at: * [Dingo](http://dingo.sourceforge.net/) - Seems to be more aligned to Java * XSDCodeGen - More of a demo on how to write a custom build tool * [CodeXS](http://www.bware.biz/CodeXS/) - Quite a good tool, but less integration, features and no longer maintained * XSDObjectGen - No longer maintained, less functionality than current xsd.exe * XSDClassGen - Could not locate it * [OXM Library](http://oxmlibrary.codeplex.com/) - **Recommend** looking at this project, maintained and great functionality * [LINQ to XSD](http://linqtoxsd.codeplex.com/) - Very **cool** project, but not what i was looking for **Addendum:** If you do decided to go ahead with XSD2Code, there are a number of issues i found working with the command-line tool. In particular, there are some bugs with the argument processing that require some arguments to be in a certain order as well as some undocumented dependencies (eg - automatic parameters & .NET version are order specific and dependent). The following are the steps i used to generate the code using XSD2Code and then cleanup the output - take the bits that apply to you as necessary: Run the following batch file to generate the initial code, changing the paths to the correct locations: ``` @echo off set XsdPath=C:\schemas set OutPath=%XsdPath%\Code set ExePath=C:\Progra~1\Xsd2Code set Namespace=InsertNamespaceHere echo.Starting processing XSD files ... for /f %%a IN ('dir %XsdPath%\*.xsd /a-d /b /s') do call:ProcessXsd %%a echo.Finished processing XSD files ... echo.&pause& goto:eof :ProcessXsd %ExePath%\Xsd2Code %~1 %Namespace% %XsdPath%\Code\%~n1%.cs /pl Net35 /if- /dc /sc /eit echo.Processed %~n1 goto:eof ``` Perform the following steps to tidy up the generated code, as necessary: 1. Regex replace - current project, case, whole word - **[System.Runtime.Serialization.DataContractAttribute(Name:b*=:b*:q,:b*Namespace:b*=:b\*{:q})] with [DataContract(Namespace = \1)]\*\* 2. Replace - current project, case, whole word - **[System.Runtime.Serialization.DataMemberAttribute()]** with **[DataMember]** 3. Regex replace - current project, case, whole word - **System.Nullable<{:w}>** with **\1?** 4. Regex replace - open documents, case, whole word - **{:w}TYPE** with **\1** 5. Replace - open documents, case, whole word - **System.DateTime** with **DateTime**, then add missing using statements 6. Replace - open documents, case, whole word - **[System.Xml.Serialization.XmlIgnoreAttribute()]** with **[XmlIgnore]** 7. Replace - current project - **System.Xml.Serialization.XmlArrayAttribute** with **XmlArray** 8. Replace - current project - **System.Xml.Serialization.XmlArrayItemAttribute** with **XmlArrayItem** 9. Regex replace - current project - **,[:Wh]+/// &lt;remarks/&gt;** with **,**
I have not yet checked this out, but [Linq2XSD](http://blogs.msdn.com/marcelolr/archive/2009/06/03/linq-to-xsd-on-codeplex.aspx) might be a useful alternative. I'm going to give this one a shot. LINQ with XSD generation would be better than any of these tools you mentioned - provided it works nicely.
Comparison of XSD Code Generators
[ "", "c#", "xsd", "code-generation", "" ]
My users are presented a basically a stripped down version of a spreadsheet. There are textboxes in each row in the grid. When they change a value in a textbox, I'm performing validation on their input, updating the collection that's driving the grid, and redrawing the subtotals on the page. This is all handled by the `OnChange` event of each textbox. When they click the `Save` button, I'm using the button's `OnClick` event to perform some final validation on the amounts, and then send their entire input to a web service, saving it. At least, that's what happens if they tab through the form to the `Submit` button. The problem is, if they enter a value, then immediately click the save button, `SaveForm()` starts executing before `UserInputChanged()` completes -- a race condition. My code does not use `setTimeout`, but I'm using it to simulate the sluggish `UserInputChanged` validation code: ``` <script> var amount = null; var currentControl = null; function UserInputChanged(control) { currentControl = control; // use setTimeout to simulate slow validation code setTimeout(ValidateAmount, 100); } function SaveForm() { // call web service to save value document.getElementById("SavedAmount").innerHTML = amount; } function ValidateAmount() { // various validationey functions here amount = currentControl.value; // save value to collection document.getElementById("Subtotal").innerHTML = amount; } </script> Amount: <input type="text" onchange="UserInputChanged(this)"> Subtotal: <span id="Subtotal"></span> <button onclick="SaveForm()">Save</button> Saved amount: <span id="SavedAmount"></span> ``` I don't think I can speed up the validation code -- it's pretty lightweight, but apparently, slow enough that code tries to call the web service before the validation is complete. On my machine, ~95ms is the magic number between whether the validation code executes before the save code begins. This may be higher or lower depending on the users' computer speed. Does anyone have any ideas how to handle this condition? A coworker suggested using a semaphore while the validation code is running and a busy loop in the save code to wait until the semaphore unlocks - but I'd like to avoid using any sort of busy loop in my code.
Use the semaphore (let's call it StillNeedsValidating). if the SaveForm function sees the StillNeedsValidating semaphore is up, have it activate a second semaphore of its own (which I'll call FormNeedsSaving here) and return. When the validation function finishes, if the FormNeedsSaving semaphore is up, it calls the SaveForm function on its own. In jankcode; ``` function UserInputChanged(control) { StillNeedsValidating = true; // do validation StillNeedsValidating = false; if (FormNeedsSaving) saveForm(); } function SaveForm() { if (StillNeedsValidating) { FormNeedsSaving=true; return; } // call web service to save value FormNeedsSaving = false; } ```
Disable the save button during validation. Set it to disabled as the first thing validation does, and re-enable it as it finishes. e.g. ``` function UserInputChanged(control) { // --> disable button here --< currentControl = control; // use setTimeout to simulate slow validation code (production code does not use setTimeout) setTimeout("ValidateAmount()", 100); } ``` and ``` function ValidateAmount() { // various validationey functions here amount = currentControl.value; // save value to collection document.getElementById("Subtotal").innerHTML = amount; // update subtotals // --> enable button here if validation passes --< } ``` You'll have to adjust when you remove the setTimeout and make the validation one function, but unless your users have superhuman reflexes, you should be good to go.
Avoiding a Javascript race condition
[ "", "javascript", "dom-events", "race-condition", "" ]
I always tell in c# a variable of type double is not suitable for money. All weird things could happen. But I can't seem to create an example to demonstrate some of these issues. Can anyone provide such an example? (edit; this post was originally tagged C#; some replies refer to specific details of `decimal`, which therefore means [`System.Decimal`](http://msdn.microsoft.com/en-us/library/system.decimal.aspx)). (edit 2: I was specific asking for some c# code, so I don't think this is language agnostic only)
Very, very unsuitable. Use decimal. ``` double x = 3.65, y = 0.05, z = 3.7; Console.WriteLine((x + y) == z); // false ``` (example from Jon's page [here](http://csharpindepth.com/Articles/General/FloatingPoint.aspx) - recommended reading ;-p)
You will get odd errors effectively caused by rounding. In addition, comparisons with exact values are extremely tricky - you usually need to apply some sort of epsilon to check for the actual value being "near" a particular one. Here's a concrete example: ``` using System; class Test { static void Main() { double x = 0.1; double y = x + x + x; Console.WriteLine(y == 0.3); // Prints False } } ```
Is a double really unsuitable for money?
[ "", "c#", "language-agnostic", "decimal", "currency", "" ]
The db I am querying from is returning some null values. How do I safeguard against this and make sure the caller gets some data back. The code I have is: Using DataReader ``` while (dr.Read()) { vo = new PlacementVO(); vo.PlacementID = dr.GetString(0); ``` If I use dataset, I can do it like this. ``` obj.email = (row["email"] == DBNull.Value) ? String.Empty : Convert.ToString(row["email"]); ``` Thanks
There is `IsDBNull(int ordinal)` if you are using ordinals (which you are). So: ``` string email = reader.IsDBNull(0) ? null : reader.GetString(0); ``` If you are working with string column names, then to use this you'll have to call `GetOrdinal` first, for example: ``` string GetSafeString(this IDataReader reader, string name) { int index = reader.GetOrdinal(name); return reader.IsDBNull(0) ? null : reader.GetString(0); } ``` Of course, it is faster to only look up ordinals once, not once per row. A similar approach can be used for `int?` etc, or using a default instead of a null.
Another way is to add **isnull**(*column which can be null* , *replacement when it is null*) to the actual SQL query. Less code and works without doing anything in the client code.
Dealing with null values from DB
[ "", "c#", ".net", "" ]
What is best language to learn next to Java? Criteria for this secondary language are: 1. High potential of being the "next big thing". e.g. If the market for Java open positions *hypothetically* dies/dwindles, what is the next programming language that will have a bigger market for open positions? Another way to frame this question is: If I own a small company that implements solutions in Java, what is the other language that I should use? 2. Can produce web applications. 3. Can produce desktop applications. 4. Easy and fun to learn. 5. Wide range of available libraries and frameworks (free or open source) that enhance and speed up your solutions.
Python almost meets all of them, but I don't know about being "the next big thing", but hey, Google uses it, and I think its popularity is raising. It's a scripting language, btw. I use it for web applications (using [django](http://djangoproject.com)), and you can definitely create desktop applications with it (although I haven't done that myself). It is easy and fun! (although this is quite subjective, but it's tons easier and "funner" than Java)
For employability: Any of the .Net languages, probably C#. Then you're well set for most potential customers. For stretching yourself: something functional (F# to cover .Net too?), or something Lisp, or Smalltalk - was once the next big thing but it probably never will be again, but still a language that changed signficantly my approach to programming in other languages.
Java Developer looking for a 2nd'ary language to play with
[ "", "java", "" ]