Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
At the company where I am right now, there are a lot of places in the code where an OurCompanyRuntimeException is thrown (where OurCompany is the actual name of the company). As far as I can tell, this exception is described as "A runtime exception thrown by code that we wrote here at this company." I'm somewhat new to Java, but I thought exception types were supposed to reflect *what* went wrong, not *whose code* threw the exception. For example, IllegalArgumentException means someone passed an illegal argument to something. You wouldn't have a SunIllegalArgumentException if an illegal argument was passed in code written by Sun, and then a IBMIllegalArgumentException -- that would be silly and pointless, right? And if you want to know where the exception was thrown, you look at the stack trace. I understand wanting to extend RuntimeException (so that you don't have as many try/catches or "throws"es all over) but why not make subclasses that explain what happened, as opposed to what company's code it happened in? Has anyone ever used the OurCompanyRuntimeException idea before, or have an idea of why they might have done it this way?
Sounds like the usual bespoke code nonsense that you find in in-house code bases to me. I suspect if you ask about there'll have been some decree that the `OurCompanyRuntimeException` was used based on some misguided logic by a senior guy that nobody dared question and has long since moved on - the story of the [monkeys, bananas and hose-pipes](http://everything2.com/index.pl?like_id=1504996&node_id=1504994&op=ilikeit) springs to mind. I agree with you, the name of the exception should be indicative of the error that has occurred.
Helps when reading stack traces, that's for sure. I.e. when scanning through a lot of lines of 'caused by's', it helps to see that it occurred in something thrown by you, not something internal to, say, a container. Also lets you perform custom actions as part of the throwable - e.g. write to a special log somewhere, etc.
What's the point of an OurCompanyRuntimeException type in Java?
[ "", "java", "exception", "" ]
I have a similar problem with delete command too.. ``` function deleteUsers($userID) { foreach($userID as $key => $val) { $query = "DELETE FROM members WHERE member_id = '$val'"; $result = mysql_query($query); } //$query = "DELETE FROM members WHERE member_id = $userID"; //$result = mysql_query($query); if($result) { return 'yes'; } } ``` its not performing multi delete.... the $userID contains array. Its not going inside the Query.
When using multiple IDs use variable IN (1,2,3) format rather than simple equality. Also if you have more than one ID maybe the variable should be called $userIDs? ``` if(count($userID) > 0) { $query = 'DELETE FROM members WHERE member_id IN ('. implode(',', $userID) .')'; } ```
Without foreach: ``` function deleteUsers($userID) { if (count($userID)) { $query = "DELETE FROM `members` WHERE `member_id` IN (".implode(",", array_values($userID)).");"; if (mysql_query($query)) { return true; } } return false; } ```
Delete command Issue in PHP
[ "", "php", "mysql", "" ]
Been hitting my head on the wall before as I don't make any test classes while using c/c++ (but instead have **a lot** of print methods). What is the most used method to perform testing in the c/c++ code? Java's JUnit has only left me with good memories while debugging things. I know that using asserts in code with a defined debug header should work, but aren't there any better ways? And since I have the intention to make test classes in the future, any useful tips are welcome.
You can check these out: <http://gamesfromwithin.com/?p=29> <http://www.opensourcetesting.org/unit_c.php> <http://msdn.microsoft.com/en-us/magazine/cc136757.aspx>
We use [Google Test](http://code.google.com/p/googletest/) and it's companion [Google Mock](http://code.google.com/p/googlemock/). Works wonderfully and supports JUnit style XML output for easy integration with CruiseControl, etc. It's also fully cross platform, and from my research a few months ago, GMock was the *ONLY* fully cross platform object mocking framework for C++.
C/C++ testing framework (like JUnit for java)
[ "", "c++", "c", "testing", "" ]
How would you convert an integer to base 62 (like hexadecimal, but with these digits: `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`)? I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.
There is no standard module for this, but I have written my own functions to achieve that. ``` BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def encode(num, alphabet): """Encode a positive number into Base X and return the string. Arguments: - `num`: The number to encode - `alphabet`: The alphabet to use for encoding """ if num == 0: return alphabet[0] arr = [] arr_append = arr.append # Extract bound-method for faster access. _divmod = divmod # Access to locals is faster. base = len(alphabet) while num: num, rem = _divmod(num, base) arr_append(alphabet[rem]) arr.reverse() return ''.join(arr) def decode(string, alphabet=BASE62): """Decode a Base X encoded string into the number Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for decoding """ base = len(alphabet) strlen = len(string) num = 0 idx = 0 for char in string: power = (strlen - (idx + 1)) num += alphabet.index(char) * (base ** power) idx += 1 return num ``` Notice the fact that you can give it any alphabet to use for encoding and decoding. If you leave the `alphabet` argument out, you are going to get the 62 character alphabet defined on the first line of code, and hence encoding/decoding to/from 62 base. PS - For URL shorteners, I have found that it's better to leave out a few confusing characters like 0Ol1oI etc. Thus I use this alphabet for my URL shortening needs - `"23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"`
I once wrote a script to do this aswell, I think it's quite elegant :) ``` import string # Remove the `_@` below for base62, now it has 64 characters BASE_LIST = string.digits + string.letters + '_@' BASE_DICT = dict((c, i) for i, c in enumerate(BASE_LIST)) def base_decode(string, reverse_base=BASE_DICT): length = len(reverse_base) ret = 0 for i, c in enumerate(string[::-1]): ret += (length ** i) * reverse_base[c] return ret def base_encode(integer, base=BASE_LIST): if integer == 0: return base[0] length = len(base) ret = '' while integer != 0: ret = base[integer % length] + ret integer /= length return ret ``` Example usage: ``` for i in range(100): print i, base_decode(base_encode(i)), base_encode(i) ```
Base 62 conversion
[ "", "python", "base62", "" ]
Is it possible to catch the exception when a referenced .dll cannot be found? For example, I have a C# project with a reference to a third-party dll; if that dll cannot be found, an exception is thrown. The exception is a System.IO.FileNotFoundException, but I am unable to determine where to catch it. The following code did not seem to work: ``` static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { try { // code goes here } catch (Exception exc) { MessageBox.Show(exc.ToString()); } } } ```
Extending Josh's answer. Assemblies in .Net are loaded on demand by the CLR. Typically an assembly load won't be attempted until a method is JIT'd which uses a type from that assembly. If you can't catch the assembly load failure with a try/catch block in the main method, it's likely beceause you're using a type from the assembly within the try/catch. So the exception occurs before the main method is actually run. Try putting all of the code from the main method in a different function. Then call that function within the try/catch block and you should see the exception.
You can use `AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);` ``` Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { } ``` To manually find the assembly if it can't find it automaticaly.
Can I catch a missing dll error during application load in C#?
[ "", "c#", ".net", "dll", "" ]
I am currently using the following PyQt code to create a simple browser: ``` import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://www.robeez.com")) web.show() sys.exit(app.exec_()) ``` Websites like google.com or stackoverflow.com work fine but robeez.com doesn't. Does anyone with Webkit experience know what might be wrong? robeez.com works fine in a regular browser like Chrome or Firefox.
try [arora](http://code.google.com/p/arora/) (a very simple wrapping on top of QtWebKit); if it works, its your code. if it doesn't, its the website.
For some reason <http://www.robeeez.com> which I think redirects to rebeez.com DOES work. In some cases rebeez.com sends out a blank index.html page, dillo and wget also receive nothing as does the qt45 demo browser. So is it the browser or the way the site is set up??
Problem loading a specific website through Qt Webkit
[ "", "python", "webkit", "pyqt", "qtwebkit", "" ]
I am relatively new to the world of Java and Maven, but I couldn't imagine starting a new Java project without using Maven. The idea of providing a human-readable project model is something that I would imagine is universally desirable across many languages. This is especially true when your application relies upon numerous external libraries. Are there any other project management or build tools for languages other than Java that are similar in nature to Maven; that is, that provide a mechanism for the project maintainer to specify dependencies and build order?
Here's some I know of. As to whether they are the most appropriate tool for a given language, form your own opinion. * .Net: [NMaven](http://incubator.apache.org/nmaven/) and [dotnet-maven-plugin](http://doodleproject.sourceforge.net/mavenite/dotnet-maven-plugin/index.html) * AspectJ: [aspectj-maven-plugin](http://www.mojohaus.org/aspectj-maven-plugin/) (still Java I know but worth mentioning) * c/c++: [native-maven-plugin](http://www.mojohaus.org/maven-native/native-maven-plugin/) compile with compilers such as gcc, msvc, etc ... * Google Web Toolkit [gwt-maven-plugin](https://gwt-maven-plugin.github.io/gwt-maven-plugin/) * PHP: [Maven for PHP](http://www.php-maven.org/) * Ruby: [Ruby on Maven](http://mojo.codehaus.org/rubyscript-maven-plugin/introduction.html) * Scala: [maven-scala-plugin](http://scala-tools.org/mvnsites/maven-scala-plugin/) * Flex and Air: [Flexmojos](http://flexmojos.sonatype.org/) Arbitrary "integrations" can be handled by using the [exec-maven-plugin](http://www.mojohaus.org/exec-maven-plugin/) to invoke the relevant compiler and binding the execution to the compile phase. There are also Maven-like products such as [Byldan](http://www.codeplex.com/byldan/) for .Net --- Updated with Flex Mojos and dotnet-maven-plugin at [Pascal](https://stackoverflow.com/users/70604/pascal-thivent)'s suggestion.
You don't really need fancy plugins to manage just about anything that can be executed from command line. As an example I have put Maven builds around poorly managed .NET projects using technics [described in this tutorial](https://web.archive.org/web/20110830022107/http://docs.codehaus.org/display/MAVENUSER/Using+Maven+to+manage+.NET+projects). Basically - plugins such as `exec`, `antrun`, `assembly` and `dependency` can be used together as I mentioned - to do practically everything you need. Of course there are specialized, targeted plugins but I found out that these are hard to use with existing legacy stuff
Maven for other languages?
[ "", "java", "maven-2", "project-management", "build-process", "" ]
I am using a simple regular expression (in C#) to find a whole word within a block of text. The word may appear at the beginning, end or in the middle of a the text or sentence with in the text. The expression I have been using `\bword\b` has been working fine however if the word included a special character (that has been escaped) it no longer works. The boundary is essential so that we do not pick up words such as vb.net as a match for .net. Two examples that fail are: ``` \bc\#\b \b\.net\b ``` I can change the word boundary to a list of other checks such as not at the start non-space etc. however this is complex and can be slow if used on a large number of words.
The `\b` matches the boundary between word characters and non-word characters, but won't match the boundary between two non-word characters. For example, in the case of `C#` there's a boundary between the `C` (a word character) and the `#` (a non-word character) but not between the `#` and whatever comes after it (space, punctuation, end-of-string etc). You can workaround this problem as follows: * Use `(?:^|\W)` instead of `\b` at the beginning of the expression. For example, `(?:^|\W)\.NET\b` This will match either the start-of-string or a non-word character before the `.` character. * Use `(?:\W|$)` instead of `\b` at the end of the expression. For example, `\bC#(?:\W|$)` This will match either a non-word character or the end-of-string after the `#` character.
I would suggest negative lookarounds: ``` (?<!\w)c#(?!\w) (?<!\w)\.net(?!\w) ``` That should be quicker than matching anchors or non-word characters, like `(?:^|\W)`, plus you don't have to deal with the extraneous characters when it's the `\W` that matches.
Regex to find a word that includes an escaped character
[ "", "c#", "vb.net", "regex", "" ]
I am creating a database that tracks replays for a game. Each replay has a different game mode that is either team-based gameplay or individual-based gameplay. Depending on the game mode, I want to record the winning team or the winning individual. I have the following MySQL table that tracks rounds in the replay and the associated winner: ``` CREATE TABLE replay_rounds ( replay_id INT UNSIGNED NOT NULL, round SMALLINT UNSIGNED NOT NULL, winning_player_id INT UNSIGNED, winning_team_id TINYINT UNSIGNED, FOREIGN KEY (replay_id) REFERENCES replays(id), FOREIGN KEY (replay_id, winning_player_id) REFERENCES replay_players(replay_id, player_id), FOREIGN KEY (winning_team_id) REFERENCES teams(id), PRIMARY KEY (replay_id, round)) CHARACTER SET=utf8 COLLATE=utf8_general_ci ENGINE=InnoDB; ``` Using what I have now, if the game mode is team-based then I will set the winning\_team\_id for each round and set the winning\_player\_id to `null`. Likewise, if the game mode is individual-based, I will set the winning\_team\_id to `null`. Performance-wise and in terms of best practice, is it all right to leave it like this? Is there a compelling reason to split this into a separate table for each game mode (even if there's only two modes)? How about a hypothetical situation where game modes are constantly being added -- would this be best resolved by creating a table for every new game mode?
I would just have one winning\_id (drop the individual winning ids for team and player) and an additional attribute for game\_type\_cd. This will be a lookup attribute that is a foreign key to a new table called GAME\_TYPE\_COES. Then all you need to do is fill in the winning\_id and the game type. This will allow for an infinite amount of game types with only having to add data to the GAME\_TYPE\_CODEs table and not having to change the data structure.
I think this database should be relational - Perhaps 1 table for the (person/team-id), then another that denotes gameid/(team/person-id)/win, then another that has ID/replayinfo/etcetc So.. ``` TeamID | Name ------------- 1 | Thunderbirds 2 | John Petravich GameID | TeamID | Win? ----------------------- 1 | 1 | 1 2 | 2 | 0 ReplayID | GameID | (Your table's other properties) ---------------------------------- 1 | 1 | etc ``` Now you can use the relationship to determine all of the different information about a particular team or individual. If you need to tailor pages based on what kind of thing they are, add a type column to the first table and display your pages based on that type id. $.02
SQL knowing when to split tables
[ "", "sql", "" ]
I need to control other application by simulating mouse movement and keyboard input. How do I accomplish this in C#? Is it even possible?
Have you looked at [White](http://www.codeplex.com/white) [TestStack](https://github.com/TestStack/White)? Sample code: ``` Application application = Application.Launch("foo.exe"); Window window = application.GetWindow("bar", InitializeOption.NoCache); Button button = window.Get<Button>("save"); button.Click(); ``` I don't think it can get better than that. The library is created by ThoughtWorks.
See "To send a keystroke to a different application" on this page: <http://msdn.microsoft.com/en-us/library/ms171548.aspx>
Control another application using C#
[ "", "c#", "winforms", "" ]
I'm trying to write a function in PHP that takes an array of strings (`needle`) and performs a comparison against another array of strings (`haystack`). The purpose of this function is to quickly deliver matching strings for an AJAX search, so it needs to be as fast as possible. Here's some sample code to illustrate the two arrays; ``` $needle = array('ba','hot','resta'); $haystack = array( 'Southern Hotel', 'Grange Restaurant & Hotel', 'Austral Hotel', 'Barsmith Hotel', 'Errestas' ); ``` Whilst this is quite easy in itself, the aim of the comparison is to count how many of the `needle` strings appear in the `haystack`. However, there are three constraints; 1. The comparison is case-insensitive 2. The `needle` must only match characters at the beginning of the word. For example, "hote" will match "Hotel", but "resta" will not match "Errestas". 3. We want to count the number of matching `needles`, not the number of `needle` appearances. If a place is named "Hotel Hotel Hotel", we need the result to be `1` not `3`. Using the above example, we'd expect the following associative array as a result: ``` $haystack = array( 'Southern Hotel' => 1, 'Grange Restaurant & Hotel' => 2, 'Austral Hotel' => 1, 'Barsmith Hotel' => 2, 'Erresta' => 0 ); ``` I've been trying to implement a function to do this, using a `preg_match_all()` and a regexp which looks like `/(\A|\s)(ba|hot|resta)/`. Whilst this ensures we only match the beginning of words, it doesn't take into account strings which contain the same `needle` twice. I am posting to see whether someone else has a solution?
I've found you're description of the problem detailed enough that I could take a TDD approach for solving it. So, because I'm so much trying to be a TDD guy, I've wrote the tests and the function to make the tests pass. Namings might not be perfect, but they're easily changeable. The algorithm of the function may also not be the best, but now that there are tests, refactoring should be very easy and painless. ### Here are the tests: ``` class MultiMatcherTest extends PHPUnit_Framework_TestCase { public function testTheComparisonIsCaseInsensitive() { $needles = array('hot'); $haystack = array('Southern Hotel'); $result = match($needles, $haystack); $this->assertEquals(array('Southern Hotel' => 1), $result); } public function testNeedleMatchesOnlyCharsAtBeginningOfWord() { $needles = array('resta'); $haystack = array('Errestas'); $result = match($needles, $haystack); $this->assertEquals(array('Errestas' => 0), $result); } public function testMatcherCountsNeedlesNotOccurences() { $needles = array('hot'); $haystack = array('Southern Hotel', 'Grange Restaurant & Hotel'); $expected = array('Southern Hotel' => 1, 'Grange Restaurant & Hotel' => 1); $result = match($needles, $haystack); $this->assertEquals($expected, $result); } public function testAcceptance() { $needles = array('ba','hot','resta'); $haystack = array( 'Southern Hotel', 'Grange Restaurant & Hotel', 'Austral Hotel', 'Barsmith Hotel', 'Errestas', ); $expected = array( 'Southern Hotel' => 1, 'Grange Restaurant & Hotel' => 2, 'Austral Hotel' => 1, 'Barsmith Hotel' => 2, 'Errestas' => 0, ); $result = match($needles, $haystack); $this->assertEquals($expected, $result); } } ``` ### And here's the function: ``` function match($needles, $haystack) { // The default result will containg 0 (zero) occurences for all $haystacks $result = array_combine($haystack, array_fill(0, count($haystack), 0)); foreach ($needles as $needle) { foreach ($haystack as $subject) { $words = str_word_count($subject, 1); // split into words foreach ($words as $word) { if (stripos($word, $needle) === 0) { $result[$subject]++; break; } } } } return $result; } ``` ### Testing that the `break` statement is necessary The following test shows when `break` is necessary. Run this test both with and without a `break` statement inside the `match` function. ``` /** * This test demonstrates the purpose of the BREAK statement in the * implementation function. Without it, the needle will be matched twice. * "hot" will be matched for each "Hotel" word. */ public function testMatcherCountsNeedlesNotOccurences2() { $needles = array('hot'); $haystack = array('Southern Hotel Hotel'); $expected = array('Southern Hotel Hotel' => 1); $result = match($needles, $haystack); $this->assertEquals($expected, $result); } ```
array and string functions are usually faster by magnitudes than regexps. It should be fairly easy to do what you want with a combination of [array\_filter](http://de3.php.net/manual/en/function.array-filter.php) and [substr\_count](http://de3.php.net/manual/en/function.substr-count.php). Cheers,
Complex String Comparisons
[ "", "php", "" ]
In Maven, you can have *compile-time* dependencies and *test* dependencies. This is a feature I love, and the M2Eclipse plugin makes this available in Eclipse, too, which is great. So if I add `jmock.jar` to my project as a test dependency, it will show up on the classpath for JUnit tests, but won't be present when I'm debugging the application itself. This is exactly what I'd like to achieve now, but without M2Eclipse or Maven. Is there a way to do this in plain Eclipse? (Possibly without installing any plugins.)
I'm afraid the answer is that you can't. There are 2 open issues which were postponed from 3.5 related to your problem: * [Ability to mark source folder as test sources](https://bugs.eclipse.org/bugs/show_bug.cgi?id=224708) * [[buildpath] Should be able to ignore warnings from certain source folders](https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928)
You could separate all your tests into another project and add the main project as a dependency (**Project->Properties**->**Java Build Path**->**Projects**->**Add...**) Update: To avoid changing the original project structure, your test projects can use linked locations. Create the test project as normal, you now need to create a linked resource to bring in the src/test/java folder. It is best to create it using a variable so that your projects can retain some platform independence. To create a new linked folder select **New**->**Folder**, input **src** in the **folder name:** field then click **Advanced>>** Click **Link to folder in the file system** Click on **Variables...** to bring up the **Select Path Variable** dialogue. If this is your first time, or you are linking to a new location select **New...** and give the variable a sensible name and path. If all your projects are located in **c:\workspaces\foo\*\* it makes sense to call the variable \*\*WORKSPACE\_ROOT** and give it that path. If you have some other convention that is fine, but it makes sense to put a comment in the .project file so someone has a chance of figuring out what the correct value should be. Assuming the values above you can now set a value of **WORKSPACE\_ROOT/[subject project name]/src** on the input field Once you confirm that you should see the src folder with a little arrow, and if you look in the .project file see something like this: ``` <linkedResources> <link> <name>src</name> <type>2</type> <locationURI>WORKSPACE_ROOT/esf-ns-core-rp/src</locationURI> </link><!--NOTE the WORKSPACE_ROOT variable points to the folder containing the subject project's sandbox--> </linkedResources> ``` You can now add the src/test/java folder as a source location as normal. Note you can also share just the src/test/java folder by changing the config to something like this: ``` <linkedResources> <link> <name>src/test/java</name> <type>2</type> <locationURI>WORKSPACE_ROOT/my-project/src/test/java</locationURI> </link> </linkedResources> ``` This gives more control over the config, but you would have to repeat for src/test/resources, src/it/java etc. You then set all the test dependencies only in the test project. Very not pretty, but it does work (I've also used this where my test compliance level is different to the main compliance level, e.g. 1.5 for tests, but 1.4 for the target environment).
Eclipse classpath entries only used for tests
[ "", "java", "eclipse", "unit-testing", "classpath", "" ]
do you know a way to select a different facelets component at runtime? I've got some of code similar to this: ``` <s:fragment rendered="#{r== 'case1'}"> <div> <ui:include src="case1.xhtml" /> </div> </s:fragment> <s:fragment rendered="#{r== 'case2'}"> <div> <ui:include src="case2.xhtml" /> </div> </s:fragment> ``` I'd like to write ``` <ui:include src="#{r}.xhtml" /> ``` Thanks.
Your solution should work OK - the [src attribute](https://facelets.dev.java.net/nonav/docs/dev/docbook.html#template-include) can be a literal or an EL expression. You might want to make the expression use a managed bean property or resolve it through a [function](https://facelets.dev.java.net/nonav/docs/dev/docbook.html#taglib-create-function). That way, you can ensure that it is never null (you could return a reference to an empty page if it was). You'll probably get a 404 error if #{r} resolves to null. ``` <ui:include src="#{myfn:resolveNotNull(r, 'pageIfRIsNull')}.xhtml" /> ```
Not sure. An alternative though would be to use a template with a ui:insert and then direct to case1 or case2 which use ui:define programatically.
Resolving facelets components at runtime
[ "", "java", "jsf", "facelets", "" ]
I've got a scenario like the following: ``` class criterion { // stuff about criteria... }; namespace hex { class criterion : public criterion //does not compile { //This should inherit from the //A hex specific criterion //criterion class in the global namespace }; }; ``` My question is -- how does one inherit from a class in a namspace which is the parent of another namespace? Billy3
Start with "::" For example ``` class criterion : public ::criterion {}; ```
You need to specify the namespace, in this case the global one: ``` class criterion : public ::criterion ``` Note that c++ doesn't specify any means of navigating namespaces as if they were a tree. For example, you can't specify the the "parent" namespace using ".." or any other shorthand - you have to use its name.
Accessing Parent Namespace in C++
[ "", "c++", "inheritance", "namespaces", "" ]
I am still a student, and I find project Euler very fun. sometimes the question requires calculations that are bigger than primitive types. I know you can implement it but I am too lazy to do this, So I tried few libraries, [MAPM](http://www.tc.umn.edu/~ringx004/mapm-main.html) :: very good performance, but it provides only big floats, with the possibility to check if it is an integer. very good to accept input, but nasty to provide output, and compiles like magic with Visual C++ 2008 express. [bigint](http://sourceforge.net/projects/cpp-bigint/) :: a small one, but needs a re engineering in many parts. Very simple to use, but very limited power, and very slow compared to others. only big integers. [ttmath](http://www.ttmath.org/ttmath) :: the most beautiful one I have tried until now!, just some files to include and you have unbelievable power/simplicity. Compiles like magic in Visual C++ 2008 express. It is fast, because it provides fixed-length numbers. It is built using Metaprogramming in C++. The only disadvantage I see, is that numbers are not arbitrary in length at run-time, but you can have 1024K numbers when writing code very easily, ``` ttmath::UInt<1024 * 1024> reallyHugeUnsignedInteger; ``` It provides three types: signed, unsigned and float. I tried to compile gmp under VC2008 express, but I failed! I know it is the best, but no where easy to compile for a beginner under VC2008 express, I appreciate also if you point to a tutorial to compile gmp under VC. EDIT :: If you know how to compile gmp using VC 2008, Please explain to me and get the bounty :) **EITD :: It seems that I was not using the right terms, So here is the magical GMP for Windows! works with VC 2008 :)** [***MPIR***](http://www.mpir.org/)
Here are a couple of links regarding GMP and Visual Studio 2008: [GMP Install Help at CodeGuru](http://www.codeguru.com/forum/showthread.php?t=462096) [GMP Compile Guide at The Edge Of Nowhere](http://www.edgeofnowhere.cc/viewtopic.php?t=393933) (this one looks really thorough)
... or just try out PARI/GP <http://pari.math.u-bordeaux.fr/>
Best bignum library to solve Project Euler problems in C++?
[ "", "c++", "bignum", "" ]
I know precisely zilch about regular expressions and figured this was as good an opportunity as any to learn at least the most basic of basics. How do I do this case-insensitive string replacement in C# using a regular expression? ``` myString.Replace("/kg", "").Replace("/KG", ""); ``` (Note that the '/' is a literal.)
You can use: ``` myString = Regex.Replace(myString, "/kg", "", RegexOptions.IgnoreCase); ``` If you're going to do this a lot of times, you could do: ``` // You can reuse this object Regex regex = new Regex("/kg", RegexOptions.IgnoreCase); myString = regex.Replace(myString, ""); ``` Using `(?i:/kg)` would make *just that bit* of a larger regular expression case insensitive - personally I prefer to use `RegexOptions` to make an option affect the whole pattern. MSDN has [pretty reasonable documentation](https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expressions) of .NET regular expressions.
Like this: ``` myString = Regex.Replace(myString, "/[Kk][Gg]", String.Empty); ``` Note that it will also handle the combinations /kG and /Kg, so it does more than your string replacement example. If you only want to handle the specific combinations /kg and /KG: ``` myString = Regex.Replace(myString, "/(?:kg|KG)", String.Empty); ```
How do you do case-insensitive string replacement using regular expressions?
[ "", "c#", ".net", "regex", "" ]
I'm having a strange issue with cookie visibility between an authentication servlet and our actual jsp. We're using a servlet to authenticate that the user is a valid user, and if they are, we go ahead and add a cookie to the HttpServletResponse with their referer url (this is so that integrations can be redirected to their own login page on logout). Logout operations go through the same servlet, and the cookie is retrieved, and the user directed back to the stored cookie url. This all works. However, within my site, if I print out the cookies pulled through the pageContext.getRequest().getCookies() [Or through firebug's console] I do not find the cookie I stored at all. There's literally no trace of it. Yet, when you click the logout link, and are directed back to the authentication servlet, the cookie is found, and the redirect followed accordingly. The thing is, I need to handle timeout operations in the same ways as logouts, but the timeout check is external to the servlet, in a jsp tag. Since the timeout can't find the cookie, it's just using the standard timout page, which the integrating customer wouldn't want to see. Any ideas what's going on here? [ANSWER] It turned out to be a path issue. I know I didn't paste any code, but I was creating the cookie without setting a path, so the cookie was only visible within the servlet directory. Once I set a path of "/" the cookie was visible throughout the site.
Actually, it turned out to be a path issue. I know I didn't paste any code, but I was creating the cookie without setting a path, so the cookie was only visible within the servlet directory. Once I set a path of "/" the cookie was visible throughout the site.
When you say "within my site", does that mean that your site is deployed on a different (sub) domain? Cookies by default are only visible to host they were set from, meaning cookie that was set from "www.example.com" will not be visible to "other.example.com". You can get around that by explicitly specifying cookie domain to be common for both (e.g. "example.com").
Java Servlet/JSP Cookie Disconnect
[ "", "java", "jsp", "cookies", "" ]
I've had a look at many tutorials regarding cookiejar, but my problem is that the webpage that i want to scape creates the cookie using javascript and I can't seem to retrieve the cookie. Does anybody have a solution to this problem?
If all pages have the same JavaScript then maybe you could parse the HTML to find that piece of code, and from that get the value the cookie would be set to? That would make your scraping quite vulnerable to changes in the third party website, but that's most often the case while scraping. (Please bear in mind that the third-party website owner may not like that you're getting the content this way.)
I responded to your [other question](https://stackoverflow.com/questions/1117491/fake-a-cookie-to-scrape-a-site-in-python/1118060#1118060) as well: take a look at [mechanize](http://wwwsearch.sourceforge.net/mechanize/). It's probably the most fully featured scraping module I know: if the cookie is sent, then I'm sure you can get to it with this module.
Retrieve cookie created using javascript in python
[ "", "python", "cookies", "urllib2", "cookiejar", "" ]
Hello I'm currently having an issue with a timer in a program I'm developing. The timer runs and calls methods which retrieve Windows Management Information from remote PC's after a set period of time and repeat this. The first time the timer calls these all is well, however the second time, after the timer has completed its task, it loops through itself again and the third time it runs it does it 3 times etc. The for loop in the code below works fine its the timer itself. So any help would be appareciated and if you require any further details please let me know. Below is my code: ``` private void tmrStore_Tick(object sender, EventArgs e) { string ipAdd; ipAdd = "127.0.0.1"; List<TblServer> Server; WMIInfo localDB = new WMIInfo("Data Source=|DataDirectory|\\WMIInfo.sdf"); Server = localDB.TblServer.ToList(); if (Server.Count == 0) { } else { for (int counter = 0; counter < Server.Count; counter++) { CPUStore cpu = new CPUStore(); cpu.Store(Server[counter].IpAdd); HDDStore hdd = new HDDStore(); hdd.Store(Server[counter].IpAdd); MemStore mem = new MemStore(); mem.Store(Server[counter].IpAdd); //delete items over 24 hours old } } ```
Right I've resolved the issue its because I had a class I was using to write the retrieved information into text boxes and within that I called a new instance of the form to gain access to the text boxes doh! Thanks for your help though guys no doubt I'll be back soon for some more lol
Try disabling the timer before performing the management task, then reenabling: ``` tmrStore.Enabled = false; try{ // do stuff }finally{ tmrStore.Enabled = true; } ``` The cause of the problem is probably that the body of your timer handler takes longer to execute than your Timer.Ticks value, so your timer events start to stack on top of each other. You might also consider putting this code in a thread instead of a timer, so that it's independent of your user interface.
C# timer issue
[ "", "c#", ".net", "timer", "" ]
I love jQuery. I am probably going to have some XML parsing and manipulation using C#. It would be a piece of cake doing it in jQuery. Is there a C# library that implements jQuery's functionality?
[Linq to XML](http://msdn.microsoft.com/en-us/library/bb387098.aspx), for what you want to do.
Old question but new answer. I've recently released version 1.1 of [CsQuery](https://github.com/jamietre/CsQuery), a jQuery port for .NET 4 written in C# that I've been working on for about a year. Also on [NuGet](http://www.nuget.org/packages/CsQuery) as "CsQuery" The current release implements all CSS2 & CSS3 selectors, all jQuery extensions, and all jQuery DOM manipulation methods. It's got extensive test coverage including all the tests from jQuery and sizzle (the jQuery CSS selection engine). I've also included some performance tests for direct comparisons with Fizzler; for the most part CsQuery dramatically outperforms it. The exception is actually loading the HTML in the first place where Fizzler is faster; I assume this is because fizzler doesn't build an index. You get that time back after your first selection, though. There's documentation on the github site, but at a basic level it works like this: Create from a string of HTML ``` CQ dom = CQ.Create(htmlString); ``` Load synchronously from the web ``` CQ dom = CQ.CreateFromUrl("http://www.jquery.com"); ``` Load asynchronously (non-blocking) ``` CQ.CreateFromUrlAsync("http://www.jquery.com", responseSuccess => { Dom = response.Dom; }, responseFail => { .. }); ``` Run selectors & do jQuery stuff ``` var childSpans = dom["div > span"]; childSpans.AddClass("myclass"); ``` the `CQ` object is like thejQuery object. The property indexer used above is the default method (like `$(...)`. Output: ``` string html = dom.Render(); ```
Is there a jQuery-like library written in C#?
[ "", "c#", ".net", "jquery", "xml", "" ]
What I want to do is display an input field with the text color `black`. Then when the person clicks inside the input field (`onfocus`) I want to change the text color to `red`. Then, when the person click outside of the input field (no longer focus), I want to change the text color back to `black`. I know how to handle the JavaScript `onfocus` event using the following: ``` <input ctype="text" onfocus="this.style.color='red';" /> ``` *But how do I handle the "off focus" to change the text color back to black?*
try using [onblur](https://www.w3schools.com/jsref/event_onblur.asp), it is called when an element loses focus.
Use the [`onBlur`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onblur) event: ``` <input ctype="text" onfocus="this.style.color='red';" onblur="this.style.color='black';"/> ```
JavaScript - OffFocus event?
[ "", "javascript", "html", "focus", "dom-events", "" ]
I have two solutions in my workspace, say A and B. Solution A is an older project which I finished coding some time ago. In solution B, I need to use some classes from Solution A. To do so, I add a reference to the dll of one of the projects in solution A. The problem is when I try to debug. I want to be able to step into A's code as well. Visual studio is not able to load the code for these classes ("There is no source code available for the current location.") and I can only view the disassembly, which is not useful. The only way I know to debug classes from solution A is by running solution B, detach all processes (in the Debug menu item) and attach the process from solution A. However, this is very inconvenient and I can only debug A OR B at once. Is there a way to allow stepping into the code of referenced dlls (for which I do have the source code)? --- **Solution:** My mistake was that I thought that a project can only be part of a single solution. In fact, a project can be part of any number of solutions. When you need to reference the old project, you should simply add the project to the solution. This is done by right clicking the new solution in the Solution Explorer > Add > Existing Project. Then, you'll be able to add the project reference. As others wrote, you should probably completely avoid using dll references to your own code (or other code you might need to change and debug). A very good reference to how solutions should be designed can be found in [MSDN](http://msdn.microsoft.com/en-us/library/bb668953.aspx).
If you have a **project** reference, it should work immediately. If it is a **file** (dll) reference, you need the debugging symbols (the "pdb" file) to be in the same folder as the dll. Check that your projects are generating debug symbols (project properties => Build => Advanced => Output / Debug Info = full); and if you have *copied* the dll, put the pdb with it. You can also load symbols directly in the IDE if you don't want to copy any files, but it is more work. The easiest option is to use project references!
I had the same issue. He is what I found: 1) make sure all projects are using the same Framework (this is crucial!) 2) in Tools/Options>Debugging>General make sure "Enable Just My Code (Managed Only) is NOT ticked 3) in Tools/Options>Debugging>Symbols clear any cached symbols, untick and delete all folder locations under the "Symbols file (.pdb) locations" listbox except the default "Microsoft Symbol Servers" but still untick it too. Also delete any static paths in the "Cache symbols in this directory" textbox. Click the "Empty Symbols Cache" button. Finally make sure the "Only specified modules" radio button is ticked. 4) in the Build/Configuration Manager menu for all projects make sure the configuration is in Debug mode.
How to debug a referenced dll (having pdb)
[ "", "c#", "visual-studio", "visual-studio-2008", "visual-studio-2005", "" ]
I have the following code that executes a query and writes it directly to a string buffer which then dumps it to a CSV file. I will need to write large amount of records (maximum to a million). This works for a million records it takes about half an hour for a file that is around 200mb! which seems to me like a lot of time, not sure if this is the best. Please recommend me better ways even if it includes using other jars/db connection utils. ``` .... eventNamePrepared = con.prepareStatement(gettingStats + filterOptionsRowNum + filterOptions); ResultSet rs = eventNamePrepared.executeQuery(); int i=0; try{ ...... FileWriter fstream = new FileWriter(realPath + "performanceCollectorDumpAll.csv"); BufferedWriter out = new BufferedWriter(fstream); StringBuffer partialCSV = new StringBuffer(); while (rs.next()) { i++; if (current_appl_id_col_display) partialCSV.append(rs.getString("current_appl_id") + ","); if (event_name_col_display) partialCSV.append(rs.getString("event_name") + ","); if (generic_method_name_col_display) partialCSV.append(rs.getString("generic_method_name") + ","); ..... // 23 more columns to be copied same way to buffer partialCSV.append(" \r\n"); // Writing to file after 10000 records to prevent partialCSV // from going too big and consuming lots of memory if (i % 10000 == 0){ out.append(partialCSV); partialCSV = new StringBuffer(); } } con.close(); out.append(partialCSV); out.close(); ``` Thanks, Tam
Just write to the `BufferedWriter` directly instead of constructing the `StringBuffer`. Also note that you should likely use `StringBuilder` instead of `StringBuffer`... `StringBuffer` has an internal lock, which is usually not necessary.
Profiling is generally the only sure-fire way to know why something's slow. However, in this example I would suggest two things that are low-hanging fruit: 1. Write directly to the buffered writer instead of creating your own buffering with the StringBuilder. 2. Refer to the columns in the result-set by integer ordinal. Some drivers can be slow when resolving column names.
improving performance of writing query results to CSV in java
[ "", "java", "performance", "" ]
Working through C++ Primer Plus and am trying to cin data to a dynamically allocated array of structures. One of the items is a char array. How do I write to these struct members? Posting code of my wrong attempt so you can see what I'm trying to do. ``` #include <iostream> using namespace std; struct contributions { char name[20]; double dollars; }; int donors; int main() { cout << "How many contributors will there be?\n"; cin >> donors; contributions * ptr = new contributions[donors]; for(int i = 0; i <= donors; i++) { cout << "Enter donor name #" << i+1 << ": \n"; cin >> ptr->contributions[i].name; cout << "Enter donation amount: \n"; cin >> ptr->contributions[i].dollars; } ``` Thanks in advance!
Try using std::string instead of char[20] for name and the sample should work just fine. ``` struct contributions { std::string name; double dollars; }; ``` also change the access to ``` ptr[i].name ```
``` cin >> ptr[i].name; ``` `ptr` is the name of the variable, it is of type `contributions*`. It is an array of `contributions`, so to access the *i*th member, use `ptr[i]`. Then access the `name` field of that member via `ptr[i].name`. Also, `cin >> char[]` may not work (I don't recall for sure), as `char[]` is more of a C-ish thing, whereas `cin` is C++. So you might need to change the type of `name` to std::string. As an aside, convention is to name your structs/classes with a singular noun. Thus `contribution` would be a more correct name; every instance represents a *single contribution*.
Accessing members of an array of structures in C++
[ "", "c++", "" ]
I'm trying to get an image via an https URL, and am having some problems. I generate a keystore with Java's keytool command. If I specify the common name (CN) equal to my hostname, such as CN=JONMORRA, and then try to query via my hostname, such as <https://JONMORRA:8443/> then it works fine. However, if I specify the common name as my ip address, such that CN=192.168.56.1, and try to query via my ip address, such as <https://192.168.56.1:8443/> then I get an error HTTPS hostname wrong: should be <192.168.56.1> Which is stating that my hostname is wrong, even though that's what I specified in the keystore. I would like to use ip addresses instead of hostnames so I can query between Linux and Windows boxes without worrying about hostnames. Why is the CN not accepting ip addresses, and how can I fix it? Thanks
This snippet might work for you: ``` import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); ``` If you do try this code, and it doesn't work, please post what is printed for `urlHostName` and `session.getPeerHost()`. Also, why does having Windows and Linux boxes interoperating require the use of IP addresses rather than hostnames?
To acutally generate a valid certificate using `keytool`, use: ``` keytool -keystore keystore.jks -genkey -ext SAN=IP:{IP_ADDRESS} ``` e.g.: ``` keytool -keystore keystore.jks -genkey -ext SAN=IP:192.168.1.1 ```
Java's keytool command with IP addresses
[ "", "java", "ssl", "keystore", "keytool", "" ]
My current query looks like this: ``` SELECT * FROM fiberbox f WHERE f.fiberBox LIKE '%1740 %' OR f.fiberBox LIKE '%1938 %' OR f.fiberBox LIKE '%1940 %' ``` I did some looking around and can't find anything similar to a LIKE IN() - I envision it working like this: ``` SELECT * FROM fiberbox f WHERE f.fiberbox LIKE IN('%140 %', '%1938 %', '%1940 %') ``` Any ideas? Am I just thinking of the problem the wrong way - some obscure command I've never seen. MySQL 5.0.77-community-log
A [REGEXP](http://dev.mysql.com/doc/refman/5.1/en/regexp.html) *might* be more efficient, but you'd have to benchmark it to be sure, e.g. ``` SELECT * from fiberbox where field REGEXP '1740|1938|1940'; ```
Paul Dixon's answer worked brilliantly for me. To add to this, here are some things I observed for those interested in using REGEXP: To Accomplish multiple LIKE filters with Wildcards: ``` SELECT * FROM fiberbox WHERE field LIKE '%1740 %' OR field LIKE '%1938 %' OR field LIKE '%1940 %'; ``` Use REGEXP Alternative: ``` SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 |1940 '; ``` Values within REGEXP quotes and between the | (OR) operator are treated as wildcards. Typically, REGEXP will require wildcard expressions such as (.\*)1740 (.\*) to work as %1740 %. If you need more control over placement of the wildcard, use some of these variants: To Accomplish LIKE with Controlled Wildcard Placement: ``` SELECT * FROM fiberbox WHERE field LIKE '1740 %' OR field LIKE '%1938 ' OR field LIKE '%1940 % test'; ``` Use: ``` SELECT * FROM fiberbox WHERE field REGEXP '^1740 |1938 $|1940 (.*) test'; ``` * Placing ^ in front of the value indicates start of the line. * Placing $ after the value indicates end of line. * Placing (.\*) behaves much like the % wildcard. * The . indicates any single character, except line breaks. Placing . inside () with \* (.\*) adds a repeating pattern indicating any number of characters till end of line. There are more efficient ways to narrow down specific matches, but that requires more review of Regular Expressions. NOTE: Not all regex patterns appear to work in MySQL statements. You'll need to test your patterns and see what works. Finally, To Accomplish Multiple LIKE and NOT LIKE filters: ``` SELECT * FROM fiberbox WHERE field LIKE '%1740 %' OR field LIKE '%1938 %' OR field NOT LIKE '%1940 %' OR field NOT LIKE 'test %' OR field = '9999'; ``` Use REGEXP Alternative: ``` SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 |^9999$' OR field NOT REGEXP '1940 |^test '; ``` OR Mixed Alternative: ``` SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 ' OR field NOT REGEXP '1940 |^test ' OR field NOT LIKE 'test %' OR field = '9999'; ``` Notice I separated the NOT set in a separate WHERE filter. I experimented with using negating patterns, forward looking patterns, and so on. However, these expressions did not appear to yield the desired results. In the first example above, I use ^9999$ to indicate exact match. This allows you to add specific matches with wildcard matches in the same expression. However, you can also mix these types of statements as you can see in the second example listed. Regarding performance, I ran some minor tests against an existing table and found no differences between my variations. However, I imagine performance could be an issue with bigger databases, larger fields, greater record counts, and more complex filters. As always, use logic above as it makes sense. If you want to learn more about regular expressions, I recommend www.regular-expressions.info as a good reference site.
MySQL LIKE IN()?
[ "", "sql", "mysql", "" ]
Is there a difference between defining a global operator that takes two references for a class and defining a member operator that takes only the right operand? Global: ``` class X { public: int value; }; bool operator==(X& left, X& right) { return left.value == right.value; }; ``` Member: ``` class X { int value; bool operator==( X& right) { return value == right.value; }; } ```
One reason to use non-member operators (typically declared as friends) is because the left-hand side is the one that does the operation. `Obj::operator+` is fine for: ``` obj + 2 ``` but for: ``` 2 + obj ``` it won't work. For this, you need something like: ``` class Obj { friend Obj operator+(const Obj& lhs, int i); friend Obj operator+(int i, const Obj& rhs); }; Obj operator+(const Obj& lhs, int i) { ... } Obj operator+(int i, const Obj& rhs) { ... } ```
Your smartest option is to make it a **friend function**. As JaredPar mentions, the global implementation cannot access protected and private class members, but there's a problem with the member function too. C++ will allow implicit conversions of function parameters, but not an implicit conversion of **`this`**. If types exist that can be converted to your X class: ``` class Y { public: operator X(); // Y objects may be converted to X }; X x1, x2; Y y1, y2; ``` Only some of the following expressions will compile with a member function. ``` x1 == x2; // Compiles with both implementations x1 == y1; // Compiles with both implementations y1 == x1; // ERROR! Member function can't convert this to type X y1 == y2; // ERROR! Member function can't convert this to type X ``` The solution, to get the best of both worlds, is to implement this as a friend: ``` class X { int value; public: friend bool operator==( X& left, X& right ) { return left.value == right.value; }; }; ```
difference between global operator and member operator
[ "", "c++", "operator-overloading", "" ]
I was working with a simple entity class with LINQ to SQL (SQL Server 2005 SP3 x64). ``` [Table( Name="TBL_REGISTRATION" )] public sealed class Registration : IDataErrorInfo { [Column( Name = "TBL_REGISTRATION_PK", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert )] public Guid RegistrationID { get; private set; } /* other properties ommited for brevity */ } ``` There are only two somewhat interesting things here: 1. The class and property names aren't the same as the table and column names 2. The primary key is a Guid (uniqueidentifier) Here's what the table looks like: ``` create table dbo.TBL_REGISTRATION ( TBL_REGISTRATION_PK uniqueidentifier primary key clustered rowguidcol default newid(), /* other columns ommited for brevity */ ) ``` When I attach this entity to my table and submit changes on my DataContext, the LINQ stack throws back a SqlException: SqlException (0x80131904): Invalid column name 'RegistrationID' LINQ seems to be ignoring the Column( Name = "TBL\_REGISTRATION\_PK" ) attribute on my RegistrationID property. I spent a while futzing with different attribute decorations trying to get it to work. In the end I settled on a private TBL\_REGISTRATION\_PK property to wrap my RegistrationID property to make LINQ happy. ``` [Table( Name="TBL_REGISTRATION" )] public sealed class Registration : IDataErrorInfo { public Guid RegistrationID { get; private set; } [Column( IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert )] private Guid TBL_REGISTRATION_PK { get { return RegistrationID; } set { RegistrationID = value; } } /* other properties ommited for brevity */ } ``` This works. Why didn't it work the first way? Am I doing something wrong here or is this a LINQ defect?
This is a bug in Linq-to-SQL. It is fixed in .net 4.0. See Connect #381883: <https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=381883>
Your property needs 'private' removed from 'private set;' When you make the short hand properties in VS 2008 without implementing get/set, the compiler creates private member variables for you (of which name who knows). The Storage option in ColumnAttribute specifies which private member to use. Linq to SQL doesn't know how to set the property if you mark the setter private and have the getter public (don't ask me why). If you wish to make your property readonly, make a private member variable like you did above. You can clean it up by writing it like the following: ``` [Table( Name="TBL_REGISTRATION" )] public sealed class Registration : IDataErrorInfo { public Guid RegistrationID { get { return _registrationID; } } [Column( IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] private Guid _registrationID; } ```
LINQ to SQL entity column name attribute ignored with guid primary key
[ "", "c#", "sql-server", "linq", "sql-server-2005", "linq-to-sql", "" ]
How to create a tab control with a dynamic number of tabs in Visual Studio C#? I've got a database with a table `customers`. I need to create a form that would show tabs with the first letters of customers' last name (only those first letters, for which there are entries in the table should be present). Each tab should contain a DataGrid control with the corresponding customers. I connect to the database using DataSet. Where should I insert the code snippet that would generate such tabs? Can I do that with the existing tab control or should I create a custom control?
You can generate dynamic tabs with the existing TabControl. Here is an example of how it can be done in a somewhat sort of pseudo code form... ``` TabControl tabControl = new TabControl(); tabControl.Dock = DockStyle.Fill; foreach (Char c in lastNameList) { TabPage tabPage = new TabPage(); tabPage.Text = c.ToString(); DataGrid grid = new DataGrid(); grid.Dock = DockStyle.Fill; grid.DataSource = dataForTheCurrentLoop; tabPage.Controls.Add(grid); tabControl.Controls.Add(tabPage); } this.Controls.Add(tabControl); ```
You would add the code to generate the tabs where you determine what letters are required to be shown, probably when you either retrieve the data or in the form's `OnLoad()` method. You should be able to dynamically add/remove tabs from the built-in tab control. You can check the designer code for some idea how to do it, or the docs. Note that it isn't necessarily a good idea to add a separate tab for each character. 26 tabs (which will happen when your database gets reasonably large) is a pretty awful number of tabs for someone to look through-- it won't necessarily make things faster at all. Instead, consider providing a dynamic filtering mechanism, similar to the search box on Vista's start menu. Your user can type a single character (assuming you aren't writing some sort of kiosk or touch-screen-only software) and zoom immediately to the relevant names. This would work ideally with a `ListView` in List or Details mode.
Creating a tab control with a dynamic number of tabs in Visual Studio C#
[ "", "c#", "visual-studio", "" ]
Right after I moved from XP to Vista,I realized my C# programs don't work. This is the situation: I wrote a C++ dll that I use in my C# application.The DLL worked fine in XP,but when I moved to Vista it's not longer working in C#. I tested it in Delphi,works fine,but C# - no. I wrote additional code to make my check easier in C#. ``` if (LoadLibrary("blowfish.dll") == 0) { Misc.LogToFile("error", true); Application.Exit(); } ``` It doesn't need C++ runtime,because Its compiled with the libraries and it works in Delphi on Vista,but not C#. Where could the problem be? Thanks in advance.
On x64 platform the JIT will compile your program into x64, since your native C++ is compiled to x86 it will fail to load it. You need to explicitly tell the JIT to compile your program to x86, you can do it using [CorFlags](http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx) or the project settings set the CPU type to x86 (Under Build/Platform target)
Shay has the quick fix - make your whole application 32 bit so it runs under WOW64. However, the "better" solution is to rebuild your C++ dll as 64-bit code so that your entire program can run natively on the 64-bit OS.
LoadLibrary fails under Vista x64
[ "", "c#", "winapi", "loadlibrary", "" ]
I have this code ``` @Entity @Table(name = "picture") public class Picture implements Serializable { @Id @Column(name = "id") @GeneratedValue private int id; @Column(name = "format", length = 8) private String format; @Basic(fetch = FetchType.LAZY) @Column(name = "context", nullable = true, columnDefinition="mediumblob") @Lob private java.sql.Blob myBlobAttribute; // protected accessor and modifier @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "branch_fk", referencedColumnName = "id", nullable = false) private Branch branch; //Some setter and getter ``` I use netbeans 6.7 and in this Ide it show me error on line `(private java.sql.Blob myBlobAttribute;)` but code run and it's make picture table on my database! is it a real error or just e notification and how must I solve it? error message was: ``` basic attributes can only be of the following types: java primitive types,wrapper of primitive types, String, java.math.bigInteger, java.math.BigDecimal, java,util.Date, java.util.Calendar, java.sql.Data, java.sql.TimeStamp, byte[], Byte[], char[], Character[], enums, or any Serializable type ```
Your property type is `java.sql.Blob` which is an interface. First of all, why? Shouldn't it be a byte array (presumably that's where you store your image)? Secondly, that's why NetBeans complains - and so will Hibernate once you try to read stuff from this table - they have no way of knowing what actual type to create to put data in your field.
The reason that NetBeans is generating this warning is that when using `java.sql.Blob`, you should only have the @Lob annotation and not @Basic. However, at runtime, it sounds like your JPA implementation is "helping you out" by ignoring the @Basic annotation and recognizing that the column is in fact a LOB. This is why your code works. It is possible that a different JPA implementation would fail or somehow behave differently.
problem with basic attributes java.sql.Blob
[ "", "java", "hibernate", "" ]
I appear to be having an issue with the following snippet of code in that, when I come to specifying what the Item is (eg CashInHand), the actual type CashInHandPayment is not available because it hasn't been carried across when I generate the proxy class (most likely because it doesn't read in XmlElementAttributes). Is there any way to force classes such as AccountPayment, CashInHandPayment and CCPayment to be serialized in the proxy class? ``` [DataContract] public class Payment { [XmlElementAttribute("Account", typeof(AccountPayment))] [XmlElementAttribute("CashInHand", typeof(CashInHandPayment))] [XmlElementAttribute("CreditCard", typeof(CCPayment))] [XmlChoiceIdentifierAttribute("ItemElementName")] [DataMember] public object Item { get; set; } } [DataContract] public enum ItemElementName { [EnumMember] Account, [EnumMember] CashInHand, [EnumMember] CreditCard } //This class will not be in the generated proxy class [DataContract] public class AccountPayment { [DataMember] public double Amount { get; set; } } //classes for CashInHandPayment and CCPayment also created, but not shown. ``` Forgive me if 'serialize' isn't the correct term to use, if you read the question and find that it isn't, please change it accordingly! **Update - answer mentioned by Simon Svensson:** ``` [KnownType(typeof(AccountPayment))] [KnownType(typeof(CashInHandPayment))] [KnownType(typeof(CCPayment))] [DataContract] public class Payment { [XmlElementAttribute("Account", typeof(AccountPayment))] [XmlElementAttribute("CashInHand", typeof(CashInHandPayment))] [XmlElementAttribute("CreditCard", typeof(CCPayment))] [XmlChoiceIdentifierAttribute("ItemElementName")] [DataMember] public object Item { get; set; } } ``` Many thanks, Simon!
Uhm. Isnt XmlElementAttribute and XmlChoiceIdentifierAttribute xml serialization, which is a older serialization compared to the DataContractSerializer which reads DataContractAttribute and DataMemberAttribute? I believe that you should use the KnownTypeAttribute for this, but I have never tried it, nor have I had this scenario in my own code.
> > Is there any way to force classes such as AccountPayment, > > CashInHandPayment and CCPayment to be serialized in the proxy class? They need to be marked with a `[DataContract]` attribute, that should be sufficient, I would think. When `svcutil.exe` (either launched directly from the command line, or from Visual Studio using `Add Service Reference`) encounters classes with the `[DataContract]` attribute on the class and `[DataMember]` on the properties (or fields), it will create a copy in the proxy for those classes. Marc
Force WCF to serialize unused class
[ "", "c#", "xml", "wcf", "" ]
I want to create an object that contains 2 links to Users. For example: ``` class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() ``` but I am getting the following errors when running the server: * > Accessor for field 'target' clashes with related field 'User.gameclaim\_set'. Add a related\_name argument to the definition for 'target'. * > Accessor for field 'claimer' clashes with related field 'User.gameclaim\_set'. Add a related\_name argument to the definition for 'claimer'. Can you please explain why I am getting the errors and how to fix them?
You have two foreign keys to User. Django automatically creates a reverse relation from User back to GameClaim, which is usually `gameclaim_set`. However, because you have two FKs, you would have two `gameclaim_set` attributes, which is obviously impossible. So you need to tell Django what name to use for the reverse relation. Use the `related_name` attribute in the FK definition. e.g. ``` class GameClaim(models.Model): target = models.ForeignKey(User, related_name='gameclaim_targets') claimer = models.ForeignKey(User, related_name='gameclaim_users') isAccepted = models.BooleanField() ```
The `User` model is trying to create two fields with the same name, one for the `GameClaims` that have that `User` as the `target`, and another for the `GameClaims` that have that `User` as the `claimer`. Here's the [docs on `related_name`](https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name-and-related-query-name), which is Django's way of letting you set the names of the attributes so the autogenerated ones don't conflict.
Django: Why do some model fields clash with each other?
[ "", "python", "django", "django-models", "" ]
My question may duplicate [Default implementation for Object.GetHashCode()](https://stackoverflow.com/questions/720177) but I'm asking again because I didn't understand the accepted answer to that one. To begin with I have three questions about the [accepted answer to the previous question](https://stackoverflow.com/questions/720177/default-implementation-for-object-gethashcode/720196#720196), which quotes [some documentation](http://authors.aspalliance.com/aspxtreme/sys/ObjectClassGetHashcode.aspx) as follows: > "However, because this index can be reused after the object is reclaimed during garbage collection, it is possible to obtain the same hash code for two different objects." Is this true? It seems to me that two objects won't have the same hash code, because an object's code isn't reused until the object is garbage collected (i.e. no longer exists). > "Also, two objects that represent the same value have the same hash code only if they are the exact same object." Is this a problem? For example, I want to associate some data with each of the node instances in a DOM tree. To do this, the 'nodes' must have an identity or hash code, so that I can use them as keys in a dictionary of the data. Isn't a hash code which identities whether it's "the exact same object", i.e. "reference equality rather than "value equality", what I want? > "This implementation is not particularly useful for hashing; therefore, derived classes should override GetHashCode" Is this true? If it's not good for hashing, then what if anything is it good for, and why is it even defined as a method of Object? --- My final (and perhaps most important to me) question is, if I must invent/override a GetHashCode() implementation for an arbitrary type which has "reference equality" semantics, is the following a reasonable and good implementation: ``` class SomeType { //create a new value for each instance static int s_allocated = 0; //value associated with this instance int m_allocated; //more instance data ... plus other data members ... //constructor SomeType() { allocated = ++s_allocated; } //override GetHashCode public override int GetHashCode() { return m_allocated; } } ``` --- **Edit** FYI I tested it, using the following code: ``` class TestGetHash { //default implementation class First { int m_x; } //my implementation class Second { static int s_allocated = 0; int m_allocated; int m_x; public Second() { m_allocated = ++s_allocated; } public override int GetHashCode() { return m_allocated; } } //stupid worst-case implementation class Third { int m_x; public override int GetHashCode() { return 0; } } internal static void test() { testT<First>(100, 1000); testT<First>(1000, 100); testT<Second>(100, 1000); testT<Second>(1000, 100); testT<Third>(100, 100); testT<Third>(1000, 10); } static void testT<T>(int objects, int iterations) where T : new() { System.Diagnostics.Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < iterations; ++i) { Dictionary<T, object> dictionary = new Dictionary<T, object>(); for (int j = 0; j < objects; ++j) { T t = new T(); dictionary.Add(t, null); } for (int k = 0; k < 100; ++k) { foreach (T t in dictionary.Keys) { object o = dictionary[t]; } } } stopWatch.Stop(); string stopwatchMessage = string.Format( "Stopwatch: {0} type, {1} objects, {2} iterations, {3} msec", typeof(T).Name, objects, iterations, stopWatch.ElapsedMilliseconds); System.Console.WriteLine(stopwatchMessage); } } ``` On my machine the results/output are as follows: ``` First type, 100 objects, 1000 iterations, 2072 msec First type, 1000 objects, 100 iterations, 2098 msec Second type, 100 objects, 1000 iterations, 1300 msec Second type, 1000 objects, 100 iterations, 1319 msec Third type, 100 objects, 100 iterations, 1487 msec Third type, 1000 objects, 10 iterations, 13754 msec ``` My implementation takes half the time of the default implementation (but my type is bigger by the size of my m\_allocated data member). My implementation and the default implementation both scale linearly. In comparison and as a sanity check, the stupid implementation starts bad and scales worse.
The most important property a hash code implementation must have is this: **If two objects compare as equal then they must have identical hash codes.** If you have a class where instances of the class compare by reference equality, then you do not need to override GetHashCode; the default implementation guarantees that two objects that are the same reference have the same hash code. (You're calling the same method twice on the same object, so of course the result is the same.) If you have written a class which implements its own equality that is different from reference equality then you are REQUIRED to override GetHashCode such that two objects that compare as equal have equal hash codes. Now, you could do so by simply returning zero every time. That would be a lousy hash function, but it would be legal. Other properties of good hash functions are: * GetHashCode should never throw an exception * Mutable objects which compare for equality on their mutable state, and therefore hash on their mutable state, are dangerously bug-prone. You can put an object into a hash table, mutate it, and be unable to get it out again. Try to never hash or compare for equality on mutable state. * GetHashCode should be extremely fast -- remember, the purpose of a good hash algorithm is to improve the performance of lookups. If the hash is slow then the lookups can't be made fast. * Objects which do not compare as equal should have dissimilar hash codes, well distributed over the whole range of a 32 bit integer
Question: > Is this true? It seems to me that two objects won't have the same hash code, because > an object's code isn't reused until the object is garbage collected (i.e. no longer exists). Two objects may share the same hash code, if it is generated by default GetHashCode implementation, because: 1. **Default GetHashCode result shouldn't be changed during object's lifetime**, and default implementation ensures this. If it could change, such types as Hashtable couldn't deal with this implementation. That's because it's expected that default hash code is a hash code of unique instance identifier (even although there is no such identifier :) ). 2. **Range of GetHashCode values is range of integer (2^32).** **Conclusion:** *It's enough to allocate 2^32 strongly-referenced objects to (must be easy on Win64) to reach the limit.* Finally, there is an explicit statement in [object.GetHashCode reference in MSDN](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx): The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.
Object.GetHashCode
[ "", "c#", ".net", "hash", "gethashcode", "" ]
Why are java generics so tricky? I thought I finally understood, but eclipse gives me an error at the line in somOtherMethod below using either of the getOuterList methods below. ``` protected List<?> getOuterList() { // blah blah } protected List<? extends Object> getOuterList() { // blah blah } protected void someOtherMethod() { ... getOuterList().add((MyObject)myObject); //compile error ... } ``` **UPDATE**: ok - so I understand the error now. It was lack of understanding on my part of what `List<?>` or `List<? extends SomeObject>` really means. In the former case, I thought it meant a list that could contain anything. In the latter case, I assumed it was a list of a bunch of objects that extend SomeObject. The proper representation of my understanding would just be `List<Object>` and `List<SomeObject>` (w/out the extends). I thought extends helped me solve a problem which they don't. So here's where my real problem lies: ``` public interface DogKennel { public List<Dog> getDogs(); } public class GreyHoundKennel implements DogKennel { protected List<GreyHound> greyHounds; public List<GreyHound> getGreyHounds() { return this.greyHounds; } public List<Dog> getDogs() { // Is there no way to handle this with generics // w/out creating a new List? return getGreyHounds(); //compiler error } } ```
You're tripping over the fact that Java generics are not polymorphic on the type parameter. Talking through your code fragment, let's pull the example apart: ``` protected List<GreyHound> greyHounds; // List<GreyHound> is fine /** This method returns a lovely List of GreyHounds */ public List<GreyHound> getGreyHounds() { return this.greyHounds; } /** Here is the problem. A List<GreyHound> is not a List<Dog> */ public List<Dog> getDogs() { return getGreyHounds(); //compiler error } ``` So your original comment is correct. The two Lists are definitely different with no inheritance between them. So, I would suggest that you investigate these two options: 1. Try returning a new list as you suggest in your comment. For example, `return new ArrayList<Dog>(this.greyHounds);` 2. Do you really need to keep a list of a specific breed of Dog? Perhaps you should define the data member to be a `List<Dog>` to which you add your specific GreyHounds. I.e., `protected List<Dog> greyHoundsOnly;` where you manage which dogs are allowed in the kennel via the object's external interface. Unless you have a good reason to keep a type-specific list, I would think seriously about option 2. EDIT: fleshing out my suggested options above: Option 1: **Return a new list**. Pros: Simple, straightforward, you get a typed list out and it eliminates a thread-safety problem (doesn't expose an internal reference to the world). Cons: seemingly a performance cost. ``` // Original code starts here. public interface DogKennel { public List<Dog> getDogs(); } public class GreyHoundKennel implements DogKennel { protected List<GreyHound> greyHounds; public List<GreyHound> getGreyHounds() { return this.greyHounds; } // Original code ends here public List<Dog> getDogs() { // This line eliminates the thread safety issue in returning // an internal reference. It does use additional memory + cost // CPU time required to copy the elements. Unless this list is // very large, it will be hard to notice this cost. return new ArrayList<Dog>(this.greyHounds); } } ``` Option 2: **Use a different data representation**. Pros: plays nicer with polymorphism, returns the generic list that was the original goal. Cons: it's a slightly different architecture which may not fit with the original task. ``` public abstract class DogKennel { protected List<Dog> dogs = new ArrayList<Dog>(); } public class GreyHoundKennel extends DogKennel { // Force an interface that only allows what I want to allow public void addDog(GreyHound greyHound) { dogs.add(greyHound); } public List<Dog> getDogs() { // Greatly reduces risk of side-effecting and thread safety issues // Plus, you get the generic list that you were hoping for return Collections.unmodifiableList(this.dogs); } } ```
You are saying that the method returns a "`List` of some unknown type" (which you can't add to, because you can't guarantee that the thing you are adding is a subtype of that type). You actually want to say, a "`List` of whatever type you want", so you have to make the method generic: ``` protected <T> List<T> getOuterList() { // blah blah } ``` Okay, I just looked at your update: It all depends on what you intend to be able to do with the result of `getDogs()`. If you do not intend to be able to add any items to the list, then `getDogs()` should return type `List<? extends Dog>`, and then the problem would be solved. If you intend to be able to add things to it, and by the type `List<Dog>` it means that you can add any kind of `Dog` to it, then logically this list cannot be the same list as `greyHounds`, because `greyHounds` has type `List<GreyHound>` and so `Dog` objects should not go in it. Which means that you must create a new list. Keeping in mind of course that any changes to the new list would not be reflected in the original list `greyHouds`.
simple generic list in java
[ "", "java", "generics", "" ]
I am new in the website scalability realm. Can you suggest to me some the techniques for making a website scalable to a large number of users?
If you expect your site to scale beyond the capabilities of a single server you will need to plan carefully. Design so the following will be possible:- * Make it so your database can be on a separate server. This isn't normally too hard. * Ensure all your static content can be moved to a CDN, as this will normally pull a lot of load off your servers. * Be prepared to spend a lot of money on hardware. More RAM and faster disks help a LOT. * It gets a lot harder when you need to split either the database or the php from a single server to multiple servers, so optimise everything, from your code, your database schema, your server config and anything else you can think of to put this final step off for as long as possible. Other than that, all you can do is stress test your site, figure out where the bottlenecks are and try and design them away.
1. Test your website under heavy load. 2. Monitor all statistics 3. Find bottleneck 4. Fix bottleneck 5. Go back to 1 good luck
Techniques for writing a scalable website
[ "", "php", "mysql", "scalability", "" ]
**EDIT** Thanks for the prompt responses. Please see what the real question is. I have made it bold this time. I do understand the difference between == and .equals. So, that's not my question (I actually added some context for that) --- I'm performing the validation below for empty strings: ``` if( "" == value ) { // is empty string } ``` In the **past** when fetching values from the db or deserializing objects from another node, this test **failed**, because the two string instances were indeed different object references, albeit they contained the same data. So the fix for those situations was ``` if( "".equals( value ) ) { // which returns true for all the empty strings } ``` I'm fine with that. That's clearly understood. Today this happened once again, but it puzzled me because this time the application is a very small **standalone application** that doesn't use **network at all**, so no new string is fetched from the database nor deserizalized from another node. So the question is: # Under which **OTHER** circumstances: ``` "" == value // yields false ``` and ``` "".equals( value ) // yields true ``` For a local standalone application? I'm pretty sure **new String()** is not being used in the code. And the only way a string reference could be "" is because it is being assigned "" directly in the code (or that's what I thought) like in: ``` String a = ""; String b = a; assert "" == b ; // this is true ``` Somehow (after reading the code more I have a clue) two different empty string object references were created, I would like to know **how** More in the line of jjnguys answer: Byte! **EDIT: Conclusion** I've found the reason. After jjnguy suggestion I was able to look with different eyes to the code. The guilty method: StringBuilder.toString() > *A new String object is allocated and initialized to contain the character sequence currently represented by this object.* Doh!... ``` StringBuilder b = new StringBuilder("h"); b.deleteCharAt( 0 ); System.out.println( "" == b.toString() ); // prints false ``` Mystery solved. The code uses StringBuilder to deal with an ever growing string. It turns out that at some point somebody did: ``` public void someAction( String string ) { if( "" == string ) { return; } deleteBankAccount( string ); } ``` and use ``` someAction( myBuilder.toString() ); // bug introduced. ``` p.s. Have I read too much CodingHorror lately? Or why do I feel the need to add some funny animal pictures here?
``` String s = ""; String s2 = someUserInputVariale.toLowercase(); // where the user entered in "" ``` Something like that would cause `s == s2` to evaluate to false. Lots of code sill create new `Strings` without exposing the call to `new String()`.
``` "" == value // yields false ``` and ``` "".equals( value ) // yields true ``` any time the value of the variable `value` has not been interned. This will be the case if the value is computed at run time. See the [JLS section 3.10.5 String Literals](http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#101084) for example code illustrating this: > Thus, the test program consisting of the compilation unit (§7.3): > > ``` > package testPackage; > class Test { > public static void main(String[] args) { > String hello = "Hello", lo = "lo"; > System.out.print((hello == "Hello") + " "); > System.out.print((Other.hello == hello) + " "); > System.out.print((other.Other.hello == hello) + " "); > System.out.print((hello == ("Hel"+"lo")) + " "); > System.out.print((hello == ("Hel"+lo)) + " "); > System.out.println(hello == ("Hel"+lo).intern()); > } > } > class Other { static String hello = "Hello"; } > ``` > > and the compilation unit: > > ``` > package other; > public class Other { static String hello = "Hello"; } > ``` > > produces the output: > > ``` > true true true true false true > ``` > > This example illustrates six points: > > * Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1). > * Literal strings within different classes in the same package represent references to the same String object. > * Literal strings within different classes in different packages likewise represent references to the same String object. > * Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals. > * Strings computed at run time are newly created and therefore distinct. > * The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.
When "" == s is false but "".equals( s ) is true
[ "", "java", "comparison", "equals", "equality", "" ]
I have lots of directories with text files written using (g)vim, and I have written a handful of utilities that I find useful in Python. I start off the utilities with a pound-bang-/usr/bin/env python line in order to use the Python that is installed under cygwin. I would like to type commands like this: %cd ~/SomeBook %which pythonUtil /usr/local/bin/pythonUtil %pythonUtil ./infile.txt ./outfile.txt (or % pythonUtil someRelPath/infile.txt somePossiblyDifferentRelPath/outfile.txt) pythonUtil: Found infile.txt; Writing outfile.txt; Done (or some such, if anything) However, my pythonUtil programs keep telling me that they can't find infile.txt. If I copy the utility into the current working directory, all is well, but then I have copies of my utilities littering the landscape. What should I be doing? Yet Another Edit: To summarize --- what I wanted was os.path.abspath('filename'). That returns the absolute pathname as a string, and then all ambiguity has been removed. BUT: IF the Python being used is the one installed under cygwin, THEN the absolute pathname will be a CYGWIN-relative pathname, like /home/someUser/someDir/someFile.txt. HOWEVER, IF the Python has been installed under Windows (and is here being called from a cygwin terminal commandline), THEN the absolute pathname will be the complete Windows path, from 'drive' on down, like D:\cygwin\home\someUser\someDir\someFile.txt. Moral: Don't expect the cygwin Python to generate a Windows-complete absolute pathname for a file not rooted at /; it's beyond its event horizon. However, you can reach out to any file on a WinXP system with the cygwin-python if you specify the file's path using the "/cygdrive/driveLetter" leadin convention. Remark: Don't use '\'s for separators in the WinXP path on the cygwin commandline; use '/'s and trust the snake. No idea why, but some separators may be dropped and the path may be modified to include extra levels, such as "Documents and Settings\someUser" and other Windows nonsense. Thanks to the responders for shoving me in the right direction.
Look at os.getcwd: * <http://docs.python.org/library/os.html#os-file-dir> Edit: For relative paths, please take a look at the os.path module: * <http://docs.python.org/library/os.path.html> in particular, os.path.join and os.path.normpath. For instance: ``` import os print os.path.normpath(os.path.join(os.getcwd(), '../AnotherBook/Chap2.txt')) ```
What happens when you type "ls"? Do you see "infile.txt" listed there?
How do I tell a Python script (cygwin) to work in current (or relative) directories?
[ "", "python", "filesystems", "cygwin", "path", "utilities", "" ]
I'm writing a screen capture module using the Robot class. I'm taking screenshots of the application every x milliseconds and writing them to disk. After screen capture is finished, I'm compiling the screenshots to video with FFMPEG. However, writing images to disk is extremely slow and grinds my application to a halt. What am I missing? Is there a better way to write a simple screen capture module? Edit: I've tried several ways of writing the images to disk, and all are very slow. I've been sticking with the following, due to its ease of use: ``` ImageIO.write(bufferedImage ,"jpg", file); ```
Or encode the image into video format right when you capture the image, and avoid writing the large temporary file at all. Full code using Xuggler can be found here: [Xuggler Screen Capture Demo Code](http://wiki.xuggle.com/MediaTool_Introduction#How_To_Take_Snapshots_Of_Your_Desktop)
Try putting your write into a new thread so you do not have to wait for slow disk IO. ``` ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10); executor.schedule(new Runnable(){ @Override public void run() { writeImageHere(bufferedImage, file); } } ``` Just watch out for concurrency issues. The second (memory intensive) solution is to buffer your jpgs and keep them all in memory and write only when a certain amount of time has passed or your program exits.
I'm writing a screen capture module in Java, but I'm having serious performance issues writing screenshots to disk. What else can I do?
[ "", "java", "swing", "screen-capture", "awtrobot", "" ]
This is puzzling me. I'm using Google Map's Geocoding to find locations. I am attempting to use the example [here](http://code.google.com/apis/maps/documentation/services.html#Geocoding), which is from Google, and it is just not working for me. --- ### Error: > <http://maps.gstatic.com/intl/en_us/mapfiles/159e/maps2.api/main.js> > Line 174 > var point = new GLatLng(,); --- ### Code: ``` <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key='.$config['locations.gMaps.key'].'" type="text/javascript"></script> <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key='.$config['locations.gMaps.key'].'" type="text/javascript"></script> <script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script> <style type="text/css"> @import url("http://www.google.com/uds/css/gsearch.css"); @import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css"); </style> <script type="text/javascript"> function addListener(element, baseName, handler) { if (element.addEventListener) element.addEventListener(baseName, handler, false); else if (element.attachEvent) element.attachEvent("on"+baseName,handler); } var map'.$num.'; function initialize'.$num.'() { if (GBrowserIsCompatible()) { map'.$num.' = new GMap2(document.getElementById("google_map'.$num.'"),{mapTypes:[G_HYBRID_MAP]}); var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.'); map'.$num.'.setCenter(new GLatLng('.$row->LocationLat.','.$row->LocationLon.'),4); var mapControl = new GMapTypeControl(); map'.$num.'.addControl(mapControl); map'.$num.'.addControl(new GLargeMapControl()); map'.$num.'.addControl(new GOverviewMapControl()); map'.$num.'.enableDoubleClickZoom(); map'.$num.'.enableScrollWheelZoom(); var bounds = new GLatLngBounds; var myIcon = new GIcon(); myIcon.image = "http://www.google.com/mapfiles/marker.png"; myIcon.iconAnchor = new GPoint((markerImage1.width/2),markerImage1.height); bounds.extend(point); setBounds(map'.$num.',bounds); var address = "' . $address . '"; var geocoder = new GClientGeocoder(); showAddress(address, geocoder); } } function showAddress(address, geocoder) { geocoder.getLatLng( address, function(point) { if (!point) { alert(address + " not found"); } else { map'.$num.'.setCenter(point, 13); var marker = new GMarker(point); map'.$num.'.addOverlay(marker); marker.openInfoWindowHtml(address); } } ); } function setBounds(map'.$num.',bounds) { map'.$num.'.setZoom(15); map'.$num.'.setCenter(bounds.getCenter()); } function chargement() { markerImage1 = new Image(); markerImage1.src = "http://www.google.com/mapfiles/marker.png"; setTimeout("initialize'.$num.'()", 500); } addListener(window, "load", chargement); </script> ``` My code is generated by PHP, so when there is an ' that means I'm opening or closing the string that is holding the JavaScript.
Maybe I didn't get it, but ``` var point = new GLatLng(,); ``` is not valid javascript It should be either ``` var point = new GLatLng(param1, param2); ``` or ``` var point = new GLatLng(); ``` or ``` var point = new GLatLng(null,null); ``` ... depending on what the GLatLng constructor is
This statement: ``` var point = new GLatLng(,); ``` Is not correct because there isn't a lat or lng number specified. This is because this statement: ``` var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.'); ``` Is incorrect. I'd try something like: ``` var point = new GLatLng(<?php echo $row->LocationLat . ',' . $row->LocationLon; ?>); ``` If that doesn't work, then `$row->LocationLat` or `$row->LocationLon` are possibly empty.
How can I fix this JavaScript syntax error?
[ "", "javascript", "google-maps", "geocoding", "" ]
I have elements that are under an element with opacity:0.5 that I want to be able to click on. How can I click "through" the topmost element? Here's an example that demonstrates my problem. Click on the boxes to toggle them on and off. You can edit it [on jsbin](http://jsbin.com/uhehe/edit) to try out your solution. **Bonus points if you can have the boxes toggle on hover.** ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <title>Sandbox</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <style type="text/css" media="screen"> body { background-color: #000; } .box {width: 50px; height: 50px; border: 1px solid white} .highlight {background-color: yellow;} </style> <script type="text/javascript"> var dthen = new Date(); $('<div id="past">').css({'height': (dthen.getMinutes()*60)+dthen.getSeconds() +'px' ,'position': 'absolute' ,'width': '200px' ,'top': '0px' ,'background-color': 'grey' ,'opacity': '0.5' }) .appendTo("#container"); setInterval(function(){ dNow = new Date(); $('#past').css('height', ((dNow.getSeconds()+(dNow.getMilliseconds()/1000))*50)%300 +'px'); },10) $(".box").click(function(){ $(this).toggleClass("highlight"); }); </script> </head> <body> <div id="container"> <div class="box" style="position:absolute; top: 25px; left: 25px;"></div> <div class="box" style="position:absolute; top: 50px; left: 125px;"></div> <div class="box" style="position:absolute; top: 100px; left: 25px;"></div> <div class="box" style="position:absolute; top: 125px; left: 125px;"></div> <div class="box" style="position:absolute; top: 225px; left: 25px;"></div> <div class="box" style="position:absolute; top: 185px; left: 125px;"></div> </div> </body> </html> ```
OK, so there are 2 things I think I would do: (1) a CSS3 answer, that isn't yet widely adopted, and (2) a Javascript backup-plan for the rest. (not sure what to do about users without JS on older browsers that don't support the CSS part). Read on... First: Use this CSS3 code to make the upper element 'invisible' to mouse-interaction: ``` pointer-events: none; ``` This is not yet cross-browser compatible. It only works on SVG & HTML Elements in Gecko & Webkit browsers, but only on SVG elements in Opera, and not at all in IE. Per the MDN: > The CSS property pointer-events allows > authors to control whether or when an > element may be the target of a mouse > event. This property is used to > specify under which circumstance (if > any) a mouse event should go "through" > an element and target whatever is > "underneath" that element instead. Here's that documentation: <https://developer.mozilla.org/en/css/pointer-events> Second: Use some javascript Feature Detection for those browsers that don't yet support this CSS. You'll have to roll your own, similar to [Modernizr](http://www.modernizr.com/), since it doesn't test for this yet (to my knowledge). The idea is that you create an element, apply the pointer-events CSS to it, check for it, and if the browser supports the feature, you'll get the expected result, as opposed to something null or undefined; then destroy the element. Anyway, once you have feature detection, you can use jQuery or similar to attach a listener to the uppermost element and assign a click from it to click through to something else. Check out jQuery and it's use of the click() function for more info (not enough reputation to post the link, sry). If I get time later, I might be able to work up a quick jsFiddle on it. I hope this helps.
If you topmost element is contained within the element below, you can let the event "bubble through". If it is not, you have to trigger the click manually. There is no way to fire the event handler just by clicking. To fire the event manually, you could do this: ``` $("#topelement").click(function() { $("#elementbelow").click(); return false; }); ``` *EDIT (response to comments):* To enumerate all boxes, you can do this (off the top of my head. no testing, could not even be syntax-error free) ``` $("#topelement").click(function(e) { $(".box").each(function() { // check if clicked point (taken from event) is inside element var mouseX = e.pageX; var mouseY = e.pageY; var offset = $(this).offset; var width = $(this).width(); var height = $(this).height(); if (mouseX > offset.left && mouseX < offset.left+width && mouseY > offset.top && mouseY < offset.top+height) $(this).click(); // force click event }); }); ```
registering clicks on an element that is under another element
[ "", "javascript", "jquery", "" ]
I am using XNA to build a project where I can draw "graffiti" on my wall using an LCD projector and a monochrome camera that is filtered to see only hand held laser dot pointers. I want to use any number of laser pointers -- don't really care about differentiating them at this point. The wall is 10' x 10', and the camera is only 640x480 so I'm attempting to use sub-pixel measurement using a spline curve as outlined here: [tpub.com](http://www.tpub.com/content/nasa1995/NASA-95-tm110221/NASA-95-tm1102210006.htm) The camera runs at 120fps (8-bit), so my question to you all is the fastest way to to find that subpixel laser dot center. Currently I'm using a brute force 2D search to find the brightest pixel on the image (0 - 254) before doing the spline interpolation. That method is not very fast and each frame takes longer to computer than they are coming in. Edit: To clarify, in the end my camera data is represented by a 2D array of bytes indicating pixel brightness. What I'd like to do is use an XNA shader to crunch the image for me. Is that practical? From what I understand, there really isn't a way to keep persistent variables in a Pixel Shader such as running totals, averages, etc. But for arguments sake, let's say I found the brightest pixels using brute force, then stored them and their neighboring pixels for the spline curve into X number of vertices using texcoords. Is is practical then to use HLSL to compute a spline curve using texcoords? I am also open to suggestions outside of my XNA box, be it DX10/DX11, maybe some sort of FPGA, etc. I just don't really have much experience with ways of crunching data in this way. I figure if they can do something like this on a Wii-Mote using 2 AA batteries than I'm probably going about this the wrong way. Any ideas?
You're dealing with some pretty complex maths if you want sub-pixel accuracy. I think [this paper](http://pubs.acs.org/doi/abs/10.1021/la900393v) is something to consider. Unfortunately, you'll have to pay to see it using that site. If you've got access to a suitable library, they may be able to get hold of it for you. The link in the original post suggested doing 1000 spline calculations for each axis - it treated x and y independantly, which is OK for circular images but is a bit off if the image is a skewed ellipse. You could use the following to get a reasonable estimate: xc = sum (xn.f(xn)) / sum (f(xn)) where xc is the mean, xn is the a point along the x-axis and f(xn) is the value at the point xn. So for this: ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * ------------------ 2 3 4 5 6 7 ``` gives: sum (xn.f(xn)) = 1 \* 2 + 3 \* 3 + 4 \* 9 + 5 \* 10 + 6 \* 4 + 7 \* 1 sum (f(xn)) = 1 + 3 + 9 + 10 + 4 + 1 xc = 128 / 28 = 4.57 and repeat for the y-axis.
If by Brute-forcing you mean looking at every pixel independently, it is basically the only way of doing it. You will have to scan through all the images pixels, no matter what you want to do with the image. Althought you might not need to find the brightest pixels, you can filter the image by color (ex.: if your using a red laser). This is easily done using a HSV color coded image. If you are looking for some faster algorithms, try OpenCV. It's been optimized again and again for image treatment, and you can use it in C# via a wrapper: [<http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx][1]> OpenCV can also help you easily find the point centers and track each points. Is there a reason you are using a 120fps camera? you know the human eye can only see about 30fps right? I'm guessing it's to follow very fast laser movements... You might want to consider bringning it down, because real-time processing of 120fps will be very hard to acheive.
Fast sub-pixel laser dot detection
[ "", "c#", "visual-studio-2008", "xna", "" ]
I have a brand new database on an ISP which I intend to use to build an ASP.NET data-driven website. However, I would like to build the whole thing locally and transplant the database to the ISP. I have TCP/IP access (i.e. I can connect to the remote database directly thru SQL Server Management Studio Express), but I do not have Terminal Services access, as this is a database shared with other users of the ISP. Is there a simple way to "replicate" my local development database to the remote server?
One way is to use something like the [Database Publishing Wizard](http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en) to create an SQL script, and then run that script in SQL Server Management studio in the remote database. Apparently [this is integrated in Visual Studio 2008](http://thetrainerph.spaces.live.com/blog/cns!9F717AF2A2401F0F!1143.entry) (didn't know that before).
I just had a similar problem. I downloaded and used the SQL Server Pulishing Wizard. Can be found [here.](http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en) You end up with a single script file that you apply to your database and it creates everything including the data.
How do I "Install" a SQL Server Database to a Remote Server Without Physical Access?
[ "", "c#", "asp.net", "sql-server", "replication", "" ]
I left the .net about 3 years back when I was working on .net 2.0. And in these three years I wasn't working on .net at all. Now, I have got a project which is in .net 3.5. But I have noticed there are a lot of technologies introduced between these two versions. Is there any resource which can help me to quickly grasp the things which are introduced after .net 2.0 It may help that my major work is in asp.net with C#
For a quick overview ... **What's New in .NET Framework 3.5** ([taken from here](http://sunnytalkstech.blogspot.com/2007/09/whats-new-in-net-framework-35.html)) > **CLR Enhancements**: Although the CLR uses the same model as 2.0, you can [read here](http://www.hanselman.com/blog/ChangesInTheNETBCLBetween20And35.aspx) about the improvements/changes to the assemblies. > > **Compiler Enhancements**: New VB.NET 9.0 compiler and support for changes to C# 3.0 like expression trees, lambda methods, extension methods, static reference for anonymous types etc. > > **LINQ**: Probably the most revolutionary change in the 3.5 framework. LINQ to XML, LINQ to SQL, LINQ to Objects and LINQ to Datasets. Along with functional programming, LINQ is an [outlook change](http://blogs.msdn.com/charlie/archive/2007/01/26/anders-hejlsberg-on-linq-and-functional-programming.aspx) to programming in C#. > > **Performance Improvements**: Quite a few performance improvements have been made in 3.5. ADO.NET gets paging support as well as synchronization from caches at local and server datastores. Also performance improvements for multicore CPUs. > > **Networking changes**: Peer-to-peer networking stack, including a managed PNRP resolver. > > **Windows Information APIs**: New wrappers for WMI and Active Directory Services. WMI 2.0 gets a managed provider. > > **ASP.NET**: New implementation of Client Application Services as well as [3 new ASP.NET controls](http://www.west-wind.com/WebLog/posts/127340.aspx). Also AJAX programming for ASP.NET is easier and better performing. > > **Windows Communication Foundation**: WCF now works with POX and JSON data. > > **Windows Presentation Foundation**: Newer plugin model for creating AddIns. SilverLight CLR is also part of the .Net Framework. > > **Misc**: The C/C++ get a standard template libarary (STL) so that these languages can use share .NET libraries for some extra reading ... * [What's New in the .NET Framework Version 3.5 SP1](http://msdn.microsoft.com/en-us/library/cc713697.aspx) * [What's New in the .NET Framework Version 3.5](http://msdn.microsoft.com/en-us/library/bb332048.aspx) * [What's New in the .NET Framework Version 3.0](http://msdn.microsoft.com/en-us/library/bb822048.aspx) * [What's New in the .NET Framework Version 2.0](http://msdn.microsoft.com/en-us/library/t357fb32.aspx) * [What's New in the .NET Framework Version 1.1](http://msdn.microsoft.com/en-us/library/9wtde3k4.aspx) * [Version Compatibility](http://msdn.microsoft.com/en-us/library/47a587hk.aspx) * [What's New in the .NET Compact Framework Version 3.5](http://msdn.microsoft.com/en-us/library/bb397835.aspx) * [What's New in ASP.NET and Web Development](http://msdn.microsoft.com/en-us/library/s57a598e.aspx) * [What's New in Visual C#](http://msdn.microsoft.com/en-us/library/bb383815.aspx) * [What's New in Visual C++ 2008](http://msdn.microsoft.com/en-us/library/bb384632.aspx) * [What's New in the Visual Basic Language](http://msdn.microsoft.com/en-us/library/y17w47af.aspx) * [What's New in Windows Presentation Foundation Version 3.5](http://msdn.microsoft.com/en-us/library/bb613588.aspx) * [What's New in Visual Studio 2008](http://msdn.microsoft.com/en-us/library/bb386063.aspx)
[What's new in the .NET Framework 3.5](http://msdn.microsoft.com/en-us/library/bb332048.aspx)
How and where to learn the changes in .net from .net 2.0 to .net 3.5?
[ "", "c#", ".net", "asp.net", ".net-3.5", ".net-2.0", "" ]
I'd like to have a good up-to-date reference for boost by my side, and the only books I found are the following: * [Beyond the C++ Standard Library: An Introduction to Boost](https://rads.stackoverflow.com/amzn/click/com/0321133544) * [The C++ Standard Library Extensions: A Tutorial and Reference](https://rads.stackoverflow.com/amzn/click/com/0321412990) Both books are somewhat dated, and I am sure boost has been evolving. Obviously I can just use a direct source of [Boost website](http://www.boost.org/). Is it enough to just use the website to learn and reference boost libraries? What If I am one of those folks who prefers hardcover books? Which one would you recommend? Thanks **--Edit--** *Does anyone know of online video tutorials on Boost, as well as text turials?*
Try this one out: <http://man.leftworld.net/develop/asio/reference/index.html> <http://alexott.blogspot.com/search/label/boost> <http://www.boost.org/doc/> <http://torjo.com/tobias/> <http://docs.huihoo.com/boost/1-33-1/libs/multi_index/doc/reference/index.html>
First, here's the *possible* [answer](http://archives.free.net.ph/message/20100215.055550.f10100b9.en.html) to your topic. I say possible because the book has not been released yet. I will have to say, though, I'm very excited about this book since it's super new. Like you, when trying to learn something, I just like reading books or watch videos. When doing development, however, I like to use the internet as I can quickly search. **My 2 cents (read if you want):** I've had experience using both Boost and Qt, and frankly speaking, I find Boost documentation to be sorely lacking, not to mention hard to use. Another major gripe about Boost that I have is that my project compiles *quite* a bit slower. Maybe it is just me, but I found Qt much more intuitive to use. I *really* wish that Boost documentation is like [Qt Assistant](http://doc.trolltech.com/4.6/). If you have never checked out the Qt documentation, you should. Actually now that I've used both, I learned one **very** important lesson: when using a third-party library, don't decide to use it simply because it's powerful, but also because it's simple to use **and** has a very clear documentation + easy-to-understand examples. I would be interested to see what people think.
where can I find a good boost reference?
[ "", "c++", "boost", "" ]
The Google Toolbar's autofill feature has been the bane of my web development existance for the past several years. I have always settled on trying to create a timer control to check for changes since the developers epically failed to fire change events on controls. This has gotten further and further complicated when controls are buried inside nested repeaters, and then trying to tie it to an UpdatePanel is a further complication. Has anyone succesfully been able to prevent Google Toolbar from filling in form fields without renaming the field to something insignifcant? (note: This doesn't work for a 'State' dropdown, it even goes as far as to check field values). For as smart as Google employees are supposed to be, this was a grandly moronic oversight. **Update:** For those who may be coming here looking for a solution. What I have found to work so far is you have ASP.net, is to use the server control "Timer" and to set this control as a trigger for the UpdatePanel. It helps to loop through and check for changed values. If you only have access to javascript, or are using another framework, then I found using the following function to work the best (I was trying to monitor state and zip changes. The focusElement is required because when hovering in a dropdownlist, it changes the selectedindex): ``` function MonitorChanges(sStateDropdownID, sZipCodeID, sHiddenStateFieldId, sHiddenZipFieldId, bDoPostback) { var state = $('#' + sStateDropdownID).val(); var zip = $('#' + sZipCodeID).val(); var hiddenstate = $('#' + sHiddenStateFieldId).val(); var hiddenzip = $('#' + sHiddenZipFieldId).val(); $('#' + sHiddenStateFieldId).val(state); $('#' + sHiddenZipFieldId).val(zip); var compareString = state + zip; var compareHiddenString = hiddenstate + hiddenzip; var focusElement = getElementWithFocus(); if (compareString != compareHiddenString && isShippingZip(zip)) { bDoPostback = true } if (parseInt(focusElement.id.search('drpState')) == -1 && parseInt(focusElement.id.search('txtZip')) == -1 && bDoPostback) { bDoPostback = false; __doPostBack(sStateDropdownID, ''); } var f = function() { MonitorChanges(sStateDropdownID, sZipCodeID, sHiddenStateFieldId, sHiddenZipFieldId, bDoPostback); } setTimeout(f, 1000); } ```
According to a [recent post](http://www.google.com/support/forum/p/Toolbar/thread?tid=7dcddc95f43dac19&hl=en) by a Google developer, using the `autocomplete="off"` attribute will disable Google toolbar auto-completion in both IE and Firefox. Note that this attribute must be applied to the `<form>` tag and not the individual `<input>` tags: ``` <form method="post" action="http://example.com" autocomplete="off"> <!-- ... --> </form> ``` While this is not an instant fix, it is probably the most reliable solution possible - if it is possible to wait until the next iteration of the Google toolbar.
I once have a problem with autofill in firefox. I did this to prevent it. ``` <div style="display:none"> <input type="text" name="user" /> <input type="password" name="password" /> </div> <input type="text" name="user" /> <input type="password" name="password" /> ``` Don't know if it also work with google autofill.
Disable Google Toolbar Autofill
[ "", "asp.net", "javascript", "html", "css", "" ]
Let's say I have a variable t that's set to this: ``` datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>) ``` If I say `str(t)`, i get: ``` '2009-07-10 18:44:59.193982+00:00' ``` How can I get a similar string, except printed in the local timezone rather than UTC?
Think your should look around: datetime.astimezone() **<http://docs.python.org/library/datetime.html#datetime.datetime.astimezone>** Also see pytz module - it's quite easy to use -- as example: ``` eastern = timezone('US/Eastern') ``` **<http://pytz.sourceforge.net/>** Example: ``` from datetime import datetime import pytz from tzlocal import get_localzone # $ pip install tzlocal utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc) print(utc_dt.astimezone(get_localzone())) # print local time # -> 2009-07-10 14:44:59.193982-04:00 ```
As of python 3.6 calling `astimezone()` without a timezone object defaults to the local zone ([docs](https://docs.python.org/3.6/library/datetime.html#datetime.datetime.astimezone)). This means you don't need to import `tzlocal` and can simply do the following: ``` #!/usr/bin/env python3 from datetime import datetime, timezone utc_dt = datetime.now(timezone.utc) print("Local time {}".format(utc_dt.astimezone().isoformat())) ``` This script demonstrates a few other ways to show the local timezone using `astimezone()`: ``` #!/usr/bin/env python3 import pytz from datetime import datetime, timezone from tzlocal import get_localzone utc_dt = datetime.now(timezone.utc) PST = pytz.timezone("US/Pacific") EST = pytz.timezone("US/Eastern") JST = pytz.timezone("Asia/Tokyo") NZST = pytz.timezone("Pacific/Auckland") print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat())) print("Eastern time {}".format(utc_dt.astimezone(EST).isoformat())) print("UTC time {}".format(utc_dt.isoformat())) print("Japan time {}".format(utc_dt.astimezone(JST).isoformat())) # Use astimezone() without an argument print("Local time {}".format(utc_dt.astimezone().isoformat())) # Use tzlocal get_localzone print("Local time {}".format(utc_dt.astimezone(get_localzone()).isoformat())) # Explicitly create a pytz timezone object # Substitute a pytz.timezone object for your timezone print("Local time {}".format(utc_dt.astimezone(NZST).isoformat())) ``` It outputs the following: ``` $ ./timezones.py Pacific time 2019-02-22T17:54:14.957299-08:00 Eastern time 2019-02-22T20:54:14.957299-05:00 UTC time 2019-02-23T01:54:14.957299+00:00 Japan time 2019-02-23T10:54:14.957299+09:00 Local time 2019-02-23T14:54:14.957299+13:00 Local time 2019-02-23T14:54:14.957299+13:00 Local time 2019-02-23T14:54:14.957299+13:00 ```
How do I print a datetime in the local timezone?
[ "", "python", "timezone", "" ]
I wrote some Groovy code, and I'd like to integrate it with the existing Java code. We'd like to be able to keep our ant scripts, and only add the needed Groovy functionality. Will Gant allow us to keep our existing scripts?
According to the Gant site, no: [Gant is a tool for scripting Ant tasks using Groovy instead of XML to specify the logic. A Gant specification is a Groovy script ...](http://gant.codehaus.org/) A Gant build script uses Groovy script, not XML, but it uses the Ant tasks. Therefore if you have any custom Ant tasks you will still be able to use those.
Perhaps you could give more detail about what you want to do. You can call normal Ant scripts from Gant and vice-versa. You can also use the groovy ant task to run arbitrary Groovy in your normal (or Gant-flavored) ant builds.
Is Gant 100% Ant compatible?
[ "", "java", "ant", "groovy", "gant", "" ]
Using C#, how can I determine which program is registered as the default email client? I don't need to launch the app, I just want to know what it is.
Use the Registry class to search the registry. This console app demonstrates the principle. ``` using System; using Microsoft.Win32; namespace RegistryTestApp { class Program { static void Main(string[] args) { object mailClient = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail", "", "none"); Console.WriteLine(mailClient.ToString()); } } } ```
You can look in the registry on the following key: ``` HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail ```
Find default email client
[ "", "c#", ".net", "email", "email-client", "" ]
Can someone please help me, I have this xml snippet ``` <?xml version="1.0" encoding="utf-8" ?> <EmailConfiguration> <DataBoxID>123</DataBoxID> <DefaultSendToAddressCollection> <EmailAddress>email@whereEver.com</EmailAddress> </DefaultSendToAddressCollection> </EmailConfiguration> ``` I want to create a corressponding c# class from this. Before you say - "Just use xsd.exe", the output from Xsd cannot be serialized and deserialized correct, because it generates the class using partial classes. Please can you tell me how to create this class.... here is the approach I took, but it doesn't work. ``` public class EmailConfiguration { private string dataBoxID; public string DataBoxID { get { return dataBoxID; } set { dataBoxID = value; } } private DefaultSendToAddressCollectionClass defaultSendToAddressCollection; public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection { get { return defaultSendToAddressCollection; } set { defaultSendToAddressCollection = value; } } } ``` And here is the class declaration for the subclass ``` public class DefaultSendToAddressCollectionClass { private string[] emailAddress; public string[] EmailAddress { get { return emailAddress; } set { emailAddress = value; } } } ```
Bare minimum working... looks like you are only required to add one attribute. ``` public class EmailConfiguration { public string DataBoxID { get; set; } public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection { get; set; } } public class DefaultSendToAddressCollectionClass { [XmlElement] public string[] EmailAddress { get; set; } } ```
Did you use VS2008's XSD? Here's the output I got: ``` c:>xsd email.xml Writing file 'c:\email.xsd' c:>xsd email.xsd /c /edb Writing file 'c:\email.cs' ``` Generates serializable output: ``` [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public partial class EmailConfiguration : object, System.ComponentModel.INotifyPropertyChanged { private string dataBoxIDField; private EmailConfigurationDefaultSendToAddressCollection[] defaultSendToAddressCollectionField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string DataBoxID { get { return this.dataBoxIDField; } set { this.dataBoxIDField = value; this.RaisePropertyChanged("DataBoxID"); } } ```
XML to C# Class Question
[ "", "c#", "xml", "class", "" ]
What's the best and most efficient book to learn JavaScript?
I think I've read them all. Here's the dark sheep. This one came out of left field. I was surprised at how good it is. [JavaScript: The Missing Manual](https://rads.stackoverflow.com/amzn/click/com/0596515898) [alt text http://ecx.images-amazon.com/images/I/51cPJ2k%2BOGL.\_BO2,204,203,200\_PIsitb-sticker-arrow-click,TopRight,35,-76\_AA240\_SH20\_OU01\_.jpg](http://ecx.images-amazon.com/images/I/51cPJ2k%2BOGL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg) The other books are great. But for actually *learning* the language, I think this one wins hands down.
Take a look at [JavaScript: The Definitive Guide](http://shop.oreilly.com/product/9780596805531.do). Also take a look at [David Flanagan's web site](http://www.davidflanagan.com/) as well as [Douglas Crockford's videos](https://www.youtube.com/playlist?list=PL7664379246A246CB) and [his essays on JavaScript](http://www.crockford.com/javascript/).
What's the best and most efficient book to learn JavaScript?
[ "", "javascript", "" ]
As a company specialized in developing custom CMS, we have been asked to deploy a open source CMS in our next project. We are free to choose a system. What would you recommend for a team familiar with MVC model and OOP in PHP5? I was told that Drupal and TYPO3 are very hard at the beginning, so what are the other options? eZ Publish or Joomla maybe?
If the people on your team are familiar with PHP then Drupal should not be difficult at all for them. There are a few conventions that Drupal follows for creating hooks which are unique to it but are implemented consistently in core so once they are learned your team will be able to write module code that can control pretty much any aspect of how the site works. The main reason for Drupal's reputation of being hard to learn is the large number of options in the administration screen, but if someone is serious about creating and maintaining a proper site this shouldn't be enough to turn them off of Drupal.
If you're looking for an enterprise-class CMS I would not even mention joomla. I see that you're not aware of [Silverstripe](http://www.silverstripe.org). I recommend to check it out!
What enterprise-class open source CMS has the steepest (easiest) learning curve for a programmers team?
[ "", "php", "drupal", "content-management-system", "joomla", "typo3", "" ]
I am drawing a graph on a `<canvas>` that requires expensive calculations. I would like to create an animation (when moving the mouse across the canvas) where the graph is unchanging, but some other objects are drawn over it. Because the canvas will have to be redrawn a lot, I don't want to perform the calculations to render the graph for every frame. How can I draw the graph once, save it, and then use the saved rendering to redraw subsequent frames of the animation, so that the expensive calculations only have to happen once & all I have to redraw is the much simpler animation layer? I tried drawing the graph on a second canvas & then using `ctx.drawImage()` to render it onto the main canvas, but drawing on the canvas doesn't seem to work unless it's in the dom & not `display:none;`. Do I have to do something hacky like position the temp canvas out of view, or is there a cleaner way to do this?
You need to use at least 2 canvases : one with the complex drawing, and the second, on top of the first (with the same size, positioned in absolute), with the animated shapes. This method will work on IE, and getImageData doesn't work with ExCanvas. Every library which does complex drawings on canvases use this method (Flot and others). ``` <div style="width: 600px; height: 300px; position: relative;" id="container"> <canvas class="canvas" style="position: absolute; left: 0px; top: 0px;" width="600" height="300"/> <canvas class="overlay" style="position: absolute; left: 0px; top: 0px;" width="600" height="300"/> </div> ```
How about drawing your graph the first time on your canvas and then ``` var imdata = ctx.getImageData(0,0,width,height); ``` and then ``` ctx.putImageData( imdata, 0,0); ``` for the rest of the rendering.
Save <canvas> contents to be redrawn in later animation frames?
[ "", "javascript", "html", "canvas", "" ]
Here at my company we have three Hudson CI servers with 100+ jobs configured. We are looking for an automated way to **periodically** backup job configurations and build history. Currently we have an ant script that we configure as a job but it's not easy to maintain and not elegant. Have any of you found a way to manage this?
There is a [Backup Plugin](http://wiki.hudson-ci.org/display/HUDSON/Backup+Plugin). I don't believe that it supports scheduling of periodic backups, but you might be able to trigger it by accessing it through the URL (like some other Hudson remote APIs), in which case you might be able to simply set up a cron job to ping the URL.
My Hudson servers run on windows, so I use Robocopy for this. I have it mirror all files in each build server's hudson home, excluding job workspace directories. Since the backups are going to a central place, I have a scheduled task on a fileserver that runs my script nightly, and the Hudson servers are unaware of the process. The script has one entry per hudson machine: robocopy path-to-buildserver-hudson-home backup-folder-path\buildserver-name /ZB /E /NP /R:1 /W:5 "/LOG:%~dp0backup\_log.txt" /TEE /XD workspace Note: after the first machine, it becomes /LOG+: instead of /LOG: so that the next ones append to the log. This mirrors without deleting files that don't exist in source, so even if Hudson is setup to delete build results after X months or Y builds, the backups could still have the full history...as well as logs to console and a file, and is resumable if it gets interrupted. It's handy. If you didn't want it to retain files Hudson has deleted, you could use /MIR instead of /E. I'm sure similar tools for robust copies or mirroring exist on other platforms. Ant is probably sufficient if done right.
Is there (an automated) way to backup Hudson CI files?
[ "", "java", "continuous-integration", "backup", "hudson", "" ]
I like the generics-feature in java and use it often. But I have a problem, if I use libraries that aren't yet aware of generics. An example are servlets. If you use `ServletRequest.getParameterMap()` the result will be a raw map, but it includes only `String` as keys and `String[]` as values. So I want to assign it to a `Map<String, String[]>`. But for this assignment I get an warning. How can I avoid this warning with the language, not by simply suppressing the warning with the `@SuppressWarnings` annotation.
As others have said the warnings cannot be avoided except by suppressing them. The issue IMHO is that either you have to litter your code with annotations that apply to small scope or ignore them globally and risk errors. IIRC there is a proposal to generate warnings where the raw types are being returned instead of at the call. Meanwhile, I think the best approach is to use a wrapper method so that the warnings are limited to a single place, where it is safe to ignore them: ``` class NoWarn { public static Map<String, String[]> getParameterMap(ServletRequest r) { @SuppressWarnings("unchecked") Map<String, String[]> result = r.getParameterMap(); return result; } } ``` **Note** This answer was edited with a comment that annotations cannot be inside method bodies. That is incorrect, the above is syntactically correct. I have reverted the change.
The cleanest thing you can do is to encapsulate the conversion from legacy to generic code and suppress the warning only there. E.g. you could put a generic facade on your legacy library, though this might not always be worthwhile.
How to avoid unchecked-conversion-warning in Java, if you use legacy libraries?
[ "", "java", "generics", "warnings", "" ]
Im my DDD Aplication I have a lot of Domain Objects like date: ``` class User() { public String Name{get;set;} } ``` The persistence of then already done! Now im going to Client Side (SilverLight). My problem is: how i work with a User object on Client Side. Example: ``` // only a example User user = Service.Login("crazyjoe","1234"); ``` The User object do not exist on Client Side. Question: Have a *clean* and fast way to pass my User object to SilverLight?? Obs: clean = dont put anything on my User class. -
This website should give you the information you need: [Silverlight 2 - Webservices Part II - User defined type](http://www.c-sharpcorner.com/UploadFile/ReefDweller/Silverlight2WebServicePartII05132009112035AM/Silverlight2WebServicePartII.aspx?ArticleID=ee52a112-1d43-4577-8573-86c3352d8068)
I would use WCF to push the data to the silverlight client.
How to return Domain objects from a WebService to my SilverLight Application
[ "", "c#", "silverlight", "web-services", "" ]
In C++ a statement like this is valid: ``` &Variable; ``` IMO it doesn't make any sense, so my question is, if you do this, will it affect the compiled result in any way, or will the compiler optimize it away? Thanks!
It's worth remembering that operator&() might be overloaded for the variable type, have some side effects and optimizing away such statement would change program behaviour. One example is a smart pointer used for controlling the non-C++ objects - [\_com\_ptr\_t](http://msdn.microsoft.com/en-us/library/417w8b3b(VS.80).aspx). It has an overloaded \_com\_ptr\_t::operator&() which checks whether the pointer inside already stores some non-null address. If it turns out that the stored address is non-null it means that the pointer is already attached to some object. If that happens the \_com\_ptr\_t::operator&() disconnects the object - calls IUnknown::Release() and sets the pointer to null. The side effect here is necessary because the typical usage is this: ``` _com_ptr_t<Interface> pointer; // some other code could be here CoCreateInstance( ..., &pointer, ...);// many irrelevant parameters here ``` [CoCreateInstance()](http://msdn.microsoft.com/en-us/library/ms686615(VS.85).aspx) or other object retrieval code has no idea about C++ and \_com\_ptr\_t so it simply overwrites the address passed into it. That's why the \_com\_ptr\_t::operator&() must first release the object the pointer is attached to if any. So for \_com\_ptr\_t this statement: ``` &variable; ``` will have the same effect as ``` variable = 0; ``` and optimizing it away would change program behaviour.
Consider this snippet: ``` #include <iostream> class A { public: A* operator &() { std::cout << "aaa" << std::endl; return this; } }; int main() { A a; &a; return 0; }; ``` In this case, `"&a;"` **will** generate code.
C++ : Will compiler optimize &Variable; away?
[ "", "c++", "optimization", "compiler-construction", "reference", "" ]
I've set the itemsource of my WPF Datagrid to a List of Objects returned from my DAL. I've also added an extra column which contains a button, the xaml is below. ``` <toolkit:DataGridTemplateColumn MinWidth="100" Header="View"> <toolkit:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Click="Button_Click">View Details</Button> </DataTemplate> </toolkit:DataGridTemplateColumn.CellTemplate> </toolkit:DataGridTemplateColumn> ``` This renders fine. However on the **Button\_Click** method, is there any way I can get the row on the datagrid where the button resides? More specifically, one of the properties of my objects is "Id", and I'd like to be able to pass this into the constructor of another form in the event handler. ``` private void Button_Click(object sender, RoutedEventArgs e) { //I need to know which row this button is on so I can retrieve the "id" } ``` Perhaps I need something extra in my xaml, or maybe I'm going about this in a roundabout way? Any help/advice appreciated.
Basically your button will inherit the datacontext of a row data object. I am calling it as MyObject and hope MyObject.ID is what you wanted. ``` private void Button_Click(object sender, RoutedEventArgs e) { MyObject obj = ((FrameworkElement)sender).DataContext as MyObject; //Do whatever you wanted to do with MyObject.ID } ```
Another way I like to do this is to bind the ID to the CommandParameter property of the button: ``` <Button Click="Button_Click" CommandParameter="{Binding Path=ID}">View Details</Button> ``` Then you can access it like so in code: ``` private void Button_Click(object sender, RoutedEventArgs e) { object ID = ((Button)sender).CommandParameter; } ```
Button in a column, getting the row from which it came on the Click event handler
[ "", "c#", "wpf", "xaml", "datagrid", "datagridview", "" ]
Is there a difference between compiling projects in \*nix environments and MS Visual C++? For example, there is a "stdafx.h" file in Visual C++. The reason I'm asking is that I submitted a piece of code which compiled in g++, to [refactormycode.com](http://refactormycode.com/codes/957-breadth-first-search-textbook-example). Then after it got a refactoring, it seemed to include a "stdafx.h", so I figured I'll download Visual C++ 2008 Express but I can't seem to get it to build. What I'm doing is creating a new project > Create a Win32 Console Application, and replacing the auto-generated .cpp with the refactored code. Am I doing something wrong here? This is the compiler errors I'm getting: ``` ------ Build started: Project: bfs, Configuration: Debug Win32 ------ Compiling... bfs.cpp c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(3) : error C2871: 'std' : a namespace with this name does not exist c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(8) : error C2143: syntax error : missing ';' before '<' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(8) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(8) : error C2238: unexpected token(s) preceding ';' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(25) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(25) : error C2143: syntax error : missing ';' before '&' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(26) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(28) : warning C4183: 'getEdges': missing return type; assumed to be a member function returning 'int' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(32) : error C2059: syntax error : '<' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(32) : error C2238: unexpected token(s) preceding ';' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(12) : error C2758: 'Vertex::Edges' : must be initialized in constructor base/member initializer list c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(25) : see declaration of 'Vertex::Edges' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(22) : error C2065: 'm_edges' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(22) : error C2228: left of '.push_back' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(27) : error C2065: 'm_edges' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(38) : error C2143: syntax error : missing ';' before '<' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(38) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(38) : error C2039: 'iterator' : is not a member of '`global namespace'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(38) : error C2238: unexpected token(s) preceding ';' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(41) : error C2059: syntax error : '<' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(41) : error C2238: unexpected token(s) preceding ';' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(83) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(83) : error C2143: syntax error : missing ';' before '&' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(84) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(86) : warning C4183: 'getVertices': missing return type; assumed to be a member function returning 'int' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(89) : error C2146: syntax error : missing ';' before identifier 'm_vertices' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(89) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(89) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(43) : error C2758: 'Graph::Vertices' : must be initialized in constructor base/member initializer list c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(83) : see declaration of 'Graph::Vertices' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(55) : error C2065: 'm_vertices' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(55) : error C2228: left of '.insert' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(61) : error C2065: 'VertexIterator' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(61) : error C2146: syntax error : missing ';' before identifier 'iter' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(61) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(62) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(62) : error C2065: 'm_vertices' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(62) : error C2228: left of '.begin' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(62) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(62) : error C2065: 'm_vertices' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(62) : error C2228: left of '.end' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(62) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(64) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(64) : error C2227: left of '->getId' must point to class/struct/union/generic type type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(65) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(78) : error C2065: 'VertexIterator' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(78) : error C2146: syntax error : missing ';' before identifier 'iter' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(78) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(79) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(79) : error C2065: 'm_vertices' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(79) : error C2228: left of '.begin' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(79) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(79) : error C2065: 'm_vertices' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(79) : error C2228: left of '.end' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(79) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(80) : error C2065: 'iter' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(80) : error C2541: 'delete' : cannot delete objects that are not pointers c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(85) : error C2065: 'm_vertices' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(119) : error C2143: syntax error : missing ';' before '<' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(119) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(119) : error C2238: unexpected token(s) preceding ';' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(106) : error C2065: 'UINT_MAX' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(138) : error C2065: 'queue' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(138) : error C2059: syntax error : 'const' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(140) : error C2065: 'Attributes' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(142) : error C2065: 'q' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(142) : error C2228: left of '.push' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(143) : error C2065: 'q' : undeclared identifier c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(143) : error C2228: left of '.empty' must have class/struct/union type is ''unknown-type'' c:\users\admin\documents\visual studio 2008\projects\alg\bfs\bfs\bfs.cpp(143) : fatal error C1903: unable to recover from previous error(s); stopping compilation Build log was saved at "file://c:\Users\Admin\Documents\Visual Studio 2008\Projects\alg\bfs\bfs\Debug\BuildLog.htm" bfs - 66 error(s), 2 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ```
The refactored code is missing certain includes. More than likely they are included in the precompiled header, stdafx.h, which usually isn't a good idea. Add the following includes to the bfs.cpp file, in between the "stdafx.h" include and the "using" declaration: ``` #include "stdafx.h" #include <set> #include <list> #include <map> #include <queue> #include <iostream> using namespace std; ``` ``` Compiling... bfs - 0 error(s), 0 warning(s) ```
Add the below headers in the refactored code, ``` #include <iostream> #include <limits> #include <map> #include <list> #include <queue> ```
Compiling differences in Visual C++ and *nix environments
[ "", "c++", "winapi", "unix", "compilation", "" ]
I have opened the Javascript Debugger (Ctrl+Shift+L) in Chrome and started using it to set breakpoints in my code. This is a much different interface compared to Firebug, (it's all command line driven) so I'm wondering how to do a simple thing like print all the properties of an object. If I have an object like this: ``` var opts = { prop1: "<some><string/></some>", prop2: 2, prop3: [1,2,3] } ``` I can set a breakpoint and inspect the object, but I only seem to get a single property back, and I'm not sure which property will appear: ``` $ print opts #<an Object> ``` Trying to get all the properties: ``` $ print for(var p in opts) p; prop1 ``` Any ideas? It obviously has more than just one...
So I've tried using the "dir" command, and it gives me something at least: ``` $dir opts 3 properties prop1: string (#11#) prop2: string (#12#) prop3: string (#13#) ``` This also works (slightly better because it gives me some values), but cuts off the end of the string if it's too long: ``` $ print var s=[];for(var p in opts) { s.push(p + ":" + opts[p]); } s.join(","); prop1:<some><string/></some>,prop2:2,prop3:[object Object] ```
Chrome has ECMA-style native JSON, so you can use ``` JSON.stringify (opts); {"prop1":"<some><string/></some>","prop2":2,"prop3":[1,2,3]} ```
In Chrome JS debugger, how do I print all the properties of an object?
[ "", "javascript", "debugging", "google-chrome", "" ]
Is there a data structure (readily available in STL or boost), that accepts two arguments and maps it to a certain value? Examples would be for returning certain information in a coordinate grid or getting the weight of an edge in a graph: > coordinate\_quadrant(-1,-1) = 3 > > weight\_of(u,v) = 10 The quadrant example could be done in a simple function with four if statements. I'm mainly looking for an example that would suit the weight example. I'm trying to avoid having to create an edge class and pass that into the weight\_of(Edge edge) function.
You could use std::map< std::pair<Type1,Type2>, Type3 >.
I would consider the following choices: **Option 1** *std::map with std::pair< Type1, Type2 > as the key and Type3 as the value* ``` std::map< std::pair< Type1, Type2 >, Type3 > data; ``` **Option 2** *2-dimensional std::vector* In case that the Type1 and Type2 are integers, as you might find when modeling a graph or Cartesian space: std::vector< std::vector< Type3 > > data; **Option 3** *user-defined class containing Type1 and Type2, which can be mapped to Type3* In case you might ever want to decorate your two types with more values, you could define a class that contains both of your types, and use a std::map to map it to the third type: ``` public: MyClass( Type1 x, Type2 y ) : x_( x ), y_( y ) Type1 x() const { return x_; } Type2 y() const { return y_; } private: Type1 x_; Type2 y_; }; std::map< MyClass, Type3 > data; ``` The benefit of Option 1 is that it's really fast and easy to code, and should make sense to anyone who knows C++. Option 2 is likely a small bit faster, and has the added benefit that it can easily be modified to have more dimensions. The downside of Option 2 is that your values need to be integer indices into the 2-dimensional vector. In my opinion Option 3 is the best choice to me because it's readable, places no requirements on the type of Type1 and Type2, and can be extended to contain more data in a very reasonable way. The downside to Option 3 is that you need to define a StrictWeakOrdering for comparing MyClass objects to each other, but that's fairly straightforward: ``` bool operator<(const MyClass & rhs) const { return ( rhs.x() <= x() && rhs.y() <= y() ); } ``` Make that a member function of your class, and you should be ready to go. Like many things in programming, there's not an obvious right answer until you consider the specifics of what you're doing and how much time you're willing to invest. Don't forget to check for key existence and out-of-bounds errors. :)
Data structure similar to a 2-argument map
[ "", "c++", "data-structures", "" ]
I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases. The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C. For example, say I have the string: `ATMM` I would like to take this string as input and output the four possible matching strings: `ATAA` `ATAC` `ATCA` `ATCC` Rather than brute force a solution, I feel like there must be some elegant Python/Perl/Regular Expression trick to do this. Thank you for any advice. **Edit, thanks cortex for the product operator. This is my solution:** Still a Python newbie, so I bet there's a better way to handle each dictionary key than another for loop. Any suggestions would be great. ``` import sys from itertools import product baseDict = dict(M=['A','C'],R=['A','G'],W=['A','T'],S=['C','G'], Y=['C','T'],K=['G','T'],V=['A','C','G'], H=['A','C','T'],D=['A','G','T'],B=['C','G','T']) def glob(str): strings = [str] ## this loop visits very possible base in the dictionary ## probably a cleaner way to do it for base in baseDict: oldstrings = strings strings = [] for string in oldstrings: strings += map("".join,product(*[baseDict[base] if x == base else [x] for x in string])) return strings for line in sys.stdin.readlines(): line = line.rstrip('\n') permutations = glob(line) for x in permutations: print x ```
Agree with other posters that it seems like a strange thing to want to do. Of course, if you really want to, there is (as always) an elegant way to do it in Python (2.6+): ``` from itertools import product map("".join, product(*[['A', 'C'] if x == "M" else [x] for x in "GMTTMCA"])) ``` Full solution with input handling: ``` import sys from itertools import product base_globs = {"M":['A','C'], "R":['A','G'], "W":['A','T'], "S":['C','G'], "Y":['C','T'], "K":['G','T'], "V":['A','C','G'], "H":['A','C','T'], "D":['A','G','T'], "B":['C','G','T'], } def base_glob(glob_sequence): production_sequence = [base_globs.get(base, [base]) for base in glob_sequence] return map("".join, product(*production_sequence)) for line in sys.stdin.readlines(): productions = base_glob(line.strip()) print "\n".join(productions) ```
You probably could do something like this in python using the yield operator ``` def glob(str): if str=='': yield '' return if str[0]!='M': for tail in glob(str[1:]): yield str[0] + tail else: for c in ['A','G','C','T']: for tail in glob(str[1:]): yield c + tail return ``` EDIT: As correctly pointed out I was making a few mistakes. Here is a version which I tried out and works.
Looking for elegant glob-like DNA string expansion
[ "", "python", "permutation", "glob", "dna-sequence", "" ]
Here is the class structure I'd like to have: ``` public class AllocationNEW<TActivity, TResource> where TActivity : AllocatableActivity<TActivity> where TResource : AllocatableResource<TResource> { public TResource Resource { get; private set; } public TActivity Activity { get; private set; } public TimeQuantity Period { get; private set; } public AllocationNEW(TResource resource, TActivity activity, DateTime eventDate, TimeQuantity timeSpent) { Check.RequireNotNull<IResource>(resource); Resource = resource; Check.RequireNotNull<Activities.Activity>(activity); Activity = activity; Check.Require(timeSpent.Amount >= 0, Msgs.Allocation_NegativeTimeSpent); TimeSpentPeriod = _toTimeSpentPeriod(eventDate, timeSpent); } } public class AllocatableResource<TResource> { public string Description { get; protected set; } public string BusinessId { get; protected set; } } public class AllocatableActivity<TActivity> { public string Description { get; protected set; } public string BusinessId { get; protected set; } protected readonly IDictionary<DateTime, Allocation<TActivity, TResource>> _allocations; public virtual void ClockIn<TResource>(DateTime eventDate, TResource resource, TimeQuantity timeSpent) { var entry = new Allocation<TActivity, TResource>(resource, this, eventDate, timeSpent); if (_allocations.ContainsKey(eventDate)) { Check.Require(_allocations[eventDate].Resource.Equals(resource), "This method requires that the same resource is the resource in this allocation."); _allocations[eventDate] = entry; } else _allocations.Add(eventDate, entry); } } ``` AllocatableActivity is where this scheme breaks down, of course. I need a collection of Allocations to work with in this class, but I don't know what TResource is going to be until a client uses the ClockIn method. I've been stuck on various ideas on how to solve the Allocation class with Resource and Activity types for awhile, so I'm hoping that I'm missing something obvious. It seems like it should be solvable with Generics. Cheers # MORE INFO Here's some examples of activities: ``` public class ProjectActivity : AllocatableActivity<Project> { public ProjectActivity(Project project) { _project = project; Description = _project.Description; BusinessId = _project.Code.ToString(); } // private readonly Project _project; --> shouldn't need anymore } public class AccountingActivity : AllocatableActivity<Account> { public AccountingActivity(Account account) { _account = account; Description = account.Description; BusinessId = account.AccountId; } // private readonly Account _account; } ``` Here's an example of a resource: ``` public class StaffMemberResource : AllocatableResource<StaffMember> { public StaffMemberResource(StaffMember staffMember) { Description = staffMember.Name.ToString(); BusinessId = staffMember.Number; } } ``` Data entry would be by a single Resource. I don't know about the recursion issue yet, but otherwise there is no business reason why TResource can't be known in a data entry session other than the cost of creating the activities (there's about 300 combinations of underlying projects, accounts that I would want to treat as an AllocatableActivity at this time. Reporting would involve multiple resources (ie, a Manager needing to sign off on time spent needs to see all time spent by her assigned resources, ad hoc reports by project, etc.) I was laying this out without generics (interfaces and base classes) but there was some awkwardness with involving the typing, so I wanted to see if generics would make for a simpler interface.
Why isn't `AllocatableActivity<TActivity>` also generic in `TResource`? That would make it all work in terms of the language - is there a business problem with that? Could you give examples of `TActivity` and `TResource`, and why you might not know what kind of resource you need when you create the activity?
For the sake of having a unified storage in AllocatableActivity, I would have an abstract base class for Allocation and all resource types, like this: ``` public abstract class Resource { public string Description { get; } } public class AllocatableResource<TResource> where TResource : Resource { ... } public abstract class Allocation<TActivity> { protected Allocation( Resource resource, TActivity activity, TimeQuantity period) { this.Resource = resource; this.Activity = activity; this.Period = period; } public virtual Resource Resource { get; protected set; } public TActivity Activity { get; protected set; } public TimeQuantity Period { get; protected set; } } public class Allocation<TActivity, TResource> : Allocation<TActivity> where TActivity : AllocatableActivity<TActivity> where TResource : AllocatableResource<TResource> { public new TResource Resource { get; private set; } public Allocation( TResource resource, TActivity activity, DateTime eventDate, TimeQuantity timeSpent) : base(resource, activity, timeSpent) { ... } } ``` Now, in AllocatableActivity, you can store all Allocations in a polymorphic fashion, like this: ``` public class AllocatableActivity<TActivity> { protected readonly IDictionary<DateTime, Allocation<TActivity>> _allocations; public virtual void ClockIn<TResource>( DateTime eventDate, TResource resource, TimeQuantity timeSpent) where TResource : Resource { var entry = new Allocation<TActivity, TResource>( resource, this, eventDate, timeSpent); if (_allocations.ContainsKey(eventDate)) { Check.Require(_allocations[eventDate].Resource.Equals(resource), "This method requires that the same resource is the resource in this allocation."); _allocations[eventDate] = entry; } else _allocations.Add(eventDate, entry); } } ``` The reason why I added a base Resource class is that you'll undoubtedly need to list resources in your application somewhere, so there should be some sort of commonality.
Can I solve this with generics types?
[ "", "c#", "generics", "" ]
Short question: How can I modify individual items in a `List`? (or more precisely, members of a `struct` stored in a `List`?) Full explanation: First, the `struct` definitions used below: ``` public struct itemInfo { ...(Strings, Chars, boring)... public String nameStr; ...(you get the idea, nothing fancy)... public String subNum; //BTW this is the element I'm trying to sort on } public struct slotInfo { public Char catID; public String sortName; public Bitmap mainIcon; public IList<itemInfo> subItems; } public struct catInfo { public Char catID; public String catDesc; public IList<slotInfo> items; public int numItems; } catInfo[] gAllCats = new catInfo[31]; ``` `gAllCats` is populated on load, and so on down the line as the program runs. The issue arises when I want to sort the `itemInfo` objects in the `subItems` array. I'm using LINQ to do this (because there doesn't seem to be any other reasonable way to sort lists of a non-builtin type). So here's what I have: ``` foreach (slotInfo sInf in gAllCats[c].items) { var sortedSubItems = from itemInfo iInf in sInf.subItems orderby iInf.subNum ascending select iInf; IList<itemInfo> sortedSubTemp = new List<itemInfo(); foreach (itemInfo iInf in sortedSubItems) { sortedSubTemp.Add(iInf); } sInf.subItems.Clear(); sInf.subItems = sortedSubTemp; // ERROR: see below } ``` The error is, "Cannot modify members of 'sInf' because it is a 'foreach iteration variable'". a, this restriction makes no sense; isn't that a primary use of the foreach construct? b, (also out of spite) what does Clear() do if not modify the list? (BTW, the List does get cleared, according to the debugger, if I remove the last line and run it.) So I tried to take a different approach, and see if it worked using a regular for loop. (Apparently, this is only allowable because `gAllCats[c].items` is actually an `IList`; I don't think it will allow you to index a regular `List` this way.) ``` for (int s = 0; s < gAllCats[c].items.Count; s++) { var sortedSubItems = from itemInfo iInf in gAllCats[c].items[s].subItems orderby iInf.subNum ascending select iInf; IList<itemInfo> sortedSubTemp = new List<itemInfo>(); foreach (itemInfo iInf in sortedSubItems) { sortedSubTemp.Add(iInf); } //NOTE: the following two lines were incorrect in the original post gAllCats[c].items[s].subItems.Clear(); gAllCats[c].items[s].subItems = sortedSubTemp; // ERROR: see below } ``` This time, the error is, "Cannot modify the return value of 'System.Collections.Generic.IList.this[int]' because it is not a variable." Ugh! What is it, if not a variable? and when did it become a 'return value'? I know there has to be a 'correct' way to do this; I'm coming to this from a C background and I know I could do it in C (albeit with a good bit of manual memory management.) I searched around, and it seems that `ArrayList` has gone out of fashion in favor of generic types (I'm using 3.0) and I can't use an array since the size needs to be dynamic.
Looking at the for-loop approach, the reason (and solution) for this is given in the [documentation for the compilation error](http://msdn.microsoft.com/en-us/library/wydkhw2c.aspx): > An attempt was made to modify a value > type that is produced as the result of > an intermediate expression but is not > stored in a variable. This error can > occur when you attempt to directly > modify a struct in a generic > collection. > > To modify the struct, first assign it > to a local variable, modify the > variable, then assign the variable > back to the item in the collection. So, in your for-loop, change the following lines: ``` catSlots[s].subItems.Clear(); catSlots[s].subItems = sortedSubTemp; // ERROR: see below ``` ...into: ``` slotInfo tempSlot = gAllCats[0].items[s]; tempSlot.subItems = sortedSubTemp; gAllCats[0].items[s] = tempSlot; ``` I removed the call to the `Clear` method, since I don't think it adds anything.
The problem you are having in your `foreach` is that structs are value types, and as a result, the loop iteration variable isn't actually a reference to the struct in the list, but rather a copy of the struct. My guess would be the compiler is forbidding you change it because it most likely would not do what you expect it to anyway. `subItems.Clear()` is less of a problem, because altho the field may be a copy of the element in the list, it is also a reference to the list (shallow copy). The simplest solution would probably be to change from a `struct` to a `class` for this. Or use a completely different approach with a `for (int ix = 0; ix < ...; ix++)`, etc.
c# modifying structs in a List<T>
[ "", "c#", "arrays", "foreach", "" ]
I'm building my own Ajax website, and I'm contemplating between [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer) and RPC. If my server supported Servlets I'd just install [persevere](http://www.persvr.org) and end the problem, but my server doesn't support Servlets. RPC is simpler to code (IMO) and can be written in PHP easily. All I need is a database query executer. I'm using the [Dojo Toolkit](http://en.wikipedia.org/wiki/Dojo_Toolkit) and JSON. Why should I choose REST over RPC or RPC over REST?
Uhm ... to put it simple, both are very abstract models ... so abstract, they naturally occur everywhere... REST is the idea of having resources addressed with a global identifier (the URI in the case of HTTP) that are accessed in a [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) way (using [POST](http://en.wikipedia.org/wiki/POST_%28HTTP%29), [GET](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods), PUT and DELETE in the case of HTTP ... well, at least that's the idea)... RPC is the idea where you call a procedure on a different machine, passing in some parameters, and taking a return value... [There is a nice short comparison on Wikipedia](http://en.wikipedia.org/wiki/Restful#REST_versus_RPC) Persevere creates a service, that allows both (in a very elegant way, admittedly) ... it is [RESTful](http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_services) (although it does not only use HTTP-features to achieve this) **and** exposes an RPC interface... In the end, you should look at what your application needs to do ... as most people, you'll probably wind up with an RPC API (be it based on [XML](http://en.wikipedia.org/wiki/XML) or [JSON](http://en.wikipedia.org/wiki/JSON) or whatever), that includes a transport layer for a partially RESTful subsystem ... this is, because having RESTfulnes, means flexibility ... if the client can more or less freely traverse the data on the server (through a set of simple CRUD methods), it does not depend on a limited (problem-specific) set of methods exposed through the API, and you can shift logic clientwards...
The best way to understand it is to read Roy T. Fielding's dissertation on it, or relevant articles on his [blog](http://roy.gbiv.com/untangled/) where he discusses the differences between pure REST and simply RPC architectures. Another thing to note is that the Wikipedia article on REST is in dismal condition and Fielding himself, the 'inventor' of REST, suggests that the article is inaccurate. The biggest thing people miss with REST is discoverability - resources should include URIs for other related resources inside their hypertext, instead of relying on URI naming conventions, which are out-of-band and non-standardized. A big problem with popular RPC implementations like SOAP or XML-RPC is that they use HTTP underneath their own proprietary architecture, rather than taking advantage of all the different properties of HTTP like PUT, GET, DELETE etc. So this doesn't fit the traditional web stack as well - a cache server in the middle doesn't work, for example, without knowing about the meaning of the contents of the RPC call. This is an incomplete introduction to REST and RPC but I think I've highlighted some of the important points that are often missed. Be careful, since there is a LOT of wrong information out there on REST. That said, REST is not for everything. It's an architecture, so it's rather flexible how you can implement it. But if it doesn't make sense to access things primarily as resources, then REST may not fit, or it may only fit for parts of your application, which is fine.
REST vs. RPC in PHP
[ "", "php", "json", "rest", "dojo", "rpc", "" ]
## Original Question: I am currently using Zend Framework with `Zend_Db_*`, and I am selecting three random rows from a table: ``` $category->getTable()->select()->order(new Zend_Db_Expr('RAND()'))->limit('3') ``` Where `$category` is a `Zend_Db_Table_Row`. I would like to grab three random rows, but have those three rows ordered by the column named `name`. Changing the `->order()` to the following had no effect: ``` ->order(array(new Zend_Db_Expr('RAND()'), 'name ASC')) ``` As the entries are still showing up un-ordered, and still random. Zend Framework solutions appreciated, but I can adapt other solutions to fit within my project. --- I am aware of the scaling issues with using RAND(), the database will never get big enough for this to become an issue, the day it does I won't have to worry about maintaining it, the robots will, as I'll be long dead! :-P --- ## Answer For those wondering how this was ultimately completed using Zend\_Db\_Select, this is what it came down to use a sub-select within the Zend\_Db\_Select (I was using `$category->findDefault_Model_projects()` to find the dependent rowset, but that does not allow me to use the select() as a subselect until [ZF-6461](http://framework.zend.com/issues/browse/ZF-6461) fixes the issue, I am stuck with what I have): ``` $projects = new Default_Model_Projects(); $subselect = $projects->select()->order(new Zend_Db_Expr('RAND()'))->limit('3')->where('cid = ?', $category->id, Zend_Db::INT_TYPE); $db = $projects->getAdapter(); $select = $db->select()->from(array("c" => new Zend_Db_Expr("({$subselect})")))->order('name'); $stmt = $select->query(); $projects = $stmt->fetchAll(); ``` The generated SQL is: ``` SELECT `c`.* FROM (SELECT `projects`.* FROM `projects` WHERE (cid = 1) ORDER BY RAND() LIMIT 3) AS `c` ORDER BY `name` ASC ``` From there $projects contains the standard row set which can be iterated over much like any other database queries, the only thing it does not do is stick it in a table specific row/rowset class, which could have its downsides.
Your initial solution is not correct because this query will generate a random value for each row and the order the rows based on it, sorting by name only if random values are equal (which is highly improbable). The problem can be solved with a subquery like the one below ``` select * from (select * from categories order by rand() limit 3) c order by name ``` I'm leaving to you the task of translating this into Zend\_Db language.
``` $subQuery = $this->select()->from('picture')->order(new Zend_Db_Expr('RAND()'))->limit(count($this->selectAll())); $select->setIntegrityCheck(false) ->from($subQuery); ``` This is what I did and it works. Cheers!
MySQL random rows sorted by a column name
[ "", "php", "mysql", "zend-framework", "zend-db", "zend-db-table", "" ]
I am writing an app that I can feed tasks with multiple steps. I have some code similar to what's below and I want to know if this is the normal way to handle exceptions. This code will probably never be seen by anyone else, but it could be, so I'd like to know I'm handling the exceptions as anyone would expect. ``` IEnumerable<Task> Tasks; foreach(var task in Tasks) { try { //boiler plate prep for task (loading libraries, connecting, logging start, etc) foreach(var step in task.Steps) { try { step.Execute(); } catch(Exception ex) { LogStepError(step, ex); throw; } } //Notify parties task has been completed successfully, log task completion } catch(Exception ex) { LogTaskFailure(task); } finally { //close connections, etc } } interface ITaskStep { void Execute() { } } ``` I also wanted to add that the Task Steps are implementing the ITaskStep interface, so the implementation of Execute is not my own (well it is in this instance, but someone could implement the interface). My code just loads up the library and runs any ITasks and their ITaskSteps.
Go ahead and catch exceptions to log their existence. But if you haven't actually resolved the problem that led to the exception being thrown, then please rethrow it for the caller to handle. Don't swallow it up. Your code above catches a `TaskIsBogusException` and a `PrinterOnFireException` and treats them the same way: Log it and keep going with the next task. Doing that with a bogus task is fine because you're done with the task anyway, but if you catch a `PrinterOnFireException` and don't rethrow it, then by golly, the printer had better not still be on fire. If you're not going to rethrow, then only catch the specific exception types that your code knows how to handle at that point. Let everything else (either stuff you don't know how to handle, or stuff you never even thought of) propagate up to the next available exception handler.
If `step.Execute()` is the only thing that's happening in your for loop, the following might be better: (edited in response to clarification) ``` IEnumerable<Task> Tasks; foreach(var task in Tasks) { try { //boiler plate prep for task } catch(Exception ex) { LogTaskFailure(task); continue; } foreach(var step in task.Steps) { try { step.Execute(); } catch(Exception ex) { LogStepError(step, ex); LogTaskFailure(task); break; } } } class TaskStep { private void Execute() { //do some stuff, don't catch any exceptions } } ``` This way you don't rethrow the exception.
When to handle the exception?
[ "", "c#", "exception", "" ]
> **Possible Duplicate:** > [Getting the class name from a static method in Java](https://stackoverflow.com/questions/936684/getting-the-class-name-from-a-static-method-in-java) When you are inside of a static method, is there a way to get the class name (a string containing the name) without typing the class name itself? For example, typing `MyClass.class.getName()` is no more useful than just `"Myclass"`.
You can do it by creating (not throwing) a new Exception and inspecting its stack trace. Your class will be the zeroth element as it is the origin of the Exception. It kinda feels wrong, but it will work. ``` System.out.println( new Exception().getStackTrace()[0].getClassName() ); ``` You can do the same with the Thread class. This seems cleaner to me, but the line is slightly longer. Your class is now the first element in the stacktrace rather than the zeroth. Thread.getStackTrace() is the zeroth. ``` System.out.println( Thread.currentThread().getStackTrace()[1].getClassName() ); ``` > For example, typing MyClass.class.getName() is no more useful than just "Myclass". On the contrary, if you rename MyClass using your IDE's refactor function it will replace MyClass.class.getName() with RenamedClass.class.getName(). If you put a string in there you'll have to do it manually.
You can use an anonymous inner class: ``` class Test { public static void main(String[] args) { String className = new Object(){}.getClass().getEnclosingClass().getName(); System.out.println(className); } } ```
Is it possible to get the class name from a static method?
[ "", "java", "static-methods", "classname", "" ]
I have an application a part of which uses shared libraries. These libraries are linked at compile time. At Runtime the loader expects the shared object to be in the `LD_LIBRARY_PATH` , if not found the entire application crashes with error "unable to load shared libraries".Note that there is no guarantee that client would be having the library, in that case I want the application to leave a suitable error message also the independent part should work correctly. For this purpose I am using `dlsym()` and `dlopen()` to use the API in the shared library. The problem with this is if I have a lot of functions in the API, i have to access them Individually using `dlsym()` and ptrs which in my case are leading to memory corruption and code crashes. Are there any alternatives for this?
The common solution to your problem is to declare a table of function pointers, to do a single dlsym() to find it, and then call all the other functions through a pointer to that table. Example (untested): ``` // libfoo.h struct APIs { void (*api1)(void); void *(*api2)(int); long (*api3)(int, void *); }; // libfoo.cc void fn1(void) { ... } void *fn2(int) { ... } long fn3(int, void *) { ... } APIs api_table = { fn1, fn2, fn3 }; // client.cc #include "libfoo.h" ... void *foo_handle = dlopen("libfoo.so", RTLD_LAZY); if (!foo_handle) { return false; // library not present } APIs *table = dlsym(foo_handle, "api_table"); table->api1(); // calls fn1 void *p = table->api2(42); // calls fn2 long x = table->api3(1, p); // calls fn3 ``` P.S. Accessing your API functions individually using dlsym and pointers *does not* in itself lead to memory corruption and crashes. Most likely you just have bugs. EDIT: You can use this exact same technique with a 3rd-party library. Create a `libdrmaa_wrapper.so` and put the `api_table` into it. Link the wrapper directly against `libdrmaa.so`. In the main executable, `dlopen("libdrmaa_wrapper.so", RTLD_NOW)`. This `dlopen` will succeed if (and only if) `libdrmaa.so` is present at runtime and provides all API functions you used in the `api_table`. If it does succeed, a single `dlsym` call will give you access to the entire API.
You can wrap your application with another one which first checks for all the required libraries, and if something is missing it errors out nicely, but if everything is allright it execs the real application.
Alternatives to dlsym() and dlopen() in C++
[ "", "c++", "shared-libraries", "dynamic-loading", "dlsym", "" ]
I'm writing a PHP script that generates gzipped files. The approach I've been using is to build up a string in PHP and gzcompress() the string before writing it out to a file at the end of the script. Now I'm testing my script with larger files and running into memory allocation errors. It seems that the result string is becoming too large to hold in memory at one time. To solve this I've tried to use gzopen() and gzwrite() to avoid allocating a large string in PHP. However, the gzipped file generated with gzwrite() is very different from when I use gzcompress(). I've experimented with different zip levels but it doesn't help. I've also tried using gzdeflate() and end up with the same results as gzwrite(), but still not similar to gzcompress(). It's not just the first two bytes (zlib header) that are different, it's the entire file. What does gzcompress() do differently from these other gzip functions in PHP? Is there a way I can emulate the results of gzcompress() while incrementally producing the result?
I am not 100% certain, but my guess is that gzcompress uses GZIP format, and gzopen/gzwrite use ZLIB. Honestly, I can't tell you what the difference between the two is, but I do know that GZIP uses ZLIB for the actual compression. It is possible that none of that will matter though. Try creating a gzip file with gzopen/gzwrite and then decompress it using the command-line gzip program. If it works, then using gzopen/gzwrite will work for you.
The primary difference is that the gzwrite function initiates zlib with the SYNC\_FLUSH option, which will pad the output to a 4 byte boundary (or is it 2), and then a little extra (0x00 0x00 0xff 0xff 0x03). If you are using these to create Zip files, beware that the default Mac Archive utility does NOT accept this format. From what I can tell, SYNC\_FLUSH is a gzip option, and is not allowed in the PKZip/Info-ZIP format, all .zip files and their derivatives come from. If you deflate a small file/text, resulting in a single deflate block, and compare it to the same text written with gzwrite, you'll see 2 differences, one of the bytes in the header of the deflate block is different by 1, and the end is padded with the above bytes. If the result is larger than one deflate block, the differences start piling up. It is hard to fix this, as the deflate stream block headers aren't even byte aligned. There is a reason everybody uses the zlib. Few people are brave enough to even attempt to rewrite that format!
PHP gzcompress vs gzopen/gzwrite
[ "", "php", "zlib", "" ]
I was wondering - how do people handle importing large numbers of commonly used modules within django views? And whats the best method to do this efficiently? For instance, I've got some views like, ``` admin_views.py search_views.py . . ``` and from what I've seen, every one of them needs to use HttpResponse or other such commonly used modules. Moreover, some of them need things like BeautifulSoup, and others need other things (md5, auth, et al). What I did when starting the project was to make an `include_all.py` which contained most of my common imports, and then added these specific things in the *view* itself. So, I had something like, **admin\_views.py** ``` from include_all import * ... [list of specific module imports for admin] ... ``` **search\_views.py** ``` from include_all import * ... [list of specific module imports for search] ... ``` As time progressed, the include\_all became a misc file with anything being needed put into it - as a result, a number of views end up importing modules they don't need. Is this going to affect efficiency? That is, does python (django?) import all the modules once and store/cache them such that any other view needing them doesn't have to import it again? Or is my method of calling this long file a very inefficient one - and I would be better of sticking to individually importing these modules in each view? Are there any best practices for this sort of thing too? Thanks!
Python itself guarantees that a module is loaded just once (unless `reload` is explicitly called, which is not the case here): after the first time, `import` of that module just binds its name directly from `sys.modules[themodulename]`, an extremely fast operation. So Django does not have to do any further optimization, and neither do you. Best practice is avoiding `from ... import *` in production code (making it clearer and more maintainable where each name is coming from, facilitating testing, etc, etc) and importing modules, "individually" as you put it, exactly where they're needed (by possibly binding fewer names that may save a few microseconds and definitely won't waste any, but "explicit is better than implicit" -- clarity, readability, maintainability -- is the main consideration anyway).
I guess you could slap your frequently used imports into your \_\_init\_\_.py file.
Efficiently importing modules in Django views
[ "", "python", "django", "performance", "import", "python-module", "" ]
When using java from Matlab, is there some way to figure out from where in matlab's java class path is a class being loaded? I'm trying to diagnose a error caused by conflicting versions of the same class being used simultaneously. Specifically, the class I'm looking for is org.apache.lucene.store.FSDirectory. It seems to be used by one of the matlab toolboxes, but I don't know which one.
From <http://www.exampledepot.com/egs/java.lang/ClassOrigin.html> ``` // Get the location of this class Class cls = this.getClass(); ProtectionDomain pDomain = cls.getProtectionDomain(); CodeSource cSource = pDomain.getCodeSource(); URL loc = cSource.getLocation(); // file:/c:/almanac14/examples/ ```
Assuming that an `URLClassLoader` is being used, you can get the `file:` URL of the class file like this: ``` ProblemClass.class.getResource("ProblemClass.class") ```
Determine location of a java class loaded by Matlab
[ "", "java", "matlab", "classpath", "" ]
I have a html form that I process with a aspx page. I want to be able to go back to my html form if the validation on the aspx page returns false (I cannot use javascript to validate the html form). I can't use Response.Redirect as I will lose the data initially entered on the html form. The set-up is: * form.html (set action attribute of form tag to processform.aspx) * processform.aspx (get values from html form using Request.Form["myvalue"]) if values are invalid, go back to form.html, otherwise Response.Redirect("success.html") Perhaps I am just going about this the wrong way. Could anyone suggest a better method? Please note: I cannot use javascript on the form.html, however I can use javascript on the processform.aspx page - although I would prefer an alternative if possible.
You say that form.html can't use any javascript on form.html - does that mean you can't use Javascript at all in this solution? My answer would be to output a javascript snippet from your processform.aspx that simply calls `history.go(-1)`. Example: ``` if(valid) { Response.Redirect("success.html", true); } Response.Clear(); Response.Write("<html><body><script>history.go(-1);</script></body></html>"); Response.Flush(); Response.End(); ``` If, however, you cannot use Javascript at all... the options are rather limited. RFC 2616 defines HTTP 204 "No Content" - you could attempt to send that, but this is a success status, and behaviour from browsers might vary. Theoretically, however, the content should stay the same. Users might be very confused, however, because there's no visible feedback. If you could explain the reasoning behind these restrictions, perhaps we could produce a better solution.
If you are using MVC, you will have to refill the model from the submitted values in Request.Form. If you are doing the classic WebForms, you need to generate your form.html dynamically inserting the previously submitted values into it. You could put your submitted values into session: ``` Session["UserName"] = Request.Form["UserName"] ``` Then you do redirect to your form.aspx: ``` <input type="text" value="<%= Session["UserName"]" /> ``` This will however return the page as form.aspx. But it shouldn't be a real problem, it's just the name.
How can I "Go Back" without using Response.Redirect
[ "", "c#", "asp.net", "html", "forms", "" ]
I have done a software in C#. How can I make a Installation Package for the software?
I would recommend [NSIS](http://nsis.sourceforge.net/Main_Page), it has been brilliant for me. If you want to use Visual Studio, [check this link out](http://en.csharp-online.net/Deploying_Windows_Applications%E2%80%94Visual_Studio_Setup_and_Deployment_Project_Types), VS does most of the work for you, but a lot of people don't like this technique. There is also [WIX](http://wix.sourceforge.net/), which i personally haven't tried but have heard a lot about.
Depends on your deployment requirements. Is this using Visual Studio? ClickOnce (Build->Publish) will probably suit your needs.
Make installation package of C# project
[ "", "c#", "installation", "package", "" ]
I know just enough about SQL tuning to get myself in trouble. Today I was doing EXPLAIN plan on a query and I noticed it was not using indexes when I thought it probably should. Well, I kept doing EXPLAIN on simpler and simpler (and more indexable in my mind) queries, until I did EXPLAIN on ``` select count(*) from table_name ``` I thought for sure this would return instantly and that the explain would show use of an index, as we have many indexes on this table, including an index on the row\_id column, which is unique. Yet the explain plan showed a FULL table scan, and it took several seconds to complete. (We have 3 million rows in this table). Why would oracle be doing a full table scan to count the rows in this table? I would like to think that since oracle is indexing unique fields already, and having to track every insert and update on that table, that it would be caching the row count somewhere. Even if it's not, wouldn't it be faster to scan the entire index than to scan the entire table? I have two theories. Theory one is that I am imagining how indexes work incorrectly. Theory two is that some setting or parameter somewhere in our oracle setup is messing with Oracle's ability to optimize queries (we are on oracle 9i). Can anyone enlighten me?
`Oracle` does not cache `COUNT(*)`. `MySQL` with `MyISAM` does (can afford this), because `MyISAM` is transactionless and same `COUNT(*)` is visible by anyone. `Oracle` is transactional, and a row deleted in other transaction is still visible by your transaction. `Oracle` should scan it, see that it's deleted, visit the `UNDO`, make sure it's still in place from your transaction's point of view, and add it to the count. Indexing a `UNIQUE` value differs from indexing a non-`UNIQUE` one only logically. In fact, you can create a `UNIQUE` constraint over a column with a non-unique index defined, and the index will be used to enforce the constraint. If a column is marked as non-`NULL`, the an `INDEX FAST FULL SCAN` over this column can be used for `COUNT`. It's a special access method, used for cases when the index order is not important. It does not traverse the `B-Tree`, but instead just reads the pages sequentially. Since an index has less pages than the table itself, the `COUNT` can be faster with an `INDEX_FFS` than with a `FULL`
It is certainly possible for Oracle to satisfy such a query with an index (specifically with an INDEX FAST FULL SCAN). In order for the optimizer to choose that path, at least two things have to be true: 1. Oracle has to be certain that every row in the table is represented in the index -- basically, that there are no NULL entries that would be missing from the index. If you have a primary key this should be guaranteed. 2. Oracle has to calculate the cost of the index scan as lower than the cost of a table scan. I don't think it necessarily true to assume that an index scan is always cheaper. Possibly, gathering statistics on the table would change the behavior.
Does an index on a unique field in a table allow a select count(*) to happen instantly? If not why not?
[ "", "sql", "oracle", "indexing", "" ]
I've just written a chunk of code that strikes me as being far more nested than is optimal. I'd like advice on how to improve the style of this, particularly so that it conforms more with "Flat is better than nested." ``` for app in apps: if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps try: a = app + '.cron' __import__(a) m = sys.modules[a] try: min = m.cron_minute() for job in min: k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB), 60*job[1], kronos.method.threaded, (), ()) except AttributeError: #no minute tasks pass try: hour = m.cron_hour() for job in hour: k.add_daytime_task(job[0], 'day task', range(1, 8), None, (job[1], r(H_LB, H_UB)), kronos.method.threaded, (), ()) except AttributeError: #no hour tasks pass except ImportError: #no cron jobs for this module pass ``` Edit: **Combining the suggestions from below, here's my rewritten form.** ``` for app in apps: if app.split('.', 1)[0] != 'zc': #only look for cron in zc apps continue try: a = app + '.cron' __import__(a) except ImportError: #no cron jobs for this module, continue to next one continue m = sys.modules[a] if hasattr(m, 'cron_minute'): min = m.cron_minute() for job in min: k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB), 60*job[1], kronos.method.threaded, (), ()) if hasattr(m, 'cron_hour'): hour = m.cron_hour() for job in hour: k.add_daytime_task(job[0], 'day task', range(1, 8), None, (job[1], r(H_LB, H_UB)), kronos.method.threaded, (), ()) ```
The main problem is that your try clauses are too broad, particularly the outermost one: with that kind of habit, you WILL sooner or later run into a mysterious bug because one of your try/except has accidentally hidden an unexpected exception "bubbling up" from some other function you're calling. So I'd suggest, instead: ``` for app in apps: if app.split('.', 1)[0] != 'zc': #only look for cron in zc apps continue try: a = app + '.cron' __import__(a) except ImportError: #no cron jobs for this module continue # etc etc ``` As an aside, I'm also applying "flat is better than nested" in another way (not dependent on any try/except) which is "if I have nothing more to do on this leg of the loop, continue [i.e. move on to the next leg of the loop] instead of "if I have something to do:" followed by a substantial amount of nested code. I've always preferred this style (of if/continue or if/return) to nested if's in languages that supply functionality such as `continue` (essentially all modern ones, since C has it;-). But this is a simple "flat vs nested" style preference, and the meat of the issue is: *keep your try clauses small*! Worst case, when you just can't simply continue or return in the except clause, you can use try/except/else: put in the try clause only what absolutely MUST be there -- the tiny piece of code that's likely and expected to raise -- and put the rest of the following code (the part that's NOT supposed nor expected to raise) in the else clause. This doesn't change the nesting, but DOES make a huge difference in lowering the risk of accidentally hiding exceptions that are NOT expected!
I wonder, if the jobs for each time unit is actually broken, would they raise an AttibuteError, or some other exception? In particular, if there's something about a job that is really busted, you probably aught not to catch them. Another option that can help is to wrap only the offending code with a try-catch, putting the exception handler as close to the exception as possible. Here's a stab: ``` for app in apps: if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps try: a = app + '.cron' __import__(a) m = sys.modules[a] except ImportError: #no cron jobs for this module #exception is silently ignored #since no jobs is not an error continue if hasattr(m, "cron_minute"): min = m.cron_minute() for job in min: k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB), 60*job[1], kronos.method.threaded, (), ()) if hasattr(m, "cron_hour"): hour = m.cron_hour() for job in hour: k.add_daytime_task(job[0], 'day task', range(1, 8), None, (job[1], r(H_LB, H_UB)), kronos.method.threaded, (), ()) ``` notice there is only one exception handler here, which we handle by correctly ignoring. since we can predict the possibility of there not being one attribute or another, we check for it explicitly, which helps to make the code a bit clearer. Otherwise, it's not really obvious why you are catching the AttributeError, or what is even raising it.
Cleaning up nested Try/Excepts
[ "", "python", "" ]
Is it possible to have 2 different jQuery versions in the same document, and have them to not collide with each other? For example if I create a bookmarklet and want to base the code on jQuery. This bookmarklet is injected on some page that uses another version of jQuery then my code would overwrite the version used on the page. Is it possible to avoid that? Or are there some other libraries that provides this functionality Or maybe I should rethink the whole thing. Thanks for answers and pointers, bob
jQuery comes with a way to avoid collisions. After you load the first version, you can assign it to a different variable. ``` var $j = jQuery.noConflict(); ``` And then load your second jQuery version. The first one you load can be accessed with $j(...) while the second one can be accessed with $(...). Alternatively, somebody made a [little helper](https://www.adaptavist.com/display/~mgibson/Versions) in an attempt to make it easier to switch between different versions.
Here is a way to detect is JQuery is already present: [jQuery in widget](https://stackoverflow.com/questions/587751/jquery-in-widget) Work out the oldest version of JQuery your code will work with.. And refuse to work if the version present is too old. Only a few people will miss out, most sites using JQuery are pretty up to date..
Two jQuery versions on the same page
[ "", "javascript", "jquery", "" ]
I use the enum to make a few constants: ``` enum ids {OPEN, CLOSE}; ``` the OPEN value is zero, but I want it as 100. Is it possible?
Java enums are not like C or C++ enums, which are really just labels for integers. Java enums are implemented more like classes - and they can even have multiple attributes. ``` public enum Ids { OPEN(100), CLOSE(200); private final int id; Ids(int id) { this.id = id; } public int getValue() { return id; } } ``` The big difference is that they are *type-safe* which means you don't have to worry about assigning a COLOR enum to a SIZE variable. See <http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html> for more.
Yes. You can pass the numerical values to the constructor for the enum, like so: ``` enum Ids { OPEN(100), CLOSE(200); private int value; private Ids(int value) { this.value = value; } public int getValue() { return value; } } ``` See the [Sun Java Language Guide](http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html) for more information.
Can I set enum start value in Java?
[ "", "java", "enums", "" ]
I'm trying to make a regex for taking some data out of a table. the code i've got now is: ``` <table> <tr> <td>quote1</td> <td>have you trying it off and on again ?</td> </tr> <tr> <td>quote65</td> <td>You wouldn't steal a helmet of a policeman</td> </tr> </table> ``` This I want to replace by: quote1:have you trying it off and on again ? quote65:You wouldn't steal a helmet of a policeman the code that I already have written is this: ``` %<td>((?s).*?)</td>% ``` But now I'm stuck.
Tim's regex probably works, but you may want to consider using the DOM functionality of PHP instead of regex, as it may be more reliable in dealing with minor changes in the markup. See [the loadHTML method](http://fi.php.net/manual/en/domdocument.loadhtml.php)
If you really want to use regexes (might be OK if you are really really sure your string will always be formatted like that), what about something like this, in your case : ``` $str = <<<A <table> <tr> <td>quote1</td> <td>have you trying it off and on again ?</td> </tr> <tr> <td>quote65</td> <td>You wouldn't steal a helmet of a policeman</td> </tr> </table> A; $matches = array(); preg_match_all('#<tr>\s+?<td>(.*?)</td>\s+?<td>(.*?)</td>\s+?</tr>#', $str, $matches); var_dump($matches); ``` A few words about the regex : * `<tr>` * then any number of spaces * then `<td>` * then what you want to capture * then `</td>` * and the same again * and finally, `</tr>` And I use : * `?` in the regex to match in non-greedy mode * `preg_match_all` to get all the matches You then get the results you want in `$matches[1]` and `$matches[2]` *(not `$matches[0]`)* ; here's the output of the `var_dump` I used *(I've remove entry 0, to make it shorter)* : ``` array 0 => ... 1 => array 0 => string 'quote1' (length=6) 1 => string 'quote65' (length=7) 2 => array 0 => string 'have you trying it off and on again ?' (length=37) 1 => string 'You wouldn't steal a helmet of a policeman' (length=42) ``` You then just need to manipulate this array, with some strings concatenation or the like ; for instance, like this : ``` $num = count($matches[1]); for ($i=0 ; $i<$num ; $i++) { echo $matches[1][$i] . ':' . $matches[2][$i] . '<br />'; } ``` And you get : ``` quote1:have you trying it off and on again ? quote65:You wouldn't steal a helmet of a policeman ``` Note : you should add some security checks *(like `preg_match_all` must return true, count must be at least 1, ...)* As a side note : **using regex to parse HTML is generally not a really good idea** ; if you can use a real parser, it should be way safer...
php regex to extract data from HTML table
[ "", "php", "html", "regex", "html-parsing", "" ]
I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code: ``` A = "10000" B = "10000" C = "100" + "00" D = "%i"%10000 E = str(10000) F = str(10000) G = str(100) + "00" H = "0".join(("10","00")) for obj in (A,B,C,D,E,F,G,H): print obj, id(obj), obj is A ``` prints: ``` 10000 4959776 True 10000 4959776 True 10000 4959776 True 10000 4959776 True 10000 4959456 False 10000 4959488 False 10000 4959520 False 10000 4959680 False ``` I don't even see the pattern - save for the fact that the first four don't have an explicit function call - but surely that can't be it, since the "`+`" in C for example implies a function call to **add**. I especially don't understand why C and G are different, seeing as that implies that the ids of the components of the addition are more important than the outcome. So, what is the special treatment that A-D undergo, making them come out as the same instance?
In terms of language specification, any compliant Python compiler and runtime is fully allowed, for any instance of an immutable type, to make a new instance OR find an existing instance of the same type that's equal to the required value and use a new reference to that same instance. This means it's always incorrect to use `is` or by-id comparison among immutables, and any minor release may tweak or change strategy in this matter to enhance optimization. In terms of implementations, the tradeoff are pretty clear: trying to reuse an existing instance may mean time spent (perhaps wasted) trying to find such an instance, but if the attempt succeeds then some memory is saved (as well as the time to allocate and later free the memory bits needed to hold a new instance). How to solve those implementation tradeoffs is not entirely obvious -- if you can identify heuristics that indicate that finding a suitable existing instance is likely and the search (even if it fails) will be fast, then you may want to attempt the search-and-reuse when the heuristics suggest it, but skip it otherwise. In your observations you seem to have found a particular dot-release implementation that performs a modicum of peephole optimization when that's entirely safe, fast, and simple, so the assignments A to D all boil down to exactly the same as A (but E to F don't, as they involve named functions or methods that the optimizer's authors may reasonably have considered not 100% safe to assume semantics for -- and low-ROI if that was done -- so they're not peephole-optimized). Thus, A to D reusing the same instance boils down to A and B doing so (as C and D get peephole-optimized to exactly the same construct). That reuse, in turn, clearly suggests compiler tactics/optimizer heuristics whereby identical literal constants of an immutable type in the same function's local namespace are collapsed to references to just one instance in the function's `.func_code.co_consts` (to use current CPython's terminology for attributes of functions and code objects) -- reasonable tactics and heuristics, as reuse of the same immutable constant literal within one function are somewhat frequent, AND the price is only paid once (at compile time) while the advantage is accrued many times (every time the function runs, maybe within loops etc etc). (It so happens that these specific tactics and heuristics, given their clearly-positive tradeoffs, have been pervasive in all recent versions of CPython, and, I believe, IronPython, Jython, and PyPy as well;-). This is a somewhat worthy and interesting are of study if you're planning to write compilers, runtime environments, peephole optimizers, etc etc, for Python itself or similar languages. I guess that deep study of the internals (ideally of many different correct implementations, of course, so as not to fixate on the quirks of a specific one -- good thing Python currently enjoys at least 4 separate production-worthy implementations, not to mention several versions of each!) can also help, indirectly, make one a better Python programmer -- but it's particularly important to focus on what's *guaranteed* by the language itself, which is somewhat less than what you'll find in common among separate implementations, because the parts that "just happen" to be in common right now (without being *required* to be so by the language specs) may perfectly well change under you at the next point release of one or another implementation and, if your production code was mistakenly relying on such details, that might cause nasty surprises;-). Plus -- it's hardly ever necessary, or even particularly helpful, to rely on such variable implementation details rather than on language-mandated behavior (unless you're coding something like an optimizer, debugger, profiler, or the like, of course;-).
Python is allowed to inline string constants; A,B,C,D are actually the same literals (if Python sees a constant expression, it treats it as a constant). `str` is actually a class, so `str(whatever)` is calling this class' constructor, which should yield a fresh object. This explains E,F,G (note that each of these has separate identity). As for H, I am not sure, but I'd go for explanation that this expression is too complicated for Python to figure out it's actually a constant, so it computes a new string.
A question regarding string instance uniqueness in python
[ "", "python", "string", "instance", "uniqueidentifier", "" ]
I have a few lists that are displayed as inline-blocks, creating the illusion of rows. Unlike tables, I cannot format rows straightforwardly. I want to apply a background color to each < li > in the row when one is hovered over. Is this possible through CSS and names/IDs? Thanks. Mike CLARIFICATION: After reading the answers, I realized my question was unclear. I have 3 lists, side by side, so the first < li > in each list would represent the first row. The second < li > in each list would be the second row. And so on.
Cross-browser support with jQuery: CSS: ``` li:hover { background-color: #F00 } ``` And for IE6 -- since it does not support the :hover pseudo-class on anything but <a> elements -- you serve it the following in your IE6-specific style sheets and script: CSS: ``` li.hover { background-color: #F00 } ``` JS: ``` $("li").hover( function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); } ); ```
Not sure if I understand correctly, but this fairly simple solution should do the trick: ``` li:hover { background-color: pink; } ``` Some browsers do not support the hover pseudo class though.
How can I apply a background-color to several elements on hover?
[ "", "javascript", "html", "css", "" ]
I was wondering if there was a way to not execute my subquery if my @ID1 is NULL? ``` CREATE PROCEDURE [dbo].[TestTable_Search] @Col1 int, @Col2 uniqueidentifier, @Col3 datetime, @Col4 datetime, @ID1 varchar(10) AS SET TRANSACTION ISOLATION LEVEL READ COMMITTED SELECT * FROM [dbo].[TestTable] WHERE [Col1] = COALESCE(@Col1, Col1) AND [Col2] = COALESCE(@Col2, Col2) AND [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND [Col5] IN (SELECT [ID2] FROM [dbo].[TestTable2] WHERE [ID1] = @ID1) ```
Not sure of your meaning, but maybe this is what you're looking for: ``` SELECT * FROM [dbo].[TestTable] WHERE [Col1] = COALESCE(@Col1, Col1) AND [Col2] = COALESCE(@Col2, Col2) AND [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND ( @ID1 IS NULL OR [Col5] IN (SELECT [ID2] FROM [dbo].[TestTable2] WHERE [ID1] = @ID1)) ```
`SQL Server` is not very good in handling `OR` conditions, especially on variables, that's why this probably will be the best decision: ``` SELECT * FROM [dbo].[TestTable] WHERE [Col1] = COALESCE(@Col1, Col1) AND [Col2] = COALESCE(@Col2, Col2) AND [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND AND @id1 IS NULL UNION ALL SELECT * FROM [dbo].[TestTable] WHERE [Col1] = COALESCE(@Col1, Col1) AND [Col2] = COALESCE(@Col2, Col2) AND [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND [Col5] IN (SELECT [ID2] FROM [dbo].[TestTable2] WHERE [ID1] = @ID1) ``` If `@id` is not `NULL`, the first subquery will return nothing because of the filter. If `@id` is `NULL`, the second subquery will return nothing, because the comparison to a `NULL` never matches, the inner subquery will return an empty set, and `col5 IN (SELECT …)` will be never satisfied. `SQL Server` can efficiently detect these things in runtime, that's why either the first of the second subquery will be optimized out almost instantly. See this article in my blog for performance comparison of `OR` against `UNION ALL`: * [**`IN` with a comma separated list: `SQL Server`**](http://explainextended.com/2009/06/23/in-with-a-comma-separated-list-sql-server/)
SQL Sub Query NO execute if null
[ "", "asp.net", "sql", "stored-procedures", "" ]
Can the default destructor be generated as a virtual destructor automatically? If I define a base class but no default destructor, is there a default virtual destructor generated automatically?
No. There is a cost associated with making a method virtual, and C++ has a philosophy of not making you pay for things that you don't explicitly state that you want to use. If a virtual destructor would have been generated automatically, you would have been paying the price automatically. Why not just define an empty virtual destructor?
In C++ 11 you can use: ``` class MyClass { // create a virtual, default destructor virtual ~MyClass() = default; }; ```
Can the default destructor be generated as a virtual destructor automatically?
[ "", "c++", "destructor", "" ]
After reading already asked question on the subject and a lot of googling I am still not able to have a clear view of **-Xms** option My question is: what's the difference between `java -Xms=512m -Xmx=512m` and `java -Xms=64m -Xmx=512m`? For now I have the following answer: The only difference is in the number of garbage collections that will be run during my application's run and the number of memory allocations. Am I right ? Here are my reasons for this answer: Setting the `-Xms` option to `512m` doesn't result in my application using really `512M` of physical memory after startup. I guess this is related to modern OS virtual memory management and lazy pages allocations. (I noticed that setting `-Xms` to `512M` or to `64M` doesn't change at all the initial used memory reported either by top on Linux or by the task manager on windows) Can someone help me to understand the impact of this `Xms` option or point me to links that will help me to understand it?
To summarize the information found after the link: The JVM allocates the amount specified by -Xms but the OS usually does not allocate real pages until they are needed. So the JVM allocates virtual memory as specified by Xms but only allocates physical memory as is needed. You can see this by using Process Explorer by Sysinternals instead of task manager on windows. So there is a real difference between using -Xms64M and -Xms512M. But I think the most important difference is the one you already pointed out: the garbage collector will run more often if you really need the 512MB but only started with 64MB.
The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory. So, * -Xms512m -Xmx512m JVM starts with 512 M, never resizes. * -Xms64m -Xmx512m JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.
JVM heap parameters
[ "", "java", "jvm-arguments", "" ]
within PHP (XAMPP) installed on a Windows XP Computer Im trying to read a dir which exists on a local network server. Im using `is_dir()` to check whether it is a dir that I can read. In Windows Explorer I type `\\\server\dir` and that dir is being shown. When I map a network drive a can access it with `z:\dir` as well. In PHP I have that script: ``` <?php if( is_dir($dir){ echo 'success' } ) ?> ``` For `$dir` I tried: * `/server/dir` * `//server/dir` * `\server\dir` * `\\server\dir` * `\\\\server\\dir` and * `z:\dir` * `z:\\dir` * `z:/dir` * `z://dir` But I never get success? Any idea? thx
I solved it by changing some stuff in the registry of the server as explained in the last answer of this discussion: <http://bugs.php.net/bug.php?id=25805> Thanks to VolkerK and Gumbo anyway! I love stackoverflow and their great people who help you so incredibly fast!! EDIT (taken from php.net): > The service has limited access to network resources, such as shares > and pipes, because it has no credentials and must connect using a null > session. The following registry key contains the NullSessionPipes and > NullSessionShares values, which are used to specify the pipes and > shares to which null sessions may connect: > HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters > Alternatively, you could add the REG\_DWORD value > RestrictNullSessAccess to the key and set it to 0 to allow all null > sessions to access all pipes and shares created on that machine.` add RestrictNullSessAccess=0 to your registery.
You probably let xampp install apache as service and run the php scripts trough this apache. And the apache service (running as [localsystem](http://msdn.microsoft.com/en-us/library/ms684190(VS.85).aspx)) is not allowed to access the network the way your user account is. > A service that runs in the context of the LocalSystem account inherits the security context of the SCM. The user SID is created from the SECURITY\_LOCAL\_SYSTEM\_RID value. *The account is not associated with any logged-on user account*. > This has several implications: > ... >    \* *The service presents the computer's credentials to remote servers*. > ... You can test this by starting the apache as console application (apache\_start.bat in the xampp directory should do that) and run the script again. You can use both forward and backward slashes in the unc path. I'd suggest using //server/share since php doesn't care about / in string literals. ``` <?php $uncpath = '//server/dir'; $dh = opendir($uncpath); echo "<pre>\n"; var_dump($dh, error_get_last()); echo "\n</pre>"; ```
php access network path under windows
[ "", "php", "networking", "path", "dir", "" ]
For a number of reasons, I have to use floats in my code instead of doubles. To use a literal in my code, I have to write something like: ``` float f = 0.75F; ``` or the compiler will barf since it treats just "0.75" as a double. Is there anything I can put in my code or set in Visual Studio that will make it treat a literal like "0.75" as a float without having to append an "F" every time?
Float comes with an F :-)
No - fortunately, IMO. Literals are treated the same way everywhere. This is a good thing - imagine some maintenance developer comes and looks at your code in a year's time. He sees "0.75" and thinks "I know C# - that's a double! Hang on, how is it being assigned to a float variable?" Ick. Is it really so painful to add the "F" everywhere? Do you really have *that* many constants? Could you extract them *as* constant values, so all your "F-suffixed" literals are in the same place.
Looking for an easier way to use floats in C#
[ "", "c#", ".net", "floating-point", "double", "" ]
I realize that you cannot iterate over a Dictionary in C# and edit the underlying Dictionary as in the following example: ``` Dictionary<Resource, double> totalCost = new Dictionary<Resource, double>(); // Populate the Dictionary in here - (not showing code). foreach (Resource resource in totalCost.Keys) { totalCost[resource] = 5; } ``` One way I see to fix this is to make a List backed by the Dictionary's keys, like this: ``` Dictionary<Resource, double> totalCost = new Dictionary<Resource, double>(); // Populate the Dictionary in here - (not showing code). foreach (Resource resource in new List(totalCost.Keys)) { totalCost[resource] = 5; } ``` Because I'm not editing the keys themselves, is there any reason that this should not be done or that it's bad to choose this as a solution. (I realize if I was editing those keys, this could cause a lot of problems.) Thank you. **Edit:** Fixed my code example. Sorry about that.
in your examples it doesn't look to me like you're editing the dictionary values (or keys)? In general your solution looks fine, you could do it with a bit less code like this: ``` List<double> total = new List<double>(); foreach (AKeyObject key in aDictionary.Keys.ToList()) { for (int i = 0; i < aDictionary[key].Count; i++) { total[i] += aDictionary[key][i]; } } ```
You can loop over dictionaries with using [KeyValuePair](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class. ``` Dictionary<string, string> d1 = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> val in d1) { ... } ```
Looping Over Dictionary in C#
[ "", "c#", "collections", "dictionary", "" ]
For my book class I'm storing an ISBN number and I need to validate the data entered so I decided to use enumeration. (First three inputs must be single digits, last one must be a letter or digit.) However, I'm wondering if it is even possible to enumerate numbers. Ive tried putting them in as regular integers, string style with double quotes, and char style with single quotes. Example: ``` class Book{ public: enum ISBN_begin{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; enum ISBN_last{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z}; ``` The compiler error says expected identifier which means that its seeing the numbers as values for the identifiers and not identifiers themselves. So is enumerating digits possible?
Why would you want to enumerate numbers? Enums exist to give numbers a name. If you want to store a number, store an integer - or in this case a char (as you also need characters to be stored). For validation, accept a string and write a function like this: ``` bool ISBN_Validate(string val) { if (!val.length == <length of ISBN>) return false; if (val[0] < '0' || val[0] > '9') return false; foreach (char ch in val) { if (ch is not between '0' and 'z') return false; } } ``` Easy - and no silly enumerations ;)
I think you're going about this the wrong way...why not just use a simple regex that will validate the entire thing a bit more simply? (yes, I know, that wasn't the original question, but it might make your life a lot easier.) [This page](http://regexadvice.com/blogs/dneimke/archive/2003/12/06/179.aspx) and [this page](http://www.geekzilla.co.uk/viewD8902276-CCD3-4B93-8D27-A7A1908D25D3.htm) provide some good examples on using regex to validate isbn numbers. I think creating an enumeration whose values are equal to the entities they're enumerating...I think you're doing a lot more than you have to.
Enumerating digits
[ "", "c++", "" ]
Is there a compiler or standalone preprocessor which takes C++ files and runs a template expansion pass, generating new C++ code with expanded template instantiations? I remember such a tool in the mid-90s when templates were still new and experimental, and the preprocessor was a way to do template programming with compilers without native template support. This is a lot more complicated than a macro-processing step since it would likely require parsing and tokenizing the code to understand the contexts. My hope is to use such a tool when writing OpenCL code. [OpenCL](http://en.wikipedia.org/wiki/OpenCL) is C++, but does not support templates. I'm hoping I can write templates, even simple ones like with integer or bool only arguments, and have some tool pre-parse the file and go through and find the use of the templates and expand the invocations and give me new C++ code that the OpenCL compiler **can** understand. Even a very limited tool could be useful, it does not need to support every template quirk, nor even support multiple modules or anything. The alternative: `#define` macros everywhere.. uglier, unsafe, less efficient, and less versatile.
[Comeau C++](http://www.comeaucomputing.com/) can "compile" C++ to C. This would seem to be close to your goal, as OpenCL does not support C++ – it's much closer to C.
C++ Insights (<https://cppinsights.io/>) is able to do this (and more generally expansion of "high-level" syntax-sugary C++ constructs. It is based on Clang so it has an understanding of the code which is as good as possible, and supports latest standards. It will for instance expand ``` extern "C" void printf(...); template<typename T> int foo(T t) { if constexpr(sizeof(T) == 4) { printf("int: %d", t); } else { printf("something else: %d", (int)t); } } int main() { const char arr[10]{2,4,6,8}; for(const char& c : arr) { foo(c); } } ``` into ``` extern "C" void printf(...); template<typename T> int foo(T t) { if constexpr(sizeof(T) == 4) { printf("int: %d", t); } else { printf("something else: %d", (int)t); } } /* First instantiated from: insights.cpp:19 */ #ifdef INSIGHTS_USE_TEMPLATE template<> int foo<char>(char t) { if constexpr(false) { } else /* constexpr */ { printf("something else: %d", static_cast<int>(t)); } } #endif int main() { const char arr[10] = {2, 4, 6, 8, '\0', '\0', '\0', '\0', '\0', '\0'}; { char const (&__range1)[10] = arr; const char * __begin1 = __range1; const char * __end1 = __range1 + 10L; for(; __begin1 != __end1; ++__begin1) { const char & c = *__begin1; foo(c); } } return 0; } ```
C++ Template preprocessor tool
[ "", "c++", "templates", "macros", "opencl", "c-preprocessor", "" ]
I have a list of rows from a dataset that I need to iterate through. The problem is that the processing in the iteration may delete one or more rows from the list. Since the list is being modified, I can't use a foreach() loop. But since it is possible some of the deletions may occur at elements BEFORE the one I'm processing, I also can't use a for() loop (i.e, if I'm processing element , and that results in the deletion of element and also other elements , I can't think of a way to adjust i to correctly point to the element following the one that I was processing). How would you tackle this problem? My current thought it is to always process the first element in the list. If it gets deleted, process the new first element. If it doesn't get deleted, the move it to an "alreadyProcessed" list, and process the new first element. Is there an easier way?
When modifying a list I'm iterating through, I always find it easiest to build a new list with the items I want to keep, and then use the new list to do whatever it was I was going to do. It really depends on what you're doing with the data when you're done, I suppose.
Typically this is done with a reverse loop: ``` List<string> Items = ... for(int i = Items.Count - 1; i >= 0; i--) { if(Items[i] == "DELETE ME") { Items.RemoveAt(i); } } ``` This causes the items to be processed in reverse order, so if you delete an item, it does not affect the position of any items still to be processed.
How to iterate through a list that is being modified?
[ "", "c#", "list", "iteration", "" ]
I have an `<img ... />` tag that I have bound a click event to in jQuery. When it is clicked I'd like to have it emulate the click of a button on the file upload to open the file system browse pop-up. I've tried these things within the click function and had no success: ``` ... $(".hiddenUploadBtn").click(); ... ... $(".hiddenUploadBtn").select(); ... ... $(".hiddenUploadBtn").submit(); ... ```
Just wrap the img in a label and set the for attribute to the file input. Works for any kind of content and it's built into the spec. You can even hide the file input at that point. ``` <input type="file" id="fileUpload"><br> <label for="fileUpload"> <img src="https://www.google.com/images/srpr/logo11w.png" /> </label> ```
Try this one using only javascript: <http://code.google.com/p/upload-at-click/> Demo: <http://upload-at-click.narod.ru/demo2.html>
Emulate a file upload click in jQuery
[ "", "javascript", "jquery", "events", "" ]
How can I get a list of strings from "A:" to "Z:" in C#? Something like this: ``` List<string> list = new List<string>(); for (int i = 0; i < 26; i++) { list.Add(string.Format("{0}:", Convert.ToChar('A' + i)); } ``` Sorry I don't have VS available for verification right now to verify. By the way, is there web site available to interactive test snip of codes?
Well, not counting missing ')' at the end of list.Ad.... line, everything is ok, altough you could write it using a bit shorter notation ``` list.Add((char)('A' + i) + ":"); ```
``` from ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" select ch + ":"; ```
C# codes to get a list of strings like A to Z?
[ "", "c#", "visual-studio-2005", "" ]
I'm designing a web site and I would like to be able to call a function 1 second after the last user input. I tried using onKeyUp, but it waited 1 second after the first keystroke. Does anyone know how would this be possible?
Another similar approach, without globals: ``` var typewatch = function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); } }(); ``` ... ``` <input type="text" onKeyUp="typewatch(function(){alert('Time elapsed!');}, 1000 );" /> ``` You can this snippet [here](http://jsbin.com/ugafe/edit).
You can use a `keyDown` (or `keyUp`) event that sets a function to run in 1 second and if the user types another key within that second, you can clear the timeout and set a new one. E.g. ``` var t; function keyDown() { if ( t ) { clearTimeout( t ); t = setTimeout( myCallback, 1000 ); } else { t = setTimeout( myCallback, 1000 ); } } function myCallback() { alert("It's been 1 second since you typed something"); } ```
How do I wait until the user has finished writing down in a text input to call a function?
[ "", "javascript", "html", "" ]
I'm lead dev for [Bitfighter](http://bitfighter.org), a game primarily written in C++, but using Lua to script robot players. We're using [Lunar](http://lua-users.org/wiki/CppBindingWithLunar) (a variant of Luna) to glue the bits together. I'm now wrestling with how our Lua scripts can know that an object they have a reference to has been deleted by the C++ code. Here is some sample robot code (in Lua): ``` if needTarget then -- needTarget => global(?) boolean ship = findClosest(findItems(ShipType)) -- ship => global lightUserData obj end if ship ~= nil then bot:setAngleToPoint(ship:getLoc()) bot:fire() end ``` Notice that ship is only set when needTarget is true, otherwise the value from a previous iteration is used. It is quite possible (likely, even, if the bot has been doing it's job :-) that the ship will have been killed (and its object deleted by C++) since the variable was last set. If so, C++ will have a fit when we call ship:getLoc(), and will usually crash. So the question is how to most elegantly handle the situation and limit the damage if (when) a programmer makes a mistake. I have some ideas. First, we could create some sort of Lua function that the C++ code can call when a ship or other item dies: ``` function itemDied(deaditem) if deaditem == ship then ship = nil needTarget = true end end ``` Second, we could implement some sort of reference counting smart pointer to "magically" fix the problem. But I would have no idea where to start with this. Third, we can have some sort of deadness detector (not sure how that would work) that bots could call like so: ``` if !isAlive(ship) then needTarget = true ship = nil -- superfluous, but here for clarity in this example end if needTarget then -- needTarget => global(?) boolean ship = findClosest(findItems(ShipType)) -- ship => global lightUserData obj end <...as before...> ``` Fourth, I could retain only the ID of the ship, rather than a reference, and use that to acquire the ship object each cycle, like this: ``` local ship = getShip(shipID) -- shipID => global ID if ship == nil then needTarget = true end if needTarget then -- needTarget => global(?) boolean ship = findClosest(findItems(ShipType)) -- ship => global lightUserData obj shipID = ship:getID() end <...as before...> ``` My ideal situation would also throw errors intelligently. If I ran the getLoc() method on a dead ship, I'd like to trigger error handling code to either give the bot a chance to recover, or at least allow the system to kill the robot and log the problem, hopefully cuing me to be more careful in how I code my bot. Those are my ideas. I'm leaning towards #1, but it feels clunky (and might involve lots of back and forth because we've got lots of short-lifecycle objects like bullets to contend with, most of which we won't be tracking). It might be easy to forget to implement the itemDied() function. #2 is appealing, because I like magic, but have no idea how it would work. #3 & #4 are very easy to understand, and I could limit my deadness detection only to the few objects that are interesting over the span of several game cycles (most likely a single ship). This has to be a common problem. What do you think of these ideas, and are there any better ones out there? Thanks! --- Here's my current best solution: In C++, my ship object is called Ship, whose lifecycle is controlled by C++. For each Ship, I create a proxy object, called a LuaShip, which contains a pointer to the Ship, and Ship contains a pointer to the LuaShip. In the Ship's destructor, I set the LuaShip's Ship pointer to NULL, which I use as an indicator that the ship has been destroyed. My Lua code only has a reference to the LuaShip, and so (theoretically, at least, as this part is still not working properly) Lua will control the lifecycle of the LuaShip once the corresponding Ship object is gone. So Lua will always have a valid handle, even after the Ship object is gone, and I can write proxy methods for the Ship methods that check for Ship being NULL. So now my task is to better understand how Luna/Lunar manages the lifecycle of pointers, and make sure that my LuaShips do not get deleted when their partner Ships get deleted if there is still some Lua code pointing at them. That should be very doable. --- Actually, it turned out not to be doable (at least not by me). What did seem to work was to decouple the Ship and the LuaShip objects a little. Now, when the Lua script requests a LuaShip object, I create a new one and hand it off to Lua, and let Lua delete it when it's done with it. The LuaShip uses a smart pointer to refer to the Ship, so when the Ship dies, that pointer gets set to NULL, which the LuaShip object can detect. It is up to the Lua coder to check that the Ship is still valid before using it. If they do not, I can trap the sitation and throw out an stern error message, rather than having the whole game crash (as was happening before). Now Lua has total control over the lifecyle of the LuaShip, C++ can delete Ships without causing problems, and everything seems to work smoothly. The only drawback is that I'm potentially creating a lot of LuaShip objects, but it's really not that bad. --- If you are interested in this topic, please see the mailing list thread I posted about a related concept, that ends in some suggestions for refining the above: [<http://lua-users.org/lists/lua-l/2009-07/msg00076.html>](http://lua-users.org/lists/lua-l/2009-07/msg00076.html)
I don't think you have a probelm on your Lua side, and you should not be solving it there. Your C++ code is deleting objects that are still being referenced. No matter how they're referenced, that's bad. The simple solution may be to let Lunar clean up all your objects. It already knows which objects must be kept alive because the script is using them, and it seems feasible to let it also do GC for random C++ objects (assuming smart pointers on the C++ side, of course - each smart pointer adds to Lunars reference count)
Our company went with solution number four, and it worked well for us. I recommend it. However, in the interests of completeness: Number 1 is solid. Let the ship's destructor invoke some Lunar code (or mark that it should be invoked, at any rate), and then complain if you can't find it. Doing things this way means that you'll have to be incredibly careful, and maybe hack the Lua runtime a bit, if you ever want to run the game engine and the robots in separate threads. Number 2 isn't as hard as you think: write or borrow a reference-counting pointer on the C++ side, and if your Lua/C++ glue is accustomed to dealing with C++ pointers it'll probably work without further intervention, unless you're generating bindings by inspecting symbol tables at runtime or something. The trouble is, it'll force a pretty profound change in your design; if you're using reference-counted pointers to refer to ships, you have to use them everywhere - the risks inherent in referring to ships with a mixture of bare pointers and smart ones should be obvious. So I wouldn't go that route, not as late in the project as you seem to be. Number 3 is tricky. You need a way to determine whether a given ship object is alive or dead even after the memory representing it has been freed. All the solutions I can think of for that problem basically devolve into number 4: you can let dead ships leave behind some kind of token that's copied into the Lua object and can be used to detect deadness (you'd keep dead objects in a std::set or something similar), but then why not just refer to ships by their tokens? In general, you can't detect whether a particular C++ pointer points to an object that's been deleted, so there's no easy magical way to solve your problem. Trapping the error of calling `ship:getLoc()` on a deleted ship is possible only if you take special action in the destructor. There's no perfect solution to this problem, so good luck.
Detecting stale C++ references in Lua
[ "", "c++", "lua", "" ]
Quite often on SO I find myself benchmarking small chunks of code to see which implemnetation is fastest. Quite often I see comments that benchmarking code does not take into account jitting or the garbage collector. I have the following simple benchmarking function which I have slowly evolved: ``` static void Profile(string description, int iterations, Action func) { // warm up func(); // clean up GC.Collect(); var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < iterations; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds); } ``` Usage: ``` Profile("a descriptions", how_many_iterations_to_run, () => { // ... code being profiled }); ``` Does this implementation have any flaws? Is it good enough to show that implementaion X is faster than implementation Y over Z iterations? Can you think of any ways you would improve this? **EDIT** Its pretty clear that a time based approach (as opposed to iterations), is preferred, does anyone have any implementations where the time checks do not impact performance?
Here is the modified function: as recommended by the community, feel free to amend this its a community wiki. ``` static double Profile(string description, int iterations, Action func) { //Run at highest priority to minimize fluctuations caused by other processes/threads Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; Thread.CurrentThread.Priority = ThreadPriority.Highest; // warm up func(); var watch = new Stopwatch(); // clean up GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); watch.Start(); for (int i = 0; i < iterations; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds); return watch.Elapsed.TotalMilliseconds; } ``` Make sure you **compile in Release with optimizations enabled, and run the tests outside of Visual Studio**. This last part is important because the JIT stints its optimizations with a debugger attached, even in Release mode.
Finalisation won't necessarily be completed before `GC.Collect` returns. The finalisation is queued and then run on a separate thread. This thread could still be active during your tests, affecting the results. If you want to ensure that finalisation has completed before starting your tests then you might want to call [`GC.WaitForPendingFinalizers`](http://msdn.microsoft.com/en-us/library/system.gc.waitforpendingfinalizers.aspx), which will block until the finalisation queue is cleared: ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ```
Benchmarking small code samples in C#, can this implementation be improved?
[ "", "c#", ".net", "performance", "profiling", "" ]
I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation. For example, you could type in 'two days ago' or 'tomorrow' and it would understand. Any libraries to suggest? Bonus points if usable from Python.
See my [SO answer](https://stackoverflow.com/questions/552073/whats-the-best-way-to-make-a-time-from-today-or-yesterday-and-a-time-in-pyth/552229#552229) for links to three Python date parsing libraries. The one of these most commonly used is [python-dateutils](http://labix.org/python-dateutil) but unfortunately it can't handle all formats.
Perhaps you are thinking of PHP's `strtotime()` function, the [Swiss Army Knife of date parsing](http://brian.moonspot.net/2008/09/20/strtotime-the-php-date-swiss-army-knife/): > Man, what did I do before `strtotime()`. Oh, I know, I had a 482 line function to parse date formats and return timestamps. And I still could not do really cool stuff. Like tonight I needed to figure out when Thanksgiving was in the US. I knew it was the 4th Thursday in November. So, I started with some math stuff and checking what day of the week Nov. 1 would fall on. All that was making my head hurt. So, I just tried this for fun. > > ``` > strtotime("thursday, november ".date("Y")." + 3 weeks") > ``` > > That gives me Thanksgiving. Awesome. Sadly, there does not appear to be a Python equivalent. The closest thing I could find is the [`dateutil.parser`](http://labix.org/python-dateutil) module.
Smart date interpretation
[ "", "python", "date-parsing", "" ]
I have an asp.net mvc 1.0 site that serves some content from a 2 level hierarchy /category/article When things work right the article maps to a view and the view gets rendered. However, when the url meets the routing condition but the view doesn't exist an exception is raised that I can't trap in the Controller action. Routing: ``` routes.MapRoute( "Article", "{category}/{article}.aspx", new { controller = "MyController", action = "Article" } ); ``` MyController Action: ``` public ActionResult Article(string category, string article) { string path = string.Format("~/Views/{0}/{1}.aspx", category, article); ViewResult vr = View(path); return vr; } ``` However, when the view is not found, a `System.InvalidOperationException` is generated that I can't catch in the Controller Action. > Exception Details: System.InvalidOperationException: The view > '~/Views/my-category/my-article-with-long-name.aspx' or its master > could not be found. The following locations were searched: > ~/Views/my-category/my-article-with-long-name.aspx I can trap the error in the `Application_Error()` method in `global.asax.cs` but: 1. don't know how to redirect to the error view from there 2. wonder if there is a better place closer to where the exception is raised.
xandy, Greg, I appreciate your answers. This article ([Strategies For Resource Based 404 Errors in aspnet mvc](http://richarddingwall.name/2008/08/17/strategies-for-resource-based-404-errors-in-aspnet-mvc/)) helped me derive the solution I was looking for in a pretty clean way. All I need to do is override Controller.OnException. Since I only have one controller where I need the behavior I only have to override OnException in that controller. That being said, my solution treats the symptoms not the disease and as both of you suggest, it would be better to check for the file's existence before invoking this.View on a path. Here is the code I used to treat the symptoms :) ``` protected override void OnException(ExceptionContext filterContext) { //InvalidOperationException is thrown if the path to the view // cannot be resolved by the viewengine if (filterContext.Exception is InvalidOperationException) { filterContext.ExceptionHandled = true; filterContext.Result = View("~/Views/Error/NotFound.aspx"); filterContext.HttpContext.Response.StatusCode = 404; } base.OnException(filterContext); } ``` One issue I couldn't resolve is how to display the NotFound View in a clean way. It is usually accessed via the ErrorController NotFound Action. I had to hardcode the path to it. I can live with this but would like to know if it is possible w/o the HC path.
There is a suitable place to handle this. If you implement your own ViewEngine, you can override the "FileExists" method. ``` public class ViewEngine : RazorViewEngine { protected override bool FileExists(ControllerContext context, string path) { if(!base.FileExists(context, path)) throw new NotFoundException(); return true; } ``` } You just need to register the view engine in your Global.asax like so, ``` ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new ViewEngine()); ``` In Application\_Error you can implement a handler that catches NotFoundExceptions, logs them, then returns a friendly message via executing an ErrorController.
How to handle 'View not found' InvalidOperationException in asp.net mvc?
[ "", "c#", "asp.net-mvc", "" ]
I'm working on a Python tool to convert image data into these color formats: * RGB565 * RGBA5551 * RGBA4444. What's the simplest way to achieve this? I've used the [Python Imaging Library (PIL)](http://www.pythonware.com/products/pil/) frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point. Is there an easier way? Perhaps some type of 'formatter' plugin for PIL? Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code. Or is there a better library than PIL to accomplish this in Python? Any tips would be appreciated. Thanks!
I ended up doing the conversions manually as Lennart Regebro suggested. However, pure Python (iterating over each pixel) turned out to be too slow. My final solution used [PIL](https://python-pillow.org/) to load the image and [numpy](https://numpy.org/) to operate on (convert) an array of pixels.
Changing something from 8 to 5 bits is trivial. In 8 bits the value is between 0 and 255, in 5 bits it's between 0 and 31, so all you need to do is divide the value with 8. Or 4 in the case for green in RGB565 mode. Or 16 in RGBA4444 mode as it uses 4 bits per channel, etc. Edit: Reading through your question again, I think there is a confusion (either with me or you). RGB555 and RGBA4444 etc are not really formats, like GIF or JPG, they are color spaces. That conversion is trivial (see above). What file format you want to save it in later is another question. Most file formats have limited support for color spaces. I think for example that JPEG always saves it in YCbCr (but I could be mistaken), GIF uses a palette (which in turn always is RGB888, I think) etc.
Using Python to convert color formats?
[ "", "python", "" ]
in vb I can do that ``` sub SetFocusControl(byref ctl as object) ctl.Focus end sub ``` in c# the compiler complaint that object doesn't have a Focus method ``` void SetFocusControl(ref object ctl) { ctl.Focus(); } ``` how can I do the same in c#? thanks
Instead of using object, use the type that has the Focus method. ``` void SetFocusControl(Control ctl) { ctl.Focus(); } ``` And I don't think you need the ref. I'd also ask whether you need a separate method. Could you not just call the Focus method directly? ``` ctl.Focus(); ``` If you don't know the type or if it has a Focus method you could do this. ``` void SetFocusControl(object ctl) { Control control = ctl as Control if (null == control) return; control.Focus(); } ```
Javier- you should read about [why C# is statically typed](https://stackoverflow.com/questions/859186/why-is-c-statically-typed).
calling a method over variable of type object in vb and c#
[ "", "c#", "vb.net", "" ]
I have a small problem. How do I set a cookie for multiple domains? I do understand the security problems, and I am sure it has been done before. The reason for this is SSO. ie. `account.domain.com` will need to set domain logged in for: domain.com, domain1.com, domain2.com. Is there any easy way, using PHP and cookies, or any alternatives?
There is absolutely no way for domain.com to set a cookie for domain1.com. What you are attempting to do can only be solved by getting the user's browser to submit requests to each domain which will then set its own cookie. Then you need a way for each domain to verify the user's identity. There are two approaches to this: 1. Back channel - the sites contact each other directly to determine if a user is logged in. 2. Passing a token in the GET or POST - when the user's broweser is redirected to the other site a digitally signed parameter is passed containing the identity and session status. It's really quite complicated. I suggest you don't roll your own. Take a look at [SimpleSAMLPHP](http://rnd.feide.no/simplesamlphp) for a PHP implementation of what I'm describing.
What you're attempting can't be done. (It's a browser security issue, not a PHP one.) Other than using some form of off-site authentication, the nearest you can achieve is making a cookie accessible across sub-domains, in which case you just use the optional 'domain' arg of PHP's [set\_cookie](http://www.php.net/set_cookie) function.
Cross domain cookies
[ "", "php", "authentication", "cookies", "single-sign-on", "" ]