Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Which of these solutions is preferred? For a List: ``` List<ExampleInfo> exampleList = new List<ExampleInfo>(); public class ExampleInfo { internal ExampleInfo() { } /* Business Properties */ public int Id { get; set; } public string Type { get; set; } public decimal Total { get; set; } } ``` I wish to get subtotals based off the 'Total' value. Option 1: ``` var subtotal1 = exampleList.Where(x => x.Type == "Subtype1").Sum(x => x.Total); var subtotal2 = exampleList.Where(x => x.Type == "Subtype2").Sum(x => x.Total); ``` Option 2: ``` decimal subtotal1 = 0m; decimal subtotal2 = 0m; foreach (ExampleInfo example in exampleList) { switch (example.Type) { case "Subtype1": subtotal1 += example.Total; break; case "Subtype2": subtotal2 += example.Total; break; default: break; } } ``` The list will be <10 items in most cases. **Edit:** Chris raised a very good point I did not mention. The program is already using .NET Framework 3.5 SP1 so compatibility isn't an important consideration here.
Both of these examples have duplicated code, and both aren't ready for a change on `Type` - what if it had three values? What if it had 30? You could use linq to group by it and get the total: ``` var totals = from p in exampleList group p by p.Type into g select new { Type = g.Key, Total = g.Sum(p => p.Total ) }; ``` So `totals` is a collection of objects with the properties `Type` and `Total`
Regardless of list size, if you're targeting .NET 3.5 I'd go with LINQ, if only for readability. I am a great fan of writing what you mean, not how it's done and LINQ makes this very easy in such cases. You can probably even pull the calculations into a single LINQ statement, grouping by Type. That way you won't have two loops for LINQ but only one as in the second example: ``` var subtotals = from x in exampleList group x by x.Type into g select new { Type = x.Key, SubTotal = g.Sum(x => x.Total) }; ``` (Not entirely sure whether the code works as it, it's just a quick adaption from one of the [101 LINQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx). Syntax should be ok, though.)
C# Linq statements or a foreach() for totalling subsets?
[ "", "c#", "linq", "foreach", "" ]
I want to access a postgreSQL database that's running on a remote machine, from Python in OS/X. Do I have to install postgres on the mac as well? Or will psycopg2 work on its own. Any hints for a good installation guide for psycopg2 for os/x?
macports tells me that the psycopg2 package has a dependency on the postgres client and libraries (but not the db server). If you successfully installed psycopg, then you should be good to go. If you haven't installed yet, consider using macports or fink to deal with dependency resolution for you. In most cases, this will make things easier (occasionally build problems erupt).
psycopg2 requires the PostgreSQL libpq libraries and the pg\_config utility, which means you need a decent chunk of PostgreSQL to be installed. You could install Postgres and psycopg2 via MacPorts, but the version situation is somewhat messy--you may need to install a newer Python as well, particularly if you want to use a recent version of the PostgreSQL libraries. Depending on what you want to do, for example if you have some other Python you want to use, it may be easier to grab a more standard PostgreSQL install and just build psycopg2 yourself. That's pretty easy if you've already got gcc etc. installed, typically the only build issue is making sure it looks in the right place for the libpq include files. See [Getting psycopg2 to work on Mac OS X Leopard](http://jasonism.org/weblog/2008/nov/06/getting-psycopg2-work-mac-os-x-leopard/) and [Installing psycopg2 on OS X](http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/) for a few recipes covering the usual build issues you might run into.
psycopg2 on OSX: do I have to install PostgreSQL too?
[ "", "python", "macos", "postgresql", "" ]
As a result of another question I asked here I want to use a HashSet for my objects I will create objects containing a string and a reference to its owner. ``` public class Synonym { private string name; private Stock owner; public Stock(string NameSynonym, Stock stock) { name=NameSynonym; owner=stock } // [+ 'get' for 'name' and 'owner'] } ``` I understand I need a comparer , but never used it before. Should I create a separate class? like: ``` public class SynonymComparer : IComparer<Synonym> { public int Compare(Synonym One, Synonym Two) { // Should I test if 'One == null' or 'Two == null' ???? return String.Compare(One.Name, Two.Name, true); // Caseinsesitive } ``` } I prefer to have a function (or nested class [maybe a singleton?] if required) being PART of class Synonym instead of another (independent) class. Is this possible? About usage: As i never used this kind of thing before I suppose I must write a Find(string NameSynonym) function inside class Synonym, but how should I do that? ``` public class SynonymManager { private HashSet<SynonymComparer<Synonym>> ListOfSynonyms; public SynonymManager() { ListOfSymnonyms = new HashSet<SynonymComparer<Synonym>>(); } public void SomeFunction() { // Just a function to add 2 sysnonyms to 1 stock Stock stock = GetStock("General Motors"); Synonym otherName = new Synonym("GM", stock); ListOfSynonyms.Add(otherName); Synonym otherName = new Synonym("Gen. Motors", stock); ListOfSynonyms.Add(otherName); } public Synonym Find(string NameSynomym) { return ListOfSynonyms.??????(NameSynonym); } } ``` In the code above I don't know how to implement the 'Find' method. How should i do that? Any help will be appreciated (PS If my ideas about how it should be implemented are completely wrong let me know and tell me how to implement)
A HashSet doesn't need a `IComparer<T>` - it needs an `IEqualityComparer<T>`, such as ``` public class SynonymComparer : IEqualityComparer<Synonym> { public bool Equals(Synonym one, Synonym two) { // Adjust according to requirements. return StringComparer.InvariantCultureIgnoreCase .Equals(one.Name, two.Name); } public int GetHashCode(Synonym item) { return StringComparer.InvariantCultureIgnoreCase .GetHashCode(item.Name); } } ``` However, your current code only compiles because you're creating a set of *comparers* rather than a set of *synonyms*. Furthermore, I don't think you really want a set at all. It seems to me that you want a dictionary or a lookup so that you can find the synonyms for a given name: ``` public class SynonymManager { private readonly IDictionary<string, Synonym> synonyms = new Dictionary<string, Synonym>(); private void Add(Synonym synonym) { // This will overwrite any existing synonym with the same name. synonyms[synonym.Name] = synonym; } public void SomeFunction() { // Just a function to add 2 synonyms to 1 stock. Stock stock = GetStock("General Motors"); Synonym otherName = new Synonym("GM", stock); Add(otherName); ListOfSynonyms.Add(otherName); otherName = new Synonym("Gen. Motors", stock); Add(otherName); } public Synonym Find(string nameSynonym) { // This will throw an exception if you don't have // a synonym of the right name. Do you want that? return synonyms[nameSynonym]; } } ``` Note that there are some questions in the code above, about how you want it to behave in various cases. You need to work out *exactly* what you want it to do. EDIT: If you want to be able to store multiple stocks for a single synonym, you *effectively* want a `Lookup<string, Stock>` - but that's immutable. You're probably best storing a `Dictionary<string, List<Stock>>`; a list of stocks for each string. In terms of not throwing an error from `Find`, you should look at `Dictionary.TryGetValue` which doesn't throw an exception if the key isn't found (and also returns whether or not the key *was* found); the mapped value is "returned" in an out parameter.
Wouldn't it be more reasonable to scrap the `Synonym` class entirely and have list of synonyms to be a `Dictonary` (or, if there is such a thing, `HashDictionary`) of strings? (I'm not very familiar with C# types, but I hope this conveys general idea) The answer I recommend (edited, now respects the case): ``` IDictionary<string, Stock>> ListOfSynonyms = new Dictionary<string,Stock>>(); IDictionary<string, string>> ListOfSynForms = new Dictionary<string,string>>(); class Stock { ... Stock addSynonym(String syn) { ListOfSynForms[syn.ToUpper()] = syn; return ListOfSynonyms[syn.ToUpper()] = this; } Array findSynonyms() { return ListOfSynonyms.findKeysFromValue(this).map(x => ListOfSynForms[x]); } } ... GetStock("General Motors").addSynonym('GM').addSynonym('Gen. Motors'); ... try { ... ListOfSynonyms[synonym].name ... } catch (OutOfBounds e) { ... } ... // output everything that is synonymous to GM. This is mix of C# and Python ... GetStock('General Motors').findSynonyms() // test if there is a synonym if (input in ListOfSynonyms) { ... } ```
How to use Comparer for a HashSet
[ "", "c#", "templates", "dictionary", "hashset", "" ]
Using PHP 5.2.6 in XAMPP : I read about sql injections [here](https://www.php.net/mysql_real_escape_string) and tried that with the following login form : ``` <html><body> <form method='post' action='login.php'> <input type='text' name='user'/> <input type='text' name='pass'/> <input type='submit'/> </form> </body></html> ``` and php code : ``` <?php $user = $_POST['user']; $pass = $_POST['pass']; $query = "Select * from users where user='$user' AND pass='$pass'"; echo $query; mysql_connect('localhost','root',''); mysql_select_db('test'); $res = mysql_query($query); if($res) $row = mysql_fetch_assoc($res); if($row) echo 'yes'; ?> ``` What I found out was, the $pass variable already had all the special characters escaped. So, is there no need to use the mysql`_`real`_`escape`_`string in PHP 5.2.6 then?
It is likely your PHP server is configure to use [Magic Quotes](http://www.php.net/magic_quotes). A deprecated setting in PHP that automatically escapes all incoming data in a PHP script. It's deprecated and will be removed in PHP 6. [Here are Zend's reasons](http://nl2.php.net/manual/en/security.magicquotes.whynot.php) for removing Magic Quotes. It's better to not rely on 'magic' that makes many things work but breaks others. Explicitly escaping your input is more reliable and makes you design better code. For example, not all input needs to be escaped in the same way.
The values may be escaped due to [Magic Quotes](https://www.php.net/magic_quotes) being enabled in your server configuration. Magic quotes are considered very bad, basically for the exact reason you mention. It is not safe to rely on a feature that may or may not be on to automagically escape your incoming data. It is *much* better to do it yourself at run time. For more information on Magic quotes, and why they're bad, and how to disable them, take a look at a few of these SO questions/answers: * [Magic quotes in PHP](https://stackoverflow.com/questions/220437/magic-quotes-in-php) * [How to turn off magic quotes on shared hosting?](https://stackoverflow.com/questions/517008/how-to-turn-off-magic-quotes-on-shared-hosting) * [PHP protecting itself from SQL injections?](https://stackoverflow.com/questions/648307/php-protecting-itself-from-sql-injections)
Sql injection attempt PHP 5.2.6
[ "", "php", "mysql-real-escape-string", "" ]
Can you please elaborate why this code crashes at the places mentioned? I am a bit stumped on this. I guess that it has got something to do with `sizeof(int)` but I am not so sure. Can anybody explain? ``` class Base { public: virtual void SomeFunction() { printf("test base\n"); } int m_j; }; class Derived : public Base { public: void SomeFunction() { printf("test derive\n"); } private: int m_i; }; void MyWonderfulCode(Base baseArray[]) { baseArray[0].SomeFunction(); //Works fine baseArray[1].SomeFunction(); //Crashes because of invalid vfptr baseArray[2].SomeFunction(); //Crashes because of invalid vfptr baseArray[3].SomeFunction(); //Works fine baseArray[4].SomeFunction(); //Crashes because of invalid vfptr baseArray[5].SomeFunction(); //Crashes because of invalid vfptr baseArray[6].SomeFunction(); //Works fine baseArray[7].SomeFunction(); //Crashes because of invalid vfptr baseArray[8].SomeFunction(); //Crashes because of invalid vfptr baseArray[9].SomeFunction(); //Works fine } int _tmain(int argc, TCHAR* argv[]) { Derived derivedArray[10]; MyWonderfulCode(derivedArray); return 0; } ```
Quote from this FAQ: [Is array of derived same as as array of base?](https://isocpp.org/wiki/faq/proper-inheritance#array-derived-vs-base) > Derived is larger than Base, the pointer arithmetic done with 2nd object baseArray is > incorrect: the compiler uses sizeof(Base) when computing the address > for 2nd object, yet the array is an array of Derived, which means > the address computed (and the subsequent invocation of > member function f()) isn’t even at the beginning of any object! It’s > smack in the middle of a Derived object.
`sizeof(Derived)` is greater than `sizeof(Base)`. That's the reason. Generally, indexing an array of `Foo` objects at index `i` works the following way: ``` element_address = array_base_address + i * sizeof(Foo) ``` You can see how this indexing breaks if the array elements are not of expected size. Why it works for some indices is because sometimes the calculated element address points to a valid object in memory (but it's not actually the `i`th object).
Why does this code crash at the places mentioned?
[ "", "c++", "arrays", "virtual", "" ]
Is there a way that I can add alias to python for encoding. There are sites on the web that are using the encoding 'windows-1251' but have their charset set to win-1251, so I would like to have win-1251 be an alias to windows-1251
The `encodings` module is not well documented so I'd instead use `codecs`, which [is](http://docs.python.org/library/codecs.html): ``` import codecs def encalias(oldname, newname): old = codecs.lookup(oldname) new = codecs.CodecInfo(old.encode, old.decode, streamreader=old.streamreader, streamwriter=old.streamwriter, incrementalencoder=old.incrementalencoder, incrementaldecoder=old.incrementaldecoder, name=newname) def searcher(aname): if aname == newname: return new else: return None codecs.register(searcher) ``` This is Python 2.6 -- the interface is different in earlier versions. If you don't mind relying on a specific version's undocumented internals, @Lennart's aliasing approach is OK, too, of course - and indeed simpler than this;-). But I suspect (as he appears to) that this one is more maintainable.
``` >>> import encodings >>> encodings.aliases.aliases['win_1251'] = 'cp1251' >>> print '\xcc\xce\xd1K\xc2\xc0'.decode('win-1251') MOCKBA ``` Although I personally would consider this monkey-patching, and use my own conversion table. But I can't give any good arguments for that position. :)
Adding encoding alias to python
[ "", "python", "unicode", "character-encoding", "" ]
I'm in the process of developing my first major project. It's a light-weight content management system. I have developed all of my own framework for the project. I'm sure that will attract many flames, and a few 'tut-tut's, but it seems to be doing quite well so far. I'm seeing page generation times of anywhere from 5-15 milliseconds. (An example, just in case my numbers are wrong, is 0.00997686386108 seconds). I want to make sure that the application is as efficient as possible. While it looks good in my testing environment, I want to be sure that it will perform as well as possible in the real world. Should I be concerned about these numbers - and thus, take the time to fine tune MySQL and my interaction with it? **Edit:** Additionally, are there some tools or methods that people can recommend for saturating a system, and reporting the results? **Additional Info:** My 'testing' system is a spare web hosting account that I have over at BlueHost. Thus, I would imagine that any performance I see (positive or negative) would be roughly indicative of what I would see in the 'real world'.
Performing well in your testing environment is a good start, but there's other issues you'll need to think about as well (if you haven't already). Here's a couple I can think of off the top of my head: 1. How does your app perform as data sizes increase? Usually a test environment has very little data. With lots of data, things like poorly optimized queries, missing indexes, etc. start to cause issues where they didn't before. Performance can start to degrade exponentially with respect to data size if things are not designed well. 2. How does your app perform under load? Sometimes apps perform great with one or two users, but resource contention or concurrency issues start to pop up when lots of users get involved.
You're doing very well at 5-15 ms. You're not going to know how it performs under load by any method other than [throwing load at it](http://en.wikipedia.org/wiki/Category:Load_testing_tools), though.
Are these generation times acceptable for php-mysql? Where can I improve? Where should I improve?
[ "", "php", "mysql", "performance", "" ]
I have the following string: `\\\?\hid#vid_04d8pid_003f#62edf110800000#{4d1e55b2-f16f-11cf-88cb-001111000030}` stored in a string variable (from a function call) called `devPathName` and the following defined: `const string myDevice = @"vid_04d8pid_003f";` but the following code always evaluates to false: ``` Boolean test = true; test = devPathName.Contains(myDevice); statusLabel.Text += "\n\tThe value of test: " + test.ToString(); ```
Assuming that you've already checked for letter "O" vs digit "0" and similar things, I'd suggest that the string you're seeing in the string variable `devPathName` is being encoded for display and isn't quite what you think it is. For example, if the string contains the character `\x000d` (`Control-M`), the Visual Studio debugger will display this as `\r` when you inspect the value of the string. Or, for another example, if the string contains the sequence 3504 (three-five-zero-four) but you instead search for `35O4` (three-five-oh-four) then you'll not find a match. (Depending on your font, you may not be able to see differences between some characters. Compare "0O1lB8S5" with "`0O1lB8S5`" in different fonts to see what I mean.)
When I stick your code into C#, the compiler doesn't like the "\h" part of your long string. It says, "unrecognized escape sequence". Could that be your problem? Oh, and if I put a "@" before the long string, the contains() method returns true. HTH, -Dan
Why is string.contains() returning false?
[ "", "c#", ".net", "string", "" ]
I have a page with a lot of textboxes. When someone clicks a link, i want a word or two to be inserted where the cursor is, or appended to the textbox which has the focus. For example, if the cursor/focus is on a textbox saying 'apple' and he clicks a link saying '[email]', then i want the textbox to say, 'apple bob@example.com'. How can I do this? Is this even possible, since what if the focus is on a radio/dropdown/non textbox element? Can the last focused on textbox be remembered?
Use this, from [here](http://web.archive.org/web/20110102112946/http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/): ``` function insertAtCaret(areaId, text) { var txtarea = document.getElementById(areaId); if (!txtarea) { return; } var scrollPos = txtarea.scrollTop; var strPos = 0; var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false)); if (br == "ie") { txtarea.focus(); var range = document.selection.createRange(); range.moveStart('character', -txtarea.value.length); strPos = range.text.length; } else if (br == "ff") { strPos = txtarea.selectionStart; } var front = (txtarea.value).substring(0, strPos); var back = (txtarea.value).substring(strPos, txtarea.value.length); txtarea.value = front + text + back; strPos = strPos + text.length; if (br == "ie") { txtarea.focus(); var ieRange = document.selection.createRange(); ieRange.moveStart('character', -txtarea.value.length); ieRange.moveStart('character', strPos); ieRange.moveEnd('character', 0); ieRange.select(); } else if (br == "ff") { txtarea.selectionStart = strPos; txtarea.selectionEnd = strPos; txtarea.focus(); } txtarea.scrollTop = scrollPos; } ``` ``` <textarea id="textareaid"></textarea> <a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a> ```
Maybe a shorter version, would be easier to understand? ``` $('#btn').click(function() { const element = $('#txt'); const caretPos = element[0].selectionStart; const textAreaTxt = element.val(); const txtToAdd = "stuff"; element.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) ); }); ``` ``` <script src="https://code.jquery.com/jquery-3.6.3.min.js" crossorigin="anonymous"></script> <textarea id="txt" rows="15" cols="70">There is some text here.</textarea> <input type="button" id="btn" value="OK" /> ``` I wrote this in response to [How to add a text to a textbox from the current position of the pointer with jquery?](https://stackoverflow.com/questions/15976574/how-to-add-a-text-to-a-textbox-from-the-current-position-of-the-pointer-with-jqu)
Inserting a text where cursor is using Javascript/jquery
[ "", "javascript", "jquery", "" ]
I say "project file" in the loosest sense. I have a few python projects that I work on with ropemacs using emacs W32 for Windows. What would be ideal is if I could have an icon I could click on on my desktop to open up emacs, open up the rope project, and set the speed bar in the top-level directory of that project. Then I could also maybe have a way to open up the next project in its own emacs set up the same way (but for that project). Of course, it's also acceptable if there were an emacs command or a shell command I could use to achieve the same effect instead of an icon on my desktop. Is there any way to do this? I have absolutely no elisp-fu. :-(
You could get everything set up the way you want for a project, then use the answer I posted about using desktop.el and named sessions: [What alternate session managers are available for Emacs?](https://stackoverflow.com/questions/847962/what-alternate-session-managers-are-available-for-emacs/849180#849180)
I'm actually working on a solution to this very problem. I always had a group of files I wanted to open/close at the same time, plus do things like open a magit-status window, a dired buffer, etc. I've started on my own project mode called metaproject. It's in the very early stages, but is functional enough that I'm using it for project groups at work now. Check it out here: <http://nafai77.github.com/metaproject/> What's in git is pretty stable, though sparsely documented. I'm going to start working on it again here soon. I currently have the basics of a small plug-in architecture, so you can register custom actions that can be done on project open.
Is there any way to create a "project file" in Emacs?
[ "", "python", "windows", "emacs", "elisp", "ropemacs", "" ]
Can anyone help with an aggregate function.. MIN. I have a car table that i want to return minimum sale price and minimum year on a tbale that has identical cars but different years and price ... Basically if i removed Registration (contains a YEAR) from the group by and select the query works but if i leave it in then i get 3 cars returned which are exactly the same model,make etc but with different years.. But i am using MIN so it should return 1 car with the year 2006 (the minimum year between the 3 cars) The MIN(SalePrice) is working perfectly .. its the registraton thats not owrking.. Any ideas? SELECT MIN(datepart(year,[Registration])) AS YearRegistered, MIN(SalePrice), Model, Make FROM [VehicleSales] GROUP BY datepart(year,[Registration]), Model, Make
IF I have correctly understood what you are looking for, you should query: ``` SELECT Model, Make, MIN(datepart(year,[Registration])) AS YearRegistered, MIN(SalePrice) FROM [VehicleSales] GROUP BY Model, Make ``` Hope it helps.
Turro answer will return the lowest registration year and the lowest price for (Model, Make), but this doesn't mean that lowest price will be for the car with lowest Year. Is it what you need? Or, you need one of those: 1. lowest price between the cars having lowest year 2. lowest year between the cars having lowest price -- EDITED --- > You are correct about the query, but I want to find the car make/model that gets cheaper the next year ;) That's why I made a comment. Imagine next situation ``` Porshe 911 2004 2000 Porshe 911 2004 3000 Porshe 911 2005 1000 Porshe 911 2005 5000 ``` You'll get result that will not really tell you if this car goes cheaper based on year or not. ``` Porshe 911 2004 1000 ``` I don't know how you'll tell if car gets cheaper next year based on one row without comparison with previous year, at least. P.S. I'd like to buy one of cars above for listed price :D
using MIN on a datepart with Group BY not working, returns different dates
[ "", "sql", "sql-server", "t-sql", "aggregate", "" ]
I'm using PHP and MySQL. I need to do a query: ``` DELETE FROM db1.players WHERE acc NOT IN (SELECT id FROM db2.accounts) ``` The problem is, that db1 and db2 are located on different servers. What is the fastest solution for such problem? To be precise: I'm using 2 connections, so I think I can't use one query for it.
You will either have to save the list you want to an array and compare it with the other database or You can make a [federated table](http://dev.mysql.com/doc/refman/5.0/en/federated-storage-engine.html) and make it seem like the query is running on 1 database.
I don't know if it is the fastest, but I would create a temporary table on db2 containing account ids, export that table to db1 and run the query there. For the exporting part you can either use mysql builtin export/import functions, where you would have to consider finding an unused table name or use the CSV-[export](http://dev.mysql.com/doc/refman/5.1/en/select.html)/[import](http://dev.mysql.com/doc/refman/5.1/en/load-data.html) of mysql. If the expected number of results from the inner query is reasonably small, you can transfer from within PHP using strings: ``` $ids = query($db1, "SELECT GROUP_CONCAT(id) FROM accounts"); query($db2, "DELETE FROM players WHERE acc NOT IN ($ids)"); ```
Delete rows across multiple databases
[ "", "php", "mysql", "" ]
When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse. My project structure is the following: * parent project (pom-packaging) + Web project (war-packaging - my JUnit-test is in here) + Flex project + Configuration project --- edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries. Here's my JUnit's run-configuration: [alt text http://www.walkner.biz/\_temp/runconfig.png](http://www.walkner.biz/_temp/runconfig.png) --- Testclass (but as I said; it doesn't work with a simple HelloWorld either...): ``` import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import biz.prognoserechnung.domain.User; import biz.prognoserechnung.domain.UserRepository; import biz.prognoserechnung.domain.hibernate.UserHibernateDao; public class UserDaoTest { /** * the applicationcontext. */ private ApplicationContext ctx = null; /** * the user itself. */ private User record = null; /** * Interface for the user. */ private UserRepository dao = null; @Before public void setUp() throws Exception { String[] paths = { "WEB-INF/applicationContext.xml" }; ctx = new ClassPathXmlApplicationContext(paths); dao = (UserHibernateDao) ctx.getBean("userRepository"); } @After public void tearDown() throws Exception { dao = null; } @Test public final void testIsUser() throws Exception { Assert.assertTrue(dao.isUser("John", "Doe")); } @Test public final void testIsNoUser() throws Exception { Assert.assertFalse(dao.isUser("not", "existing")); Assert.assertFalse(dao.isUser(null, null)); Assert.assertFalse(dao.isUser("", "")); } } ```
I've come across that situation several times and, after a lot of attempts, I found the solution. *Check your project build-path and enable specific output folders for each folder.* Go one by one though each source-folder of your project and set the output folder that maven would use. For example, your web project's `src/main/java` should have `target/classes` under the web project, test classes should have `target/test-classes` also under the web project and so. Using this configuration will allow you to execute unit tests in eclipse. Just one more advice, if your web project's tests require some configuration files that are under the resources, be sure to include that folder as a source folder and to make the proper build-path configuration.
Carlos approach helped! [Eclipse - java.lang.ClassNotFoundException](https://stackoverflow.com/questions/1052978/eclipse-java-lang-classnotfoundexception/1062435#1062435) Try to check the classpath of the junit run configuration: 1. Open your run configurations 2. Click on the jUnit-Test you want to start 3. go to the classpath tab 4. Try to add a folder (click on user entries, click on advanced, click on add folders, click on ok and search the outputfolder for your test classes(those you find under projektproperties java build path, source)) works for me.
Eclipse - java.lang.ClassNotFoundException
[ "", "java", "eclipse", "exception", "maven-2", "" ]
Can anyone help point me in the right direction - I have the following in a function: document.form1.textbox1.style.display = 'none'; which works fine. But I'm trying to find a list of all the possible 'elements'(?) that could come after style, e.g. '.display=', '.length=' etc, but I don't know the proper name/terms so the searches i'm doing are not returning what I want. Any ideas? Thanks in advance! :) leddy
See the [CSS spec](http://www.w3.org/TR/CSS21/propidx.html). Convert hyphenated-names to camelCase (e.g. backgroundColor not background-color). Also see the [DOM spec](http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-extended-h2). That said, in most cases it is usually better to modify the `element.className` (and have a pre–written, external style sheet) instead of modifying the `element.style.*`
Are you looking for [this](http://www.w3schools.com/HTMLDOM/dom_obj_style.asp)? It also shows browser compatibility.
javascript - document.form.textbox.style....can't seem to find this?
[ "", "javascript", "" ]
I would like to feed the result of a simple SQL query (something like: `select SP_NUMBER from SERVICE_PACK`) which I run inside my ant script (using the `sql` task) back into an ant property (e.g. `service.pack.number`). The `sql` task can output to a file, but is there a more direct way?
Although I would have preferred not creating a file, I eventually went with the following solution: The sql task is called as follows ``` <sql ... print="yes" output="temp.properties" expandProperties="true" showheaders="false" showtrailers="false" > <![CDATA[ select 'current.sp.version=' || NAME from SERVICE_PACK; select 'current.major.version=' || NAME from VERSION; ]]> </sql> ``` The generated properties file will contain: ``` current.sp.version=03 current.major.version=5 ``` Then you just load the properties file and delete it: ``` <property file="temp.properties" /> <delete file="temp.properties" /> <echo message="Current service pack version: ${current.sp.version}" /> <echo message="Current major version: ${current.major.version}" /> ``` This works, and everything is right there in the ant script (even if it's not the prettiest thing in the world!).
Perhaps the Ant [exec](http://ant.apache.org/manual/Tasks/exec.html) task is more useful here ? You can execute a standalone and get the result in a property via `outputproperty`. You'll have to execute your SQL in some standalone fashion, unfortunately. Alternatively is it worth looking at the code to the Ant Sql task and modify it to accept an `outputproperty` ? It sounds a bit of a pain, but I think it could well be a very simple modification if you can't find anything more direct.
How can I read output of an sql query into an ant property?
[ "", "sql", "ant", "" ]
Where can I get a complete list of all multi-byte functions for PHP? I need to go through my application and switch the non MB string functions to the new mb functions.
How about: <https://www.php.net/manual-lookup.php?pattern=mb> <https://www.php.net/mbstring> <http://www.php.net/manual/en/ref.mbstring.php>
And for the "and switch the non MB string functions to the new mb functions" part of the question: You might be interested in <http://php.net/mbstring.overload>: > mbstring supports a 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb\_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.
Where can I get a complete list of all multi-byte functions for PHP?
[ "", "php", "multibyte", "mbstring", "" ]
I know in general it is a good practice to move as much processing as possible from Sql Server to the application (in my case ASP.NET). However what if the processing on the application level means passing 30+ extra parameters to the Sql Server. In this case is it worth moving the processing to the Sql Server? Here's the specific dilemma I am facing - which procedure will offer better performance overall? ``` CREATE PROCEDURE MyProc1 @id int AS BEGIN UPDATE MyTable SET somevalue1 = somevalue1 + 1, somevalue2 = somevalue2 + 1, somevalue3 = somevalue3 + 1, ... somevalueN = somevalueN + 1 WHERE id = @id END ``` Or ``` CREATE PROCEDURE MyProc2 @id int, @somevalue1 int, @somevalue2 int, @somevalue3 int, ... @somevalueN int AS BEGIN UPDATE MyTable SET somevalue1 = @somevalue1, somevalue2 = @somevalue2, somevalue3 = @somevalue3, ... somevalueN = @somevalueN WHERE id = @id END ``` I am using a managed hosting, but I guess it is valid to assume that Sql Server and ASP.NET runtime reside on the same machine, so the transfer of data between the two would probably be pretty fast/negligible(or is it). --- The 30 Parameters are basically totalNumberOfRatings for different items. So whenever a user of my web app gives a new rating for itemN then totalNumberOfRatingsItemN is incremented by 1. In most cases the rating will be given to several items (but not necessarily all), so totalNumberOfRatings is not the same for different items.
I'll make a wild guess that you've read that SQL Server is not the appropriate place to do math. I think SQL is quite appropriate for doing a handful of arithmetic operations and aggregate operations, like SUM. Only measuring both implementations in realistic load scenarios can say for sure. What SQL isn't appropriate for are things like multiple regression and matrix inversion. Moving incrementors to the application tier sounds to me like a micro-optimization that is unlikely to pay for itself. Implement the logic to increment the values in either tier that makes the code readable and maintainable.
> in general it is a good practice to move as much processing as possible from Sql Server to the application Says who? SQL Server is good at some things, not so good at others. Use your judgement. and by "application", do you mean * the web page * an application-service layer * an enterprise service bus component * a web service * something else? There are many choices... As to your specific question, incrementing 30 fields seems ludicrous. Passing 30 parms seems excessive. Some context is in order...
Sql Processing vs. ASP.NET Runtime processing
[ "", "asp.net", "sql", "sql-server-2008", "" ]
I have a Winforms `ComboBox` that contains instances of a custom class. When the items are first added to the Items collection of the `ComboBox`, the `ToString` method is call on each of them. However when the user changes the language the application is running in, the result of the `ToString` method changes. Therefore how can I get the `ComboBox` to call the `ToString` method on all items again without having to remove all items from the `ComboBox` and adding them back in?
Thanks svick, RefreshItems() work, however as it is protected (so can only be called by a subclass) I had to do ``` public class RefreshingComboBox : ComboBox { public new void RefreshItem(int index) { base.RefreshItem(index); } public new void RefreshItems() { base.RefreshItems(); } } ``` I have just had to do the same for a ToolStripComboBox, however it was a bit harder as you can not subclass the Combro box it contains, I did ``` public class RefreshingToolStripComboBox : ToolStripComboBox { // We do not want "fake" selectedIndex change events etc, subclass that overide the OnIndexChanged etc // will have to check InOnCultureChanged them selfs private bool inRefresh = false; public bool InRefresh { get { return inRefresh; } } public void Refresh() { try { inRefresh = true; // This is harder then it shold be, as I can't get to the Refesh method that // is on the embebed combro box. // // I am trying to get ToString recalled on all the items int selectedIndex = SelectedIndex; object[] items = new object[Items.Count]; Items.CopyTo(items, 0); Items.Clear(); Items.AddRange(items); SelectedIndex = selectedIndex; } finally { inRefresh = false; } } protected override void OnSelectedIndexChanged(EventArgs e) { if (!inRefresh) { base.OnSelectedIndexChanged(e); } } } ``` I had to do the same trip to stop unwanted events for the normal CombroBox, by overriding OnSelectedValueChanged, OnSelectedItemChanged and OnSelectedIndexChanged, as the code is the same as for the ToolStripComboBox I have not included it here.
You should be able to do this by calling the `RefreshItems()` method.
Dynamically changing the text of items in a Winforms ComboBox
[ "", "c#", ".net", "winforms", "combobox", "tostring", "" ]
I have a class that holds an "error" function that will format some text. I want to accept a variable number of arguments and then format them using `printf`. **Example:** ``` class MyClass { public: void Error(const char* format, ...); }; ``` The `Error` method should take in the parameters, call `printf`/`sprintf` to format it and then do something with it. I don't want to write all the formatting myself so it makes sense to try and figure out how to use the existing formatting.
Use `vfprintf`, like so: ``` void Error(const char* format, ...) { va_list argptr; va_start(argptr, format); vfprintf(stderr, format, argptr); va_end(argptr); } ``` This outputs the results to `stderr`. If you want to save the output in a string instead of displaying it use `vsnprintf`. (Avoid using `vsprintf`: it is susceptible to buffer overflows as it doesn't know the size of the output buffer.)
have a look at vsnprintf as this will do what ya want <http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/> you will have to init the va\_list arg array first, then call it. Example from that link: /\* vsprintf example \*/ ``` #include <stdio.h> #include <stdarg.h> void Error (char * format, ...) { char buffer[256]; va_list args; va_start (args, format); vsnprintf (buffer, 255, format, args); //do something with the error va_end (args); } ```
How to pass variable number of arguments to printf/sprintf
[ "", "c++", "printf", "variadic-functions", "" ]
For 6 years I've had a [random number generator](http://andrew.hedges.name/experiments/random/) page on my website. For a long time, it was the first or second result on Google for "random number generator" and has been used to decide dozens, if not hundreds of contests and drawings on discussion forums and blogs (I know because I see the referrers in my web logs and usually go take a look). Today, someone emailed me to tell me **it may not be as random as I thought.** She tried generating very large random numbers (e.g., between 1 and 10000000000000000000) and found that they were almost always the same number of digits. Indeed, I wrapped the function in a loop so I could generate thousands of numbers and sure enough, for very large numbers, **the variation was only about 2 orders of magnitude.** Why? Here is the looping version, so you can try it out for yourself: <http://andrew.hedges.name/experiments/random/randomness.html> It includes both a straightforward implementation taken from the [Mozilla Developer Network](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/random) and some code from 1997 that I swiped off a web page that no longer exists (Paul Houle's "Central Randomizer 1.3"). View source to see how each method works. I've read [here](https://stackoverflow.com/questions/424292) and [elsewhere](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVASCRIPT/java-script.html) about **Mersenne Twister.** What I'm interested in is why there wouldn't be greater variation in the results from JavaScript's built-in **Math.random** function. Thanks!
Given numbers between 1 and 100. * 9 have 1 digit (1-9) * 90 have 2 digits (10-99) * 1 has 3 digits (100) Given numbers between 1 and 1000. * 9 have 1 digit * 90 have 2 digits * 900 have 3 digits * 1 has 4 digits and so on. So if you select some at random, then that vast majority of selected numbers will have the same number of digits, because the vast majority of possible values have the same number of digits.
Your results are actually expected. If the random numbers are uniformly distributed in a range 1 to 10^n, then you would expect about 9/10 of the numbers to have n digits, and a further 9/100 to have n-1 digits.
How random is JavaScript's Math.random?
[ "", "javascript", "random", "" ]
I'm developing an interface for an add-on to a game. I can't use the game API (for several reasons including the fact that the code must be game-agnostic) and I need to get keyboard input from the user so I've decided to use a keyboard hook (WH\_KEYBOARD) to process user input when certain conditions are met. The problem is that while I can receive and process the input correctly, when my hook returns TRUE instead of [CallNextHookEx](http://msdn.microsoft.com/en-us/library/ms644974(VS.85).aspx) the system seems to take up a lot of time (well over 800ms) before letting things go on as expected and that's not acceptable because it doesn't even allow for a fluid typing experience. What I have to achieve is preventing the key press message to reach the WndProc, so the question is: what can I do to achieve my target without hurting the game performance so much that the result will be unacceptable? **EDIT:** due to specific requirements (games using anticheats which might create problems with my code despite it's not cheating-related) subclassing the active wndproc is not an option.
As much as I don't like answering my own question I've found the cause of the delay. The message pump of the games I've tested my code against was implemented with a while(PeekMessage) { GetMessage... } and removing the keyboard input message somehow caused GetMessage to block for sometime. Using PostMessage and WM\_NULL helped preventing GetMessage from blocking.
1. First you need your DLL to be injected into the target process, either by hooks, or by [any other way](http://www.codeproject.com/KB/threads/completeinject.aspx). 2. Find the window handle of interest. 3. Obtain the current window procedure of that window, by calling GetWindowLongPtr(wnd, GWLP\_WNDPROC), and save it. 4. Sub-class the window, by calling SetWindowLongPtr( wnd, GWLP\_WNDPROC, &NewWndProc ) where NewWndProc is your DLL-implemented message procedure. Inside NewWndProc you'll want to process keyboard messages (there're a dozen of them, type "keyboard input" in MSDN index, I can't post more then 1 link). For the rest of windows messages call the original window procedure you've saved during (3), and return the value it returned. Don't call it directly, use CallWindowProc instead. This way is not very reliable, some antivirus and anti-bot (e.g. "warden client") software might not like it, and debugging may be challenging. However it should work.
KeyboardProc returning TRUE causes performance drops
[ "", "c++", "windows", "winapi", "hook", "" ]
I have a MS SQL query that joins multiple tables and an example of the results are: ``` EmailAddress Column2 --------------------- ---------------- sean@abc.com Value1 sean@abc.com Value2 test@abc.com Value5 What I really want to achieve are the following results: EmailAddress Column2 --------------------- ------------------ sean@abc.com Value1, Value2 test@abc.com Value5 ``` There are other columns that are identical for each row with the same email address. Can anyone help me with the SQL to return distinct email addresses and concatenate the column2 information? Thanks for any feedback.
Try the answer to [this question](https://stackoverflow.com/questions/6899/is-there-a-way-to-create-a-mssql-function-to-join-multiple-rows-from-a-subquery)
In `SQL Server 2005+`: ``` WITH q AS ( SELECT 'sean@abc.com' AS address, 'Value1' AS value UNION ALL SELECT 'sean@abc.com', 'Value2' UNION ALL SELECT 'test@abc.com', 'Value5' ) SELECT ( SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY value) > 1 THEN ', ' ELSE '' END + value FROM q qi WHERE qi.address = qo.address FOR XML PATH('') ) FROM ( SELECT DISTINCT address FROM q ) qo ```
SQL Query Distinct Column Concatenate Other Column
[ "", "sql", "sql-server", "" ]
If I have an action where the result is a redirectAction to another action in a different class, is it possible to get validation errors to display in the resulting action? E.g. in the following example, if a user executes actionA (which has no views associated with it), and there are errors, is there any way to display those errors in the actionB result (foo.jsp)? Or am I going about this in completely the wrong way? ``` <package name="a" extends="struts-default" namespace="/a"> <action name="actionA" class="actionAClass"> <result name="input" type="redirectAction"> <param name="actionName">actionB</param> <param name="namespace">/b</param> </result> <result type="redirectAction"> <param name="actionName">actionB</param> <param name="namespace">/b</param> </result> </action> </package> <package name="b" extends="struts-default" namespace="/b"> <action name="actionB" class="actionBClass"> <result>/foo.jsp</result> </action> </package> ```
There may be a way to do that, but I don't think it's a very good way to use struts. If actionA is failing validation, you most likely would want to either have a non-redirect input result for it that shows the errors, or perhaps a global error page that can show it. I suppose you could store the action errors somewhere like the session in between the redirect, but you wouldn't really be using the framework how it was designed.
Struts2 by default has a store interceptor. It stores the actionMessages, actionErrors and fieldErrors in session in STORE mode and you can retrieve the same in the next redirect by using the same interceptor by using it in RETRIEVE mode. More details can be found [here](https://struts.apache.org/core-developers/message-store-interceptor.html)
Can I propagate struts2 ActionErrors between different action classes?
[ "", "java", "model-view-controller", "error-handling", "struts2", "struts", "" ]
I have a map like this: ``` private Map<String, List<List<String>>> someMap; private List<List<String>> someList1; private List<String> someList2; ``` ....Some initialization..... ....Some list population.... Then I have, ``` if(someMap.get(someKey) == null){ someList1.add(someList2); someMap.put(someKey, someList1); } else { someMap.get(someKey).add(someList2); } ``` Note that the list gets clear after adding to the map and gets populated afterward. For instance, I have two keys "Apple" and "Orange" with some values. After the loop, I get only Orange. The previous key gets overridden!!! **EDIT:** In every iteration of a loop, a list gets populated. End of the loop, it gets added to the map and after adding, the list gets clear(). Any advice? Thanks. **CODE:** <http://pastebin.com/m2712e04> [On request.. so please don't blame me for posting it..]
I doubt that you want to add the same lists over and over again. You need to create new list instances for each new key. **Edit:** Does your someKey variable change at all? Have you used the debugger to step into the code and look what is happening? **Edit:** Do it more like this: ``` // store the current payment info reportDataSubList = new ArrayList<String>(); reportDataSubList.add(clientCode); //... reportDataList = reportData.get(clientCode); if(reportDataList == null){ reportDataList = new ArrayList<List<String>>(); reportData.put(clientCode, reportDataList); } reportDataList.add(reportDataSubList); ``` But I'm not sure that the data structure you're using is well suited for the task. Proper entity objects or even XML would be a batter match IMHO.
Based on your comment to Lucero's question: Are you reusing the same List instance over and over again, i.e. doing ``` someList1.add(someList2); someMap.put(someKey, someList1); someList1.clear() someList1.add(stuff) someMap.put(someOtherKey, someList1); ``` That will not work, as someList1.clear() will clear the list *inside someMap*. You need to create a fresh List instance every time: ``` someList1.add(someList2); someMap.put(someKey, someList1); someList1 = new List<...>(); someList1.add(stuff) someMap.put(someOtherKey, someList1); ```
Updating a Map
[ "", "java", "collections", "" ]
I'm using the default framework code that was created with the Zend Framework Application tool, I added some autoloader magic so that any classes named `Default_<*>_<*>` would automatically be loaded from the correct directory, in this case `Default_Model_TableName`. application/models/ProjectCategories.php: ``` <?php class Default_Model_ProjectCategories extends Zend_Db_Table_Abstract { protected $_name = 'categories'; protected $_dependentTables = array('Projects'); } ``` application/models/Projects.php: ``` <?php class Default_Model_Projects extends Zend_Db_Table_Abstract { protected $_name = 'projects'; protected $_referenceMap = array( 'Category' => array( 'columns' => 'cid', 'refTableClass' => 'ProjectCategories', 'refColumns' => 'id', 'onUpdate' => self::CASCADE, 'onDelete' => self::CASCADE, ) ); } ``` What I am attempting to do is the following: ``` <?php $categories = new Default_Model_ProjectCategories(); $category = $categories->find('1'); $category->findProjects(); ``` At which point I get an error thrown at me that it is unable to find Projects.php, and or that the file might not have contained a class named Projects. At that point I place Projects.php in the include path that was set up by the framework (/../library/) and the file is found, but now I lose my whole directory structure, and naming because I had to rename `Default_Model_Projects` to `Projects`. I am able to get everything to work if I place the file back in its original location, and change ``` protected $_dependentTables = array('Projects'); ``` to ``` protected $_dependentTables = array('Default_Model_Projects'); ``` but this also means that my `->findProjects()` now becomes `->findDefault_Model_Projects()`. Is there a way to tell it that when I am looking for `findProjects()` that it has to instantiate `Default_Model_Projects`? Is this something that is missing from Zend Framework, or am I attempting to shoehorn something in a way that it does not belong? How have you solved this issue?
This problem may have been introduced by the new Autoloader, and the way in which it prefers to load namespaced classes (e.g. those prefixed as you have ). In my applications I simply name models like 'Projects' and add a separate models folder to the include path for that application. This is one solution - unfortunately I don't know how you can make the namespaced models load correctly, but I would suggest looking at Zend\_Loader in greater detail, and possible the pluginLoaders.
i used to be able to do something like ``` $resourceLoader = new Zend_Loader_Autoloader_Resource(array( 'basePath' => APPLICATION_PATH, 'namespace' => 'App', )); $resourceLoader->addResourceType('model', 'models/', ''); ``` to shrink my model classes to App\_TableName but seems like its not working now...
Relationships in Zend_DB_Table_Abstract
[ "", "php", "zend-framework", "" ]
I've been looking at the PollingDuplexHttpBinding available in silverlight 2 and 3 and had a couple of questions I haven't been able to find any information on. 1. Am I able to use this in non-silverlight apps? 2. From the descriptions it doesn't seem like its actually polling, but maintaining an open connection and reconnecting as necessary. Is this correct? 3. Is it possible to use this over https?
1. Creating a duplex service is intended to be done using WCF, this means the client that accesses the PollingDuplex service, such as adobe air or silverlight, must support the binding. 2. I'm not too familiar with the inner workings of this binding, from what ive [seen](http://msdn.microsoft.com/en-us/library/dd470106(VS.96).aspx), the client keeps listening on an agreed port awaiting the callback after the initial call, the polling comes in when the client "polls" the server asking if its done yet, where the server can send information on its status (customizable). At the end of the day, when the servers done, it will call the client 3. Yes, and if you are going to, remember, cross domain policies for https (must be specified in crossdomain policy)
I've just completed some work with SL4 and this binding and it does poll from the client, it's "fake" bidirectional comms. (You'll see there's config settings for how many messages the server must return on each poll) If you want real bidrection calls you have to use net.tcp.
WCF PollingDuplexHttpBinding questions
[ "", "c#", "wcf", "silverlight", "" ]
A string variable str contains the following somewhere inside it: `se\">` I'm trying to find the beginning of it using: ``` str.IndexOf("se\\\">") ``` which returns -1 Why isn't it finding the substring? Note: due to editing the snippet showed 5x \ for a while, the original had 3 in a row.
Your code is in fact searching for `'se\\">'`. When searching for strings including backslashes I usually find it easier to use verbatim strings: ``` str.IndexOf(@"se\"">") ``` In this case you also have a quote in the search string, so there is still some escaping, but I personally find it easier to read. **Update**: my answer was based on the edit that introduced extra slashes in the parameter to the `IndexOf` call. Based on current version, I would place my bet on `str` simply not containing the expected character sequence. **Update 2**: Based on the comments on this answer, it seems to be some confusion regarding the role of the '\' character in the strings. When you inspect a string in the Visual Studio debugger, it will be displayed with escaping characters. So, if you have a text box and type 'c:\' in it, inspecting the Text property in the debugger will show 'c:\\'. An extra backslash is added for escaping purposes. The actual string content is still 'c:\' (which can be verified by checking the `Length` property of the string; it will be 3, not 4). If we take the following string (taken from the comment below) > " '<em > class=\"correct\_response\">a > night light</em><br > /><br /><table > width=\"100%\"><tr><td > class=\"right\">Ingrid</td></tr></table>')" ...the `\"` sequences are simply escaped quotation marks; the backslashes are not part of the string content. So, you are in fact looking for `'se">'`, not `'se\">'`. Either of these will work: ``` str.IndexOf(@"se"">"); // verbatim string; escape quotation mark by doubling it str.IndexOf("se\">"); // regular string; escape quotation mark using backslash ```
This works: ``` string str = "<case\\\">"; int i = str.IndexOf("se\\\">"); // i = 3 ``` Maybe you're not correctly escaping one of the two strings? *EDIT* there's an extra couple of `\` in the string you are searching for.
.NET string IndexOf unexpected result
[ "", "c#", ".net", "string", "indexof", "" ]
I need to read an XML file using Java. Its contents are something like ``` <ReadingFile> <csvFile> <fileName>C:/Input.csv</fileName> <delimiter>COMMA</delimiter> <tableFieldNamesList>COMPANYNAME|PRODUCTNAME|PRICE</tableFieldNamesList> <fieldProcessorDescriptorSize>20|20|20</fieldProcessorDescriptorSize> <fieldName>company_name|product_name|price</fieldName> </csvFile> </ReadingFile> ``` Is there any special reader/JARs or should we read using *FileInputStream*?
Another suggestion: Try out Commons digester. This allows you to develop parsing code very quickly using a rule-based approach. There's a tutorial [here](http://www.javaworld.com/javaworld/jw-10-2002/jw-1025-opensourceprofile.html) and the library is available [here](http://commons.apache.org/digester/) I also agree with Brian and Alzoid in that JAXB is great to get you up and running quickly. You can use the xjc binding compiler that ships with the JDK to auto generate your Java classes given an XML schema.
Check out Java's [JAXP](http://www.ibm.com/developerworks/java/library/x-jaxp/) APIs which come as standard. You can read the XML in from the file into a DOM (object model), or as SAX - a series of events (your code will receive an event for each start-of-element, end-of-element etc.). For both DOM and SAX, I would look at an API tutorial to get started. Alternatively, you may find [JDOM](http://www.jdom.org/) easier/more intuitive to use.
How to read an XML file using Java?
[ "", "java", "xml", "jar", "" ]
I'm trying to fetch some records from MSSQL DB using EntityObject with EntitySQL query. The field i'm using to filter is type of datetime. The generated query projected without millisecond, to the SQL Server returns nothing. When i'm adding the milliseconds, i get results. How can i use the EntitySQL to get result without the milliseconds? thanks.
It's not elegant, but this worked for me: ``` foos.SingleOrDefault(f => f.EntryDate.Year == bar.EntryDate.Year && f.EntryDate.Month == bar.EntryDate.Month && f.EntryDate.Day == bar.EntryDate.Day && f.EntryDate.Hour == bar.EntryDate.Hour && f.EntryDate.Minute == bar.EntryDate.Minute && f.EntryDate.Second == bar.EntryDate.Second); ```
One way to do it is to create a view of your data, where your datetime column is converted to smalldatetime (which does not have milliseconds). Then add the view to your entity framework model, and read the data through the view. Hope this helps Shiraz
Entity SQL compare datetime without milliseconds
[ "", "c#", "t-sql", "entity-framework", "objectquery", "" ]
With some Javascript I openup a popup no prob using: ``` function myPopup2(x){ if (x==1) { myWindow = window.open( "timer.html", "", "height = 150, width = 300" ); }else { myWindow.close(); } } ``` I then run some PHP script which refresh reloads the page. When I later then go to close the popup - it doesn't, because the page has been reloaded and `myWindow` variable gone. 'myWindow' is undefined is the Javascript error. Anyone know how I can get around this?
If you give your window a name when you open it, it is possible to get a handle to the window later. ``` function myPopup2(x){ if (x==1) { myWindow = window.open( "timer.html", "windowName", "height = 150, width = 300" ); }else { if (!myWindow) { myWindow = window.open("", "windowName"); } myWindow.close(); } } ```
As outlined here: <http://www.faqts.com/knowledge_base/view.phtml/aid/1460> window.open() takes a second parameter, which is the name of the window. On refresh, you could check on the status of that window and close it if necessary. As discussed in the link, there's no direct way to check for the window after refresh, so you have to do something like this: ``` var win = window.open ('', 'windowName') ``` and then operate on win. (edit: I initally had a second idea involving cookies, but I don't think that really saves you anything, since you still have to do the above to access the window.)
Close popup window if it exists
[ "", "javascript", "dom-events", "" ]
i have a QMainWindow. It has this parameters: > ``` > this->setWindowFlags(Qt::Tool); > this->setFocusPolicy(Qt::StrongFocus); > this->setAttribute(Qt::WA_QuitOnClose,true); > ``` After showEvent calles my window is shown but unactivated. I tried to overload show function: ``` ... QMainWindow::showEvent(event); this->activateWindow(); ... ``` But it doesn't help me. **EDIT:** When i commented line ``` this->setWindowFlags(Qt::Tool); ``` everything worked fine, but i need in tool-flag. Any ideas? **EDIT:** * OS: Linux * Programming language: c++ * Qt version: 4.5.1
**The Windows Manager Decides** Before I start: As pointed out by [elcuco](https://stackoverflow.com/questions/1053006/qt-activate-window/1053048#1053048) and [Javier](https://stackoverflow.com/questions/1053006/qt-activate-window/1081099#1081099), focus policy and other aspects of the windows layout (e.g. the title bar) belongs to a substantial extend to the respective windows manager, and Qt might have limited control. To see this, just look at a user interface that has a "[focus follows mouse](http://en.wikipedia.org/wiki/Focus_%28computing%29#Focus_follows_mouse)" policy. In these cases, the windows manager might ignore Qt's focus request. For this reasons, the Qt documentation calls many of the respective flags "hints". Consequently, some of the suggested solutions might or might not work for you. **QApplication::setActiveWindow()** This not withstanding, [e.tadeu's](https://stackoverflow.com/questions/1053006/qt-activate-window/1080717#1080717) solution to use [`QApplication::setActiveWindow()`](http://qt-project.org/doc/qt-5.0/qtwidgets/qapplication.html#setActiveWindow) works for me for both Windows and Ubuntu with Gnome. I tested it with the following code. Apologies that it is Python using PyQt (I use questions like these to learn a bit about PyQt). It should be fairly easy for you to read it and translate it into C++. ``` import sys from PyQt4 import QtGui from PyQt4 import QtCore class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self) # main window self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Test') # text editor self.textEdit = QtGui.QTextEdit() self.setCentralWidget(self.textEdit) def closeEvent(self, event): QtGui.QApplication.instance().quit() #main app = QtGui.QApplication(sys.argv) testWindow = MainWindow() testWindow.setWindowFlags(QtCore.Qt.Tool) testWindow.show() app.setActiveWindow(testWindow) app.exec_() ``` Note that you have to add some handling of the close event of the `testWindow`, because the app does not exit automatically if you close a `Qt::Tool` window. **The grabKeyboard() Hack** If this does not work for you, the following hack might. I assume that you have a window in your application that is active. You can then use [`grabKeyboard()`](http://qt-project.org/doc/qt-5.0/qtwidgets/qgraphicsitem.html#grabKeyboard) to redirect the input. The `Qt::Tool` window doesn't get the focus, but receives the input. The following main code demonstrates it (the other code remains unchanged). ``` #main app = QtGui.QApplication(sys.argv) testWindow = MainWindow() testWindow.setWindowFlags(QtCore.Qt.Tool) testWindow2 = MainWindow() # second window which is active testWindow2.show() testWindow.show() testWindow.textEdit.grabKeyboard() app.exec_() ``` Basically, while the window `testWindow2` is the active one, all text entered shows up in `testWindow.textEdit`. It is not nice, I know... **Creating Your Own Window** You gain the most flexibility (and create the most work for yourself) by rolling out your own window layout. The idea is described in the following [FAQ](http://www.qtsoftware.com/developer/faqs/535). **Other "Solutions"** You could directly call the respective window manager's API function to get the desired result (clearly against the very reason for using Qt in the first place). You could also hack the Qt source code. For example, on Windows, Qt uses the [`ShowWindow()`](http://msdn.microsoft.com/en-us/library/ms633548%28VS.85%29.aspx) function with a `SW_SHOWNOACTIVATE` flag, to show a window with style [`WS_EX_TOOLWINDOW`](http://msdn.microsoft.com/en-us/library/ms960010.aspx) if you set the `Qt::Tool` flag. You could easily replace the `SW_SHOWNOACTIVATE` with whatever you want. Linux should be the same. Clearly also not recommended.
The original apple Human Interface Guidelines(\*) said that toolbox windows were "always on top but never activated". It also advises against using text boxes on them, precisely because the lack of activation-state feedback. Check how other 'toolbox heavy' apps behave. I faintly recall that at least GIMP and InkScape seem very different in this aspect. As [elcuco](https://stackoverflow.com/questions/1053006/qt-activate-window/1053048#1053048) said, the window manager can do whatever it wants with Qt's flags. Also, it sure would be different under KDE, Gnome, fluxbox, whatever. (\*):great document! somewhat outdated; but tool windows were already used and considered
Activate window
[ "", "c++", "qt", "show", "" ]
I'm writing a calendar control in .Net WinForms that will show a tooltip for each date. What's the best way to determine when to show the tooltip? Showing it immediately in `MouseMove` would make it get in the way, so I'd like it to show when the mouse hovers over each date cell. The `MouseHover` event only fires on the first hover after `MouseEnter`, so I can't use it. What's the best way to do this? **EDIT**:I'm using WinForms
The time delay between Enter and Hover is specified in [SystemInformation.MouseHoverTime](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.mousehovertime.aspx). If for some reason the built-in tooltip handling code for whichever UI framework you're using isn't sufficient, you could just spin up a Timer after each MouseMove and show a Tooltip when it fires. Obviously, you'd need to reset the Timer each time the mouse is moved to prevent a long series "rain of tooltips".
Have a look at the AutoPopDelay, InitialDelay and ReshowDelay properties of the ToolTip class, as they control the behaviour of the tooltip. I generally play around with the values until I get something that 'feels' right. It's annoying when a tooltip shows immediately, and for short tooltips, it's also annoying when they disappear too soon. For really long tooltips, say, several paragraphs (yes, poor design decision, but if there's a lot of info to read, at least let me read it!) then it should stay open as long as my mouse is stationary. A [tooltip example](http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.autopopdelay.aspx) from MSDN gives the following values: ``` AutoPopDelay = 5000; InitialDelay = 1000; ReshowDelay = 500; // Force the ToolTip text to be displayed whether or not the form is active. ShowAlways = true; ``` As mentioned in a comment, the poster wants to trigger the tooltip programatically. For that, ToolTip.Show( ) needs to be called. To get a delay effect, you'll likely want to have a timer running which counts the time that the mouse is stationary. Whenever the mouse enters, leaves or moves within the control, this time should be reset.
How do I determine when to show a tooltip?
[ "", "c#", ".net", "winforms", "controls", "tooltip", "" ]
Suppose I have a junction table ``` EmployeeId DeptId --------- ------ 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 4 1 5 2 5 3 6 1 6 2 6 3 ``` So 1 employee can work in many departments My problem is to find which employee works in multiple departments? e.g. If I want to search an employee who works for department `1,2,3`, the result will be: `1,2,6` If I want to search an employee who works for department `2 & 3` the result will be `1,2,5,6` If I want to search an employee who works for department `1 & 2` the result will be `1,2 ,3,6` I tried with the following queries ``` a) SELECT DISTINCT EmployeeId FROM dbo.EmpDept WHERE DeptId in (2,3) ``` I got wrong result ``` b) SELECT DISTINCT EmployeeId FROM dbo.EmpDept WHERE DeptId = 2 AND DeptId = 3 ``` This time I got no records Please help me out. **N.B.**~ I only simulated my real time project scenario. I cannot reveal the exact schema or table names or anything related to the project as it is confidential. Thanks in advance
this query will find all employees that work for more than 1 department. ``` select employeeid, count(*) from dbo.EmpDept group by employeeid having count(*) > 1; ``` if you are hoping to gather data on the employees that cross between a set of specific EmpDepts, you can utilize self joins: ``` select a.employeeid from dbo.EmpDept a, dbo.EmpDept b where a.employeeid = b.employeeid and a.deptid = 1 and b.deptid = 2; ``` using this method, you will have to add another join for every new department you are looking for.
``` select employeeid from EmpDept where DeptId in (2,3) group by employeeid having count(*) = 2 ``` or ``` select employeeid from EmpDept where DeptId in (1,2,3) group by employeeid having count(*) = 3 ``` So, the count must match the number of DeptIds you are checking for. These queries assume you want to specify the DeptIds, which is what I gathered from your question.
Employees and departments database query with Sql
[ "", "sql", "database", "select", "distinct", "" ]
Does anyone know why. ``` CREATE PROCEDURE My_Procedure (@Company varchar(50)) AS SELECT PRD_DATE FROM WM_PROPERTY_DATES WITH (NOLOCK) WHERE PRD_COMPANY = @Company GO ``` Gives me an error message in SQL management studio: > `Msg 102, Level 15, State 1, Procedure My_Procedure, Line 1 > Incorrect syntax near 'GO'.` Now, this is the last statement of a batch, maybe the last statement should not have a `GO` ?
There was a bug released in SQL Server that parses the GO statement incorrectly. I believe it was introduced when you could do *GO **X***, and execute the batch ***X*** multiple times. Sometimes I've had to add a comments section ("***--***") to force the parser to terminate rather than produce a syntax error. This has been seen when I've had 400,000 lines in a batch of code. Example: PRINT "This is a test." **GO --** PRINT "This is not a test." **GO 5 --**
If you go to "Save As...", click on the little down-arrow on the Save button and select "Save with Encoding..." then you can set your Line endings to Windows (CR LF). That seems to have resolved the issue for me...
Creating Stored Procedure Syntax, relating to use of GO
[ "", "sql", "sql-server", "sql-server-2005", "stored-procedures", "" ]
my application has to deal with calendar information (incl. single occurrence, recurrence, etc.). In order to easily interface with other applications I thought that it would be a good idea to create my database schema based on the iCalendar format (fields, relationships, constraints) directly so that I get iCalendar compatible objects via ORM that I can easily expose when needed. I know that the RFC is available but it's kind of complicated because of all the additional information in it that I don't use at the moment. Could somebody point me to an easier source to create a database schema based on the iCal standard (meaning a list of fields/fieldnames and their relationship for iCal entries)? Thanks!
I've done this (for VEvents only, not supporting TODO items or Journal entires or anything like that). My implementation looks like this (after removing columns that are not specific to the question): ``` -- One table for each event. An event may have multiple rRules. Create Table [vEvent] (vEventID Integer Identity(1, 1) Not Null Constraint [vEvent.pk] Primary Key Clustered ,title nVarChar(200) Not Null); -- One table for rRules. -- My application does NOT support the "bySetPos" rule, so that is not included. Create Table [rRule] (rRuleID Integer Identity(1, 1) Not Null Constraint [rRule.pk] Primary Key Clustered ,vEventID Integer Not Null Constraint [fk.vEvent.rRules] Foreign Key References [vEvent] (vEventID) On Update Cascade On Delete Cascade ,[class] varChar( 12) Not Null Default('public') ,[created] DateTime Not Null Default(getUTCDate()) ,[description] nVarChar(max) Null ,[dtStart] DateTime Not Null ,[dtEnd] DateTime Null ,[duration] varChar( 20) Null ,[geoLat] Float Null ,[geoLng] Float Null ,[lastModified] DateTime Not Null Default(getUTCDate()) ,[location] nVarChar(max) Null ,[organizerCN] nVarChar( 50) Null ,[organizerMailTo] nVarChar( 100) Null ,[seq] Integer Not Null Default(0) ,[status] varChar( 9) Not Null Default('confirmed') ,[summary] nVarChar( 75) Null ,[transparent] Bit Not Null Default(0) ,[freq] varChar( 8) Not Null Default('daily') ,[until] DateTime Null ,[count] Integer Null ,[interval] Integer Not Null Default(1) ,[bySecond] varChar( 170) Null ,[byMinute] varChar( 170) Null ,[byHour] varChar( 61) Null ,[byDay] varChar( 35) Null ,[byMonthDay] varChar( 200) Null ,[byYearDay] varChar(3078) Null ,[byWeekNo] varChar( 353) Null ,[byMonth] varChar( 29) Null ,[wkSt] Char ( 2) Null Default('mo')); -- Class must be one of "Confidential", "Private", or "Public" Alter Table [rRule] Add Constraint [rRule.ck.Class] Check ([class] In ('confidential', 'private', 'public')); -- Start date must come before End date Alter Table [rRule] Add Constraint [rRule.ck.dtStart] Check ([dtEnd] Is Null Or [dtStart] <= [dtEnd]); -- dtEnd and duration may not both be present Alter Table [rRule] Add Constraint [rRule.ck.duration] Check (Not ([dtEnd] Is Not Null And [duration] Is Not Null)); -- Check valid values for [freq]. Note that 'single' is NOT in the RFC; -- it is an optimization for my particular iCalendar calculation engine. -- I use it as a clue that this pattern has only a single date (dtStart), -- and there is no need to perform extra calculations on it. Alter Table [rRule] Add Constraint [rRule.ck.freq] Check ([freq] In ('yearly' ,'monthly' ,'weekly' ,'daily' ,'hourly' ,'minutely' ,'secondly' ,'single')); -- Single is NOT part of the spec! -- If there is a latitude, there must be a longitude, and vice versa. Alter Table [rRule] Add Constraint [rRule.ck.geo] Check (([geoLat] Is Null And [geoLng] Is Null) Or ([geoLat] Is Not Null And [geoLng] Is Not Null)); -- Interval must be positive. Alter Table [rRule] Add Constraint [rRule.ck.interval] Check ([interval] > 0); -- Status has a set of defined values. Alter Table [rRule] Add Constraint [rRule.ck.status] Check ([status] In ('cancelled', 'confirmed', 'tentative')); -- Until and Count may not coexist in the same rule. Alter Table [rRule] Add Constraint [rRule.ck.until and count] Check (Not ([until] Is Not Null And [count] Is Not Null)); -- One table for exceptions to rRules. In my application, this covers both -- exDate and rDate. I do NOT support extended rule logic here; The RFC says -- you should support the same sort of date calculations here as are supported -- in rRules: exceptions can recur, etc. I don't do that; mine is simply a -- set of dates that are either "exceptions" (dates which don't appear, even -- if the rule otherwise says they should) or "extras" (dates which do appear, -- even if the rule otherwise wouldn't include them). This has proved -- sufficient for my application, and something that can be exported into a -- valid iCalendar file--even if I can't import an iCalendar file that makes -- use of recurring rules for exceptions to recurring rules. Create Table [exDate] (exDateID Integer Identity(1, 1) Not Null Constraint [exDate.pk] Primary Key Clustered ,rRuleID Integer Not Null Constraint [fk.rRule.exDates] Foreign Key References [rRule] (rRuleID) On Update Cascade On Delete Cascade ,[date] DateTime Not Null ,[type] varChar(6) Not Null); -- Type = "exDate" or "rDate" for me; YMMV. ``` To go along with this, I have several SQL Server 2005+ CLR functions that can be used to calculate the dates for various events. I have found the following forms to be very useful: ``` Select * From dbo.getDatesByVEventID(@id, @startDate, @endDate) Select * From dbo.getEventsByDateRange(@startDate, @endDate, @maxCount) ``` Implementation of the above is darn fun to figure out!
Sunbird, the open source Mozilla calendar, is based on sqlite. I just downloaded and unzipped their source code. It has `.sql` files in it. <http://archive.mozilla.org/pub/calendar/sunbird/releases/0.9/source/lightning-sunbird-0.9-source.tar.bz2> The file `mozilla\calendar\providers\storage\schema-7.sql` is the schema sunbird uses to make valid iCal files, so it can't be too bad.
iCalendar "Field" list (for database schema based on iCalendar standard)
[ "", "sql", "icalendar", "" ]
What is the best way to combine a path with a filename? That is, given `c:\foo` and `bar.txt`, I want `c:\foo\bar.txt`. Given `c:\foo` and `..\bar.txt`, I want either an error or `c:\foo\bar.txt` (so I cannot use `Path.Combine()` directly). Similarly for `c:\foo` and `bar/baz.txt`, I want an error or `c:\foo\baz.txt` (not `c:\foo\bar\baz.txt`). I realize, I could check that the filename does not contain '\' or '/', but is that enough? If not, what is the correct check?
If you want "bad" filenames to generate an error: ``` if (Path.GetFileName(fileName) != fileName) { throw new Exception("'fileName' is invalid!"); } string combined = Path.Combine(dir, fileName); ``` Or, if you just want to silently correct "bad" filenames without throwing an exception: ``` string combined = Path.Combine(dir, Path.GetFileName(fileName)); ```
You could use: ``` Path.Combine(folder, Path.GetFileName(fileName)) ``` or, to skip out the \ (not tested, maybe the Path.GetFileName handles this automatically) ``` Path.Combine(folder, Path.GetFileName(fileName.Replace("/","\\"))) ```
What is the best way to combine a path and a filename in C#/.NET?
[ "", "c#", ".net", "path", "filenames", "" ]
I am wondering if there is a simple snippet which converts links of any kind: ``` http://www.cnn.com to <a href="http://www.cnn.com">http://www.cnn.com</a> cnn.com to <a href="http://www.cnn.com">cnn.com</a> www.cnn.com to <a href="http://www.cnn.com">www.cnn.com</a> abc@def.com to to <a href="mailto:mailto:abc@def.com">mailto:abc@def.com</a> ``` I do not want to use any PHP5 specific library. Thank you for your time. **UPDATE** I have updated the above text to what i want to convert it to. Please note that the href tag and the text are different for case 2 and 3. **UPDATE2** Hows does gmail chat do it? Theirs is pretty smart and works only for real domains names. e.g. a.ly works but a.cb does not work.
yes , <http://www.gidforums.com/t-1816.html> ``` <?php /** NAME : autolink() VERSION : 1.0 AUTHOR : J de Silva DESCRIPTION : returns VOID; handles converting URLs into clickable links off a string. TYPE : functions ======================================*/ function autolink( &$text, $target='_blank', $nofollow=true ) { // grab anything that looks like a URL... $urls = _autolink_find_URLS( $text ); if( !empty($urls) ) // i.e. there were some URLS found in the text { array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) ); $text = strtr( $text, $urls ); } } function _autolink_find_URLS( $text ) { // build the patterns $scheme = '(http:\/\/|https:\/\/)'; $www = 'www\.'; $ip = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'; $subdomain = '[-a-z0-9_]+\.'; $name = '[a-z][-a-z0-9]+\.'; $tld = '[a-z]+(\.[a-z]{2,2})?'; $the_rest = '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}'; $pattern = "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest"; $pattern = '/'.$pattern.'/is'; $c = preg_match_all( $pattern, $text, $m ); unset( $text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern ); if( $c ) { return( array_flip($m[0]) ); } return( array() ); } function _autolink_create_html_tags( &$value, $key, $other=null ) { $target = $nofollow = null; if( is_array($other) ) { $target = ( $other['target'] ? " target=\"$other[target]\"" : null ); // see: http://www.google.com/googleblog/2005/01/preventing-comment-spam.html $nofollow = ( $other['nofollow'] ? ' rel="nofollow"' : null ); } $value = "<a href=\"$key\"$target$nofollow>$key</a>"; } ?> ```
Try this out. (for links not email) ``` $newTweet = preg_replace('!http://([a-zA-Z0-9./-]+[a-zA-Z0-9/-])!i', '<a href="\\0" target="_blank">\\0</a>', $tweet->text); ```
Php parse links/emails
[ "", "php", "regex", "" ]
I am a beginner in Java and do not understand what **`if(!s.add(a))`** means in this code excerpt: ``` Set<String> s = new HashSet<String>(); for(String a:args) { if(!s.add(a)) System.out.println("Duplicate detected:"+a); } ```
if collection s already has item a, then the add method will return false. The ! is a "not" operator, turning that false into true. So, if the item is already in the collection, you will see the println result.
[`add`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#add(E)) is specified in the [`Collection` interface](http://java.sun.com/javase/6/docs/api/java/util/Collection.html) to return a `boolean` indicating whether the addition was successful. From the Javadocs: > Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.) This code prints out a message if the addition was unsuccessful, which happens when there is a duplicate in the set.
What does this statement mean?
[ "", "java", "collections", "set", "" ]
i have problem with enum I need make a enum in base class or interface (but empty one) ``` class Base { public enum Test; // ??? } ``` and after make diffrent enums in some parent classes ``` class Parent1 { public enum Test {A, B, C}; } class Parent2 { public enum Test {J, H, K}; } ``` and now i have next class with method when i have to use enum ``` class Test<T> { public void Foo(Test enum) { int value = (int) enum; // ... } } ``` It's there any way to do something like that ? If not i have to use static ints in every class ... ``` class Parent1 { public static int A = 0; public static int B = 5; public static int C = 7; } class Parent2 { public static int J = 1; public static int H = 3; public static int K = 6; } class Test<T> { public void Foo(int enum) { int value = enum; // ... } } ``` I't looks bad in code ... in some classes i have to use ~20+ variables
There is no such thing as an abstract enum (that can have different implementations in subclasses) - but generics may be an option: ``` class Base<T> where T : struct { private T value; public void Foo(T value) { this.value = value; } } class Parent1 : Base<Parent1.Enum1> { public enum Enum1 {A, B, C}; } class Parent2 : Base<Parent2.Enum2> { public enum Enum2 { J, H, K }; } ``` The only problem is that this doesn't enforce that only enums are usable - you can do this at runtime, though - for example in a type initializer: ``` static Base() { if (!typeof(T).IsEnum) throw new InvalidOperationException( typeof(T).Name + " is not an enum"); } ```
It's amazing how often I find people arguing about *why* something is required, rather than answering the question asked or keeping schtum - either of which would be more helpful than wasting time questioning *why* a given enquiry has been made in preference to a different enquiry the respondent actually knows the answer to. Answering questions that have not been asked is in no way helpful, OK guys?! Getting back to the topic at hand, I've hit exactly the above scenario this morning, and can understand why it would be useful to be able to define an Enum in an interface or base class, then re-define that same-named Enum in a class that derives from either the base or interface. One use for such a design is in object-relational mapping and control binding. You might have a set of Enums that describe which Properties of your derived classes are bindable to which types of Control, such as: ``` public enum WebControlTextBoxProperties { } public enum WebControlLabelProperties { } ``` ...and so on. Since you don't know exactly which Properties will exist for a given derived class until the pertinent inheritance takes effect, but since you may also wish to have consistent Methods that consume the above Enums in your base or interface, it's a perfectly-valid design to expect to be able to define that the Enum *will exist* in the base/interface, but define exactly *what members* it has in a specific context in any derived classes. I really wish this were possible in C# as it is in VB, because it'd be a really useful feature.
C# enum in interface/base class?
[ "", "c#", "enums", "virtual", "parent", "" ]
I'm a beginner in PHP. What I'm trying to do is stop Post Data coming from another webpage. The problem I am having is let's say someone copies my form and pastes it in their website. I want to be able to stop that Post Data from running the script on my email form. How can I do this? Let me know if I'm not being clear enough. My PHP Contact form runs on one page with conditional statements. i.e. if data checks out, submit.
$\_SERVER['HTTP\_Referrer'] would be nice but it isn't reliable. You could use a hidden form field that MD5's something and then you check it on the other side.
**"accepted answer" has security holes**. Instead, you should use more secure methods. A simple example: **Step 1:** Disable framing of the page (`.php`), where the form is generated, in the top add: ``` header('X-Frame-Options: Deny'); ``` **Step 2: (important part ! ):** In order to avoid XSS and 3rd party exploits, you should create a expirable validation. For example: * `ASP.NET` builtin forms use dynamic input **csrf** (example value: `gtlkjh29f9ewduh024cfvefb` ) * `WordPress` builtin forms use dynamic input **nonce** (example value: `340297658942346` ) So, if you are on a custom platform, which doesn't have built-in temporary token validation methods, then implement your approach. A simple concept: ``` <?php $secret_key = 'fjd3vkuw#KURefg'; //change this $encrypted_value = Cryptor::encrypt( time(), $_SERVER['REMOTE_ADDR'] . $secret_key); ?> <form> ... ... <input value="<?php echo $encrypted_value;?>" name="temp_random" type="hidden" /> </form> ``` *(Cryptor code is [here](https://github.com/tazotodua/useful-php-scripts/blob/master/two-way-encrypt-decrypt.php) )* on submission, check: ``` if(!empty($_POST)){ // If REFERRER is empty, or it's NOT YOUR HOST, then STOP it if( !isset($_SERVER['HTTP_REFERRER']) || parse_url($_SERVER['HTTP_REFERRER'])['host'] != $_SERVER['HTTP_HOST'] ){ exit("Not allowed - Unknown host request! "); } // Now, check if valid if ( Cryptor::decrypt( $_POST['temp_random'], $_SERVER['REMOTE_ADDR'] . $secret_key) < time() - 60* 15 ) { exit("Not allowed - invalid attempt! "); } ........................................... ... Now, you can execute your code here ... ........................................... } ```
Stop Post Data From Different Domain PHP
[ "", "php", "forms", "post", "" ]
So in Code::Blocks in Ubuntu (latest). I have a project in which I load a file and read a number from it. ``` #include <fstream> using namespace std; int main(){ ifstream in("data/file.t"); int n;in>>n; } ``` now with a `cout<<n` it shows `-1203926` (and other random numbers) though the number in the file is `0`. `data` is where the binary is(I mean data and binary are in the same folder(Program)) and I was expecting the path to be relative like in Windows... but only if I put the full path `/home/csiz/Desktop/C++/ep0/Program/data/file.t` it will get me a `0`. Can you tell me how to make it a relative path? I would prefer something so that in Windows the code can compile without any changes.
After using the absolute path I found the mistake. In codeblocks you can enter the working directory (that in wich it will launch the program) and I accidentally put a . in there.
The path is relative to the current working directory, not to the directory your application is under. A simple solution would be to have a SH script that changes the working directory to your application's directory, and then executes your app, like so: ``` $!/bin/sh cd `dirname $0` # changes the working dir to the script's dir ./application-name # executes your application # no need changing back to your previous working directory # the chdir persists only until the end of the script ``` It's not uncommon for applications to have initialization scripts. You could also do this inside your main C/C++ application. Since the path of the executable is passed in the main method's argv[0], you could do the same. But I would advise against it, because when you're redistributing your application on Linux, data files are usually placed in a different directory (usually /var/lib) than your executables (usually /usr/bin). So it's either an initialization script, or passing the path of your data directory in an environment variable, executing it like so ... ``` MY_APP_DATA_PATH=/var/lib/my-app /path/to/executable ```
absolute path... confused (ubuntu)
[ "", "c++", "linux", "ubuntu", "path", "codeblocks", "" ]
I've learned (the hard way) that I need to add parentheses around JSON data, like this: ``` stuff = eval('(' + data_from_the_wire + ')'); // where data_from_the_wire was, for example {"text": "hello"} ``` (In Firefox 3, at least). What's the reason behind this? I hate writing code without understanding what´s behind the hood.
Putting the parentheses around `data_from_the_wire` is effectively equivalent to ``` stuff = eval('return ' + data_from_the_wire + ';'); ``` If you were to eval without the parentheses, then the code would be evaluated, and if you did have any named functions inside it those would be defined, but not returned. Take as an example the ability to call a function just as it han been created: ``` (function() { alert('whoot'); })() ``` Will call the function that has just been defined. The following, however, does not work: ``` function() { alert('whoot'); }() ``` So we see that the parentheses effectively turn then code into an expression that returns, rather than just code to run.
`eval` accepts a sequence of Javascript statements. The Javascript parser interprets the ‘{’ token, occuring within a statement as the start of a block and not the start of an object literal. When you enclose your literal into parentheses like this: `({ data_from_the_wire })` you are switching the Javascript parser into expression parsing mode. The token ‘{’ inside an expression means the start of an object literal declaration and **not** a block, and thus Javascript accepts it as an object literal.
Why does JavaScript's eval need parentheses to eval JSON data?
[ "", "javascript", "json", "eval", "" ]
## Update mysql with $\_POST data from while loop I'm trying to get this round my head, but i am failing quite hard :[ I have 3 rows in a database which i am echoing out in a while() loop. A user can change `search_terms` and then save the fields in mysql, however i don't quite know how to do this, as there are 3 rows, so i can't just do; ``` <?php if($_POST['update']) { mysql_query("...."); } ?> ``` Here is my code; ``` <?php $box_query = mysql_query("SELECT * FROM `ta_boxs`"); while($box = mysql_fetch_array($box_query)) { echo '<div class="box_content">'; echo '<div class="box">'."\n"; echo '<span class="box_top"></span>'; echo '<div class="box_header"><input type="text" id="title" name="title" class="title-input" value="'.$box['title'].'" /></div>'; echo '<span class="sept"></span>'; echo '<div class="admin-back">'; echo '<form id="form-'.$box['id'].'" name="form-'.$box['id'].'" method="post" action="">'; echo '<p class="sub"><span>Includes:</span> Search for these terms in Twitter Feeds.</p>'; echo '<p class="sub-small">Please enter one word per field or click "add word".</p>'; echo '<p><input type="text" id="search_term_1" name="search_term_1" value="'.$box['search_term_1'].'" class="term-input" />'; echo '<p><input type="text" id="search_term_2" name="search_term_2" value="'.$box['search_term_2'].'" class="term-input" />'; echo '<p><input type="text" id="search_term_3" name="search_term_3" value="'.$box['search_term_3'].'" class="term-input" />'; echo '<span class="hr"></span>'; echo '<p class="sub"><span>Excludes:</span> Ignore these terms in Twitter Feeds.</p>'; echo '<p class="sub-small">Please enter one word per field or click "add word".</p>'; echo '<p><input type="text" id="search_term_1" name="search_term_1" value="'.$box['exc_search_term_1'].'" class="term-input" />'; echo '<p><input type="text" id="search_term_2" name="search_term_2" value="'.$box['exc_search_term_2'].'" class="term-input" />'; echo '<p><input type="text" id="search_term_3" name="search_term_3" value="'.$box['exc_search_term_3'].'" class="term-input" />'; echo '<input type="hidden" id="update" name="update" value="yes" />' echo '<p><input type="submit" id="update_'.$box['id'].'" name="update_'.$box['id'].'" value="Update" /></p>'; echo '</form>'; echo '</div>'; echo '</div>'."\n"; echo '<span class="box_bottom"></span>'; echo '</div>'; } ?> ``` There could be 1 output, or 100, but i need a way to save them all, onsubmit. Any ideas?
Since you're outputting each box in a different `<form>` you'll only every get one back. If you change: ``` <input type="hidden" id="update" name="update" value="yes" /> ``` to ``` <input type="hidden" id="update" name="update" value="' . $box['id'] . '" /> ``` Then you'll be able to look which one was posted back.
I don't think your approach will work because you are generating multiple forms, so PHP will only get the one form that is submitted, and you won't be able to save all the changes on your page. You might want to consider using one form and naming your inputs like an array (see <http://php.net/manual/en/faq.html.php#faq.html.arrays>) . e.g. (simplified) ``` <form method="post"> <?php while($box = mysql_fetch_array($box_query)): ?> <!-- div box thing --> <input name="box[<?php echo $box['id'];?>][search_term_1]" value="<?php echo $box['search_term_1']; ?>"> <input name="box[<?php echo $box['id'];?>][search_term_2]" value="<?php echo $box['search_term_2']; ?>"> <input name="box[<?php echo $box['id'];?>][search_term_3]" value="<?php echo $box['search_term_3']; ?>"> <input name="box[<?php echo $box['id'];?>][exc_search_term_1]" value="<?php echo $box['exc_search_term_1']; ?>"> <input name="box[<?php echo $box['id'];?>][exc_search_term_2]" value="<?php echo $box['exc_search_term_2']; ?>"> <input name="box[<?php echo $box['id'];?>][exc_search_term_3]" value="<?php echo $box['exc_search_term_3']; ?>"> <!-- end div box thing --> <?php endwhile; ?> </form> ``` If you `print_r($_POST)` after submitting that form you should see that it will be fairly easy to loop over/process.
Update mysql with $_POST data from while loop
[ "", "php", "mysql", "post", "" ]
> **Possible Duplicate:** > [Python dictionary: are keys() and values() always the same order?](https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order) If i have a dictonary in python, will .keys and .values return the corresponding elements in the same order? E.g. ``` foo = {'foobar' : 1, 'foobar2' : 4, 'kittty' : 34743} ``` For the keys it returns: ``` >>> foo.keys() ['foobar2', 'foobar', 'kittty'] ``` Now will foo.values() return the elements always in the same order as their corresponding keys?
It's hard to improve on the [Python documentation](http://docs.python.org/library/stdtypes.html#mapping-types-dict): > Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If `items()`, `keys()`, `values()`, `iteritems()`, `iterkeys()`, and `itervalues()` are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of `(value, key)` pairs using `zip(): pairs = zip(d.values(), d.keys()).` The same relationship holds for the `iterkeys()` and `itervalues()` methods: `pairs = zip(d.itervalues(), d.iterkeys())` provides the same value for pairs. Another way to create the same list is `pairs = [(v, k) for (k, v) in d.iteritems()]` So, in short, "yes" with the caveat that you must not modify the dictionary in between your call to `keys()` and your call to `values()`.
Yes, they will Just see the doc at [Python doc](http://docs.python.org/library/stdtypes.html) : > Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. Best thing to do is still to use dict.items()
Will Dict Return Keys and Values in Same Order?
[ "", "python", "" ]
I know in HTML you can use `<ol><li></li></ol>` to get a nice ordered list but doing that with list-style-type: decimal always increments the number by 1. I'm looking for a way to set the value of the bullet text. I might end up with a list that looks something like 12 item 22 item  2 item I don't want to do any crazy use of images if at all possible. Is there an easy solution for this? I have HTML, CSS, javascript (jquery) and PHP available.
That isn't really an **ordered** list then is it? You should just emulate a bullet in an unordered list: ``` <ul> <li><span>22</span> item </ul> ``` Remove the bullet with `list-style-type: none` then style to taste.
SOFlow: [Is it possible to specify a starting number for an ordered list with css?](https://stackoverflow.com/questions/779016/is-it-possible-to-specify-a-starting-number-for-an-ordered-list-with-css) [Make OL list start from number different than 1 using CSS](http://www.arraystudio.com/as-workshop/make-ol-list-start-from-number-different-than-1-using-css.html). Other than that, the only way to accomplish this is through fancy positioning. This is one of those things I wish they hadn't deprecated.
specifing text as bullets in list
[ "", "php", "html", "css", "" ]
What the best way to report a syntax error when I'm loading a JSON feed with jQuery? I can establish the error reporting settings like this: ``` error: function(xhr){ alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText); } ``` however this function doesn't fire when the URL I've called loads a valid page (albeit not one with a JSON object in it). Futhermore, I can't check the data that it does return because (according to Firebug at least) `jQuery.getJSON` breaks at the syntax error before it passes the object to the function that executes it. The reason I'd like to report errors is because this is my way of checking whether the user has supplied a URL that will produce a valid JSON feed. Here's a [related answer that requires control over what the server will respond with](https://stackoverflow.com/questions/407596/how-do-you-handle-errors-from-ajax-calls). Here's the syntax error that Firebug gives me [The syntax error Firebug gives me http://img.skitch.com/20090623-8c97g47jha4mn6adqqtjd41cwy.jpg](http://img.skitch.com/20090623-8c97g47jha4mn6adqqtjd41cwy.jpg) Any ideas? Thanks
Thanks to all who answered. Because I was calling a JSON feed from an external domain, I wasn't able to just use jQuery's AJAX functionality and pull the feed as "text" instead of "json". jQuery only allows you to pull "json" and "script" from a remote source. What I ended up doing instead was writing a PHP script to make the external call that lived on my own server. I use jQuery AJAX to call this, pass the requested source in the URL, and then grab that as "text." I then run my own check to ensure that it's properly formatted JSON, and then parse it with another library. jQuery doesn't have the ability to parse JSON at the moment; $.getJSON only works if you pass a URL to it.
You can bind a function to global ajaxerror events ``` $(document).ajaxError(function(event, request, ajaxOptions, thrownError){ if ( 4==request.readyState) { // failed after data has received alert(ajaxOptions['url'] + " did not return valid json data"); } else { alert("something else wnet wrong"); } }); ``` or use $.ajax() instead of $.getJSON() ``` function foo() { // $.getJSON("http://localhost/test.txt", function(data){}); $.ajax({ type: "GET", url: "http://localhost/test.txt", success: function (data, textStatus) { alert("succuess"); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("request failed: " + textStatus); }, dataType: "json" }); } ``` edit: But you might want to keep in mind that both [ajax(dataType:"json")](http://docs.jquery.com/Ajax/jQuery.ajax#options) and [getJSON()](http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback) (which simply invokes .ajax(dataType:"json") boil down to `data = window["eval"]("(" + data + ")")` ...this might not be what you want if you don't know what (arbitrary) data your script requests. And this could explain why firebug is catching a syntax error when you feed it an html document instead of json data. In that case better request dataType:"string" und run the data through a fully fledged json parser lib.
Reporting syntax errors in a JSON object with jQuery and/or Javascript
[ "", "javascript", "jquery", "json", "syntax-error", "" ]
This program takes 2 numbers from user input, asks them whether they'd like to find out the permutations or combinations, and then outputs the result. Here's the code. ``` #include "std_lib_facilities.h" int permutation(int first, int second) { int top_fac; int bottom_fac; for (int i = first-1; i >= 1; --i) top_fac *=i; for (int i2 = (first-second)-1; i2>=1; --i2) bottom_fac *= i2; return (top_fac/bottom_fac); } int combination(int first, int second) { int bottom_fac; for (int i = second-1; i>=1; --i) bottom_fac *= i; return permutation(first, second)/(bottom_fac); } int main() { cout << "Enter two numbers.\n"; int first = 0; int second = 0; cin >> first >> second; cout << "Now choose permutation(p) or combination(c).\n"; string choice; cin >> choice; if (choice == "p") cout << "Number of permutations: " << permutation(first,second) << endl; else if (choice == "c") cout << "Number of combinations: " << combination(first,second) << endl; else cout << "p or c stupid.\n"; keep_window_open("q"); } ``` When I try to run the program, and I choose p or c, I get a "permutations\_combinations.exe has stopped working" message. I tried to catch an error, but nothing is coming up. Any ideas? Thanks in advance.
You're not initializing the local variables `top_fac` and `bottom_fac` inside of your functions. Unlike other languages, local variables are NOT initialized to anything in particular in C or C++. The values that they receive are whatever garbage happens to be on the stack when you call the function. You should explicitly initialize `top_fac` and `bottom_fac` to 1 at the beginning of the `permutation()` and `combination()` functions. I'm guessing that `bottom_fac` is accidentally getting initialized to 0, and then you're dividing by 0 at the end of the function, which is causing the runtime failure you're seeing.
Make sure you initialize `top_fac` and `bottom_fac`.
Permutations and Combinations - Runtime Failure
[ "", "c++", "" ]
Is it possible to send an array from Flash (AS3) to JavaScript using an ExternalInterface call? I currently am calling a function multiple times from a 'for each' loop inside Flash but it goes too fast for the JavaScript to keep up. My idea is to create an array of the attributes, pass that to the JavaScript function and then to loop through that in the JavaScript. Thanks, Josh
Further to the suggestion of using JSON, this should be faster for small arrays and wouldn't require the use of eval or an external library to parse. Join an array in a string like this in flash: item1|item2|item3|item4 Pass the string to the JS and split it again using split("|")
Yes, it's possible. <http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html#call()> > ... arguments — The arguments to pass > to the function in the container. You > can specify zero or more parameters, > separating them with commas. They can > be of any ActionScript data type. When > the call is to a JavaScript function, > the ActionScript types are > automatically converted into > JavaScript types; when the call is to > some other ActiveX container, the > parameters are encoded in the request > message. A quick test: AS code: ``` if(ExternalInterface.available) { ExternalInterface.call("jsTest", [0,1,"two",{a:1,b:2}]); } ``` JS code: ``` function jsTest(arg) { alert(arg); } ```
Send array from Flash (AS3) to JavaScript
[ "", "javascript", "flash", "actionscript-3", "externalinterface", "" ]
is it possible to tell if an assembly has changed? I have a standard project that generates an assembly called MyAssembly.dll. In a separate project i read the assembly and generate a hash. When i generate a hash for the assembly it is different each time i recompile. I have set the assembly version to be static, are there any other attributes that i need to change? ``` class Program { static void Main(string[] args) { var array = File.ReadAllBytes(@"MyAssembly.dll"); SHA256Managed algo = new SHA256Managed(); var hash = algo.ComputeHash(array); Console.WriteLine(Convert.ToBase64String(hash)); } } ``` Thanks Rohan
You are probably going to need to use the version number attribute. A hash will not work because any time you recompile an assembly, it's going to be different -- even if the code didn't change at all. The reason is that every time you compile, the compiler embeds a guid into the assembly, and it puts the same guid into the corresponding .pdb file. The guid will change every time the assembly is compiled. This is how the debugger matches an assembly to the correct version of its .pdb file (it's also why you have to always save the .pdb's on anything you release, and you cannot rely upon being able to generate a pdb to match an existing assembly)
Every assembly has a `ModuleVersionId` GUID that works like a hash. If you change a single character, module id changes, but if you revert it you get the old id back. It's useful for comparing two versions of an assembly. ``` var assembly = Assembly.GetEntryAssembly(); var hashId = assembly.ManifestModule.ModuleVersionId; Console.WriteLine(hashId); ``` ``` 40744db8-a8fe-4591-9b2c-d9e3e04a2f0a ``` <https://learn.microsoft.com/en-us/dotnet/api/system.reflection.module.moduleversionid?view=net-5.0>
How to check if an assembly has changed
[ "", "c#", ".net", "" ]
We have some client code which is using the SqlConnection class in .NET to talk to a SQLServer database. It is intermittently failing with this error: "ExecuteReader requires an open and available Connection. The connection's current state is Closed" The "temporary" solution is to reboot the process, after which everything works - however, that's obviously unsatisfactory. The code is keeping a cache of SqlConnection instances, one for each database. We'd like to re-write the code, but before I do, I need to know a few things: My first question is: Is it inefficient to repeatedly connect and disconnect SqlConnection objects, or does the underlying library perform connection pooling on our behalf? ``` // Is this bad/inefficient? for(many-times) { using(SQLConnection conn = new SQLConnection(connectionString)) { // do stuff with conn } } ``` Because our code does *not* do the above, what seems the likely cause of the problem is that something happens to the underlying SQLServer database during the "lifetime" of the connection that causes the connection to be closed... If it turns out that it is worthwile to "cache" SqlConnection objects, what is the recommended way to handle all errors that could be resolved simply by "reconnecting" to the database. I'm talking about scenarios such as: * The database is taken offline and brought back online, but the client process had no open transactions while this was happening * The database was "disconnected", then "reconnected" I notice that there is a "State" property on SqlConnection... is there an appropriate way to query that? Finally, I have a test SQLServer instance set up with full access rights: how can I go about reproducing the exact error "ExecuteReader requires an open and available Connection. The connection's current state is Closed"
No, it's not inefficient to create lots of `SqlConnection` objects and close each of them when you're done. That's exactly the right thing to do. Let the .NET framework connection pooling do its job - don't try to do it yourself. You don't need to do anything specific to enable connection pooling (although you can disable it by setting `Pooling=false` in your connection string). There are many things that could go wrong if you try to cache the connection yourself. Just say no :)
You should enable [connection pooling](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.pooling.aspx) on your connection string. In that case the runtime will add back your connections to the 'pool' when you close them, instead of really disconencting. When a 'new' connection is taken out of the pool it will be reset (ie. sp\_reset\_connection is called ) then presented to your application as a brand new, fresh connection. The pool is handling transparently such cases as if the connection is closed while idling in the pool. The cost of creating a new connection 'from scratch' is significant because the authentication requires several roundtrips between client and server (depending on the authentication method and on SSL settings it can be 1 roundtrip in best case vs. about 10 in worse). And to answer your question, connection raise the [OnStateChange](http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.onstatechange.aspx) event when their state changes, but you shouldn't care about this if you use the pooling.
.NET SqlConnection class, connection pooling and reconnection logic
[ "", "c#", ".net", "sql-server", "connection-pooling", "" ]
I am having an issue with serializing and object, I can get it to create all the correct outputs except for where i have an Element that needs a value and an attribute. Here is the required output: ``` <Root> <Method>Retrieve</Method> <Options> <Filter> <Times> <TimeFrom>2009-06-17</TimeFrom> </Times> <Document type="word">document name</Document> </Filter> </Options> </AdCourierAPI> ``` I can build all of it but can not find a way to set the Document type attribute, here is a segment of the object class ``` [XmlRoot("Root"), Serializable] public class Root { [XmlElement("Method")] public string method="RetrieveApplications"; [XmlElement("Options")] public _Options Options; } public class _Options { [XmlElement("Filter")] public _Filter Filter; } public class _Filter { [XmlElement("Times")] public _Times Times; [XmlElement("Documents")] public string Documents; } ``` which gives me: ``` <Document>document name</Document> ``` rather than: ``` <Document type="word">document name</Document> ``` but I can not find a way to correct this, please advise. Thanks
Where do you have the `type` stored? Normally you could have something like: ``` class Document { [XmlAttribute("type")] public string Type { get; set; } [XmlText] public string Name { get; set; } } public class _Filter { [XmlElement("Times")] public _Times Times; [XmlElement("Document")] public Document Document; } ```
The `string` class doesn't have a `type` property, so you can't use it to create the desired output. You should create a `Document` class instead : ``` public class Document { [XmlText] public string Name; [XmlAttribute("type")] public string Type; } ``` And you should change the `Document` property to type `Document`
How to add attributes for C# XML Serialization
[ "", "c#", "xml-serialization", "" ]
When working with pointers and references in C++, it is sometimes difficult to see whether the pointer has ownership over the referenced data, or if it is just a temporal reference. For example: ``` Instance* i = new Instance(); Instance* j = i; ``` **How can it be made clear which of the 2 pointers has ownership over the instance?** In other words, how to make clear on which pointer delete has to be called? *Note:* In the above example this is not hard to see, as it is a very short piece of code. However, when the pointer is duplicated and passed around a lot, this can become unclear.
You cannot determine the owner, since there is no built in mechanism to know which pointer is owning the memory the pointer points to. If you are really concerned about this, you could always introduce your own naming convention, e.g. through some pre/post-fix to your variable names. In other words, it's your code design that can give you this information. Since you (and your coworkers) are writing the code you can always make sure that this design is enforced during implementation. This of course means that everyone has to follow these "rules". This is one reason why a common coding convention is so important. So you can read your own and other peoples code and understand it.
Firstly, it seems unnecessarily confounding to use a reference to refer to data that must be deleted. Use a pointer instead. Secondly, if you want to indicate ownership of an object, use a wrapper class that manages ownership. There is `auto_ptr` specifically for this purpose, although it has shortcomings. (These should be addressed by unique\_ptr in the next version of the language, though that doesn't help you now). Thirdly, in the simplest cases (as often as possible), don't use the heap directly. Just declare a local object, e.g. ``` std::vector<int> v; ``` This doesn't stop you transfering ownership when you need to (use `swap`).
How to make data ownership explicit in C++
[ "", "c++", "" ]
The below are the set of log data found in text file ``` ********************************************************************************** **2008/04/06** 00:35:35 193111 1008 O 9448050132# 74 **2008/04/06** 00:35:35 193116 1009 O 9448050132# 74 **12/15/2008** 8:36AM 106 01 090788573 00:01'23" ..06 **10/10/2008** 14:32:32 4400 4653 00:00:56 26656 0 0 OG AL# & 0000 0000 N 124 00 8630 T001045 **10/16** 05:04 00:01:02 A 34439242360098 *************************************************************************************** ``` I need to extract only date details(may be 200/04/06 or 10/16) from all of the above lines and display it in textbox. I know how to segregate date if the data is ordered like below ``` *************************************************************************************** 10/10/2008 14:32:32 4400 4653 00:00:56 26656 0 0 OG AL# 10/10/2008 14:33:29 4400 4653 00:00:02 26656434 0 0 OG LL# 10/10/2008 14:33:31 4400 4653 00:00:11 26656434 0 0 OG LL# *************************************************************************************** ``` The code for it is: ``` StreamReader rr = File.OpenText("C:/1.txt"); string input = null; while ((input = rr.ReadLine()) != null) { char[] seps = { ' ' }; string[] sd = input.Split(seps, StringSplitOptions.RemoveEmptyEntries); string[] l = new string[1000]; for (int i = 0; i < sd.Length; i++) { l[i] = sd[i]; textBox4.AppendText(l[i] + "\r\n"); //The date is 10 characters in length. ex:06/08/2008 if (l[i].Length == 10) textBox1.AppendText(l[i]+"\r\n"); //The time is of 8 characters in length. ex:00:04:09 if (l[i].Length == 8) textBox2.AppendText(l[i] + "\r\n"); //The phone is of 11 characters in length. ex:9480455302# if (l[i].Length == 11) textBox3.AppendText(l[i] + "\r\n"); } } ``` Can you please help me with this!!!!
There are a few oddities in your code. Most notably, the following line inside the while loop: ``` string[] l = new string[1000]; ``` This will create a 1000-element string array for each round in the while loop. Later, you will use only element `i` in that array, leaving the 999 other elements unused. Judging from the rest of the code, you could just as well simply use `sd[i]`. Also, I am guessing that textBox1, textBox2 and textBox3 should never contain the same value; if a value goes into one of them, it should never go into another one of them (except textBox4 that seem to collect all data). Then there is also no need to keep testing the value, once the correct textbox is found. Finally the following line inside the while loop: ``` char[] seps = { ' ' }; ``` This will create an identical character array for each round in the while loop; you can move that outside the loop and just reuse the same array. As for the date detection; from the data that you present, the date is the only data that contains a / character, so you could test for that rather than the length. You can try the following: ``` StreamReader rr = File.OpenText("C:/1.txt"); string input = null; char[] seps = { ' ' }; while ((input = rr.ReadLine()) != null) { string[] sd = input.Split(seps, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < sd.Length; i++) { textBox4.AppendText(sd[i] + "\r\n"); if (sd[i].Contains("/")) { // The string contains a / character; assume it is a date textBox1.AppendText(sd[i] + "\r\n"); } else if (sd[i].Length == 8) { //The time is of 8 characters in length. ex:00:04:09 textBox2.AppendText(sd[i] + "\r\n"); } else if (sd[i].Length == 11) { //The phone is of 11 characters in length. ex:9480455302# textBox3.AppendText(sd[i] + "\r\n"); } } } ```
they best option in this context is to use Regular Expression which are more accurate and won't require any sort of formating... a general Regex would be "[0-9]{2}[/]{1}[0-9]{2}[/]{1}[0-9]{4}" you can tweak it to fit your needs, in matches you can find the match value which is the exact date.. i happen to see a good regex evaluator built in silverlight <http://regexhero.net/>
Issue With Split In C#
[ "", "c#", "parsing", "string", "" ]
I am getting the following error when trying to run this query in SQL 2005: ``` SELECT tb.* FROM ( SELECT * FROM vCodesWithPEs INNER JOIN vDeriveAvailabilityFromPE ON vCodesWithPEs.PROD_PERM = vDeriveAvailabilityFromPE.PEID INNER JOIN PE_PDP ON vCodesWithPEs.PROD_PERM = PE_PDP.PEID ) AS tb; Error: The column 'PEID' was specified multiple times for 'tb'. ``` I am new to SQL.
The problem, as mentioned, is that you are selecting PEID from two tables, the solution is to specify which PEID do you want, for example ``` SELECT tb.* FROM ( SELECT tb1.PEID,tb2.col1,tb2.col2,tb3.col3 --, and so on FROM vCodesWithPEs as tb1 INNER JOIN vDeriveAvailabilityFromPE as tb2 ON tb1.PROD_PERM = tb2.PEID INNER JOIN PE_PDP tb3 ON tb1.PROD_PERM = tb3.PEID ) AS tb; ``` That aside, as Chris Lively cleverly points out in a comment the outer SELECT is totally superfluous. The following is totally equivalent to the first. ``` SELECT tb1.PEID,tb2.col1,tb2.col2,tb3.col3 --, and so on FROM vCodesWithPEs as tb1 INNER JOIN vDeriveAvailabilityFromPE as tb2 ON tb1.PROD_PERM = tb2.PEID INNER JOIN PE_PDP tb3 ON tb1.PROD_PERM = tb3.PEID ``` or even ``` SELECT * FROM vCodesWithPEs as tb1 INNER JOIN vDeriveAvailabilityFromPE as tb2 ON tb1.PROD_PERM = tb2.PEID INNER JOIN PE_PDP tb3 ON tb1.PROD_PERM = tb3.PEID ``` but please **avoid using SELECT \* whenever possible**. It may work while you are doing interactive queries to save typing, but in production code never use it.
Looks like you have the column *PEID* in both tables: *vDeriveAvailabilityFromPE* and *PE\_PDP*. The `SELECT` statement tries to select both, and gives an error about duplicate column name.
SQL 2005 - The column was specified multiple times
[ "", "sql", "database", "" ]
I have several methods that I need to wrap in new methods in basically the same manner. My first solution doesn't work, and I understand why, but I don't know if there is a simple solution to this problem or if it can't be done the way that I want to do it. Here's an example. I have objects a-c that have an onClick method. I need to execute some code before the onClick methods. I tried the following: ``` // objects a-c a = {onClick : function () { console.log('a'); }}; b = {onClick : function () { console.log('b'); }}; c = {onClick : function () { console.log('c'); }}; // first try var arr = [a, b, c] for (var i = 0; i < arr.length; i++) { var oldOnClick = arr[i].onClick; arr[i].onClick = function () { // new code here oldOnClick(); } } // outputs 'c' // what i want is to maintain a reference to the original method // so in this case, execute my new code and output 'a' a.onClick(); ``` This doesn't work because when the new method is called, oldOnClick will point to the method from the last iteration and not the to method when it was assigned. Is there a simple solution that I'm overlooking?
What you need is closure: ``` for(var i=0, l=arr.length; i<l; i++){ (function(i){ var oldOnclick = arr[i].onClick; //etc. })(i); } ```
Javascript binding rules are pretty odd. Really, javascript is pretty odd. I don't know that I'd call this *the* way to fix it, but by introducing a sub-function you can get introduce another bind and thereby fix this particular problem. Your (modified for quick-y Chrome hacking) code becomes: ``` a = {onClick : function () { alert('a'); }}; b = {onClick : function () { alert('b'); }}; c = {onClick : function () { alert('c'); }}; var arr = [a, b, c] for (var i = 0; i < arr.length; i++) { var oldOnClick = arr[i].onClick; arr[i].onClick = bind(oldOnClick); } a.onClick(); b.onClick(); c.onClick(); function bind(oldFunc) { return function () { //New Code oldFunc(); } } ``` The above code throws up three alerts: a, b, c. Anything replacing '//New Code' will be run at the right time.
How can I replace (wrap) methods in new methods programmatically?
[ "", "javascript", "methods", "scope", "variable-assignment", "" ]
I am trying to get inline C# to work in my JavaScript files using the MVC Framework. I made this little test code up. ``` $(document).ready(function() { alert(<%= ViewData["Message"] %>); }); ``` When this code is used inside of the view it works perfectly. When I get outside of my aspx view and try this in a JavaScript file I get illegal XML character. I figure this is by design in the MVC Framework but I haven't been able to find any material on this on the web. Has anyone gotten inline C# to work in JavaScript files using the MVC Framework?
As others have said, the C# is not being processed by the server. A possible solution would be to have a separate view that uses the same model and outputs the JavaScript, then reference that view in your `<script type="text/javascript" src="yourJSview.aspx"></script>`. Added as per [SLaks' answer](https://stackoverflow.com/questions/1045451/using-inline-c-inside-javascript-file-in-mvc-framework/1045499#1045499): Set the content-type to `text/javascript`, and put your JavaScript source **directly** below the `<%@ Page` directive (without a `<script>` tag). Beware that you won't get any IntelliSense for it in VS.
You could make an ASPX view that renders JavaScript. Set the content-type to `text/javascript`, and put your JavaScript source **directly** below the `<%@ Page` directive (without a `<script>` tag). Beware that you won't get any IntelliSense for it in VS.
Using Inline C# inside Javascript File in MVC Framework
[ "", "javascript", "asp.net-mvc", "" ]
In this very contrived example, I have an array with 3 elements that I'm looping over using the [`.each()`](http://www.prototypejs.org/api/enumerable/each) method. ``` var vals = $w('foo bar baz'); vals.each( function(val) { alert(val); if( val == 'bar' ) { //This exits function(val) //but still continues with the .each() return; } }); ``` I can easily return out of the function being called by **`.each()`** if I need to. My question is, **how can I break out of the `.each()` loop from inside the function that `.each()` is calling?**
``` if( val == 'bar' ) { throw $break; } ``` It's documented at the same page you linked. It's an exception specially handled by the each function. When thrown, it prevents your function from being called on further elements.
Your are correct, and Prototype has created an object (**$break**) that can be thrown from the each-function to enable this functionality. According to the Prototype API docs: > Regular loops can be short-circuited in JavaScript using the break and continue statements. However, when using iterator functions, your code is outside of the loop scope: the looping code happens behind the scene. > > In order to provide you with equivalent (albeit less optimal) functionality, Prototype provides two global exception objects, $break and $continue. Throwing these is equivalent to using the corresponding native statement in a vanilla loop. These exceptions are properly caught internally by the each method. Also, note that the $continue object has been deprecated, and to simulate a *continue*-statement, use a vanilla return statement instead. Code example: ``` var result = []; $R(1,10).each(function(n) { if (0 == n % 2) return; // this equals continue if (n > 6) throw $break; result.push(n); }); // result -> [1, 3, 5] ``` You can read more about the each-function here: <http://www.prototypejs.org/api/enumerable/each>
Breaking out of a PrototypeJS .each() loop
[ "", "javascript", "prototypejs", "" ]
Good day everyone. I am working on a Firefox extension, and I want to pop up a tooltip at a certain offset from the mouse cursor. However, the problem comes when this offset is out of the viewport. It gets displayed but the user will have to scroll over there. I hope to enhance this by moving the tooltip pop-up within the current viewport. However, a problem arises because the only clue I have to where I am in the document is the mouse-position. A partial solution would be to calculate how much to move my tooltip by finding out if the current mouse coordinate + the tooltip width/height and see if it will exceed window.innerHeight or window.innerWidth. However, I come to realize that if it was a very long document and the user scrolled down a fair bit, the mouse coordinate would have a very large y value. Therefore, I can't rely solely on window.innerHeight to see if I am still within the viewport. Anyone found a way to find out the mouse coordinate of the top left corner in the viewport if the user has scrolled down a lot? Thank you in advance! =)
More specifically in your case, `document.body.scrollTop`. However, that's pretty IE-specific, which defeats the purpose of most FireFox extensions. ;-) There are also some DTD dependencies to boot. This looks like what you want: [Determining browser dimensions and document scroll offsets](http://www.javascriptkit.com/javatutors/static2.shtml)
I think you are looking for something like the *[scrollTop](https://developer.mozilla.org/en/DOM/element.scrollTop)* property: > scrollTop gets or sets the number of pixels that the content of an element is scrolled upward.
Firefox: Get mouse coordinates of top-left corner of viewport
[ "", "javascript", "firefox", "firefox-addon", "xul", "" ]
I have an Eclipse project where I want to keep my Java project built into a JAR automatically. I know I have an option to export the project into a JAR; if I do a right click; but what I am really looking for is, that like Eclipse automatically builds a project's `.class` files and put them in target folder; it should also build a JAR automatically and copy the latest JAR at some or a specific location. Is there a option to configure Eclipse in such a way, to build JARs automatically? Just to make it clear for guys, patient enough to answer my question; I am not looking at ANT as solution; as I already use it, but what I would like it something that gets initiated automatically either with a time based trigger or immediate build with change.
Check out [Apache Ant](http://ant.apache.org/ "Apache Ant") It's possible to use Ant for automatic builds with eclipse, [here's how](http://www.simonwhatley.co.uk/using-ant-with-eclipse)
You want a `.jardesc` file. They do not kick off automatically, but it's within 2 clicks. 1. Right click on your project 2. Choose `Export > Java > JAR file` 3. Choose included files and name output JAR, then click `Next` 4. Check "Save the description of this JAR in the workspace" and choose a name for the new `.jardesc` file Now, all you have to do is right click on your `.jardesc` file and choose `Create JAR` and it will export it in the same spot.
Build project into a JAR automatically in Eclipse
[ "", "java", "eclipse", "jar", "" ]
I have clients who still using dot matrix for making copies of printed documents (like invoice, reports, etc). I did a development using grails (web application) for internal company only (so it doesnt matter to install / update all java re in all computers) I am still learning (just started) Javafx. can i use this javafx to print from file to dotmatrix printer ? or shall i use applet instead ? *friends of mine told me that java has lib to print to dot matrix, that's why i am stick to javafx or applet* which one is the easier and better (also faster) using applet or javafx? the interface is quite simple, just a form with 2 input fields and a button for printing.
Any Java API/Library can be accessed from JavaFX - there is no limitation. You can do the UI of the application and core logic in JavaFX and use the existing Java Lib for printing stuff (the [Print Service API](http://java.sun.com/j2se/1.4.2/docs/guide/jps/index.html) might be a good start). Doing this as an Applet might not be best idea, I would recommend using WebStart deployment.
Java has a [Print Service API](http://java.sun.com/j2se/1.4.2/docs/guide/jps/index.html). It would be worth checking that out. I suspect it won't work via an applet, however (I would guess the security model gets in the way).
can javafx print to dot matrix printer?
[ "", "java", "grails", "printing", "javafx", "" ]
I recently started experimenting with Python decorators (and higher-order functions) because it looked like they might make my Django unit tests more concise. e.g., instead of writing: ``` def visit1(): login() do_stuff() logout() ``` I could instead do ``` @handle_login def visit1(): do_stuff() ``` However, after some experimenting, I have found that decorators are not as simple as I had hoped. First, I was confused by the different decorator syntax I found in different examples, until I learned that decorators behave very differently when they [take arguments](http://www.artima.com/weblogs/viewpost.jsp?thread=240845). Then I tried decorating a method, and eventually learned that it wasn't working because I first have to [turn my decorator into a descriptor](http://www.nabble.com/Decorating-methods---where-do-my-arguments-go--td23448341.html) by adding a `__get__` method. During this whole process I've ended up confused more than a few times and still find that debugging this "decorated" code is more complicated than it normally is for Python. I'm now re-evaluating whether I really need decorators in my code, since my initial motivation was to save a bit of typing, not because there was anything that really required higher-order functions. So my question is: should decorators be used liberally or sparingly? Is it ever more Pythonic to avoid using them?
Decorators are fine in their place and definitely not to be avoided -- when appropriate;-). I see your question as meaning essentially "OK so when *are* they appropriate"? Adding some prefix and/or postfix code around some but not all methods of some classes is a good example. Were it all methods, a *class* decorator to wrap all methods would be better than repeating `@thisonetoo` endlessly;-). If it's once in a blue moon then it's not worth refactoring out to wrappers (decorators or otherwise). In the middle, there's a large ground where decorators are quite suitable indeed. It boils down to one of the golden rules of programming -- DRY, for Don't Repeat Yourself. When you see your code becoming repetitious, you should refactor the repetition out -- and decorators are an excellent tool for that, although they're far from the only one (auxiliary methods and functions, custom metaclasses, generators and other iterators, context managers... *many* of the features we added to Python over the last few years can best be thought of as DRY-helpers, easier and smoother ways to factor out this or that frequent form of repetition!). If there's no repetition, there's no real call for refactoring, hence (in particular) no real need for decorators -- in such cases, YAGNI (Y'Ain't Gonna Need It) can trump DRY;-).
Alex already answered your question pretty well, what I would add is decorators, make your code MUCH easier to understand. (Sometimes, even if you are doing it only once). For example, initially, I write my Django views, without thinking about authorisation at all. And when, I am done writing them, I can see which need authorised users and just put a @login\_required for them. So anyone coming after me can at one glance see what views are auth protected. And of course, they are much more DRY and putting this everywhere. if not request.user.is\_authenticated(): return HttpResponseREdiect(..)
How frequently should Python decorators be used?
[ "", "python", "django", "decorator", "" ]
This seems to be a bit of an infamous error all over the web. So much so that I have been unable to find an answer to my problem as my scenario doesn't fit. An exception gets thrown when I save the image to the stream. Weirdly this works perfectly with a png but gives the above error with jpg and gif which is rather confusing. Most similar problem out there relate to saving images to files without permissions. Ironically the solution is to use a memory stream as I am doing.... ``` public static byte[] ConvertImageToByteArray(Image imageToConvert) { using (var ms = new MemoryStream()) { ImageFormat format; switch (imageToConvert.MimeType()) { case "image/png": format = ImageFormat.Png; break; case "image/gif": format = ImageFormat.Gif; break; default: format = ImageFormat.Jpeg; break; } imageToConvert.Save(ms, format); return ms.ToArray(); } } ``` More detail to the exception. The reason this causes so many issues is the lack of explanation :( ``` System.Runtime.InteropServices.ExternalException was unhandled by user code Message="A generic error occurred in GDI+." Source="System.Drawing" ErrorCode=-2147467259 StackTrace: at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(Stream stream, ImageFormat format) at Caldoo.Infrastructure.PhotoEditor.ConvertImageToByteArray(Image imageToConvert) in C:\Users\Ian\SVN\Caldoo\Caldoo.Coordinator\PhotoEditor.cs:line 139 at Caldoo.Web.Controllers.PictureController.Croppable() in C:\Users\Ian\SVN\Caldoo\Caldoo.Web\Controllers\PictureController.cs:line 132 at lambda_method(ExecutionScope , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) InnerException: ``` OK things I have tried so far. 1. Cloning the image and working on that. 2. Retrieving the encoder for that MIME passing that with jpeg quality setting.
OK I seem to have found the cause just by sheer luck and its nothing wrong with that particular method, it's further back up the call stack. Earlier I resize the image and as part of that method I return the resized object as follows. I have inserted two calls to the above method and a direct save to a file. ``` // At this point the new bitmap has no MimeType // Need to output to memory stream using (var m = new MemoryStream()) { dst.Save(m, format); var img = Image.FromStream(m); //TEST img.Save("C:\\test.jpg"); var bytes = PhotoEditor.ConvertImageToByteArray(img); return img; } ``` It appears that the memory stream that the object was created on **has** to be open at the time the object is saved. I am not sure why this is. Is anyone able to enlighten me and how I can get around this. I only return from a stream because after using the resize code similar to [this](https://stackoverflow.com/questions/30569/resize-transparent-images-using-c) the destination file has an unknown mime type (img.RawFormat.Guid) and Id like the Mime type to be correct on all image objects as it makes it hard write generic handling code otherwise. **EDIT** This didn't come up in my initial search but [here's](https://stackoverflow.com/questions/336387/image-save-throws-a-gdi-exception-because-the-memory-stream-is-closed) the answer from Jon Skeet
If you are getting that error , then I can say that your application doesn't have a write permission on some directory. For example, if you are trying to save the Image from the memory stream to the file system , you may get that error. Please if you are using XP, make sure to add write permission for the aspnet account on that folder. If you are using windows server (2003,2008) or Vista, make sure that add write permission for the Network service account. Hope it help some one.
A generic error occurred in GDI+, JPEG Image to MemoryStream
[ "", "c#", "gdi+", "" ]
Lets say I have model inheritance set up in the way defined below. ``` class ArticleBase(models.Model): title = models.CharField() author = models.CharField() class Review(ArticleBase): rating = models.IntegerField() class News(ArticleBase): source = models.CharField() ``` If I need a list of all articles regardless of type (in this case both Reviews and News) ordered by title, I can run a query on ArticleBase. Is there an easy way once I have an ArticleBase record to determine if it relates to a Review or a News record without querying both models to see which has the foreign key of the record I am on?
I am assuming that all ArticleBase instances are instances of ArticleBase subclasses. One solution is to store the subclass name in ArticleBase and some methods that return the subclass or subclass object based on that information. As multi-table inheritance defines a property on the parent instance to access a child instance, this is all pretty straight forward. ``` from django.db import models class ArticleBase(models.Model): title = models.CharField() author = models.CharField() # Store the actual class name. class_name = models.CharField() # Define save to make sure class_name is set. def save(self, *args, **kwargs): self.class_name = self.__class__.__name__ super(ArticleBase, self).save(*args, **kwargs) # Multi-table inheritance defines an attribute to fetch the child # from a parent instance given the lower case subclass name. def get_child(self): return getattr(self, self.class_name.lower()) # If indeed you really need the class. def get_child_class(self): return self.get_child().__class__ # Check the type against a subclass name or a subclass. # For instance, 'if article.child_is(News):' # or 'if article.child_is("News"):'. def child_is(self, cls): if isinstance(cls, basestring): return cls.lower() == self.class_name.lower() else: return self.get_child_class() == cls class Review(ArticleBase): rating = models.IntegerField() class News(ArticleBase): source = models.CharField() ``` This is by no means the only way to go about this. It is, however, a pretty simple and straight forward solution. The excellent contrib contenttypes app and the generic module which leverages it offer a wealth of ways to do this, well, generically. It could be useful to have the following in ArticleBase: ``` def __unicode__(self) return self.get_child().__unicode__() ``` In that case, be aware that failure to define `__unicode__` in the subclasses, or calling `__unicode__` on an instance of ArticleBase (one that has not been subclassed) would lead to an infinite recursion. Thus the admonition below re sanity checking (for instance, preventing just such an instantiation of ArticleBase directly). **Disclaimer:** This code is untested, I'm sure I've got a typo or two in there, but the basic concept should be sound. Production level code should probably have some sanity checking to intercept usage errors.
You don't ever need to know the subclass of an ArticleBase. The two subclasses -- if you design this properly -- have the same methods and can be used interchangeably. Currently, your two subclasses aren't trivially polymorphic. They each have unique attributes. For the 80% case, they have nothing to do with each other, and this works out fine. The phrase "all articles regardless of type" is a misleading way to describe what you're doing. It makes it sound simpler than it really is. What you're asking for a is a "union of News and Reviews". I'm not sure what you'd do with this union -- index them perhaps. For the index page to work simply, you have to delegate the formatting details to each subclass. They have to emit an HTML-friendly summary from a method that both subclasses implement. This summary is what your template would rely on. ``` class Review(ArticleBase): rating = models.IntegerField() def summary( self ): return '<span class="title">%s</span><span class="author">%s</span><span class="rating">%s</span>' % ( self.title, self.author, self.rating ) ``` A similar `summary` method is required for News. Then you can union these two disjoint types together to produce a single index.
Can you access a subbed-classed model from within the super-class model in the Django ORM?
[ "", "python", "django", "django-models", "" ]
I am at a point where I need to take the decision on what to do when caching of objects reaches the configured threshold. Should I store the objects in a indexed file (like provided by JCS) and read them from the file (file IO) when required or have the object stored in a distributed cache (network, serialization, deserialization) We are using Solaris as OS. ============================ Adding some more information. I have this question so as to determine if I can switch to distributed caching. The remote server which will have cache will have more memory and better disk and this remote server will only be used for caching. One of the problems we cannot increase the locally cached objects is , it stores the cached objects in JVM heap which has limited memory(using 32bit JVM). ======================================================================== Thanks, we finally ended up choosing Coherence as our Cache product. This provides many cache configuration topologies, in process vs remote vs disk ..etc.
It's going to depend on many things such as disk speed, network latency and the amount of data, so some experimentation might be the best way to get an idea. I recommend you have a look at <http://ehcache.org/>, it might come in handy.
The only way to really know is to test it, but with good network latency from your cache, it could well be faster than local disk access. Once you are dealing with a large enough rate of cache requests, serialised random access to the local disk is likely to become a problem.
Java object caching, which is faster, reading from a file or from a remote machine?
[ "", "java", "caching", "jcs", "" ]
I am using [jquery's "$.post()"](http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype) function to add a list entry to the mysql database, in php. ``` $(document).ready(function(){ $(".theSubmit").click(function(){ var content = $("textarea").val(); var listn = $("input[name='list_name']").val(); var groupn = $("input[name='group_name']").val(); $.post("/secret_url/lists/add_to_list", {list_item: content, list_name: listn, group_name:groupn}, function(html){$("li:last").after(html);}); }); }); ``` All that works fine and the new list item is added to the page. However,using firebug, I observe that I get this extra html header information (see below) as well as my returned data. The info I want and render to the page is inside the "li" below. Everything from the doctype after I'd like to strip or prevent from being included since it becomes visible inside a [jeditable](http://www.appelsiini.net/projects/jeditable) edit in place input also on the page. ``` <li> <input type="checkbox" name="row" class="checkbox"> <input type ="hidden" name="id" value="60" class="contentId"> <div id="60" class="editable">test Item 4</div> </li> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html/strict.dtd"> <html> <head> <title>Checklists</title> <link href="http://checklist.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript" src="jquery-ui-1.7.custom.min.js"></script> <script type="text/javascript" src="jquery.jeditable.js"></scrip > </head> <body> ``` Can I strip the html head content or stop it from being sent back along with the pertinent info?
Just add an ``` exit; ``` statement in the file where you output your response data. Directly after you have output all you want as response body. simplified example ``` <?php .... do something do process request ... ?> <li> <input type="checkbox" name="row" class="checkbox"> <input type ="hidden" name="id" value="60" class="contentId"> <div id="60" class="editable">test Item 4</div> </li> <?php exit; ?> ```
What do you use? ASP.NET, PHP? You have to tell your server to stop processing the request after you've written the desired response. It seems that the server continues to add the normal GET/POST content for that URL. (as if you would submit the form without AJAX)
How to stop html header content from being included in jquery post results?
[ "", "php", "jquery", "html", "ajax", "" ]
I am using `file_put_contents($file, $data);` function for putting contents in file, because these files are created on fly with name of sessions, **$data** is an multi-dimensional array, when i am echoing array it prints out fine but in file no contents get recorded except the word **Array** What should i do or is there any other function which automatically creates the file and records the data (array)? Thank You.
You want to `serialize()` the array on writting, and `unserialize()` after reading the file. ``` $array = array('foo' => 'bar'); file_put_contents('foo.txt', serialize($array)); $array = unserialize(file_get_contents('foo.txt'))); ``` Oh, and I really don't now how you echo'd your array, but `echo array('foo' => 'bar');` will always print `Array`.
Or use [print\_r](http://php.net/manual/en/function.print-r.php) if you want to return a formatted array that is more easily readable in the txt file > If you would like to capture the output of print\_r(), use the return > parameter. When this parameter is set to TRUE, [print\_r()](https://www.php.net/manual/en/function.print-r.php) will return > the information rather than print it. Code is: ``` $txt = "<pre>".print_r($data, true)."</pre>"; file_put_contents('file.txt', $txt); ```
file put contents with array
[ "", "php", "" ]
Consider: ``` class A { public: A( int val ) : m_ValA( val ) {} A( const A& rhs ) {} int m_ValA; }; class B : public A { public: B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {} B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {} int m_ValB; }; int main() { A* b1 = new B( 1, 2 ); A* b2 = new A( *b1 ); // ERROR...but what if it could work? return 0; } ``` Would C++ be broken if "new A( *b1 )" was able to resolve to creating a new B copy and returning an A*? Would this even be useful?
Do you need this functionality, or is this just a thought experiment? If you need to do this, the common idiom is to have a `Clone` method: ``` class A { public: A( int val ) : m_ValA( val ) {} A( const A& rhs ) {} virtual A *Clone () = 0; int m_ValA; }; class B : public A { public: B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {} B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {} A *Clone() { return new B(*this); } int m_ValB; }; int main() { A* b1 = new B( 1, 2 ); A* b2 = b1->Clone(); return 0; } ```
What you're really looking for is called a [virtual copy constructor](https://isocpp.org/wiki/faq/virtual-functions#virtual-ctors), and what eduffy posted is the standard way of doing it. There are also [clever ways of doing it with templates](http://nerdland.net/2009/06/covariant-templatized-virtual-copy-constructors/). (disclaimer: self-promotion)
C++: Could Polymorphic Copy Constructors work?
[ "", "c++", "copy-constructor", "" ]
I want to inherit from a class in a file that lies in a directory above the current one. Is it possible to relatively import that file?
`from ..subpkg2 import mod` Per the Python docs: When inside a package hierarchy, use two dots, as the [import statement](http://docs.python.org/reference/simple_stmts.html#the-import-statement) doc says: > When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after `from` you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. **Two dots means up one package level**. Three dots is up two levels, etc. So if you execute `from . import mod` from a module in the `pkg` package then you will end up importing `pkg.mod`. If you execute `from ..subpkg2 import mod` from within `pkg.subpkg1` you will import `pkg.subpkg2.mod`. The specification for relative imports is contained within [PEP 328](http://www.python.org/dev/peps/pep-0328/). [PEP 328](http://www.python.org/dev/peps/pep-0328/) deals with absolute/relative imports.
``` import sys sys.path.append("..") # Adds higher directory to python modules path. ```
How to import a Python class that is in a directory above?
[ "", "python", "module", "directory", "python-import", "" ]
I'm running a web application in JBoss AS 5. I also have a servlet filter which intercepts all the requests to the server. Now, I want to redirect the users to the login page, if the session has expired. I need to do this 'isSessionExpired()' check in the filter and need to redirect the user accordingly. How do I do it? I'm setting my session time limit in web.xml, as below: ``` <session-config> <session-timeout>15</session-timeout> </session-config> ```
You could use a [Filter](https://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html) and do the following test: ``` HttpSession session = request.getSession(false);// don't create if it doesn't exist if(session != null && !session.isNew()) { chain.doFilter(request, response); } else { response.sendRedirect("/login.jsp"); } ``` **The above code is untested**. This isn't the most extensive solution however. You should also test that some domain-specific object or flag is available in the session before assuming that because a session isn't new the user must've logged in. **Be paranoid**!
> *How to redirect to Login page when Session is expired in Java web application?* This is a wrong question. You should differentiate between the cases "User is not logged in" and "Session is expired". You basically want to redirect to login page when user is not logged in. Not when session is expired. The currently accepted answer only checks `HttpSession#isNew()`. But this obviously fails when the user has sent more than one request in the same session when the session is implicitly created by the JSP or what not. E.g. when just pressing F5 on the login page. As said, you should instead be checking if the user is logged in or not. Given the fact that you're asking this kind of question while standard authentication frameworks like `j_security_check`, Shiro, Spring Security, etc already transparently manage this (and thus there would be no need to ask this kind of question on them), that can only mean that you're using a homegrown authentication approach. Assuming that you're storing the logged-in user in the session in some login [servlet](https://stackoverflow.com/tags/servlets/info) like below: ``` @WebServlet("/login") public class LoginServlet extends HttpServlet { @EJB private UserService userService; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); User user = userService.find(username, password); if (user != null) { request.getSession().setAttribute("user", user); response.sendRedirect(request.getContextPath() + "/home"); } else { request.setAttribute("error", "Unknown login, try again"); doGet(request, response); } } } ``` Then you can check for that in a login [filter](https://stackoverflow.com/tags/servlet-filters/info) like below: ``` @WebFilter("/*") public class LoginFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); String loginURI = request.getContextPath() + "/login"; boolean loggedIn = session != null && session.getAttribute("user") != null; boolean loginRequest = request.getRequestURI().equals(loginURI); if (loggedIn || loginRequest) { chain.doFilter(request, response); } else { response.sendRedirect(loginURI); } } // ... } ``` No need to fiddle around with brittle `HttpSession#isNew()` checks.
How to redirect to Login page when Session is expired in Java web application?
[ "", "java", "servlets", "authentication", "servlet-filters", "" ]
**Scenario:** I have a directory on a server that hosts my website that contains hundreds of user-submitted images. I am creating a backup script that takes all the images from the directory and compresses them into one .tar.gz file. The command I have so far is: tar -czpf /path/to/backups/my\_backup.tar.gz path/to/images/ **Problem:** No inside my path/to/images/ I have a directory called tmp/. When I run the command, I get a .tar.gz file containing all the image in the path/to/images/ directory and a subdirectory called tmp/. **Question:** How can I get the command to skip/not include the tmp/ subdirectory in the .tar.gz file. Thanks a million in advance.
You are looking for the `--exclude` argument. ``` --exclude=PATTERN ``` Some users find `exclude` options confusing. Here are some common pitfalls: * The main operating mode of `tar` does not act on a path name explicitly listed on the command line if one of its file name components is excluded. In the example above, if you create an archive and exclude files that end with `*.o`, but explicitly name the file `dir.o/foo` after all the options have been listed, `dir.o/foo` will be excluded from the archive. * You can sometimes confuse the meanings of `--exclude=PATTERN` and `--exclude-from=FILE-OF-PATTERNS` (`-X FILE-OF-PATTERNS`). Be careful: use `--exclude=PATTERN` when files to be excluded are given as a pattern on the command line. Use `--exclude-from=FILE-OF-PATTERNS` to introduce the name of a file which contains a list of patterns, one per line; each of these patterns can exclude zero, one, or many files. * When you use `--exclude=PATTERN`, be sure to quote the PATTERN parameter, so GNU `tar` sees wildcard characters like `*`. If you do not do this, the shell might expand the `*` itself using files at hand, so `tar` might receive a list of files instead of one pattern, or none at all, making the command somewhat illegal. This might not correspond to what you want. For example, write: ``` $ tar -c -f ARCHIVE.TAR --exclude '*.o' DIRECTORY ``` rather than: ``` $ tar -c -f ARCHIVE.TAR --exclude *.o DIRECTORY ``` * You must use use shell syntax, or globbing, rather than `regexp` syntax, when using exclude options in `tar`. If you try to use `regexp` syntax to describe files to be excluded, your command might fail.
``` tar -czpf /path/to/backups/my_backup.tar.gz --exclude path/to/images/tmp path/to/images/ ```
Linux tar command: compressing a directory but exluding subdirectories
[ "", "php", "command-line", "tar", "" ]
I am working in a mailing application in C# and, basically, I need to be able to determine which recipients successfully received the message, which ones did not, no matter what was the failure reason. In summary, I need an exception to be thrown whenever the email address does not exist, for example. However, SmtpClient.Send does not throw an exception in this case, so I'd need to monitor the delivery failure replies and parse them, maybe. I know this is not a simple task, so I'd ask you experts some tips on how to handle the main issues with email sending. Thanks in advance!!
Unless you used images with hashes you track or similar, I don't think you will be able to for security reasons. A lot of mail clients don't automatically download images too. Imagine if spammers could reliably determine which of their emails were being received? You could try ping the server... i.e. gmail.com but I don't know how reliable this will be either.
There's no way you could detect that reliably. It's the nature of SMTP protocol. It's completely up to the recipient SMTP server to choose to tell you if the email is delivered or not.
Determine if e-mail message can be successfully sent
[ "", "c#", "email", "spam-prevention", "" ]
I am writing a validation tool that checks the versions of files referenced in a project. I want to use the same resolution process that MSBuild uses. For example, Assembly.Load(..) requires a fully-qualified assembly name. However, in the project file, we may only have something like "System.Xml". MSBuild probably uses the project's target framework version and some other heuristics to decide which version of System.Xml to load. How would you go about mimicking (or directly using) msbuild's assembly resolution process? In other words, at run-time, I want to take the string "System.Xml", along with other info found in a .csproj file and find the same file that msbuild would find.
I had this problem today, and I found this old blog post on how to do it: <http://blogs.msdn.com/b/jomo_fisher/archive/2008/05/22/programmatically-resolve-assembly-name-to-full-path-the-same-way-msbuild-does.aspx> I tried it out, works great! I modified the code to find 4.5.1 versions of assemblies when possible, this is what I have now: ``` #if INTERACTIVE #r "Microsoft.Build.Engine" #r "Microsoft.Build.Framework" #r "Microsoft.Build.Tasks.v4.0" #r "Microsoft.Build.Utilities.v4.0" #endif open System open System.Reflection open Microsoft.Build.Tasks open Microsoft.Build.Utilities open Microsoft.Build.Framework open Microsoft.Build.BuildEngine /// Reference resolution results. All paths are fully qualified. type ResolutionResults = { referencePaths:string array referenceDependencyPaths:string array relatedPaths:string array referenceSatellitePaths:string array referenceScatterPaths:string array referenceCopyLocalPaths:string array suggestedBindingRedirects:string array } let resolve (references:string array, outputDirectory:string) = let x = { new IBuildEngine with member be.BuildProjectFile(projectFileName, targetNames, globalProperties, targetOutputs) = true member be.LogCustomEvent(e) = () member be.LogErrorEvent(e) = () member be.LogMessageEvent(e) = () member be.LogWarningEvent(e) = () member be.ColumnNumberOfTaskNode with get() = 1 member be.ContinueOnError with get() = true member be.LineNumberOfTaskNode with get() = 1 member be.ProjectFileOfTaskNode with get() = "" } let rar = new ResolveAssemblyReference() rar.BuildEngine <- x rar.IgnoreVersionForFrameworkReferences <- true rar.TargetFrameworkVersion <- "v4.5.1" rar.TargetedRuntimeVersion <- "v4.5.1" rar.TargetFrameworkDirectories <- [||] //[|@"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\"|] rar.Assemblies <- [|for r in references -> new Microsoft.Build.Utilities.TaskItem(r) :> ITaskItem|] rar.AutoUnify <- true rar.SearchPaths <- [| "{CandidateAssemblyFiles}" "{HintPathFromItem}" "{TargetFrameworkDirectory}" // "{Registry:Software\Microsoft\.NetFramework,v3.5,AssemblyFoldersEx}" "{AssemblyFolders}" "{GAC}" "{RawFileName}" outputDirectory |] rar.AllowedAssemblyExtensions <- [| ".exe"; ".dll" |] rar.TargetProcessorArchitecture <- "x86" if not (rar.Execute()) then failwith "Could not resolve" { referencePaths = [| for p in rar.ResolvedFiles -> p.ItemSpec |] referenceDependencyPaths = [| for p in rar.ResolvedDependencyFiles -> p.ItemSpec |] relatedPaths = [| for p in rar.RelatedFiles -> p.ItemSpec |] referenceSatellitePaths = [| for p in rar.SatelliteFiles -> p.ItemSpec |] referenceScatterPaths = [| for p in rar.ScatterFiles -> p.ItemSpec |] referenceCopyLocalPaths = [| for p in rar.CopyLocalFiles -> p.ItemSpec |] suggestedBindingRedirects = [| for p in rar.SuggestedRedirects -> p.ItemSpec |] } [<EntryPoint>] let main argv = try let s = resolve([| "System" "System.Data" "System.Core, Version=4.0.0.0" "Microsoft.SqlServer.Replication" |], "") printfn "%A" s.referencePaths finally ignore (System.Console.ReadKey()) 0 ```
This should show you how to do what you really want, but I think you should use the FXCop answer I provided. ``` static void Main() { string targetFile = @"test.csproj"; XDocument xmlDoc = XDocument.Load(targetFile); XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; var references = from reference in xmlDoc.Descendants(ns + "ItemGroup").Descendants(ns + "Reference") select reference.Attribute("Include").Value; foreach (var reference in references) { Assembly.LoadWithPartialName(reference); } foreach (var item in AppDomain.CurrentDomain.GetAssemblies()) { var assemblyVersion = ((AssemblyFileVersionAttribute)item.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true)[0]).Version.ToString(); Console.WriteLine("\r\nFullname:\t{0}\r\nFileVersion:\t{1}", item.FullName, assemblyVersion); } Console.WriteLine("\r\nPress any key to continue"); Console.ReadKey(); } ```
Mimicking assembly resolution of the msbuild process
[ "", "c#", "msbuild", "assembly-resolution", "" ]
I was looking at Zend\_Paginator in Zend Framework project using MVC, and it looks like an intersting tool. It looks like we can give a select object as argument to the factory, it's interesting because it means that i should return a select object from my model, is it a good way to do ? It seems to be a bit heavy to do this, since it won't be needed all the times... I can also give an array, which could come as a result of my method model, but in the case where i have a lot of data, it could be complicated to retrieve all the data from my database each times. How can i handle this ?
Well, i finally found an interesting way to do. First, i implemented a Domain Model pattern after a read on [Matthew Weier O'Phinney's blog](http://weierophinney.net/matthew/archives/202-Model-Infrastructure.html), who explains how to. Then, i created my [own adapter of Zend\_Paginator](http://www.noginn.com/2009/01/18/models-and-zend_paginator/), to agree with my Model. It's the most interesting way to do, i've found until now.
From the doc: <http://framework.zend.com/manual/en/zend.paginator.usage.html> > However, it is possible to directly supply a count or count query yourself. See the setRowCount() method in the DbSelect adapter for more information. And > In the case of the Null adapter, in lieu of a data collection you must supply an item count to its constructor. I would suggest doing the count yourself, and then manually setting it. That is, based upon the reading I just did. Also, the doc states that if you go the NULL route, you can provide an item-count (Integer) to the Paginator constructor instead - this seems a bit more reasonable than querying for the number with each request.
How do you handle Zend_Paginator?
[ "", "php", "design-patterns", "zend-framework", "pagination", "" ]
If in the stored procedure, I just execute one statement, `select count(*) from sometable`, then from client side (I am using C# ADO.Net SqlCommand to invoke the stored procedure), how could I retrieve the `count(*)` value? I am using SQL Server 2008. I am confused because `count(*)` is not used as a return value parameter of stored procedure. thanks in advance, George
Either you use ExecuteScalar as Andrew suggested - or you'll have to change your code a little bit: ``` CREATE PROCEDURE dbo.CountRowsInTable(@RowCount INT OUTPUT) AS BEGIN SELECT @RowCount = COUNT(*) FROM SomeTable END ``` and then use this ADO.NET call to retrieve the value: ``` using(SqlCommand cmdGetCount = new SqlCommand("dbo.CountRowsInTable", sqlConnection)) { cmdGetCount.CommandType = CommandType.StoredProcedure; cmdGetCount.Parameters.Add("@RowCount", SqlDbType.Int).Direction = ParameterDirection.Output; sqlConnection.Open(); cmdGetCount.ExecuteNonQuery(); int rowCount = Convert.ToInt32(cmdGetCount.Parameters["@RowCount"].Value); sqlConnection.Close(); } ``` Marc PS: but in this concrete example, I guess the alternative with just executing `ExecuteScalar` is simpler and easier to understand. This method might work OK, if you need to return more than a single value (e.g. counts from several tables or such).
When you execute the query call [`ExecuteScalar`](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx) - this will return the result. > Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. Since you are only returning one value this would return just the value from your `count` expression. You will need to cast the result of this method to an `int`.
How to retrieve scalar value from stored procedure (ADO.NET)
[ "", "sql", "sql-server-2008", "stored-procedures", "ado.net", "" ]
I'm using a progress bar to show the user how far along the process is. It has 17 steps, and it can take anywhere from ~5 seconds to two or three minutes depending on the weather (well, database) I had no problem with this in XP, the progress bar went fine, but when testing it in vista I found that it is no longer the case. For example: if it takes closer to 5 seconds, it *might* make it a 1/3 of the way through before disappearing because it's completed. Even though it's progress is at 17 of 17, it doesn't show it. I believe this is because of the animation Vista imposes on progress bars and the animation cannot finish fast enough. Does anyone know how I can correct this? Here is the code: This is the part that updates the progress bar, waiting is the form that has the progress bar. ``` int progress = 1; //1 Cash Receipt Items waiting.setProgress(progress, 18, progress, "Cash Receipt Items"); tblCashReceiptsApplyToTableAdapter1.Fill(rentalEaseDataSet1.tblCashReceiptsApplyTo); progress++; //2 Cash Receipts waiting.setProgress(progress, "Cash Receipts"); tblCashReceiptsTableAdapter1.Fill(rentalEaseDataSet1.tblCashReceipts); progress++; //3 Checkbook Codes waiting.setProgress(progress, "Checkbook Codes"); tblCheckbookCodeTableAdapter1.Fill(rentalEaseDataSet1.tblCheckbookCode); progress++; //4 Checkbook Entries waiting.setProgress(progress, "Checkbook Entries"); tblCheckbookEntryTableAdapter1.Fill(rentalEaseDataSet1.tblCheckbookEntry); progress++; //5 Checkbooks waiting.setProgress(progress, "Checkbooks"); tblCheckbookTableAdapter1.Fill(rentalEaseDataSet1.tblCheckbook); progress++; //6 Companies waiting.setProgress(progress, "Companies"); tblCompanyTableAdapter1.Fill(rentalEaseDataSet1.tblCompany); progress++; //7 Expenses waiting.setProgress(progress, "Expenses"); tblExpenseTableAdapter1.Fill(rentalEaseDataSet1.tblExpense); progress++; //8 Incomes waiting.setProgress(progress, "Incomes"); tblIncomeTableAdapter1.Fill(rentalEaseDataSet1.tblIncome); progress++; //9 Properties waiting.setProgress(progress, "Properties"); tblPropertyTableAdapter1.Fill(rentalEaseDataSet1.tblProperty); progress++; //10 Rental Units waiting.setProgress(progress, "Rental Units"); tblRentalUnitTableAdapter1.Fill(rentalEaseDataSet1.tblRentalUnit); progress++; //11 Tenant Status Values waiting.setProgress(progress, "Tenant Status Values"); tblTenantStatusTableAdapter1.Fill(rentalEaseDataSet1.tblTenantStatus); progress++; //12 Tenants waiting.setProgress(progress, "Tenants"); tblTenantTableAdapter1.Fill(rentalEaseDataSet1.tblTenant); progress++; //13 Tenant Transaction Codes waiting.setProgress(progress, "Tenant Transaction Codes"); tblTenantTransCodeTableAdapter1.Fill(rentalEaseDataSet1.tblTenantTransCode); progress++; //14 Transactions waiting.setProgress(progress, "Transactions"); tblTransactionTableAdapter1.Fill(rentalEaseDataSet1.tblTransaction); progress++; //15 Vendors waiting.setProgress(progress, "Vendors"); tblVendorTableAdapter1.Fill(rentalEaseDataSet1.tblVendor); progress++; //16 Work Order Categories waiting.setProgress(progress, "Work Order Categories"); tblWorkOrderCategoryTableAdapter1.Fill(rentalEaseDataSet1.tblWorkOrderCategory); progress++; //17 Work Orders waiting.setProgress(progress, "Work Orders"); tblWorkOrderTableAdapter1.Fill(rentalEaseDataSet1.tblWorkOrder); progress++; //18 Stored procs waiting.setProgress(progress, "Stored Procedures"); getAllCheckbookBalancesTableAdapter1.Fill(rentalEaseDataSet1.GetAllCheckbookBalances); getAllTenantBalancesTableAdapter1.Fill(rentalEaseDataSet1.GetAllTenantBalances); //getCheckbookBalanceTableAdapter1; //getTenantBalanceTableAdapter1; getTenantStatusID_CurrentTableAdapter1.Fill(rentalEaseDataSet1.GetTenantStatusID_Current); getTenantStatusID_FutureTableAdapter1.Fill(rentalEaseDataSet1.GetTenantStatusID_Future); getTenantStatusID_PastTableAdapter1.Fill(rentalEaseDataSet1.GetTenantStatusID_Past); selectVacantRentalUnitsByIDTableAdapter1.Fill(rentalEaseDataSet1.SelectVacantRentalUnitsByID); getRentBasedBalancesTableAdapter1.Fill(rentalEaseDataSet1.GetRentBasedBalances); getAgingBalanceTableAdapter2.Fill(rentalEaseDataSet1.GetAgingBalance); waiting.Close(); ``` Here is the waiting form: ``` public partial class PleaseWaitDialog : Form { public PleaseWaitDialog() { CheckForIllegalCrossThreadCalls = false; InitializeComponent(); } public void setProgress(int current, int max, int min, string loadItem) { Debug.Assert(min <= max, "Minimum is bigger than the maximum!"); Debug.Assert(current >= min, "The current progress is less than the minimum progress!"); Debug.Assert(current <= max, "The progress is greater than the maximum progress!"); prgLoad.Minimum = min; prgLoad.Maximum = max; prgLoad.Value = current; lblLoadItem.Text = loadItem; } public void setProgress(int current, string loadItem) { this.setProgress(current, prgLoad.Maximum, prgLoad.Minimum, loadItem); } } ```
Try invoking the call to the `waiting.setProgess()` method since `waiting` seems to live in another thread and this would be a [classic cross thread call](http://www.google.com/search?q=Cross-thread+operation+not+valid) (which the compiler warns you about if you let him). Since `Control.Invoke` is a bit clumsy to use I usually use an extension method that allows me to pass a lambda expression: ``` waiting.ThreadSafeInvoke(() => waiting.setProgress(...)); ``` . ``` // also see http://stackoverflow.com/questions/788828/invoke-from-different-thread public static class ControlExtension { public static void ThreadSafeInvoke(this Control control, MethodInvoker method) { if (control != null) { if (control.InvokeRequired) { control.Invoke(method); } else { method.Invoke(); } } } } ```
Vista introduced an animation effect when updating the progress bar - it tries to smoothly scroll from the previous position to the newly-set position, which creates a nasty time lag in the update of the control. The lag is most noticeable when you jump a progress bar in large increments, say from 25% to 50% in one jump. As another poster pointed out, you can disable the Vista theme for the progress bar and it will then mimic the behavior of XP progress bars. I have found another workaround: if you set the progress bar backwards, it will immediately paint to this location. So, if you want to jump from 25% to 50%, you would use the (admittedly hackish) logic: ``` progressbar.Value = 50; progressbar.Value = 49; progressbar.Value = 50; ``` I know, I know - it's a silly hack - but it does work!
How can I make the progress bar update fast enough?
[ "", "c#", ".net-3.5", "windows-vista", "progress-bar", "" ]
I am writing a custom .pac script for use with Firefox. Following numerous examples I've seen, I intersperse alert()s in order to debug it, but no alerts popup, even though the script is clearly being invoked. (I am clicking "Reload" in the "Connection settings" after each change to my script. I have even tried restarting Firefox.) Are alerts supposed to work from PAC scripts? Maybe this is an IE-only feature?
<http://mxr.mozilla.org/mozilla-central/source/netwerk/base/src/nsProxyAutoConfig.js> The alert function is added to the sandbox: ``` 80 // add predefined functions to pac 81 this._sandBox.importFunction(myIpAddress); 82 this._sandBox.importFunction(dnsResolve); 83 this._sandBox.importFunction(proxyAlert, "alert"); ``` And the mapped function calls dump, which goes to the Error Console: ``` 108 function proxyAlert(msg) { 109 msg = XPCSafeJSObjectWrapper(msg); 110 try { 111 // It would appear that the console service is threadsafe. 112 var cns = Components.classes["@mozilla.org/consoleservice;1"] 113 .getService(Components.interfaces.nsIConsoleService); 114 cns.logStringMessage("PAC-alert: "+msg); 115 } catch (e) { 116 dump("PAC: proxyAlert ERROR: "+e+"\n"); 117 } ```
1. Use `alert` function in your `.pac` file. 2. * In **Firefox** Browser: **Tools** -> **Web Developer** -> **Browser Console (Ctrl+Shift+J)** [This is not **Web Console**!!] -> Filter output: `PAC-alert` * In **Chrome** Browser: Go to `chrome://net-internals/#events` -> Search for a record with description: `PAC_JAVASCRIPT_ALERT` *(About Chrome, thank [this answer](https://serverfault.com/a/738871))* --- Sample `.pac` file: ``` function FindProxyForURL(url, host) { alert("url = " + url + " *** host = " + host + " *** Resolved IP = " + dnsResolve(host)); return "DIRECT"; } ```
Debugging autoproxy (PAC) javascript with alert()?
[ "", "javascript", "firefox", "pac", "autoproxy", "" ]
Ive been reading Liang's Introduction to Java Programming for a couple of weeks, and that question came up when the author said "There is no need for developers to create, and for users to install, major new software versions.". How does software update work? For example, patches for games, new version of products, and that kind of things. In the book, there's an example that, as long as you keep an interface of a class the same, you dont need to do any changes in any of the classes that are dependent on the one you changed. That's fine, but still a little abstract (for example, how do I create an update patch with only that class?). Im also interested in books on the subject. Thank you.
Have a look at the book [Practical API Design - Confessions of a Java Framework Architect](https://rads.stackoverflow.com/amzn/click/com/1430209739) (Jaroslav Tulach, Apress, 2008) I think it covers most of the aspects you are asking about. For the topic on shipping new software versions or updates, have a look at the technology [Java Web Start](http://java.sun.com/javase/technologies/desktop/javawebstart/index.jsp) for example. Shipping an update to a web application could be considered implicit in the face of the users as the changes made on a centralized server1 are delivered by the web browser itself. 1 or a set of servers
I think the concept you're trying to understand is using an interface as a type. In a java program, a variable can be declared to have the type of some defined interface. Classes that implement that interface can then be instantiated for variables of the interface type. However, only methods declared on the interface can be used. At compile time, the interface is used for type checking. At runtime however, the bytecode that actually does the work comes from the interface implementor. An example: ``` public interface foo { public void bar(); } public class A implements foo { public void bar() { // some code } } public class Example { public static void main(String[] args) { foo aFoo = new A(); aFoo.bar(); } } ``` In the class Example, a variable named aFoo is declared to be of type foo, the interface. A, which implements the foo interface, will contain the code to do the work of method bar(). In the class Example, the variable aFoo gets an instance of the class A, so whatever code is in the bar() method of A will be executed when aFoo.bar() is called even though aFoo is declared to be of type foo. So, we've established that all the work is done in class A. The two classes and one interface above can each be defined in their own file. All three resulting .class files can be packaged into a jar and shipped to customers as version 1.0 of the program. Sometime later, a bug might be discovered in the implementation of bar() in class A. Once a fix is developed, assuming the changes are all contained inside the bar() method, just the .class file for A needs to be shipped to customers. The updated A.class can be inserted into the program's .jar file (.jar files are just .zip files after all) overwriting the previous, broken version of A.class. When the program is restarted the JVM will load the new implementation of A.bar() and the class Example will get the new behavior. As with almost everything, more complicated programs can get, well, more complicated. But the principles are the same.
How does software update work?
[ "", "java", "version-control", "" ]
I'm in a process of selecting an API for building a GWT application. The answer to the following questions will help me choose among a set of libraries. 1. Does a third-party code rewritten in GWT run faster than a code using a wrapped JavaScript library? 2. Will code using a wrapped library have the same performance as a pure GWT code if the underlying JavaScript framework is well written and tuned?
While JavaScript libraries get a lot of programming eyeballs and attention, GWT has the advantage of being able to doing some hideously not-human-readable things to the generated JavaScript code per browser for the sake of performance. In theory, anything the GWT compiler does, the JavaScript writers should be able to do. But in practice the JS library writers have to maintain their code. Look at the jQuery code. It's obviously not optimized per browser. With some effort, I could take jQuery and target it for Safari *only*, saving a lot of code and speeding up what remains. It's an ongoing battle. The JavaScript libraries compete against each other, getting faster all the time. GWT gets better and better, and has the advantage of being able to write ugly unmaintainable JavaScript *per browser*. For any given task, you'll have to test to see where the arms race currently places us, and it'll likely vary between browsers.
In some cases you don't have another option. You can not rewrite everything when moving to GWT. In a first step you could just wrap your existing code in a wrapper and if it turns out to be a performance bottleneck you can still move the code to Java/GWT The code optimisation in GWT will certainly be better than what the majority of JS developpers can write. And when the Browsers change, it is just a matter of modifying the GWT optimizer and your code will be better tuned for the latest advances in Js technology.
Are GWT wrappers on top of javascript libraries discouraged?
[ "", "javascript", "api", "gwt", "wrapper", "" ]
The question is simple. I have a `foreach` loop in my code: ``` foreach($array as $element) { //code } ``` In this loop, I want to react differently when we are in first or last iteration. How to do this?
You could use a counter: ``` $i = 0; $len = count($array); foreach ($array as $item) { if ($i == 0) { // first } else if ($i == $len - 1) { // last } // … $i++; } ```
If you prefer a solution that does not require the initialization of the counter outside the loop, then you can compare the current iteration key against the function that tells you the last / first key of the array. ### PHP 7.3 and newer: ``` foreach ($array as $key => $element) { if ($key === array_key_first($array)) { echo 'FIRST ELEMENT!'; } if ($key === array_key_last($array)) { echo 'LAST ELEMENT!'; } } ``` ### PHP 7.2 and older: PHP 7.2 is already EOL (end of life), so this is here just for historic reference. Avoid using. ``` foreach ($array as $key => $element) { reset($array); if ($key === key($array)) { echo 'FIRST ELEMENT!'; } end($array); if ($key === key($array)) { echo 'LAST ELEMENT!'; } } ```
PHP How to determine the first and last iteration in a foreach loop?
[ "", "php", "loops", "foreach", "" ]
I am trying to get the following: [today's date]\_\_\_[textfilename].txt from the following code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication29 { class Program { static void Main(string[] args) { WriteToFile(); } static void WriteToFile() { StreamWriter sw; sw = File.CreateText("c:\\testtext.txt"); sw.WriteLine("this is just a test"); sw.Close(); Console.WriteLine("File created successfully"); } } } ``` I tried putting in `DateTime.Now.ToString()` but i cannot combine the strings. Can anybody help me? I want the date in FRONT of the title of the new text file I am creating.
``` static void WriteToFile(string directory, string name) { string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, name); string path = Path.Combine(directory, filename); using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("This is just a test"); } } ``` To call: ``` WriteToFile(@"C:\mydirectory", "myfilename"); ``` Note a few things: * Specify the date with a custom format string, and avoid using characters illegal in NTFS. * Prefix strings containing paths with the '@' string literal marker, so you don''t have to escape the backslashes in the path. * Combine path parts with Path.Combine(), and avoid mucking around with path separators. * Use a using block when creating the StreamWriter; exiting the block will dispose the StreamWriter, and close the file for you automatically.
You'd want to do a custom string format on DateTime.Now. You can use String.Format() to combine the results of that with your base filename. To append on the path to the filename, use Path.Combine(). Finally, use a using() block to properly close & dispose your StreamWriter when you are finished with it... ``` string myFileName = String.Format("{0}__{1}", DateTime.Now.ToString("yyyyMMddhhnnss"), "MyFileName"); strign myFullPath = Path.Combine("C:\\Documents and Settings\\bob.jones\\Desktop", myFileName) using (StreamWriter sw = File.CreateText(myFullPath)) { sw.WriteLine("this is just a test"); } Console.WriteLine("File created successfully"); ``` Edit: fixed sample to account for path of "C:\Documents and Settings\bob.jones\Desktop"
Creating a new .txt file with date in front, C#
[ "", "c#", "datetime", "text-files", "" ]
I am looking into QUnit for JavaScript unit testing. I am in a strange situation where I am checking against the value returned from the Ajax call. For the following test I am purposely trying to fail it. ``` // test to check if the persons are returned! test("getPersons", function() { getPersons(function(response) { // persons = $.evalJSON(response.d); equals("boo", "Foo", "The name is valid"); }); }); ``` But it ends up passing all the time. Here is the getPersons method that make the Ajax call. ``` function getPersons(callback) { var persons = null; $.ajax({ type: "POST", dataType: "json", data: {}, contentType: "application/json", url: "AjaxService.asmx/GetPersons", success: function(response) { callback(response); } }); } ```
Starting and stopping using the QUnit library seems to be working! ``` // test to check if the persons are returned! test("getPersons", function() { stop(); getPersons(function(response) { persons = $.evalJSON(response.d); equals(persons[0].FirstName, "Mohammad"); start(); }); }); ```
The real problem here isn't needing to call the start() and stop() methods - in fact you could get into trouble using that approach if you are not careful in calling stop() again at the end of your callback if you have additional .ajax() methods. Which then means you find yourself in some snarled mess of having to keep track if all the callbacks have been fired to know if you still need to call stop() again. The root of the problem involves the default behavior of asynchronous requests - and the simple solution is to make the .ajax() request happen synchronously by setting the **async** property to false: ``` test("synchronous test", function() { $.ajax({ url:'Sample.asmx/Service', async:false, success: function(d,s,x) { ok(true, "Called synchronously"); } }); }); ``` Even still, the best approach is to allow the asynchronous behavior and use the right test method invocation: **[asyncTest()](http://docs.jquery.com/QUnit/asyncTest)**. According to the docs "*Asynchronous tests are queued and run one after the other. Equivalent to calling a normal test() and immediately calling stop().*" ``` asyncTest("a test", function() { $.ajax({ url: 'Sample.asmx/Service', success: function(d,s,x) { ok(true, "asynchronous PASS!"); start(); } }); }); ```
QUnit with Ajax, QUnit passes the failing tests
[ "", "javascript", "jquery", "ajax", "unit-testing", "qunit", "" ]
Below is the code from a plugin for Joomla. It works on it's own and it's purpose is to detect external links on the page and force them into new browser windows using \_blank. I've tried for about an hour (I don't know javascript well) but I can't seem to figure out how to get an onclick function working. End result, I want to add to this script the ability of a confirmation dialog, shown in the 2nd code section. An external link, when clicked, will pop up the confirmation dialog, and if it says yes, they will be able to get to the external URL, opening in a new window. Otherwise, it cancels, and does nothing. When I create a link with ``` onclick="return ExitNotice(this.href);" ``` within it it works perfectly, but since my website has multiple people submitting input, I'd like the confirmation box global. ``` this.blankwin = function(){ var hostname = window.location.hostname; hostname = hostname.replace("www.","").toLowerCase(); var a = document.getElementsByTagName("a"); this.check = function(obj){ var href = obj.href.toLowerCase(); return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false; }; this.set = function(obj){ obj.target = "_blank"; obj.className = "blank"; }; for (var i=0;i<a.length;i++){ if(check(a[i])) set(a[i]); }; }; this.addEvent = function(obj,type,fn){ if(obj.attachEvent){ obj['e'+type+fn] = fn; obj[type+fn] = function(){obj['e'+type+fn](window.event );} obj.attachEvent('on'+type, obj[type+fn]); } else { obj.addEventListener(type,fn,false); }; }; addEvent(window,"load",blankwin); ``` Second Part ``` /* ---------- OnClick External Link Notice ---------- */ function ExitNotice(link,site,ltext) { if(confirm("-----------------------------------------------------------------------\n\n" + "You're leaving the HelpingTeens.org website. HelpingTeens.org\ndoes not " + "control this site and its privacy policies may differ\nfrom our own. " + "Thank you for using our site.\n\nYou will now access the following link:\n" + "\n" + link + "\n\nPress \'OK\' to proceed, or press \'Cancel\' to remain here." + "\n\n-----------------------------------------------------------------------")) { return true; } history.go(0); return false; } ``` A) Can anyone help me fix this problem? or B) Is there a better solution?
So, I'll summarize my what I think you're asking and then tell you how I think that can be solved. It's possible I've misunderstood your question. You've got code that goes through all tags and sets their target attribute to "\_blank" and sets their className to "blank", and you'd like to instead rewrite the links to use JavaScript to show a confirmation dialog and only go to the location if the user clicks Yes. In this case I believe you want the links to end up as though they were written like so: ``` <a href="javascript:void(0)" onclick="if (ExitNotice('http://www.whatever.com')) window.location.assign('http://www.whatever.com')"> ``` The javascript:void(0) causes the normal browser handling of the click to not go to another page, so that your onclick has time to execute. To make this happen, you'll want to change the definition of this.set (inside this.blankwin) to something like this: ``` this.set = function(obj){ var href = obj.href; obj.href = "javascript:void(0)"; obj.onclick = function() { (if ExitNotice(href) window.location.assign(href); }; obj.target = "_blank"; obj.className = "blank"; }; ``` See [here](http://www.tizag.com/javascriptT/javascriptvoid.php) for info on void(0). Also, note that the code that sets obj.className to "blank" isn't great, because it will remove any other className already assigned to the link. You could instead just add the class name to the existing ones, like so: ``` obj.className = obj.className + " blank"; ```
Everything works as I want it now. Thank you for your help. As this is my first time using SO, I hope I credited you correctly. Since I can't figure out how to (or even if it's possible) to show code in comment boxes, I'm choosing to answer my own question with the final code for others to benefit. Once again, you showed me the syntax I needed to modify to get it working the way I wanted. THANK YOU! Final code ``` this.set = function(obj){ var href = obj.href; //obj.href = "javascript:void(0)"; obj.onclick = function() { return ExitNotice(href)}; obj.target = "_blank"; obj.className = obj.className + " blank"; }; ```
Javascript problem with a global external link confirmation alert
[ "", "javascript", "joomla", "hyperlink", "joomla1.5", "confirm", "" ]
How can I define a function's prototype in JavaScript? I want to do this like I would do it in C where you would do something like: ``` void myfunction(void); void myfunction(void){ } ``` So is there any way to do this in JavaScript? I'm asking this because of the function declaration order that is required in JavaScript. --- ### Edit: I have an object: ``` function something(){ var anArrayOfSomethingObjects; aPrivateFunction(){ // does some stuff anArrayOfSomethingObjects[3].aPublicFunction(); } return { functionA: function() { }, aPublicFunction: function() { }, functionC: function() { } } } ``` `privateFunction` needs to access `publicFunction` which is declared afterwards. How can I do this?
you have to really understand what is a dynamic language, and why your question doesn't really make a lot of sense. your problem is not about 'definition vs. declaration' like on C, it's most about statements order. in JavaScript (as with most dynamic languages) a function definition like this ``` function whatever (params) { ... } ``` is in fact syntactic sugar for an assignment statement like this: ``` whatever = function (params) { ... } ``` as you can see, `whatever` is in fact a variable, and it's assigned a function value. so you can't call it before assigning it. Of course, execution order doesn't have to follow lexical order. If that's your case, you just have to make sure you assign the needed variable before using it. If it's a local variable and you want closure semantics, you can define it first and assign later, like this: ``` var myfunc = undefined; function first () { ... myfunc (...); ... } myfunc = function (...) { ... } ```
JavaScript is dynamic language there is no need to do that. Meaning Javascript has dynamic binding and dynamic typing, so the check will be on the run time. So no need to define forward declaration like in static languages. **Reply to edit**: Even in this case you still do not need to define forward declaration. Once object will have that method or field in run-time it will work fine. But you probably tackled to the problem of scoping in JavaScript, assuming you asking your question after something gone wrong.
How can I define a function's prototype in JavaScript?
[ "", "javascript", "" ]
I have a small site where I want to get Related Videos on basis of Tags... what could be the best MS SQL 2005 query to get related Videos on basis of Tags. If you can give LINQ query that would be awsome. Here is Database Schema: ``` CREATE TABLE Videos (VideoID bigint not null , Title varchar(100) NULL, Tags varchar(MAX) NULL, isActive bit NULL ) INSERT INTO Videos VALUES ( 1,'Beyonce Shakira - Beautiful Liar','shakira, beyonce, music, video',1) INSERT INTO Videos VALUES ( 2,'Beyonce Ego Remix','beyonce, music, video',1) INSERT INTO Videos VALUES ( 3,'Beyonce Ego','beyonce, music, video',1) ``` What I want that on Viewing of Video with ID 1 it should show related videos on basis of its tags and most matched terms should come on top. Thanks in Advance
The schema you show, denormalized with all tags for each video stuffed into the Tags string, is badly designed for your purposes -- there is no reasonable way in TSQL to compute a meaningful "commonality" between two strings in such format, and therefore no reasonable way to check what pairs of items have relatively high commonality and thus may be deemed "related". If the schema is untouchable, you'll have to implement a user-defined function (in C# or other .NET language) for the purpose, and even then you will more or less have to scan the whole table since there's no reasonable way to index on such a basis. If you can redesign the schema (with two more tables: one to hold the tags, and one to give the many-many relationship between tags and videos) there may be better prospects; in this case, some indication on roughly how many (order of magnitude) videos you expect to hav, how many (ditto) distinct tags overall, and roughly what number of tags a video would be expected to have, might allow designing and effective way to pursue your purposes. Edit: per comments, apparently the schema can be redesigned, although still no indication was given about the numbers I asked, so appropriate indices &c will remain a total mystery. Anyway, suppose the schema is something like (each table can have other columns as desired, just add them to the query; and the VARCHAR lenghts don't matter either): ``` CREATE TABLE Videos (VideoID INT PRIMARY KEY, VideoTitle VARCHAR(80)); CREATE TABLE Tags (TagID INT PRIMARY KEY, TagText VARCHAR(20)); CREATE TABLE VideosTags (VideoID FOREIGN KEY REFERENCES Videos, TagID FOREIGN KEY REFERENCES Tags, PRIMARY KEY (VideoId, TagId)); ``` i.e. just the classic 'many-many relationship' textbook example. Now given the title of a video, say @MyTitle, titles of the 5 videos most "related" to it could easily be queried by, for example: ``` WITH MyTags(TagId) AS ( SELECT VT1.TagID FROM Videos V1 JOIN VideosTags VT1 ON (V1.VideoID=VT1.VideoID) WHERE V1.VideoTitle=@MyTitle ) SELECT TOP(5) V2.VideoTitle, COUNT(*) AS CommonTags FROM Videos V2 JOIN VideosTags VT2 ON (V2.VideoID=VT2.VideoID) JOIN MyTags ON (VT2.TagId=MyTags.TagId) GROUP BY V2.VideoId ORDER BY CommonTags DESC; ```
You would be better off splitting the schema so that the tags are in a separate table and are then linked to the videos using an intermediate table an example of this could be... ``` select v.* from Video v inner join VideoTag vt inner join Tag t on vt.TagID = t.TagID on v.VideoID = vt.VideoID where t.Description = @tagText ``` where the revised schema looks like Video ``` VideoID Title Description ``` Tag ``` TagID Description ``` VideoTag ``` VideoID TagID ``` Alternatively, you could try using a simpler query like ``` select VideoID, Title, Description from Video where Tags like '%' + @tag + '%' ``` but this would match on tags that contain other tags (such as 'art' and 'martial art') which is why I believe the splitting of the schema to be a better solution.
Whats the best SQL Query to get Related Items?
[ "", "sql", "linq", "sql-server-2005", "t-sql", "" ]
I am trying to import a **.csv file** into a MySQL table via **phpMyAdmin**. The .csv file is separated by pipes, formated like this: ``` data|d'ata|d'a"ta|dat"a| data|"da"ta|data|da't'a| dat'a|data|da"ta"|da'ta| ``` The data contains quotes. I have no control over the format in which I recieve the data -- it is generated by a third party. The problem comes when there is a **| followed by a double quote**. I always get an "invalid field count in CSV input on line N" error. I am uploading the file from the import page, using Latin1, CSV, terminated by |, separated by ". I would like to just **change the "enclosed by" character**, but I keep getting **"Invalid parameter for CSV import: Fields enclosed by"**. I have tried various characters with no success. **How can I tell MySQL to accept this format in phpMyAdmin?** Setting up these tables is the first step in writing a program that will use uploaded gzipped .csv files to maintain the catalog of an e-commerce site.
I've been having a similar problem for the last several hours and I've finally gotten an import to work so I'll share my solution, even though it may not help the original poster. Short version: 1.) if an Excel file, save as ODS (open document spreadsheet) format. 1a.) If the file is some kind of text format with delimiters (like the original poster has), then open Excel, and once inside Excel use File/Open to open the file. There you will be able to select the appropriate delimiter to view the file. Make sure the file looks alright, THEN save as ODS format (and close the file). 2.) Open the file in OpenOffice Calc (free download from Oracle/Sun). 2a.) Press Ctrl-F to open the Find dialog box. Click More Options and make sure "Current Selection Only" is NOT checked. 2b.) Search for double quotes. If there are none in your file, you can skip steps 4 and 5. 3.) Save As -> Text CSV. Select options for UTF-8 format (press "u" 3 times to get there fast), select ";" (semi colon) as separator, and select double quotes for text. 4.) If there were any double quotes found in your file in step 2b, continue, otherwise just import the file as CSV with phpMyAdmin (see step 6). It should work. 5a.) Open in Word or any other text editor where you can do Find -> Replace All. 5b.) Find all instances of three double quotes in a row by searching for """ (if you do find any, you might even want to search for 4, 5, 6 etc. in a row until you come up empty). 5c.) Replace the """ with a placeholder that is not found anywhere else in your csv. I replaced them with 'abcdefg'. 5d.) Find -> Replace all instances of "" (two double quotes in a row) with " (forward slash and double quote). 5e.) Find -> Replace all instances of abcdefg (or your chosen placeholder from step 5c) with "". 5c and this step ensure that any quotes occuring at the end of a field just before the text-delimiting quote are properly 'escaped'. 5f.) Finally, save the file, keeping in UTF-8 (or whatever format you need for import). 6.a) In phpMyAdmin, click the "import" tab, click the "choose file" button, and select the file you just saved. 6b.) under 'Format of imported file' CSV should be selected. If column names are in the first row, make sure that checkbox is checked. Most importantly, 'Fields terminated by' should be set to ; (semi colon), 'Fields enclosed by' should be set to " (double quotes), and 'Fields escaped by' should be set to \ (forward slash). You set that up in your file by following step 3, and if necessary by following steps 5a - 5f. 7.) Click "Go" and pray you didn't just waste another hour. Now that the short version has turned out this long, I'll skip the long version. Suffice it to say, there seem to be 2 major problems with importing through phpmyadmin. 1.) There's some kind of memory problem that prevents large Excel and ODS files (how large is large? not sure yet) being imported. 2.) Neither OpenOffice nor Excel seem to save their csv files in a way that's compatible with phpmyadmin. They want to escape double quotes with double quotes. phpMyAdmin wants double quotes escaped with something else, like forward slash. The first problem will hopefully be fixed in an update of phpmyadmin (and/or the Excel importing add-on 'PHPExcel'). The second one could be fixed if there was an easy way to change the escape character for Excel or ODS files saved as CSV, or if phpMyAdmin could be made compatible with their format (that should actually be pretty easy. Simply have it perform the same find-replace actions we performed manually above to skirt the double quote problem). I hope this helps somebody, as I spent 3-4 hours discovering this solution and another hour writing it here. I hope it's not too long, but I was hoping to help people at all levels of expertise from zero to wherever I am (probably around 0.1).
I found a hack that works -- I use the $ as the "enclosed by" character and all is well. Since this is for a European site, I know that they'll never use it in the table content.
MySQL import in phpmyadmin (CSV) chokes on quotes
[ "", "php", "csv", "import", "phpmyadmin", "" ]
Is it possible to call a non-static function that uses a public non-static class inside a static function in C#? ``` public class MyProgram { private Thread thd = new Thread(myStaticFunction); public AnotherClass myAnotherClass = new AnotherClass(); public MyProgram() { thd.Start(); } public static void myStaticFunction() { myNonStaticFunction(); } private void myNonStaticFunction() { myAnotherClass.DoSomethingGood(); } } ``` Well, the invalid code like above is what I need. Any idea?
It sounds like you want to pass data to your thread. Try this: ``` public class MyProgram { private Thread thd; public AnotherClass myAnotherClass = new AnotherClass(); public MyProgram() { thd = new Thread(() => myStaticFunction(this)); thd.Start(); } public static void myStaticFunction(MyProgram instance) { instance.myNonStaticFunction(); } private void myNonStaticFunction() { myAnotherClass.DoSomethingGood(); } } ```
Not directly no. You must have an instance of Program in order to call the non-static method. For example ``` public static void MyStaticFunc(Program p) { p.myNonStaticFunction(); } ```
Is it possible to call a non-static function inside static function in C#?
[ "", "c#", "static", "" ]
i'm trying to get web-page data in string that than i could parse it. I didn't found any methods in qwebview, qurl and another. Could you help me? Linux, C++, Qt. **EDIT:** Thanks for help. Code is working, but some pages after downloading have broken charset. I tried something like this to repair it: ``` QNetworkRequest *request = new QNetworkRequest(QUrl("http://ru.wiktionary.org/wiki/bovo")); request->setRawHeader( "User-Agent", "Mozilla/5.0 (X11; U; Linux i686 (x86_64); " "en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1" ); request->setRawHeader( "Accept-Charset", "win1251,utf-8;q=0.7,*;q=0.7" ); request->setRawHeader( "charset", "utf-8" ); request->setRawHeader( "Connection", "keep-alive" ); manager->get(*request); ``` Any results =(.
Have you looked at [QNetworkAccessManager](http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html)? Here's a rough and ready sample illustrating usage: ``` class MyClass : public QObject { Q_OBJECT public: MyClass(); void fetch(); public slots: void replyFinished(QNetworkReply*); private: QNetworkAccessManager* m_manager; }; MyClass::MyClass() { m_manager = new QNetworkAccessManager(this); connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); } void MyClass::fetch() { m_manager->get(QNetworkRequest(QUrl("http://stackoverflow.com"))); } void MyClass::replyFinished(QNetworkReply* pReply) { QByteArray data=pReply->readAll(); QString str(data); //process str any way you like! } ``` In your in your handler for the [finished](http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html#finished) signal you will be passed a [QNetworkReply](http://qt-project.org/doc/qt-4.8/qnetworkreply.html) object, which you can read the response from as it inherits from [QIODevice](http://qt-project.org/doc/qt-4.8/qiodevice.html). A simple way to do this is just call [readAll](http://qt-project.org/doc/qt-4.8/qiodevice.html#readAll) to get a [QByteArray](http://qt-project.org/doc/qt-4.8/qbytearray.html). You can construct a [QString](http://qt-project.org/doc/qt-4.8/qstring.html#QString-8) from that QByteArray and do whatever you want to do with it.
Paul Dixon's answer is probably the best approach but Jesse's answer does touch something worth mentioning. cURL -- or more precisely libcURL is a wonderfully powerful library. No need for executing shell scripts and parsing output, libCURL is available C,C++ and more languages than you can shake an URL at. It might be useful if you are doing some weird operation (like http POST over ssl?) that qt doesnt support.
How can i get content of web-page
[ "", "c++", "qt", "html", "" ]
I have a background of programming in Java and C++, so I know all about basic logic and OOP. However I'm at a new job and they are a C# coding company. Are there any good tutorials/examples out there that show the specific differences between these languages, or at least show me the features of C#? I briefly looked at the MSDN and looked over their 'intro to C#' but that was way too basic for my needs. Will I just have to poke around the MSDN a little more in depth and come up with ideas on my own about little test projects to get my feet wet in C#?
MSDN has their Ramp up website - <http://msdn.microsoft.com/en-us/rampup/default.aspx> Specifically for Java developers - <http://msdn.microsoft.com/en-us/rampup/bb421266.aspx>
These links sounds promising: [C# from JAVA](http://www.25hoursaday.com/CsharpVsJava.html) [C# from C++](http://msdn.microsoft.com/en-us/magazine/cc301520.aspx)
Where can a C++/Java developer find C# learning materials?
[ "", "c#", "" ]
I got an abstract class : ``` abstract class ClassBase { public abstract string Test { get; } } ``` I want to derive it and by the way add a set accesor ``` class ClassDerive : ClassBase { string _s; public override string Test { get { return _s; } set { _s = value; } } } ``` I can't do that because i may not override set ``` class ClassDerive2 : ClassBase { string _s; public string Test { override get { return _s; } set { _s = value; } } } ``` Syntax error ``` class ClassDerive3 : ClassBase { string _s; public override string ClassBase.Test { get { return _s; } } public string Test { set { _s = value; } } } ``` Syntax error Any Idea ??? thx
If at first you have defined a read-only property in a type, you can't later change it to a read/write property in a derived class. That's simply how .NET works, and can't be changed. If, on the other hand, you define an *interface* with a read-only property, you can later implement that interface in a class with a writable property. If you'd like to share what you are trying to achieve, perhaps we can come up with a design that works and can compile :)
You cannot do *exactly* what you want to do but here is a workaround: ``` abstract class ClassBase { public abstract String Test { get; } } class ClassDerive : ClassBase { string _s; public override string Test { get { return _s; } } public void SetTest(String test) { this._s = test; } } ``` This will make `Test` only settable in `ClassDerived` via the public `SetTest` method. I know this is not as clean as using the property's setter but it is about as good as it's going to get.
Override only Get accessor
[ "", "c#", "" ]
I have a GridView control bound to an ObjectDataSource which returns a list of objects that look like this: ``` public class X { public string DisplayName { get; } public string Guid { get; } } ``` I don't want to show the `Guid` property in the GridView, but I need to retrieve it when an object is selected. I could not find a "DataValueField" property, like for the ListBox control. As a workaround, I tried to set `Visible=false` for the column bound to the Guid property and get the cell text from the `Row` object in the `SelectedIndexChanged` method: ``` protected void GridView1_SelectedIndexChanged(object sender,EventArgs e){ GridViewRow row = GridView1.SelectedRow; string id = row.Cells[2].Text; // empty } ``` But this does not work - apparently if the column is not visible its Text property is left empty. How can I get the Guid of the selected object while showing only the DisplayName?
Not sure about how this works with ObjectDataSource, but with SqlDataSource we set keys on the rows of the GridView. ``` GridView1.DataKeyNames = new String[] {"Guid"}; ``` Then, you can get the key by doing this: ``` string guid = GridView1.DataKeys[GridView1.SelectedRow.RowIndex]; ```
Add "Guid" into the DataKeyNames property of the GridView. That will allow it to be available even though the column is hidden.
asp.net (C#): get value of a non-displayed field from a gridview selection
[ "", "c#", "asp.net", "gridview", "" ]
In java i would like to read a file line by line and print the line to the output. I want to solve this with regular expressions. ``` while (...) { private static java.util.regex.Pattern line = java.util.regex.Pattern.compile(".*\\n"); System.out.print(scanner.next(line)); } ``` The regex in the code is not correct, as i get InputMismatchException. I am working on this regex for 2 hours. Please help with it. With regex powertoy i see that ".\*\n" is correct. But my program runs incorrectly. The whole source is: ``` /** * Extracts the points in the standard input in off file format to the standard output in ascii points format. */ import java.util.regex.Pattern; import java.util.Scanner; class off_to_ascii_points { private static Scanner scanner = new Scanner(System.in); private static Pattern fat_word_pattern = Pattern.compile("\\s*\\S*\\s*"); private static Pattern line = Pattern.compile(".*\\n", Pattern.MULTILINE); public static void main(String[] args) { try { scanner.useLocale(java.util.Locale.US); /* skip to the number of points */ scanner.skip(fat_word_pattern); int n_points = scanner.nextInt(); /* skip the rest of the 2. line */ scanner.skip(fat_word_pattern); scanner.skip(fat_word_pattern); for (int i = 0; i < n_points; ++i) { System.out.print(scanner.next(line)); /* Here my mistake is. next() reads only until the delimiter, which is by default any white-space-sequence. That is next() does not read till the end of the line what i wanted. Changing "next(line)" to "nextLine()" solves the problem. Also, setting the delimiter to line_separator right before the loop solves the problem too. */ } } catch(java.lang.Exception e) { System.err.println("exception"); e.printStackTrace(); } } } ``` The beginning of an example input is: ``` OFF 4999996 10000000 0 -28.6663 -11.3788 -58.8252 -28.5917 -11.329 -58.8287 -28.5103 -11.4786 -58.8651 -28.8888 -11.7784 -58.9071 -29.6105 -11.2297 -58.6101 -29.1189 -11.429 -58.7828 -29.4967 -11.7289 -58.787 -29.1581 -11.8285 -58.8766 -30.0735 -11.6798 -58.5941 -29.9395 -11.2302 -58.4986 -29.7318 -11.5794 -58.6753 -29.0862 -11.1293 -58.7048 -30.2359 -11.6801 -58.5331 -30.2021 -11.3805 -58.4527 -30.3594 -11.3808 -58.3798 ``` I first skip to the number 4999996 which is the number of lines containing point coordinates. These lines are that i am trying to write to the output.
I suggest using ``` private static Pattern line = Pattern.compile(".*"); scanner.useDelimiter("[\\r\\n]+"); // Insert right before the for-loop System.out.println(scanner.next(line)); //Replace print with println ``` --- Why your code doesn't work as expected: This has to do with the Scanner class you use and how that class works. The javadoc states: > A Scanner breaks its input into tokens > using a delimiter pattern, which by > default matches whitespace. That means when you call one of the Scanner's.next\* methods the scanner reads the specified input until the next delimiter is encountered. So your first call to `scanner.next(line)` starts reading the following line ``` -28.6663 -11.3788 -58.8252 ``` And stops at the space after -28.6663. Then it checks if the token (-28.6663) matches your provided pattern (.\*\n) which obviously doesn't match (-28.6663). That's why.
If you only want to print the file to standard out, why do you want to use regexps? If you know that you always want to skip the first two lines, there are simpler ways to accomplish it. ``` import java.util.Scanner; import java.io.File; public class TestClass { public static void main(String[] args) throws Exception { Scanner in=new Scanner(new File("test.txt")); in.useDelimiter("\n"); // Or whatever line delimiter is appropriate in.next(); in.next(); // Skip first two lines while(in.hasNext()) System.out.println(in.next()); } } ```
java regex line
[ "", "java", "regex", "" ]
I've started using this alot to link elements of my UI to their data backing class (whatever that might be). What are some of the common uses you put the Tag property to use for? Indeed, do you use it at all? I know I didn't for a very long time.
Just as you describe, the most frequent use of the `Tag` property I have come across and use in both WinForms, WPF and Silverlight is to indicate the real data that the control relates to. This is especially useful on `ListViewItem` instances or auto-generated user interface where you want to use the same event handler for multiple objects where only the target data is different (i.e. the action to be performed remains the same). However, I have also used the `Tag` to store an enumeration value (though you should avoid value types as it would cause boxing when assigning the value to the `Tag` property) or a string that is then used to determine the action that needs to be performed instead of the data on which to perform it, and in one particular usage, I stored a delegate so that I could auto-generate some buttons and embed their handlers in the `Tag` (the handler information was supplied in a data driven manner). I am sure there are many other ways to use `Tag` and many other ways to replace the uses of `Tag` with something more strongly typed, but that's how I've used it.
The Tag property is an ancient (in programming language terms) hold over for controls. To my knowledge, it's been used in everything from visual basic, delphi, and pretty much any other gui based language. It is simply an extra property that allows you to add a numeric value for any reason you want to the control. I've seen it used for everything from a counter to holding a record id that the control is tied to.
Common uses for the Tag property
[ "", "c#", "wpf", "winforms", "silverlight", "" ]
I've been struggling with this for quite a while My application contains a list view, populated with file-names, which are located on a server. I'm trying to implement drag and drop functionality, so the user can drag files from my application into his/her's local computer. In order to do this, first i'm downloading the files into a temporary location, and then calling my application's DoDragDrop() method. The problem is that I want to perform the download process only **after** the DoDragDrop method is called. I've tried every event related to drag drop methods (GiveFeedback, ItemDrag, etc...) but nothing works so basically what I need is an event, raised after the DoDragDrop is done any ideas??
Not sure how to do this in .NET, but in regular Win32 programming, the object that implements the IDataObject interface can optionally implement the IAsyncOperation interface as well. The IDropTarget can then use that interface to perform the drag-n-drop in a background thread so that the source and target are not blocked during the actual transfer. The only gotcha is that the target, not the source, decides whether to take advantage of this or not. The alternative is to use an "optimized move" transfer, where the IDataObject provides the filenames and the IDropTarget moves the files directly. MSDN has details on that: [Handling Shell Data Transfer Scenarios](http://msdn.microsoft.com/en-us/library/bb776904.aspx). Of course, this still means you have to download the files before beginning the drag-n-drop. There really is no way to perform a drag-n-drop to determine the target and then perform the download afterwards. What you could do, though, is have the IDataObject hold `CFSTR_FILEDESCRIPTOR` and `CFSTR_FILECONTENTS` entries (described here: [Shell Clipboard Formats](http://msdn.microsoft.com/en-us/library/bb776902.aspx)), where the `CFSTR_FILEDESCRIPTOR` is filled in from information you used to populate your ListView, and the `CFSTR_FILECONTENTS` uses IStream interfaces whose implementations perform the download during the actual drop operation rather than prior to it. At least that way, you are only downloading the files that the target actually wants and can skip the rest. Couple that with IAsyncOperation, and that may give you the final effect you are looking for.
[Here is an example](https://learn.microsoft.com/en-us/archive/blogs/delay/creating-something-from-nothing-asynchronously-developer-friendly-virtual-file-implementation-for-net-improved) that may be similar to Remy's solution...
Perform dragdrop implementation after DoDragDrop method is called
[ "", "c#", "winforms", "events", "drag-and-drop", "" ]
I want to filter the keyboard inputs into textbox based on the type of input I allow. e.g. 0 for Digits only 1 for Alphabets only 2 for Alphanumerics So if 0 is configured and a character 'a' is pressed on the keyboard, it is not shown in the textbox. How do I do that in C#? Thanks
You need to subscribe to control's KeyPress event (and optionally KeyDown method), and if key stroke must be eaten set **Handled** property to true. Read more in [msdn](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx) (with sample that cover your problem).
Not sure I understood your question correctly but you can use [masked text box](http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx) for creating many types of input filters.
Filter input from keyboard in Textbox, C#
[ "", "c#", "winforms", "c#-3.0", "c#-4.0", "" ]
I understand that T-SQL is not object oriented. I need to write a set of functions that mimics method overloading in C#. Is function overloading supported in T-SQL in any way? If there is a hack to do this, is it recommended?
No, there is no way to do this. I recommend you revisit the requirement, as "make apples look like oranges" is often difficult to do, and of questionable value.
One thing I have done successfully is to write the function in such a way as to allow it to handle null values, and then call it with nulls in place of the parameters you would like to omit. Example: ``` create function ActiveUsers ( @departmentId int, @programId int ) returns int as begin declare @count int select @count = count(*) from users where departmentId = isnull(@departmentId, departmentId) and programId = isnull(@programId, programId) return @count end go ``` Uses: ``` select ActiveUsers(1,3) -- users in department 1 and program 3 select ActiveUsers(null,3) -- all users in program 3, regardless of department select ActiveUsers(null,null) -- all users ```
T-SQL User defined function overloading?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I am developing a desktop application with a MainForm that's grown rather large. There are lots controls in several containers on different levels (SplitContainers, TabPages, Panels). Now I want to refactor this class by separating all the controller code responsible for data binding & clearing the controls or carrying out user interactions into separate Controller classes. **[EDIT]** **Purpose** The purpose of this application is to track orders (called Job) and their positions (called Jobitem). Each Job is related to a customer, each Jobitem to an Article (Jobitems contain information that's specific to the manufacturing process of its article, therefore it's wrapping the article). Job, Jobitem, Customer and Article have dynamic properties (basicalyl key/value pairings) which are managed by a PropertyManager class. **Architecture** My application is split into 2 main projects: The core contains the data model in 3 LinqToSQL DataContext Classes: * `ArticleManagement` * `JobManagement` * `PropertyManagement` For every DataContext class there is a `XyzManager` class which provides the LinqToSQL Object in a Collection to the GUI, encapsulating the LinqToSQL data source. It also handles creation, deletion and modification to its corresponding DataContext types. Then I've got a GUI project, naturally containing a main form and some additional forms for stuff like options etc. As of now, my GUI project holds a reference to each XyzManager class and gets & sets the data through the Manager classes as the user interactions dictate, containing all the controlling logic. I've put most of the independent logic for this into a static Utility class outside of the main form class, but that's an less than ideal approach I guess. **[/EDIT]** This is my first bigger Desktop Application and I am having a hard time encapsulating the GUI. As of right now, all the controller code responsible for handling user interactions resides within the MainForm class. I know about the MVC pattern but I'm not sure how to apply it on a C# WinForm with my current design. My custom code alone is over 2400 lines of code long, not counting in the automatic generated code of the form, with a rising tendency. I want to refactor this, but am lost as to how I could solve this in a more elegant fashion.
For small scale applications you should take a look at Model-View-Presenter (MVP), there is a good presentation of the (in my opinion) best way to do MVP: <http://martinfowler.com/eaaDev/SupervisingPresenter.html>
Normally I try to compose a complex GUI by using smaller UserControls. But a few points are very important: * Each of these UserControls should be independent (especially from the Form) * UserControls that have the purpuse to show or change certain data should depend only on this data. You should try to implement your controls in a way that they can be bound to a DataSource that serves all data the control needs. * When you need to hand over informations to the parent container (another UserControl or the Form) use events to which the container can subscribe. * When you use (context-)menus, check if they are bound to certain items. You should create the menus near to the items and not within the UserControls. So, when you show the same item on the GUI in different views (controls) more than once, every item should have the same contextmenu. * Try to apply a command pattern for actions of buttons/menus. Your solutions sounds like you could not seperate the different responsiblities until now. Just dividing the code into different controls without clear borders and responsibilities is not enough.
C#: How to cleverly design a GUI for a Desktop Application with encapsulation in mind
[ "", "c#", "winforms", "model-view-controller", "encapsulation", "" ]
In a table, I have a column called MEMO\_TEXT that is a text data type. When I try creating a view and use a GROUP BY, I get the following error: > SQL Server Database Error: The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. I get this error when I try to do a DISTINCT on the query as well. Any ideas on how to get around this? If you need any more information, please let me know.
One hack around it is to cast it as an `nvarchar(max)`. This is a [documented](http://technet.microsoft.com/es-es/library/ms176089.aspx) way to increase the string length beyond 4,000: > `nvarchar [ ( n | max ) ]` > > Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. **max indicates that the maximum storage size is 2^31-1 bytes (2 GB).** The storage size, in bytes, is two times the actual length of data entered + 2 bytes. The ISO synonyms for nvarchar are national char varying and national character varying. A similar trick applies to [varchar()](http://technet.microsoft.com/es-es/library/ms176089.aspx).
Try these... ``` SELECT DistinctMemo = DISTINCT(CAST(MEMO_TEXT AS varchar(max))) FROM MyTable -- or SELECT DistinctMemo = CAST(MEMO_TEXT AS varchar(max)) FROM MyTable GROUP BY CAST(MEMO_TEXT AS varchar(max)) ```
Is there any way to DISTINCT or group by a text (or ntext) in SQL Server 2005?
[ "", "sql", "sql-server", "types", "" ]
I've been building a site. At some stage I noticed that IE display was a little broken and Chrome had all but rendered nothing but the body tag (empty), and FF all looked good. After throwing my keyboard around the room and bashing my head against my mouse, I discovered the problem. I had left (don't ask how or why, must have been some lightning speed cut and paste error) an HTML comment unclosed in an inline script block. ``` <script type="text/javascript"> <!-- ... </script> ``` I'm guessing (not tested) the problem would have either not come up, or manifested itself in a far more noticeable way if the script was external. So anyways, I got to thinking, is there ever a time when you have a really good reason to write inline script??
No. Write [Unobtrusive Javascript](http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.html).
If you want your Javascript to run as early as possible, it *might* make sense to include inline Javascript, since it will run before any other HTTP requests have necessarily completed. And in some cases, you're including Javascript from a 3rd party provider and you don't really have a choice. Certain ad systems, as well as Google Analytics, spring to mind.
Is there any good reason for javascript to be inline
[ "", "javascript", "html", "scripting", "inline", "" ]
Does anyone know a way to get the mean amplitude of a .wav file using C# (even if it means calling an outside command line program and parsing the output)? Thanks!
Here is a snip that reads in a stereo wav and puts the data in two arrays. It's untested because I had to remove some code (converting to mono and calculate a moving average) ``` /// <summary> /// Read in wav file and put into Left and right array /// </summary> /// <param name="fileName"></param> private void ReadWavfiles(string fileName) { byte[] fa = File.ReadAllBytes(fileName); int startByte = 0; // look for data header { var x = 0; while (x < fa.Length) { if (fa[x] == 'd' && fa[x + 1] == 'a' && fa[x + 2] == 't' && fa[x + 3] == 'a') { startByte = x + 8; break; } x++; } } // Split out channels from sample var sLeft = new short[fa.Length / 4]; var sRight = new short[fa.Length / 4]; { var x = 0; var length = fa.Length; for (int s = startByte; s < length; s = s + 4) { sLeft[x] = (short)(fa[s + 1] * 0x100 + fa[s]); sRight[x] = (short)(fa[s + 3] * 0x100 + fa[s + 2]); x++; } } // do somthing with the wav data in sLeft and sRight } ```
The [NAudio](http://www.codeplex.com/naudio) library for .NET sounds like your best bet. It allows access to the waveform of an audio file, which can loop over to calculate the value of the mean ampltiude.
Mean amplitude of a .wav in C#
[ "", "c#", "audio", "wav", "" ]
Is there a thread-safe way to concurrently consume the stdout from an external process, using ProcessBuilder in Java 1.6? Background: I need to invoke pbzip2 to unzip large files to stdout and to process each line as the file is decompressed (pbzip2 utilizes multiple CPUs, unlike other implementations). The logical approach is to create a child thread to loop over the InputStream (i.e. stdout; don't you just love the naming?), as follows: ``` while((line = reader.readLine()) != null) { // do stuff } ``` However, unzipping is slow, so what I really need is for the reader.readLine method to quietly wait for the next line(s) to become available, instead of exiting. Is there a good way to do this?
You should be able to wrap your input stream with an [InputStreamReader](http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputStreamReader.html) and [BufferedReader](http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html). You can then call `readLine()` and that will block as required. Note that you should have a corresponding reader for the stderr. You don't have to do anything with it, but you will need to consume the stderr stream, otherwise your spawned process may well block. See [this answer](https://stackoverflow.com/questions/882772/capturing-stdout-when-calling-runtime-exec/882795#882795) for links etc.
You more or less have the solution yourself. You just create a new thread which reads the next line in a loop from the stream of your external process and processes that line. readLine() will block and wait until an entire new line is available. If you're on a multicore/processor machine, your external process can happily continue unzipping while your thread processes a line. Atleast unzipping can continue until the OS pipes/buffers becomes full. Just note that if your processing is slower than unzipping, you'll block the unzipping, and at this point it becomes a memory vs speed issue. e.g. you could create one thread that does nothing but read lines(so unzipping will not block), buffer them up in a queue in memory and a another thread - or even several, that consumes said queue. > readLine method to quietly wait for > the next line(s) to become available, > instead of exiting nd that's exactly what readLine should do, it will just block until a whole line is available.
Concurrently consume stdout from an external process
[ "", "java", "" ]