Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the unfortunate task of having to import data from excel into a database on a regular basis. The table looks something like this: ``` IssueID References 1234 DocID1<cr>DocID2<cr>DocID3 1235 DocID1 1236 DocID2 1237 DocID2<cr>DocID3 ``` References is a multi-line text field. What I'm trying to do is create a Docs table with one-to-many relationship to the Issue table, rather than having these multi-line references. I have the following tables defined: Issue: IssueKey, IssueID, IssueFields Doc: DocKey, DocID, DocRev, DocOwner, etc DocLink: LinkKey, DocKey, IssueKey Since this will be run repeatedly, the Doc table will already exist with the DocIDs defined. So, what I want to do is have a query or VBA code search for each DocID in the References column and add a link based on IssueID if one does not already exist. Simple, Right? Jeff Clarifications: 1) I had a third column called "Val1" to show that there were other columns, but that seemed to confuse the issue. There are actually many (way to many, most ignored) columns in the source table, but I only care about the two above. 2) I don't have to parse for a delimiter or anything too paranoid: References contains one or more uniquely defined document reference numbers (stored as text). So, a LIKE filter will turn up the list of IssueIDs on a case by case basis. 3) Here is an example of acceptable output: ``` IssueID References 1234 DocID1 1234 DocID2 1234 DocID3 1235 DocID1 1236 DocID2 1237 DocID2 1237 DocID3 ``` The ideal solution would take the original excel table (top) and these two tables: ``` IssueKey IssueID 1 1234 2 1235 3 1236 4 1237 DocKey DocID 1 DocID1 2 DocID2 3 DocID3 ``` And populate/update the link table: ``` LinkKey IssueKey DocKey 1 1 1 2 1 2 3 1 3 4 2 1 5 3 2 6 3 3 ``` 4) Here is an example of what I expected for a solution (creates #3 above). Unfortunately it crashes Access, so I can't tell if the syntax is correct (edited to reflect field names above). ``` SELECT Q1.IssueID, D1.DocID FROM Docs AS D1, Issues AS Q1 WHERE Q1.IssueID IN ((SELECT Q2.IssueID from Issues AS Q2 where (Q2.References) Like D1.DocID)); ``` 5) Giving up on Access for the moment, I've got the following working in MySQL: ``` SELECT Q1.IssueID, D1.DocID FROM Docs AS D1, Issues AS Q1 WHERE Q1.IssueID IN ((SELECT Q2.IssueID from Issues AS Q2 where (Q2.References) Like '%DocID1%')); ``` This works as I'd expect - I get every IssueID with a Reference to DocID1, repeated for every Doc in the table. With the above data it would look like: ``` IssueID References 1234 DocID1 1234 DocID2 1234 DocID3 1235 DocID1 1235 DocID2 1235 DocID3 ``` Now I just want to replace the '%DocID1%' with '%'+D1.DocID+'%' - limiting the results to those document IDs which actually have a match. For some reason I'm getting zero records when I do this - I think I have the syntax for putting wildcards on the correlated field wrong. 6) The following works to provide #3 above in MySQL, but the same query translated to access crashes it: ``` SELECT Q1.IssueID, D1.DocID FROM Docs AS D1, Issues AS Q1 WHERE Q1.IssueID IN ((SELECT Q2.IssueID from Issues AS Q2 where (Q2.References) Like CONCAT('%',D1.DocID,'%'))); ``` [in access it becomes ('*' & D1.DocID & '*')] Conclusion: Access sucks
I think using the word "parse" in the title has confused the crap out of everyone. The bug in Access was that a correlated query performed on a query (instead of a table) causes a hang. So instead, I created a temporary table that ads the References column (with the multi-line text) to the Issues table so I have access to the other fields. The final query creates the link table described above, along with the DocID and IssueID for reference: ``` SELECT Q1.IssueID, Q1.IssueKey, D1.DocKey, D1.DocID FROM Issues AS Q1, Documents AS D1 WHERE Q1.IssueID in (SELECT Q2.IssueID FROM Issues AS Q2 WHERE Q2.References LIKE ("*" & D1.DocID & "*")); ``` The inner select pulls the list of issues which has a given document in the references column. The outer select performs this for each document, resulting in the aggregate list.
This has been chosen as the answer: ``` Q2.References LIKE ("*" & D1.DocID & "*")); ``` However, I don't think this is safe. Consider if one of the value for the column named 'References' contained this data: ``` DocID1<cr>DocID999<cr>DocID3 ``` and a value `DocID = 9` existed in the other table. The problem here is that ``` "DocID1<cr>DocID999<cr>DocID3" LIKE "*" & "DocID9" & "*" ``` will evaluate to `TRUE`, which is probably undesirable. To address this problem, I think the values in the search/join condition should be made safe by surrounding the values using the delimiter character e.g. ``` (CHR(13) & Q2.References & CHR(13)) LIKE ("*" & CHR(13) & D1.DocID & CHR(13) & "*")); ```
SQL for parsing multi-line data?
[ "", "sql", "mysql", "excel", "ms-access", "vba", "" ]
I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python: ``` import socket import sys HOST = ??????? PORT = 80 # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) data,addr = sock.recv(1024) print "Received: %s" % data print "Addr: %s" % addr ``` What should I use as host? I know the IP of the sender but it seems anything thats not local gives me socket.error: [Errno 10049]. The IP that the VPN gives me (the same IP that the sender sends to, that is)? Or just localhost?
The host argument is the host IP you want to bind to. Specify the IP of one of your interfaces (Eg, your public IP, or 127.0.0.1 for localhost), or use 0.0.0.0 to bind to all interfaces. If you bind to a specific interface, your service will only be available on that interface - for example, if you want to run something that can only be accessed via localhost, or if you have multiple IPs and need to run different servers on each.
"0.0.0.0" will listen for all incoming hosts. For example, ``` sock.bind(("0.0.0.0", 999)) data,addr = sock.recv(1024) ```
What host to use when making a UDP socket in python?
[ "", "python", "sockets", "udp", "" ]
I am looking for a way to add parameters on a print function, because I have to print only the table and when I alert the table it shows me the correct value but when I'm printing it prints the entire page. My code is ``` aa = document.getElementById('tablename').innerHTML ``` If I `alert(aa)` it gives me the write value then I `print(aa)` it give me the entire page. so I tried `print(aa)` and `aa.print` and it doesn't work. Does anyone know the solution for this?
Print stylesheets are nice, but you can still accomplish this in Javascript. Just pass your value to be printed to the following function... ``` function printIt(printThis) { var win = window.open(); self.focus(); win.document.open(); win.document.write('<'+'html'+'><'+'body'+'>'); win.document.write(printThis); win.document.write('<'+'/body'+'><'+'/html'+'>'); win.document.close(); win.print(); win.close(); } ```
Define a print stylesheet which will only display the table. * <http://www.webcredible.co.uk/user-friendly-resources/css/print-stylesheet.shtml> * <http://www.alistapart.com/articles/goingtoprint/> There's no need for it to be dynamic. Simply define those sections you don't wan to see as display:none (as stated in the alistapart article)
Can you add parameters inside a print() function in javascript
[ "", "javascript", "" ]
I want to write a standalone application with IOC, how do I use springs dependency injection in there? I'm using JIdea. There is spring 2.5 support but I want to use spring 3.0 here is the way I tried! > I experience in using Spring MVC we can inject dependencies there in a WebApplicationContext but how do I inject dependencies in a standalone application I tried this > `ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"com\\ttg\\xmlfile.xml"});` but I cannot see that the dependencies are injected by the beans defined there (in the XML file) I put the above code in the main method and two bean definitions for two Objects,in one Java class's constructor I used the other class's object - which was injected to this object - and called a method on that which will print some thing but it didn't worked I thought that the above code creates all the dependencies and injects them but it doesn't seem like that > How do I properly use Springs IOC, dependency injection in my stand alone app which does not contain a WebApplicationContext? Please mention steps.
suppose you have: ``` class Bean1 { Bean2 bean2; } class Bean2 { String data; } ``` the context.xml file ``` <bean id="bean1" class="Bean1"> <property name="bean2" ref="bean2" /> </bean> <bean id="bean2" class="Bean2" /> ``` then this should be true ``` ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"context.xml"}); Bean1 bean1 = (Bean1) context.getBean("bean1"); // bean1.bean2 should not be null here. ```
you can use autowiring support provided by spring, in order to inject dependencies (and possibly apply post processors) to an object that is not part of the application context. In your case, this object is your standalone application. Here is the way to achieve this. In this example, I use @Autowired (for b1), traditional DI (for b2) and initialization hook for b3. The autowiring support with annotations assumes you have defined the appropriate spring post-processor in your application context (e.g. by declaring `<context:annotation-config/>`). ``` public class StandaloneApp implements InitializingBean { @Autowired private Bean1 b1; private Bean2 b2; private Bean3 b3; public void afterPropertiesSet() throws Exception { this.b3 = new Bean3(b1, b2); } public void setB2(Bean2 b2) { this.b2 = b2; } public static void main(String... args) { String[] locations = // your files relative to the classpath ApplicationContext ac = new ClasspathXmlApplicationContext(locations); // or use FileSystemXmlApplicationContext if the files are not in the classpath StandaloneApp app = new StandaloneApp(); AutowireCapableBeanFactory acbf = ac.getAutowireCapableBeanFactory(); acbf.autowireBeanProperties(app, AUTOWIRE_BY_NAME, false); acbf.initializeBean(app, "standaloneApp"); // any name will work } } ``` In this example, all b1, b2 and b3 should be non-null (assuming b1 and b2 beans exist in your application context). I haven't tested it (might not even compile due to some typo), but the idea is in the last 3 lines. See the javadocs for `AutowireCapableBeanFactory` and mentionned methods to see exactly what happens.
Spring- How to use Spring Dependency Injection to write a Standalone Java Application
[ "", "java", "dependency-injection", "inversion-of-control", "spring", "" ]
I'm in the process of rewriting a Perl-based web crawler I wrote nearly 8 years ago in PHP. I used the quite handy URI::URL module in perl to do things like: ``` $sourceUrl = '/blah.html'; $baseHost = 'http://www.example.com'; my $url = URI::URL->new($sourceUrl, $baseHost); return $url->abs; ``` returns: '<http://www.example.com/blah.html>' the parse\_url function in PHP is quite handy, but is there something more robust? Specifically something that will give the above functionality?
Maybe [Zend\_Uri](http://framework.zend.com/manual/en/zend.uri.html) is what you are looking for?
``` print $baseHost . $sourceURL; ``` Am I missing something? Your way seems needlessly overcomplicated.
PHP Equivalent to Perl's URI::URL
[ "", "php", "url", "" ]
I've recently found the need to check at *compile-time* whether either: a) a certain assembly reference exists and can be successfully resolved, or b) a certain class (whose fully qualified name is known) is defined. These two situations are equivalent for my purposes, so being able to check for one of them would be good enough. Is there any way to do this in .NET/C#? Preprocessor directives initially struck me as something that might help, but it seems it doesn't have the necessary capability. Of course, checking for the existence of a type at runtime can be done easily enough, but unfortunately that won't resolve my particular problem in this situation. (I need to be able to ignore the fact that a certain reference is missing and thus fall-back to another approach in code.)
I seem to have found a solution here, albeit not precisely for what I was initially hoping. **My Solution:** What I ended up doing is creating a new build configuration and then defining a precompiler constant, which I used in code to determine whether to use the reference, or to fall back to the alternative (guaranteed to work) approach. It's not fully automatic, but it's relatively simple and seems quite elegant - good enough for my purposes. **Alternative:** If you wanted to fully automate this, it could be done using a pre-build command that runs a Batch script/small program to check the availabilty of a given reference on the machine and then updates a file containing precompiler constants. This however I considered more effort than it was worth, though it may have been more useful if I had multiple independent references that I need to resolve (check availability).
Is there a reason you can't add a reference and then use a typeof expression on a type from the assembly to verify it's available? ``` var x = typeof(SomeTypeInSomeAssembly); ``` If the assembly containing SomeTypeInSomeAssembly is not referenced and available this will not compile.
Checking for the existence a reference/type at compile time in .NET
[ "", "c#", ".net", "types", "reference", "compile-time", "" ]
I need to do something like: ``` SELECT value_column1 FROM table1 WHERE datetime_column1 >= '2009-01-01 00:00:00' ORDER BY datetime_column1; ``` Except in addition to `value_column1`, I also need to retrieve a [moving average](http://en.wikipedia.org/wiki/Moving_average) of the previous 20 values of `value_column1`. Standard SQL is preferred, but I will use MySQL extensions if necessary.
This is just off the top of my head, and I'm on the way out the door, so it's untested. I also can't imagine that it would perform very well on any kind of large data set. I did confirm that it at least runs without an error though. :) ``` SELECT value_column1, ( SELECT AVG(value_column1) AS moving_average FROM Table1 T2 WHERE ( SELECT COUNT(*) FROM Table1 T3 WHERE date_column1 BETWEEN T2.date_column1 AND T1.date_column1 ) BETWEEN 1 AND 20 ) FROM Table1 T1 ```
Tom H's approach will work. You can simplify it like this if you have an identity column: ``` SELECT T1.id, T1.value_column1, avg(T2.value_column1) FROM table1 T1 INNER JOIN table1 T2 ON T2.Id BETWEEN T1.Id-19 AND T1.Id ```
How do I calculate a moving average using MySQL?
[ "", "sql", "mysql", "statistics", "" ]
I'm trying to get the process handle of, say example.exe, so I can call `TerminateProcess` on it. How can I do this? Notice, it doesn't have a window so `FindWindow` won't work.
``` #include <cstdio> #include <windows.h> #include <tlhelp32.h> int main( int, char *[] ) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, "target.exe") == 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Do stuff.. CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; } ``` Also, if you'd like to use PROCESS\_ALL\_ACCESS in OpenProcess, you could try this: ``` #include <cstdio> #include <windows.h> #include <tlhelp32.h> void EnableDebugPriv() { HANDLE hToken; LUID luid; TOKEN_PRIVILEGES tkp; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = luid; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL); CloseHandle(hToken); } int main( int, char *[] ) { EnableDebugPriv(); PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, "target.exe") == 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Do stuff.. CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; } ```
The following code shows how you can use toolhelp and OpenProcess to get a handle to the process. Error handling removed for brevity. ``` HANDLE GetProcessByName(PCSTR name) { DWORD pid = 0; // Create toolhelp snapshot. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 process; ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(process); // Walkthrough all processes. if (Process32First(snapshot, &process)) { do { // Compare process.szExeFile based on format of name, i.e., trim file path // trim .exe if necessary, etc. if (string(process.szExeFile) == string(name)) { pid = process.th32ProcessID; break; } } while (Process32Next(snapshot, &process)); } CloseHandle(snapshot); if (pid != 0) { return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); } // Not found return NULL; } ```
How can I get a process handle by its name in C++?
[ "", "c++", "winapi", "process", "" ]
One of the disadventage I found in WPF is it doesnot have a Numeric UpDown control. So I make a listbox with height as 25 so that it will display only one item at a time and the vertical scroll feels like a UpDown controls. My problem is when I use the scroll to change the value, I can't get the current value shown in listbox. Can any idea to get the value shown in listbox without selecting it?
Though there's no standard WPF NumericUpDown, you can try [NumericUpDown Custom Control with Theme and UI Automation Support Sample](http://msdn.microsoft.com/en-us/library/ms771573.aspx).
The Extented WPF Toolkit has one: [NumericUpDown](http://wpftoolkit.codeplex.com/wikipage?title=NumericUpDown&referringTitle=Home) ![enter image description here](https://i.stack.imgur.com/KbVoa.png)
ListBox as Numeric UpDown control in WPF
[ "", "c#", ".net", "wpf", "listbox", "" ]
In our code, we have a 16-byte packed `struct` that we call "ISOTIME": ``` typedef struct isotime { struct { uint16_t iso_zone : 12; // corresponding time zone uint16_t iso_type : 4; // type of iso date } iso_fmt; int16_t iso_year; // year uint8_t iso_month; // month uint8_t iso_day; // day uint8_t iso_hour; // hour uint8_t iso_minute; // minute uint8_t iso_second; // second uint8_t iso_centi; // centi-second uint8_t iso_hundred; // hundreds of micro-seconds uint8_t iso_micro; // micro-seconds uint32_t iso_unused; // pad out to 16 bytes } ISOTIME; ``` I'm trying to figure out what standard that this is supposed to be implementing. Anyone have a clue? My Google-fu is failing me.
International standards rarely concern themselves with detailed in-memory representations of data , particularly at the bit level (exceptions of course for floating point standards). This is because such things are inherently unportable. That's not to say that there is no standard for this structure, but I think it unlikely.
As Gary Ray says, the main standard for interchange of date and time data is ISO 8601:2004. The data structure shown can handle the standard Gregorian calendar with time resolution to microseconds. There are other standards of relevance - ISO/IEC 9899:1999 (C) for example. It defines a different structure and specifies the encoding of years (year number - 1900 is stored in the tm\_year element, for example; also, month numbers run from 0 for January to 11 for December - good for indexing into an array of month names but lousy otherwise). POSIX (ISO/IEC 9945-1:2008) inherits its time handling from the C standard. SQL (ISO/IEC 9075-2:2008) works more closely with ISO 8601 than with C/POSIX. But the structure shown could be used in any of these environments - though it is not standard in the C/POSIX environment.
What standard does this "ISOTIME" structure represent?
[ "", "c++", "datetime", "data-structures", "timezone", "" ]
I've been struggling to find a nice algorithm to change a number (could be a float or integer) into a nicely formated human readable number showing the units as a string. For example: ``` 100500000 -> '100.5 Mil' 200400 -> '200.4 K' 143000000 -> '143 Mil' 52000000000 -> '52 Bil' ``` etc, you get the idea. Any pointers?
I'd adapt the code below (which i found on the net): Code credit goes to this link i found: <http://www.phpfront.com/php/human-readable-byte-format/> ``` function humanReadableOctets($octets) { $units = array('B', 'kB', 'MB', 'GB', 'TB'); // ...etc for ($i = 0, $size =$octets; $size>1024; $size=$size/1024) $i++; return number_format($size, 2) . ' ' . $units[min($i, count($units) -1 )]; } ``` Don't forget to change 1024 to 1000 though ...
``` <?php function prettyNumber($number) // $number is int / float { $orders = Array("", " K", " Mil", " Bil"); $order=0; while (($number/1000.0) >= 1.5) { // while the next step up would generate a number greater than 1.5 $order++; $number/=1000.0; } if ($order) return preg_replace("/\.?0+$/", "", substr(number_format($number, 2),0,5)).$orders[$order]; return $number; } $tests = array(100500000,200400,143000000,52000000000); foreach ($tests as $test) { echo $test." -> '".prettyNumber($test)."'\n"; } ```
Nice PHP algorithm to convert 120000000 into '120 mil'?
[ "", "php", "algorithm", "formatting", "numbers", "" ]
I guess I'm getting this error because the string is trying to substring a `null` value. But wouldn't the `".length() > 0"` part eliminate that issue? Here is the Java snippet: ``` if (itemdescription.length() > 0) { pstmt2.setString(3, itemdescription.substring(0,38)); } else { pstmt2.setString(3, "_"); } ``` I got this error: ``` java.lang.StringIndexOutOfBoundsException: String index out of range: 38 at java.lang.String.substring(Unknown Source) at MASInsert2.itemimport(MASInsert2.java:192) at MASInsert2.processRequest(MASInsert2.java:125) at MASInsert2.doGet(MASInsert2.java:219) at javax.servlet.http.HttpServlet.service(HttpServlet.java:627) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:835) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:640) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1286) at java.lang.Thread.run(Unknown Source) ```
> I"m guessing i'm getting this error > because the string is trying to > substring a Null value. But wouldn't > the ".length() > 0" part eliminate > that issue? No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on **null**. As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate): ``` final String value; if (itemdescription == null || itemdescription.length() <= 0) { value = "_"; } else if (itemdescription.length() <= 38) { value = itemdescription; } else { value = itemdescription.substring(0, 38); } pstmt2.setString(3, value); ``` Might be a good place for a utility function if you do that a lot...
It is a pity that `substring` is not implemented in a way that handles short strings – like in other languages e.g. Python. Ok, we cannot change that and have to consider this edge case every time we use `substr`, instead of if-else clauses I would go for this shorter variant: ``` myText.substring(0, Math.min(6, myText.length())) ```
Java substring: 'String index out of range'
[ "", "java", "string", "substring", "indexoutofboundsexception", "string-length", "" ]
I need to determine the version of SQL Server (2000, 2005 or 2008 in this particular case) that a connection string connects a C# console application (.NET 2.0). Can anyone provide any guidance on this? Thanks, MagicAndi **Update** I would like to be able to determine the SQL Server version form the ADO.NET connection object if possible.
This code will determine the version of SQL Server database being used - 2000, 2005 or 2008: ``` try { SqlConnection sqlConnection = new SqlConnection(connectionString); Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection)); switch (server.Information.Version.Major) { case 8: MessageBox.Show("SQL Server 2000"); break; case 9: MessageBox.Show("SQL Server 2005"); break; case 10: MessageBox.Show("SQL Server 2008"); break; default: MessageBox.Show(string.Format("SQL Server {0}", server.Information.Version.Major.ToString())); break; } } catch (Microsoft.SqlServer.Management.Common.ConnectionFailureException) { MessageBox.Show("Unable to connect to server", "Invalid Server", MessageBoxButtons.OK, MessageBoxIcon.Error); } ``` The code below will do the same, this time using [NinthSense's](https://stackoverflow.com/users/73722/ninethsense) answer: ``` try { SqlConnection sqlConnection = new SqlConnection(connectionString); sqlConnection.Open(); string serverVersion = sqlConnection.ServerVersion; string[] serverVersionDetails = serverVersion.Split( new string[] {"."}, StringSplitOptions.None); int versionNumber = int.Parse(serverVersionDetails[0]); switch (versionNumber) { case 8: MessageBox.Show("SQL Server 2000"); break; case 9: MessageBox.Show("SQL Server 2005"); break; case 10: MessageBox.Show("SQL Server 2008"); break; default: MessageBox.Show(string.Format("SQL Server {0}", versionNumber.ToString())); break; } } catch (Exception ex) { MessageBox.Show(string.Format("Unable to connect to server due to exception: {1}", ex.Message), "Invalid Connection!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { sqlConnection.Close(); } ```
``` SqlConnection con = new SqlConnection("Server=localhost;Database=test;user=admin;password=123456;"); con.Open(); Text = con.ServerVersion; con.Close(); ``` **con.ServerVersion** will give you: * 9.x.x for SQL Server 2005 * 10.x.x for SQL Server 2008
Determine version of SQL Server from ADO.NET
[ "", "c#", ".net", "sql-server", "ado.net", ".net-2.0", "" ]
I'm new to programming and I'm starting to create a simple notepad, with only 4 buttons (Open, Save, New and Font). If I open or save I'm getting an error. This is my code: ``` //Declare save as a new SaveFileDailog SaveFileDialog save = new SaveFileDialog(); //Declare filename as a String equal to the SaveFileDialog's FileName String filename = save.FileName; //Declare filter as a String equal to our wanted SaveFileDialog Filter String filter = "Text Files|*.txt|All Files|*.*"; //Set the SaveFileDialog's Filter to filter save.Filter = filter; //Set the title of the SaveFileDialog to Save save.Title = "Save"; //Show the SaveFileDialog if (save.ShowDialog(this) == DialogResult.OK) { //Write all of the text in txtBox to the specified file System.IO.File.WriteAllText(filename, textBox1.Text); } else { //Return return; }//Declare save as a new SaveFileDailog SaveFileDialog save = new SaveFileDialog(); //Declare filename as a String equal to the SaveFileDialog's FileName String filename = save.FileName; //Declare filter as a String equal to our wanted SaveFileDialog Filter String filter = "Text Files|*.txt|All Files|*.*"; //Set the SaveFileDialog's Filter to filter save.Filter = filter; //Set the title of the SaveFileDialog to Save save.Title = "Save"; //Show the SaveFileDialog if (save.ShowDialog(this) == DialogResult.OK) { //Write all of the text in txtBox to the specified file System.IO.File.WriteAllText(filename, textBox1.Text); } else { //Return return; } ``` ## Update Here is the error: > Error: ArgumentException was unhandled. > Empty path name is not legal I get this if I open a text file. Then it highlighted this line code: `textBox1.Text=System.IO.File.ReadAllText(filename,System.Text.Encoding.Default)`. And if I save nothing happens.
I expect you should be reading the filename *after* the user has used the dialog: ``` System.IO.File.WriteAllText(save.FileName, textBox1.Text); ``` Also - `SaveFileDialog` is `IDisposable`, so you should be "`using`" it... ``` using (SaveFileDialog save = new SaveFileDialog()) { // your code that involves "save" } ```
Try moving the line ``` String filename = save.FileName; ``` inside the IF block. You are assigning to filename *before* the SaveDialog's property is set by the user. You need to understand that this line does not create a permanent link between your `filename` variable and the `FileName` property of the dialog.
C# notepad program throws "Empty path name is not legal"
[ "", "c#", "" ]
Does VB.NET have the equivalent of C#'s `lock` statement?
Yes, the [SyncLock](http://msdn.microsoft.com/en-us/library/3a86s51t.aspx) statement. For example: ``` // C# lock (someLock) { list.Add(someItem); } // VB SyncLock someLock list.Add(someItem) End SyncLock ```
It is called SyncLock example: ``` Sub IncrementWebCount() SyncLock objMyLock intWebHits += 1 Console.WriteLine(intWebHits) End SyncLock End Sub ```
Is there a lock statement in VB.NET?
[ "", "c#", "vb.net", "" ]
I'm writing an export function, where I need to export contacts to Excel, and I've run into a technical snag - or perhaps a gap in my SQL skills is closer to the truth. ;) Here's the scenario: I've got a bunch of contacts in a database. Each contact can have many different roles, for example a contact can be both C# Developer and DBA, or DBA and IT-manager. These are split into three tables, like so: ``` ------------------- ------------------- ------------------- * Contact * * ContactRole * * Role * ------------------- ------------------- ------------------- * ID * * ContactID * * ID * * Name * * RoleID * * Name * * Address * ------------------- ------------------- ------------------- ``` Not too hard to follow. There's a set of contacts, and a set of roles. These are joined by the ContactRole table on the respective IDs. When I export the contacts, I need to have a column in the export with all the roles comma separated, like `C# Developer, DBA` or `DBA, IT-manager`. The export will be done from ASP.NET/C# codebehind, so I figured I could do this in code should it come to that, but I've got a feeling it's possible to do in the SQL. The data comes from SQL Server 2005.
Try this ``` declare @Roles nvarchar(max) select @Roles = case when @Roles is null then '' else @Roles + ', ' end + Role.Name from Role inner join ContactRole on Role.ID = ContactRole.RoleID where ContactRole.ContactID = @ContactID select @Roles ``` update: Above code covers functionality for a single contact. You can create a scalar function with parameter @ContactID and call the function from a ``` Select Name, dbo.GetContactRoles(ID) From Contact ```
Just because you use SQL Server 2005 (and if you are lucky and have all XML settings properly set), here is your simple SQL query (pure SQL and no functions): ``` SELECT c.ID, c.Name, c.Address, ( SELECT r.Name + ',' FROM "ContactRole" cr INNER JOIN "Role" r ON cr.RoleID = r.ID WHERE cr.ContactID = c.ID ORDER BY r.ID --r.Name FOR XML PATH('') ) AS "Roles" FROM "Contact" c ``` To test if it works for you, just execute the whole snippet below: ``` WITH "Contact" (ID, Name, Address) AS ( SELECT 1, 'p1-no role', NULL UNION ALL SELECT 2, 'p2-one role', NULL UNION ALL SELECT 3, 'p3-two roles', NULL ) , "Role" (ID, Name)AS ( SELECT 1, 'teacher' UNION ALL SELECT 2, 'student' ) , "ContactRole" (ContactID, RoleID) AS ( SELECT 2, 1 UNION ALL SELECT 3, 1 UNION ALL SELECT 3, 2 ) SELECT c.ID, c.Name, c.Address, ( SELECT r.Name + ',' FROM "ContactRole" cr INNER JOIN "Role" r ON cr.RoleID = r.ID WHERE cr.ContactID = c.ID ORDER BY r.ID --r.Name FOR XML PATH('') ) AS "Roles" FROM "Contact" c ``` and you should get the following result: ``` ID Name Address Roles ----------- ------------ ----------- ------------------ 1 p1-no role NULL NULL 2 p2-one role NULL teacher, 3 p3-two roles NULL teacher,student, ```
TSQL Comma Separation
[ "", "sql", "sql-server", "t-sql", "" ]
Assuming I have the following tables. ``` PARENT: PARENT_ID serial, DESCRIPTION character varying(50) CHILD: PARENT_ID integer, CHILD_ID integer, DESCRIPTION character varying(50) ``` What I would like to see is each row in CHILD having a CHILD\_ID that starts at 1 and increments by 1, unique per PARENT\_ID. It would be similar to a revision number. For example.. ``` PARENT_ID 1, CHILD_ID 1 PARENT_ID 1, CHILD_ID 2 PARENT_ID 1, CHILD_ID 3 PARENT_ID 2, CHILD_ID 1 PARENT_ID 3, CHILD_ID 1 PARENT_ID 3, CHILD_ID 2 ``` Is there any way to have the CHILD\_ID value assigned automatically, such as a sequence or constraint, only with the ability to reuse a CHILD\_ID that has been deleted? The only way I can figure out is something to the effect of this SQL. ``` INSERT INTO child SELECT parent_id, MAX(child_id)+1, 'description' FROM child WHERE parent_id = :PARENT_ID GROUP BY parent_id ``` That's a bit of a hack though. I realize that database normalization suggests you should not have one key related to another, but I don't have that option for some other reasons. Any ideas? **EDIT:** The title's ugly. If any of you high-scoring folks can think of one that's more accurate, please feel free to change it.
I'd suggest using: ``` CHILD: PARENT_ID integer, CHILD_ID serial, DESCRIPTION character varying(50) ``` When you need to get a desired result: * You can count rows on client side. * When selecting rows where PARENT\_ID=? you can use temporary sequence. * In soon to be released Postgresql 8.4 you can use windowing functions like this: ``` $ create table child (parent_id integer, child_id serial); NOTICE: CREATE TABLE will create implicit sequence "child_child_id_seq" for serial column "child.child_id" CREATE TABLE $ insert into child (parent_id) values (1), (1), (1), (2), (3), (3); $ select * from child; parent_id | child_id -----------+---------- 1 | 1 1 | 2 1 | 3 2 | 4 3 | 5 3 | 6 (6 rows) $ select parent_id, row_number() over (partition by parent_id order by child_id) from child; parent_id | row_number -----------+------ 1 | 1 1 | 2 1 | 3 2 | 1 3 | 1 3 | 2 (6 rows) ``` It is very fast, easy to implement and will scale very well as there will be no concurrency issues to worry about.
That insert isn't the whole story though. You'll also need to handle deletes to close the gap that was created if you really want the numbers to be contiguous. My suggestion would be to derive this value as you need it. What determines the order of the number? If it's the date entered into the system then add that date to your table and put your PK over the parent\_id and that date, then you can pretty easily come up with the number either through SQL or in the front end as you need it.
How do you create an auto-incrementing revision number unique to a key in PGSQL?
[ "", "sql", "postgresql", "sequence", "constraints", "" ]
I'm writing a simple control in C# that works like a picture box, except the image is constantly scrolling upwards (and re-appearing from the bottom). The animation effect is driven by a timer (System.Threading.Timer) which copies from the cached image (in two parts) to a hidden buffer, which is then drawn to the control's surface in its Paint event. The problem is that this scrolling animation effect is slightly jerky when run at a high frame rate of 20+ frames per second (at lower frame rates the effect is too small to be perceived). I suspect that this jerkiness is because the animation is not synchronized in any way with my monitor's refresh rate, which means that each frame stays on the screen for a variable length of time instead of for exactly 25 milliseconds. Is there any way I can get this animation to scroll smoothly? You can download a sample application [here](http://www.musigenesis.com/TestApp.exe) (run it and click "start"), and the source code is [here](http://www.musigenesis.com/TestApp.zip). It doesn't look horribly jerky, but if you look at it closely you can see the hiccups. **WARNING**: this animation produces a pretty weird optical illusion effect which might make you a little sick. If you watch it for awhile and then turn it off, it will look as if your screen is stretching itself vertically. **UPDATE**: as an experiment, I tried creating an AVI file with my scrolling bitmaps. The result was less jerky than my WinForms animation, but still unacceptable (and it still made me sick to my stomach to watch it for too long). I think I'm running into a fundamental problem of not being synced with the refresh rate, so I may have to stick to making people sick with my looks and personality.
You would need to wait for a [VSYNC](http://de.wikipedia.org/wiki/Vertikale_Synchronisation) before you draw the buffered image. There is a [CodeProject article](http://www.codeproject.com/KB/GDI/tearingfreedrawing.aspx) that suggests using a multimedia timer and DirectX' method [`IDirectDraw::GetScanLine()`](http://msdn.microsoft.com/en-us/library/aa911301.aspx). I'm quite sure you can use that method via [Managed DirectX](http://msdn.microsoft.com/en-us/directx/default.aspx) from C#. **EDIT:** After some more research and googling I come to the conclusion that drawing via GDI doesn't happen in realtime and even if you're drawing in the exact right moment it might actually happen too late and you will have tearing. So, with GDI this seems not to be possible.
(<http://www.vcskicks.com/animated-windows-form.html>) This link has an animation and they explain the way they accomplish it. There is also a sample project that you can download to see it in action.
How can I get rid of jerkiness in WinForms scrolling animation?
[ "", "c#", "graphics", "animation", "" ]
There are different calling conventions available in C/C++: `stdcall`, `extern`, `pascal`, etc. How many such calling conventions are available, and what do each mean? Are there any links that describe these?
Simple answer: **I use cdecl, stdcall, and fastcall. I seldom use fastcall. stdcall is used to call Windows API functions.** Detailed answer (Stolen from [Wikipedia](https://en.wikipedia.org/wiki/X86_calling_conventions)): **cdecl** - In cdecl, subroutine arguments are passed on the stack. Integer values and memory addresses are returned in the EAX register, floating point values in the ST0 x87 register. Registers EAX, ECX, and EDX are caller-saved, and the rest are callee-saved. The x87 floating point registers ST0 to ST7 must be empty (popped or freed) when calling a new function, and ST1 to ST7 must be empty on exiting a function. ST0 must also be empty when not used for returning a value. **syscall** - This is similar to cdecl in that arguments are pushed right-to-left. EAX, ECX, and EDX are not preserved. The size of the parameter list in doublewords is passed in AL. **pascal** - the parameters are pushed on the stack in left-to-right order (opposite of cdecl), and the callee is responsible for balancing the stack before return. **stdcall** - The stdcall[4] calling convention is a variation on the Pascal calling convention in which the callee is responsible for cleaning up the stack, but the parameters are pushed onto the stack in right-to-left order, as in the \_cdecl calling convention. Registers EAX, ECX, and EDX are designated for use within the function. Return values are stored in the EAX register. **fastcall** - \_\_fastcall convention (aka \_\_msfastcall) passes the first two arguments (evaluated left to right) that fit into ECX and EDX. Remaining arguments are pushed onto the stack from right to left. **vectorcall** - In Visual Studio 2013, Microsoft introduced the \_\_vectorcall calling convention in response to efficiency concerns from game, graphic, video/audio, and codec developers.[7] For IA-32 and x64 code, \_\_vectorcall is similar to \_\_fastcall and the original x64 calling conventions respectively, but extends them to support passing vector arguments using SIMD registers. For x64, when any of the first six arguments are vector types (float, double, \_\_m128, \_\_m256, etc.), they are passed in via the corresponding XMM/YMM registers. Similarly for IA-32, up to six XMM/YMM registers are allocated sequentially for vector type arguments from left to right regardless of position. Additionally, \_\_vectorcall adds support for passing homogeneous vector aggregate (HVA) values, which are composite types consisting solely of up to four identical vector types, using the same six registers. Once the registers have been allocated for vector type arguments, the unused registers are allocated to HVA arguments from left to right regardless of position. Resulting vector type and HVA values are returned using the first four XMM/YMM registers. **safecall** - n Delphi and Free Pascal on Microsoft Windows, the safecall calling convention encapsulates COM (Component Object Model) error handling, thus exceptions aren't leaked out to the caller, but are reported in the HRESULT return value, as required by COM/OLE. When calling a safecall function from Delphi code, Delphi also automatically checks the returned HRESULT and raises an exception if necessary. The safecall calling convention is the same as the stdcall calling convention, except that exceptions are passed back to the caller in EAX as a HResult (instead of in FS:[0]), while the function result is passed by reference on the stack as though it were a final "out" parameter. When calling a Delphi function from Delphi this calling convention will appear just like any other calling convention, because although exceptions are passed back in EAX, they are automatically converted back to proper exceptions by the caller. When using COM objects created in other languages, the HResults will be automatically raised as exceptions, and the result for Get functions is in the result rather than a parameter. When creating COM objects in Delphi with safecall, there is no need to worry about HResults, as exceptions can be raised as normal but will be seen as HResults in other languages. **Microsoft X64 Calling Convention** - The Microsoft x64 calling convention[12][13] is followed on Windows and pre-boot UEFI (for long mode on x86-64). It uses registers RCX, RDX, R8, R9 for the first four integer or pointer arguments (in that order), and XMM0, XMM1, XMM2, XMM3 are used for floating point arguments. Additional arguments are pushed onto the stack (right to left). Integer return values (similar to x86) are returned in RAX if 64 bits or less. Floating point return values are returned in XMM0. Parameters less than 64 bits long are not zero extended; the high bits are not zeroed. When compiling for the x64 architecture in a Windows context (whether using Microsoft or non-Microsoft tools), there is only one calling convention – the one described here, so that stdcall, thiscall, cdecl, fastcall, etc., are now all one and the same. In the Microsoft x64 calling convention, it is the caller's responsibility to allocate 32 bytes of "shadow space" on the stack right before calling the function (regardless of the actual number of parameters used), and to pop the stack after the call. The shadow space is used to spill RCX, RDX, R8, and R9,[14] but must be made available to all functions, even those with fewer than four parameters. The registers RAX, RCX, RDX, R8, R9, R10, R11 are considered volatile (caller-saved).[15] The registers RBX, RBP, RDI, RSI, RSP, R12, R13, R14, and R15 are considered nonvolatile (callee-saved).[15] For example, a function taking 5 integer arguments will take the first to fourth in registers, and the fifth will be pushed on the top of the shadow space. So when the called function is entered, the stack will be composed of (in ascending order) the return address, followed by the shadow space (32 bytes) followed by the fifth parameter. In x86-64, Visual Studio 2008 stores floating point numbers in XMM6 and XMM7 (as well as XMM8 through XMM15); consequently, for x86-64, user-written assembly language routines must preserve XMM6 and XMM7 (as compared to x86 wherein user-written assembly language routines did not need to preserve XMM6 and XMM7). In other words, user-written assembly language routines must be updated to save/restore XMM6 and XMM7 before/after the function when being ported from x86 to x86-64.
Neither Standard C nor Standard C++ has such a concept - these are features of specific compilers, linkers and/or operating systems, so you should really indicate which specific technologies you are interested in.
What are the different calling conventions in C/C++ and what do each mean?
[ "", "c++", "c", "winapi", "visual-c++", "calling-convention", "" ]
How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.
``` import imaplib obj = imaplib.IMAP4_SSL('imap.gmail.com','993') obj.login('username','password') obj.select() obj.search(None,'UnSeen') ```
I advise you to use [Gmail atom feed](https://developers.google.com/gmail/gmail_inbox_feed) It is as simple as this: ``` import urllib url = 'https://mail.google.com/mail/feed/atom/' opener = urllib.FancyURLopener() f = opener.open(url) feed = f.read() ``` You can then use the feed parse function in this nice article: [Check Gmail the pythonic way](http://g33k.wordpress.com/2006/07/31/check-gmail-the-python-way/)
Check unread count of Gmail messages with Python
[ "", "python", "email", "gmail", "imap", "" ]
I have a homework assignment to write a multi-threaded sudoku solver, which finds all solutions to a given puzzle. I have previously written a very fast single-threaded backtracking sudoku solver, so I don't need any help with the sudoku solving aspect. My problem is probably related to not really grokking concurrency, but I don't see how this problem benefits from multi-threading. I don't understand how you can find different solutions to the same problem at the same time without maintaining multiple copies of the puzzle. Given this assumption (please prove it wrong), I don't see how the multi-threaded solution is any more efficient than a single-threaded. I would appreciate it if anyone could give me some starting suggestions for the algorithm (please, no code...) --- I forgot to mention, the number of threads to be used is specified as an argument to the program, so as far as I can tell it's not related to the state of the puzzle in any way... Also, there may not be a unique solution - a valid input may be a totally empty board. I have to report `min(1000, number of solutions)` and display one of them (if it exists)
Pretty simple really. The basic concept is that in your backtracking solution you would branch when there was a choice. You tried one branch, backtracked and then tried the other choice. Now, spawn a thread for each choice and try them both simultaneously. Only spawn a new thread if there are < some number of threads already in the system (that would be your input argument), otherwise just use a simple (i.e your existing) single-threaded solution. For added efficiency, get these worker threads from a thread pool. This is in many ways a divide and conquer technique, you are using the choices as an opportunity to split the search space in half and allocate one half to each thread. Most likely one half is harder than the other meaning thread lifetimes will vary but that is what makes the optimisation interesting. The easy way to handle the obvious syncronisation issues is to to copy the current board state and pass it into each instance of your function, so it is a function argument. This copying will mean you don't have to worry about any shared concurrency. If your single-threaded solution used a global or member variable to store the board state, you will need a copy of this either on the stack (easy) or per thread (harder). All your function needs to return is a board state and a number of moves taken to reach it. Each routine that invokes several threads to do work should invoke n-1 threads when there are n pieces of work, do the nth piece of work and then wait with a syncronisation object until all the other threads are finished. You then evaluate their results - you have n board states, return the one with the least number of moves.
Multi-threading is useful in any situation where a single thread has to wait for a resource and you can run another thread in the meantime. This includes a thread waiting for an I/O request or database access while another thread continues with CPU work. Multi-threading is also useful *if* the individual threads can be farmed out to diffent CPUs (or cores) as they then run truly concurrently, although they'll generally have to share data so there'll still be some contention. I can't see any reason why a multi-threaded Sudoku solver would be more efficient than a single-threaded one, simply because there's no waiting for resources. Everything will be done in memory. But I remember some of the homework I did at Uni, and it was similarly useless (Fortran code to see how deep a tunnel got when you dug down at 30 degrees for one mile then 15 degrees for another mile - yes, I'm pretty old :-). The point is to show you can do it, not that it's useful. On to the algorithm. I wrote a single threaded solver which basically ran a series of rules in each pass to try and populate another square. A sample rule was: if row 1 only has one square free, the number is evident from all the other numbers in row 1. There were similar rules for all rows, all columns, all 3x3 mini-grids. There were also rules which checked row/column intersects (e.g. if a given square could only contain 3 or 4 due to the row and 4 or 7 due to the column, then it was 4). There were more complex rules I won't detail here but they're basically the same way you solve it manually. I suspect you have similar rules in your implementation (since other than brute force, I can think of no other way to solve it, and if you've used brute force, there's no hope for you :-). What I would suggest is to allocate each rule to a thread and have them share the grid. Each thread would do it's own rule and only that rule. **Update:** Jon, based on your edit: > [edit] I forgot to mention, the number of threads to be used is specified as an argument to the program, so as far as I can tell it's not related to the state of the puzzle in any way... > > Also, there may not be a unique solution - a valid input may be a totally empty board. I have to report min(1000, number of solutions) and display one of them (if it exists) It looks like your teacher doesn't want you to split based on the rules but instead on the fork-points (where multiple rules could apply). By that I mean, at any point in the solution, if there are two or more possible moves forward, you should allocate each possibility to a separate thread (still using your rules for efficiency but concurrently checking each possibility). This would give you better concurrency (assuming threads can be run on separate CPUs/cores) since there will be no contention for the board; each thread will get it's own copy. In addition, since you're limiting the number of threads, you'll have to work some thread-pool magic to achieve this. What I would suggest is to have a work queue and N threads. The work queue is initially empty when your main thread starts all the worker threads. Then the main thread puts the beginning puzzle state into the work queue. The worker threads simply wait for a state to be placed on the work queue and one of them grabs it for processing. The work thread is your single-threaded solver with one small modification: when there are X possibilities to move forward (X > 1), your worker puts X-1 of those back onto the work queue then continues to process the other possibility. So, lets say there's only one solution (true Sudoku :-). The first worker thread will whittle away at the solution without finding any forks and that will be exactly as in your current situation. But with two possibilities at move 27 (say, 3 or 4 could go into the top left cell), your thread will create another board with the first possibility (put 3 into that cell) and place that in the work queue. Then it would put 4 in its own copy and continue. Another thread will pick up the board with 3 in that cell and carry on. That way, you have two threads running concurrently handling the two possibilities. When any thread decides that its board is insoluble, it throws it away and goes back to the work queue for more work. When any thread decides that its board is solved, it notifies the main thread which can store it, over-writing any previous solution (first-found is solution) or throw it away if it's already got a solution (last-found is solution) then the worker thread goes back to the work queue for more work. In either case, the main thread should increment a count of solutions found. When all the threads are idle and the work queue is empty, main either will or won't have a solution. It will also have a count of solutions. Keep in mind that all communications between workers and main thread will need to be mutexed (I'm assuming you know this based on information in your question).
Multi-threaded algorithm for solving sudoku?
[ "", "java", "multithreading", "algorithm", "sudoku", "" ]
i'm working on Linq To Sql,WPF and i have a database now i need to save some picture in the database but i don't know which is the correct datatype to save the pictures Database(this database would be connect from 10 users in the same time). Can you point me in the right way to overcome this step? If i didn't wrong it is not a good idea to save pictures in the database but if you can advice me a better method i will apply it. Thanks so much for your time. Nice Regards
You can use a 'varbinary(MAX)' or 'image' column type. Linq2Sql will auto-generate a class that uses a Binary object to wrap your image. The Binary object is just a wrapper around a byte[]. ``` myObject.Image = new Binary(imageByteArray); ```
Store your picture as a blob, the variable defined in your class containing the image could be a byte[] stream. Alternatively you just store a reference to the picture in the database and store the image on a file server.
How to save picture in the database?
[ "", "c#", ".net", "wpf", "linq", "" ]
How can I access request headers from a SessionListener? I need to set a timeout on the current session when it is created. The timeout needs to vary based on a header in the HttpServletRequest. I already have a SessionListener (implements HttpSessionListener) that logs the creation and destruction of new sessions, and it seems to be the most logical place to set the timeout. I've tried the following, but it always sets ctx to null. ``` FacesContext ctx = FacesContext.getCurrentInstance(); ```
The `HttpSessionListener` does not have access to the request because it is invoked when no request has been made—to notify of session destruction. So, a `Filter` or `Servlet` would be better places to examine the request and specify the session timeout.
``` FacesContext ctx = FacesContext.getCurrentInstance(); ``` JSF contexts are per-request and thread-local. So, this method call will probably return null outside the JSF controller invocations (e.g. [FacesServlet.service](http://java.sun.com/javaee/5/docs/api/javax/faces/webapp/FacesServlet.html#service(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse))) - so, other threads and any requests that don't pass through the Faces servlet mapping. It is technically possible to set this time-out using a JSF mechanism - you could use a [phase listener](http://java.sun.com/javaee/5/docs/api/javax/faces/event/PhaseListener.html) to check for a session after [RENDER RESPONSE](http://java.sun.com/javaee/5/docs/api/javax/faces/event/PhaseId.html), though you would still have to [cast to the servlet API](http://java.sun.com/javaee/5/docs/api/javax/faces/context/ExternalContext.html#getSession(boolean)) to set the time-out. The advantage of phase listeners is that they can be registered either globally in faces-config ([see spec](http://java.sun.com/javaee/javaserverfaces/reference/api/index.html)) or [for specific views](http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/tlddocs/f/phaseListener.html). A global phase listener defined in a JAR with a *META-INF/faces-config.xml* can be dropped into multiple WARs, allowing you to easily reuse the functionality. (You could also [override how the session is provisioned to JSF](http://java.sun.com/javaee/5/docs/api/javax/faces/context/FacesContextFactory.html), but the amount of work is excessive.) For a one-off, [erickson's suggestion](https://stackoverflow.com/questions/953572/how-can-i-get-httpservletrequest-when-in-an-httpsessionlistener/953666#953666) of a [Filter](http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html) is really straightforward.
How can I get HttpServletRequest when in an HttpSessionListener?
[ "", "java", "session", "jsf", "jakarta-ee", "request", "" ]
I have a JSON object with a key element called callback. ``` { "id":34, "description":"", "item_id":4, "callback":"addNew", "filename":"0000072.doc", "type":"News", "ext":"doc", "size":46592 } ``` I would like to call the javascript "addNew" function. I tried. ``` json.callback(json); ``` But does not work. Any idea?
Assuming it is a global function (it shouldn't be): ``` window[json.callback](json); ``` If your code is well structured you will probably have an object containing all the functions the JSON could call. ``` var myObject = { func1: function myObject_func1_method(foo) { return 1; }, func2: function myObject_func2_method(foo) { return 2; } } ``` Then you can: ``` myObject[json.callback](json); ```
Don't use eval, use ``` window[json.callback](json); ``` If the function is in the global scope. Use the scope instead of window otherwise.
How to invoke a function, whose name is passed in Json object?
[ "", "javascript", "json", "callback", "" ]
I am writing a server app and I want it to be console based. I need the user to be able to input different commands, but at the same time there is a possibility that something will be output to the console while the user is writing. This messes the buffer up. Is there any clean way of doing this? Thanks.
I started work on a test program to show how you could divide the console into an output area and an input area, where the input area is moved down as the output area expands with more output. It's not perfect yet, but you may be able to develop it into the answer you're looking for: ``` static int outCol, outRow, outHeight = 10; static void Main(string[] args) { bool quit = false; System.DateTime dt = DateTime.Now; do { if (Console.KeyAvailable) { if (Console.ReadKey(false).Key == ConsoleKey.Escape) quit = true; } System.Threading.Thread.Sleep(0); if (DateTime.Now.Subtract(dt).TotalSeconds > .1) { dt = DateTime.Now; WriteOut(dt.ToString(" ss.ff"), false); } } while (!quit); } static void WriteOut(string msg, bool appendNewLine) { int inCol, inRow; inCol = Console.CursorLeft; inRow = Console.CursorTop; int outLines = getMsgRowCount(outCol, msg) + (appendNewLine?1:0); int outBottom = outRow + outLines; if (outBottom > outHeight) outBottom = outHeight; if (inRow <= outBottom) { int scrollCount = outBottom - inRow + 1; Console.MoveBufferArea(0, inRow, Console.BufferWidth, 1, 0, inRow + scrollCount); inRow += scrollCount; } if (outRow + outLines > outHeight) { int scrollCount = outRow + outLines - outHeight; Console.MoveBufferArea(0, scrollCount, Console.BufferWidth, outHeight - scrollCount, 0, 0); outRow -= scrollCount; Console.SetCursorPosition(outCol, outRow); } Console.SetCursorPosition(outCol, outRow); if (appendNewLine) Console.WriteLine(msg); else Console.Write(msg); outCol = Console.CursorLeft; outRow = Console.CursorTop; Console.SetCursorPosition(inCol, inRow); } static int getMsgRowCount(int startCol, string msg) { string[] lines = msg.Split('\n'); int result = 0; foreach (string line in lines) { result += (startCol + line.Length) / Console.BufferWidth; startCol = 0; } return result + lines.Length - 1; } ```
Personally i would use event handlers to managed a console that handles both input and outup at the same time, create a class ScreenManager or whatever, inside that class add a void RunProgram() mthod, create an event with handler and required variables for reading the input key "Console.ReadKey(bool).key". ``` static Consolekey newKey; ``` on your main program, creat an instance of your class "whatev you called it", then create a thread of that instances internal method, Thread coreThread = new Thread(delegate() {myinstance.myProgramMrthod()}); loop in your main until the threads up and running. while (!Thread.IsAlive) ; then create the main program loop. ``` while (true) { } ``` then for safty, join your custom thread so the main program doesnt continue until the custom thread is closed/disposed. ``` customThread.Join(); ``` you now have two threads running seperatly. back to your class, create a switch inside your event handler method. ``` switch (newkey) { case Consolekey.enter Console.WriteLine("enter pressed"); break; ect, ect. default: Console.write(newkey); // writes character key that dont match above conditions to the screen. break; } ``` stick allyour logic inhere with how you want to handle keys. [How to use multiple modifier keys in C#](https://stackoverflow.com/questions/1434867/how-to-use-multiple-modifier-keys-in-c-sharp) might be of some help. inside your instance's method RunProgram() or whatev you choose to call it, after you've done whatever code you need to, create an infinite loop to check for key change. ``` while (true) { newKey = Console.ReadKey(true).Key; if (newKey != oldKey) { KeyChange.Invoke(); } } ``` this loop stores any key pressed and then checks to see if theres a new key, if true fires the event. you now have the core of what your looking for, one string that loops askng for a new key, whilst the main loop is free to display whatever text you wish to display. two fixable bugs with this that i can think of, one is "default" inside switch will print to console in caps or strings. and the other is any text added to the console is added at the cursor point so it adds to the text the user has just input. hwoever i will, since i've just made it, how you have to manager the text been added to the console. again im using an event. i could use methods and functions throughout but events add move flexability to the program, i think. okay so we want to be able to add text to the console, without it upsetting the input we enter. keeping the input at the bottom; create a new delegate that has a signiture with a string argument, void delegate myDelegate(string Arg). then create an event with this delegate, call it newline, newinput, whatev you like. the events handler will take a string argument (repersenting the console update text: what you want to insert into the console above the users input) it will grab the text the user has been entering into the console, store it, then print out the paramiter string onto the console, then print out the users input underneith. personally i chose to create a static string at the top outside the method, initialise it to empty, cos its going to be frequently used and you dont want to be creating a new identifyer and then initialising the variable everytime the method is called, then dispose of it at the end of the method, only to recreate a new one again, and again. call the string "input" or whatever. in the default area of the keychange event handle add input +=newkey. in the Consolekey.enter section console writline input then input = string.empty Or string = "". in the event handler add some logic. ``` public void OnInsert(string Argument) { Console.CursorTop -= 1; // moves the cursor to far left so new input overwrites the old. // if arg string is longer, then print arg string then print input // string. if (Argument.Length > input.Length) { Console.WriteLine(Argument); Console.WriteLine(input); } else { // if the users input if longer than the argument text then print // out the argument text, then print white spaces to overwrite the // remaining input characters still displayed on screen. for (int i = 0; i < input.Length;i++ ) { if (i < Argument.Length) { Console.Write(Argument[i]); } else { Console.Write(' '); } } Console.Write(Environment.NewLine); Console.WriteLine(input); } } hope this helps some of you, its not perfect, a quick put together test that works enough to be built on. ```
C# simultanous console input and output?
[ "", "c#", "console", "" ]
Is there a simpler way to swap two elements in an array? ``` var a = list[x], b = list[y]; list[y] = a; list[x] = b; ```
You only need one temporary variable. ``` var b = list[y]; list[y] = list[x]; list[x] = b; ``` --- Or with [ES6](https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015) and later: Given the array `arr = [1,2,3,4]`, you can swap values in one line now like so: ``` [arr[0], arr[1]] = [arr[1], arr[0]]; ``` This would produce the array `[2,1,3,4]`. This is [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
If you want a single expression, using native JavaScript, remember that the return value from a splice operation contains the element(s) that was removed. ``` var A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1; A[x] = A.splice(y, 1, A[x])[0]; alert(A); // Alerts "2,1,3,4,5,6,7,8,9" ``` The `[0]` is necessary at the end of the expression as `Array.splice()` returns an array, and in this situation we require the single element in the returned array.
Swap array elements in JavaScript
[ "", "javascript", "arrays", "" ]
Is it wrong to have static and non-static methods in the same class?
Not really in regular java programming. But if you're working extensively with dependency injection you probably have few or no static methods at all. In such a context it's fairly common to have only a few utility classes with static methods, and no other static methods.
No, it's not wrong. For example, a common use is to have static factory methods in a class definition.
Is it wrong to have static and non-static methods in the same class?
[ "", "java", "design-patterns", "static", "" ]
In order to ensure that some initialization code runs before `main` (using Arduino/avr-gcc) I have code such as the following: ``` class Init { public: Init() { initialize(); } }; Init init; ``` Ideally I'd like to be able to simply write: ``` initialize(); ``` but this doesn't compile... Is there a less verbose way to achieve the same effect? **Note:** the code is part of an Arduino sketch so the `main` function is automatically generated and cannot be modified (for example to call `initialize` before any other code). **Update:** ideally the initialization would be performed in the `setup` function, but in this case there is other code depending on it which occurs before `main`.
You can use GCC's [`constructor` attribute](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pointer-arguments) to ensure that it gets called before `main()`: ``` void Init(void) __attribute__((constructor)); void Init(void) { /* code */ } // This will always run before main() ```
You can make the above very slightly shorter by giving "initialize" a return type, and using that to initialize a global variable: ``` int initialize(); int dummy = initialize(); ``` However, you need to be careful with this, the standard does not guarantee that the above initialization (or the one for your init object) takes place before main is run (3.6.2/3): > It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main. The only thing that is guaranteed is that the initialization will take place before 'dummy' is ever used. A more intrusive option (if it's possible) might be to use "-D main=avr\_main" in your makefile. You could then add your own main as follows: ``` // Add a declaration for the main declared by the avr compiler. int avr_main (int argc, const char * argv[]); // Needs to match exactly #undef main int main (int argc, const char * argv[]) { initialize (); return avr_main (argc, argv); } ``` At least here you're guaranteed that the initialization will take place when you expect.
How can I perform pre-main initialization in C/C++ with avr-gcc?
[ "", "c++", "c", "initialization", "arduino", "avr-gcc", "" ]
How do I increase the volume of an outgoing wav audio stream using Java? I'm having issues with various Java TTS engines and the output volume of the synthesized speech. Is there an API call or a doo-hickey.jar I can use to pump up the volume?
If you're using the Java Sound API, you can set the volume with the [MASTER\_GAIN](http://java.sun.com/javase/6/docs/api/javax/sound/sampled/FloatControl.Type.html#MASTER_GAIN) control. ``` import javax.sound.sampled.*; AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( new File("some_file.wav")); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(-10.0f); // Reduce volume by 10 decibels. clip.start(); ```
You can adjust volume using a GainControl, try something like this after you have opened the line ``` FloatControl volume= (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); ```
Audio volume control (increase or decrease) in Java
[ "", "java", "audio", "javasound", "" ]
I am trying to connect to a Web Service which is password protected and the url is https. I can't figure out how to authenticate before the script makes a request. It seems like it makes a request as soon as I define the service. For instance, if I put in: ``` $client = new SoapClient("https://example.com/WSDL/nameofservice", array('trace' => 1,) ); ``` and then go to the site on the browser, I get: ``` Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://example.com/WSDL/nameofservice' in /path/to/my/script/myscript.php:2 Stack trace: #0 /path/to/my/script/myscript.php(2): SoapClient->SoapClient('https://example...', Array) #1 {main} thrown in /path/to/my/script/myscript.php on line 2 ``` If I try defining the service as a Soap Server, like: ``` $server= new SoapServer("https://example.com/WSDL/nameofservice"); ``` I get: ``` <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>WSDL</faultcode> <faultstring> SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://example.com/WSDL/nameofservice' </faultstring> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` I haven't tried sending a raw request envelope yet to see what the server returns, but that may be a workaround. But I was hoping someone could tell me how I can set it up using the php built-in classes. I tried adding "userName" and "password" to the array, but that was no good. The problem is that I can't even tell if I'm reaching the remote site at all, let alone whether it is refusing the request.
The problem seems to be that the WSDL document is somehow protected (basic authentication - I don't thinkg that digest authentication is supported with `SoapClient`, so you'd be out of luck in this case) and that the `SoapClient` therefore cannot read and parse the service description. First of all you should try to open the WSDL location in your browser to check if you're presented an authentication dialog. If there is an authentication dialog you must make sure that the `SoapClient` uses the required login credentials on retrieving the WSDL document. The problem is that `SoapClient` will only send the credentials given with the `login` and `password` options (as well as the `local_cert` option when using certificate authentication) on creating the client when invoking the service, not when fetching the WSDL (see [here](http://bugs.php.net/bug.php?id=27777)). There are two methods to overcome this problem: 1. Add the login credentials to the WSDL url on the `SoapClient` constructor call ``` $client = new SoapClient( 'https://' . urlencode($login) . ':' . urlencode($password) . '@example.com/WSDL/nameofservice', array( 'login' => $login, 'password' => $password ) ); ``` This should be the most simple solution - but in PHP [Bug #27777](http://bugs.php.net/bug.php?id=27777) it is written that this won't work either (I haven't tried that). 2. Fetch the WSDL manually using the HTTP stream wrapper or `ext/curl` or manually through your browser or via `wget`for example, store it on disk and instantiate the `SoapClient` with a reference to the local WSDL. This solution can be problematic if the WSDL document changes as you have to detect the change and store the new version on disk. If no authentication dialog is shown and if you can read the WSDL in your browser, you should provide some more details to check for other possible errors/problems. This problem is definitively not related to the service itself as `SoapClient` chokes already on reading the service descripion document before issuing a call to the service itself. **EDIT:** Having the WSDL file locally is a first step - this will allow the `SoapClient` to know how to communicate with the service. It doesn't matter if the WSDL is directly served from the service location, from another server or is read from a local file - service urls are coded within the WSDL so `SoapClient` always knows where to look for the service endpoint. The second problem now is that `SoapClient` has no support for the [WS-Security](http://en.wikipedia.org/wiki/WS-Security) specifications natively, which means you must extend `SoapClient` to handle the specific headers. An extension point to add the required behaviour would be [`SoapClient::__doRequest()`](https://www.php.net/manual/en/soapclient.dorequest.php) which pre-processes the XML payload before sending it to the service endpoint. But I think that implementing the WS-Security solution yourself will require a decent knowledge of the specific WS-Security specifications. Perhaps WS-Security headers can also be created and packed into the XML request by using [`SoapClient::__setSoapHeaders()`](https://www.php.net/manual/en/soapclient.setsoapheaders.php) and the appropriate [`SoapHeader`](https://www.php.net/manual/en/class.soapheader.php)s but I doubt that this will work, leaving the custom `SoapClient` extension as the lone possibility. A simple `SoapClient` extension would be ``` class My_SoapClient extends SoapClient { protected function __doRequest($request, $location, $action, $version) { /* * $request is a XML string representation of the SOAP request * that can e.g. be loaded into a DomDocument to make it modifiable. */ $domRequest = new DOMDocument(); $domRequest->loadXML($request); // modify XML using the DOM API, e.g. get the <s:Header>-tag // and add your custom headers $xp = new DOMXPath($domRequest); $xp->registerNamespace('s', 'http://www.w3.org/2003/05/soap-envelope'); // fails if no <s:Header> is found - error checking needed $header = $xp->query('/s:Envelope/s:Header')->item(0); // now add your custom header $usernameToken = $domRequest->createElementNS('http://schemas.xmlsoap.org/ws/2002/07/secext', 'wsse:UsernameToken'); $username = $domRequest->createElementNS('http://schemas.xmlsoap.org/ws/2002/07/secext', 'wsse:Username', 'userid'); $password = $domRequest->createElementNS('http://schemas.xmlsoap.org/ws/2002/07/secext', 'wsse:Password', 'password'); $usernameToken->appendChild($username); $usernameToken->appendChild($password); $header->appendChild($usernameToken); $request = $domRequest->saveXML(); return parent::__doRequest($request, $location, $action, $version); } } ``` For a basic WS-Security authentication you would have to add the following to the SOAP-header: ``` <wsse:UsernameToken> <wsse:Username>userid</wsse:Username> <wsse:Password>password</wsse:Password> </wsse:UsernameToken> ``` But as I said above: I think that much more knowledge about the WS-Security specification and the given service architecture is needed to get this working. *If you need an enterprise grade solution for the whole WS-\* specification range and if you can install PHP modules you should have a look at the [WSO2 Web Services Framework for PHP (WSO2 WSF/PHP)](http://wso2.org/projects/wsf/php)*
Simply extend the SoapHeader to create a Wsse compilant authentication: ``` class WsseAuthHeader extends SoapHeader { private $wss_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; function __construct($user, $pass, $ns = null) { if ($ns) { $this->wss_ns = $ns; } $auth = new stdClass(); $auth->Username = new SoapVar($user, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wss_ns); $auth->Password = new SoapVar($pass, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wss_ns); $username_token = new stdClass(); $username_token->UsernameToken = new SoapVar($auth, SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'UsernameToken', $this->wss_ns); $security_sv = new SoapVar( new SoapVar($username_token, SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'UsernameToken', $this->wss_ns), SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'Security', $this->wss_ns); parent::__construct($this->wss_ns, 'Security', $security_sv, true); } } $wsse_header = new WsseAuthHeader($username, $password); $x = new SoapClient('{...}', array("trace" => 1, "exception" => 0)); $x->__setSoapHeaders(array($wsse_header)); ``` --- If you need to use ws-security with a nonce and a timestamp, Peter has posted an update version on <http://php.net/manual/en/soapclient.soapclient.php#114976> of which he wrote that it did work for him: ``` class WsseAuthHeader extends SoapHeader { private $wss_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; private $wsu_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'; function __construct($user, $pass) { $created = gmdate('Y-m-d\TH:i:s\Z'); $nonce = mt_rand(); $passdigest = base64_encode(pack('H*', sha1(pack('H*', $nonce) . pack('a*', $created) . pack('a*', $pass)))); $auth = new stdClass(); $auth->Username = new SoapVar($user, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wss_ns); $auth->Password = new SoapVar($pass, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wss_ns); $auth->Nonce = new SoapVar($passdigest, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wss_ns); $auth->Created = new SoapVar($created, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wsu_ns); $username_token = new stdClass(); $username_token->UsernameToken = new SoapVar($auth, SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'UsernameToken', $this->wss_ns); $security_sv = new SoapVar( new SoapVar($username_token, SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'UsernameToken', $this->wss_ns), SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'Security', $this->wss_ns); parent::__construct($this->wss_ns, 'Security', $security_sv, true); } } ``` compare as well with the details given in answer <https://stackoverflow.com/a/18575154/367456>
Connecting to WS-Security protected Web Service with PHP
[ "", "php", "web-services", "soap", "ws-security", "" ]
I'm looking for a lightweight, PHP based, layout framework. Like how the Zend Framework, uses layouts, I would like to create a layout template and include only the content for the necessary pages. ``` <html> <head> <title><?= $pageTitle ?></title> </head> <body> <?= $content ?> </body> </html> ``` Anyone know of anything that does this? I would use the Zend Framework, but it's just too much for what I want to achieve.
I'm actually about to release one at europaphp.org along with examples and a full documentation. It's very similar to the Zend Framework in conventions and coding standards. I'll post something when it is done; probably within the next week. You can get the code at: [<http://code.google.com/p/europa/source/browse/#svn/trunk/Sandbox> - Default][1]. That link will bring up the latest svn for the Sandbox which you can just download and start using without any configuration. Currently, it's faster than most any other PHP framework out there. [1]: <http://code.google.com/p/europa/source/browse/#svn/trunk/Sandbox> - Default
I vote for PHP. (PHP *is* a templating engine.) ``` function template($file, $vars) { ob_start(); if(count($vars) > 0) { extract($vars); } include 'views/'.strtolower($file).'.php'; return ob_get_clean(); } ``` Which, incidentally, lets you do the following. ``` echo template('layout', array( 'content' => template('page', $myData) )); ``` Should you even bother using another templating/layout engine at all, when PHP itself can suffice in a mere 6 lines? **Edit:** Perhaps I wasn't clear with how this works. `template()` is called with the name of the template (subdirectories for organization work too) with an array object as the second parameter. If the variables given aren't blank, like `template('index',null)` is, then the array is treated as an associative array: and every key becomes a variable containing the value. So the logic becomes: ``` template('my_template', array( 'oranges' => 'apples' )); ``` And "views/my\_template.php" is: ``` <html> <head> <title>Are apples == <?= $oranges ?>?</title> </head> <body> <p style="color: <?= $oranges == 'oranges' ? 'orange" : 'darkgreen' ?>"> Are apples == oranges? </p> </body> </head> ``` So, every time the variable `$oranges` is used PHP gets the data that was exported from the array, `$vars['oranges']`. So all the output is then taken by `ob_get_clean()` and returned as a string. To output this string just `echo` or `print`, or assign it to an array to be passed as content to the layout. If you understand this, then it is very easy to take what I've written and make a layout out of it, or pages with logic that output JSON even. I would advise you to experiment with this answer before discarding it. It has a tendency to grow on you. **Edit 2:** As requested I'll show the directory layout that my project would use. Do note that other MVC frameworks use a different structure. But, I like the simplicity of mine. ``` index.php application/ framework.php controllers/ welcome.php views/ template.php index.php ``` For security purposes, I have an `.htaccess` file that routes every request, except those to `js/` or `css/`, to the `index.php` script, effectively making my directories hidden. You could even make the CSS via a template if you wished, which I've done, for the use of variables, etc. So, any call made to `template('template', array())` will load the file `./views/template.php` automatically. If I included a slash in the name, it becomes part of the path, like so: `./views/posts/view.php`. **Edit 3:** > thanks for your update. So you must have some code in your index.php file that routes the requested url to the appropriate controller, correct? Could you show some of this? Also, it doesn't look like your views mirror your controller directory. Can you explain a little more how urls map to controllers and/or views? What do you have in framework.php? What does it do? Thanks! The code I've shown is a tiny excerpt of my private framework for web development. [I've talked already about potentially releasing it](https://stackoverflow.com/questions/990816/how-do-i-release-sell-promote-a-semi-commercial-open-source-project) with a dual-license, or as donation-ware for commercial use, but it's nothing that can't be written by anyone else in a short (15-21 days) time. If you want you can [read my source code on GitHub](http://github.com/rk/uFramework/tree/master)... but just remember that it's still alpha material. The license is [Creative Commons SA](http://creativecommons.org/licenses/by-sa/3.0/us/).
Lightweight, PHP based, layout framework...know of any?
[ "", "php", "layout", "frameworks", "" ]
Is it normal to have a short delay after .innerHTML = xmlhttp.responseText; ? *Delay aproxamilty 1 sec. after xmlhttp.readyState==4.* *Using firefox 3.0.10*
No, this sounds like you may have some malformed or large response. The browser will parse the responsetext and construct nodes in the DOM. This is typically very fast in Firefox. Perhaps you could describe your circumstances and response text a little more and it would help us debug.
Do you have firebug installed? If not, install that from here (<https://addons.mozilla.org/en-US/firefox/addon/1843>) and enable the console and script and then you'll be able to see when the responseText is returned. But generally, yes its normal to have a short delay while the request is being made.
Is it normal to have a short delay after .innerHTML = xmlhttp.responseText;?
[ "", "javascript", "ajax", "" ]
I'm looking for a free library for python that can calculate your direction and your speed from GPS coordinates and maybe can calculate if you are in some boundaries or things like this. Are there Libraries that you know and that worked well for you? We are using python on a linux machine and getting the data from the gpsd. So I hope there is no need for a speciel library for only talking to the device. What I'm looking for is python code doing some basic calculations with the data. Such as comparing the last positions and calculate speed and direction.
Apparently the python module that comes with gpsd is the best module to go with for us. The gps module coming with the gpsd has some very useful functions. The first one is getting the data from gpsd and transforming those data in a usable data structure. Then the moduls give you access to your speed, and your current heading relative to north. Also included is a function for calculating the distance between two coordinates on the earth taking the spherical nature of earth into account. The functions that are missing for our special case are: * Calculating the heading between to points. Means I am at point a facing north to which degree do I have to turn to face the point I want to navigate to. * Taking the data of the first function and our current heading to calculate a turn in degrees that we have to do to face a desired point (not a big deal because it is mostly only a subtraction) The biggest problem for working with this library is that it is mostly a wrapper for the gpsd so if you are programming on a different OS then you gpscode should work on like Windows or MacOS you are not able to run the code or to install the module.
I'm not sure I understand your exact requirements, but, depending on your device &c, there seem to be many possible candidates, such as: * [S60 GPS Info Viewer](http://gagravarr.org/code/) * [pygarmin](https://github.com/quentinsf/pygarmin) * [pygps](http://linux.softpedia.com/get/Utilities/pygps-6071.shtml) (mirror) If what you mean is that you've already obtained the GPS' unit output and just need to parse it &c, I suspect that one or more of the above examples (which unfortunately I have not tried) will contain well-isolated modules for that task, which, depending on licensing conditions, you could repurpose; [this SO question](https://stackoverflow.com/questions/311763/parsing-gps-receiver-output-via-regex-in-python) might also help if that's what you're doing.
Which gps library would you recommend for python?
[ "", "python", "gps", "gpsd", "" ]
I am trying to use inline member functions of a particular class. For example the function declaration and implementation without inlining is as such: in the header file: ``` int GetTplLSize(); ``` in the .cpp file: ``` int NeedleUSsim::GetTplLSize() { return sampleDim[1]; } ``` For some reason if I put the "inline" keyword in either one of the implementation and declaration, as well as in both places, I get linker errors as shown: ``` Creating library C:\DOCUME~1\STANLEY\LOCALS~1\TEMP\MEX_HN~1\templib.x and object C:\DOCUME~1\STANLEY\LOCALS~1\TEMP\MEX_HN~1\templib.exp mexfunction.obj : error LNK2019: unresolved external symbol "public: int __thiscall NeedleUSsim::GetTplLSize(void)" (?GetTplLSize@NeedleUSsim@@QAEHXZ) referenced in function _mexFunction mexfunction.mexw32 : fatal error LNK1120: 1 unresolved externals C:\PROGRA~1\MATLAB\R2008B\BIN\MEX.PL: Error: Link of 'mexfunction.mexw32' failed. ``` What needs to be in order to get rid of this error (i.e. what am I doing wrong in terms of making these inline member functions)?
You need to put function definition into the header then. The simplest way to hint the compiler to inline is to include method body in the class declaration like: ``` class NeedleUSsim { // ... int GetTplLSize() const { return sampleDim[1]; } // ... }; ``` or, if you insist on separate declaration and definition: ``` class NeedleUSsim { // ... int GetTplLSize() const; // ... }; inline int NeedleUSsim::GetTplLSize() const { return sampleDim[1]; } ``` The definition has to be visible in each translation unit that uses that method.
from C++ FAQ Lite > If you put the inline function's > definition into a .cpp file, and if it > is called from some other .cpp file, > you'll get an "unresolved external" > error from the linker. [How do you tell the compiler to make a member function inline?](http://www.cs.technion.ac.il/users/yechiel/c++-faq/inline-member-fns.html)
inline function linker error
[ "", "c++", "inline", "linker-errors", "" ]
I'm looking for a server-side implementation to disable a browser from saving invalid login credentials. For example, user "foo" logs in with password "bar". Browser asks foo if he wants to save the password. However, foo's password is actually "baz" and therefor would be saving the incorrect password. I've tried manipulating the HTTP codes, such as sending HTTP/1.1 401, but without success. This is NOT solved by adding "autocomplete" to the form, as this prevents any saving (even valid). Server backend is PHP.
You can't have it dismiss that box if the authentication fails. However, you could have it prevent subsequent fillings of that field on the "Password Failed" page after the initial attempt. Once the page has loaded, manipulate the DOM to remove the text value from the password field if the last login attempt was invalid. It would still display the password on subsequent "fresh" visits to the site, but hopefully the correct password will have been saved by then.
I don't think you can - that's a browser behaviour. Closest you could come, is write a Firefox plugin that maybe could intercept the request. But I'm not even sure about that, and it only applies to Firefox. You'd need to look at Chrome, IE, Safari and any other browser you're interested in.
Disabling Browser's "save password" feature on auth failure
[ "", "php", "security", "firefox", "browser", "passwords", "" ]
This is a generic database design question - What are the benefits of using a synonym in database development, over a simple view? What are the main considerations to keep in mind when choosing between the two? An example **view**: ``` CREATE VIEW Users AS SELECT * FROM IdentitySystem.dbo.Users ``` And the equivalent synonym: ``` CREATE SYNONYM Users FOR IdentitySystem.dbo.LCTs ```
They are different things. A synonym is an alias for the object directly, a view is a construct over one or more tables. Some reasons to use a view: * May need to filter, join or otherwise frig with the structure and semantics of the result set * May need to provide legacy support for an underlying structure that has changed but has dependencies that you do not want to re-work. * May provide security where some of the contents of the table should be visible to a class of users but not all. This could involve removing columns with sensitive information or filtering out a subset of the records. * May wish to encapsulate some business logic in a form that is accessible to users for reporting purposes. * You may wish to unify data from more than one source. ... Plus many more. Reasons to use a synonym: * You may wish to alias an object in another database, where you can't (or don't want to) hard code the reference to the specific database. * You may wish to redirect to a source that changes over time, such as an archive table. * You want to alias something in a way that does not affect the query optimiser. ... Plus many more.
There are lots of considerations. In short, use the tool that works best for each situation. With a view, I can * hide columns * add predicates (WHERE clause) to restrict rows * rename columns * give a column name to a SQL expression With a synonym, I can: * reference objects in other schemas and databases without qualifying the name There's probably more that can be done with synonyms. In the designs of our (Oracle database) applications, we use an "owner" schema (user) for all of the database objects (tables, views, triggers, etc.), and we grant privileges on those objects to other "app" users. In each of the "app" user schemas, we create synonyms to reference the "owner" objects. HTH
What are the pros/cons of using a synonym vs. a view?
[ "", "sql", "database", "database-design", "" ]
I'm new to using JAXB, and I used JAXB 2.1.3's xjc to generate a set of classes from my XML Schema. In addition to generating a class for each element in my schema, it created an ObjectFactory class. There doesn't seem to be anything stopping me from instantiating the elements directly, e.g. ``` MyElement element = new MyElement(); ``` whereas tutorials seem to prefer ``` MyElement element = new ObjectFactory().createMyElement(); ``` If I look into ObjectFactory.java, I see: ``` public MyElement createMyElement() { return new MyElement(); } ``` so what's the deal? Why should I even bother keeping the ObjectFactory class around? I assume it will also be overwritten if I were to re-compile from an altered schema.
Backward compatibility isn't the only reason. :-P With more complicated schemas, such as ones that have complicated constraints on the values that an element's contents can take on, sometimes you need to create actual `JAXBElement` objects. They are not usually trivial to create by hand, so the `create*` methods do the hard work for you. Example (from the XHTML 1.1 schema): ``` @XmlElementDecl(namespace = "http://www.w3.org/1999/xhtml", name = "style", scope = XhtmlHeadType.class) public JAXBElement<XhtmlStyleType> createXhtmlHeadTypeStyle(XhtmlStyleType value) { return new JAXBElement<XhtmlStyleType>(_XhtmlHeadTypeStyle_QNAME, XhtmlStyleType.class, XhtmlHeadType.class, value); } ``` This is how you get a `<style>` tag into a `<head>` tag: ``` ObjectFactory factory = new ObjectFactory(); XhtmlHtmlType html = factory.createXhtmlHtmlType(); XhtmlHeadType head = factory.createXhtmlHeadType(); html.setHead(head); XhtmlStyleType style = factory.createXhtmlStyleType(); head.getContent().add(factory.createXhtmlHeadTypeStyle(style)); ``` The first three uses of the `ObjectFactory` could be considered superfluous (though useful for consistency), but the fourth one makes JAXB much, much easier to use. Imaging having to write a `new JAXBElement` out by hand each time!
As @Chris pointed out, sometimes JAXB cannot work with POJOs, because the schema cannot be mapped exactly on to Java. In these cases, `JAXBElement` wrapper objects are necessary to provide the additional type information. There are two concrete examples that I've come across where this is common. * If you want to marshal an object of a class that does not have the `@XmlRootElement` annotation. By default XJC only generates `@XmlRootElement` for some elements, and not for others. The exact logic for this is a bit complicated, but you can force XJC to generate more `@XmlRootElement` classes using the ["simple binding mode"](https://jaxb.dev.java.net/nonav/2.2-ea/docs/vendorCustomizations.html#simple) * When your schema uses substituion groups. This is pretty advanced schema usage, but XJC translates substitution groups into Java by making heavy use of `JAXBElement` wrappers. So in an XJC-generated object model which makes heavy use of `JAXBElement` (for whatever reason), you need a way of constructing those `JAXBElement` instances. The generated `ObjectFactory` is by far the easiest way to do it. You *can* construct them yourself, but it's clunky and error-prone to do so.
What's the point of JAXB 2's ObjectFactory classes?
[ "", "java", "jaxb", "" ]
I have a problem where I need `x` threads to wait until they have all reached a synchronization point. My solution uses the `synchronise` method below which is called by each threaded function when they need to synchronise. Is there a better way to do this? ``` thread_count = 0 semaphore = threading.Semaphore() event = threading.Event() def synchronise(count): """ All calls to this method will block until the last (count) call is made """ with semaphore: thread_count += 1 if thread_count == count: event.set() event.wait() def threaded_function(): # Do something # Block until 4 threads have reached this point synchronise(4) # Continue doing something else ```
There are many ways to synchronize threads. Many. In addition to synchronize, you can do things like the following. 1. Break your tasks into two steps around the synchronization point. Start threads doing the pre-sync step. Then use "join" to wait until all threads finish step 1. Start new threads doing the post-sync step. I prefer this, over synchronize. 2. Create a queue; acquire a synchronization lock. Start all threads. Each thread puts an entry in the queue and waits on the synchronization lock. The "main" thread sits in a loop dequeueing items from the queue. When all threads have put an item in the queue, the "main" thread releases the synchronization lock. All other threads are now free to run again. There are a number of interprocess communication (IPC) techniques -- all of which can be used for thread synchronization.
Note that Barrier has been implemented [as of Python 3.2](https://docs.python.org/3/whatsnew/3.2.html#threading) Example of using barriers: ``` from threading import Barrier, Thread def get_votes(site): ballots = conduct_election(site) all_polls_closed.wait() # do not count until all polls are closed totals = summarize(ballots) publish(site, totals) all_polls_closed = Barrier(len(sites)) for site in sites: Thread(target=get_votes, args=(site,)).start() ```
Synchronising multiple threads in python
[ "", "python", "multithreading", "synchronize", "" ]
I'd like to do a line-graph on a web-page using Javascript. I want it to be animated so that when the page loads, the line is slowly "drawn" onto the graph. I've managed to get a static graph working, using [flot](http://code.google.com/p/flot/), however I'm unsure how to animate it. It would be half my job done to just make it draw a line *half-way* along the graph, but when I try to do this by modifying the data-set, it modifies the structure of the graph as well, so that the line fills 100% of the graph area. So is there a way to draw the line data in stages, so I can animate it? Or alternatively, is there some other javascript graphing framework that I've overlooked?
**Here's a simple example using Flot** ``` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples</title> <link href="layout.css" rel="stylesheet" type="text/css"></link> <!--[if IE]><script language="javascript" type="text/javascript" src="../excanvas.pack.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../jquery.js"></script> <script language="javascript" type="text/javascript" src="../jquery.flot.js"></script> </head> <body> <h1>Animated Flot Example</h1> <div id="placeholder" style="width:600px;height:300px;"></div> <script id="source" language="javascript" type="text/javascript"> $(function () { var linePoints = [[0, 3], [4, 8], [8, 5], [9, 13]]; var i = 0; var arr = [[]]; var timer = setInterval(function(){ arr[0].push(linePoints[i]); $.plot($("#placeholder"), arr); i++; if(i === linePoints.length) clearInterval(timer); },300); }); </script> </body> </html> ```
Thinking outside the box (since the box that is flot is unfamiliar to me), you could just cover the graph with a div which slow recedes and displays the line. Shrinking a div in javascript is a trivial task even without third party libraries. **Edit:** I had to see how easy it was, so I threw this together in about 10 mins. ``` <html> <head> </head> <body> <div style="width:480px;height:480px;position:relative;"> <img onload="setTimeout(function(){reduce();}, interval);" src="http://images.freshmeat.net/editorials/r_intro/images/line-graph-1.jpg" /> <div id="dvCover" style="position:absolute;width:370px;height:320px;background-color:white;border:solid 1px white;top:70px;left:70px;"></div>color:white;border:solid 1px blue;top:70px;left:70px;"></div> </div> <script type="text/javascript"> var step = 3; var interval = 20; var cover = document.getElementById("dvCover"); var currentWidth = 370; var currentLeft = 70; setTimeout(function(){reduce();}, interval); function reduce() { if (currentWidth > 0) { currentWidth -= step; currentLeft += step; cover.style.width = currentWidth + "px"; cover.style.left = currentLeft + "px"; setTimeout(function(){reduce();}, interval); } else { cover.style.display = "none"; } } </script> </body> </html> ```
Animated line graph in Javascript?
[ "", "javascript", "graph", "flot", "animated", "" ]
I'm getting this warning all over the place in some perfectly well functioning objective-c code within XCode. My google-fu has failed me... others have run into this but I could not find an explanation on what exactly is causing it or how it can be fixed.
Found the problem and fixed it. I had this: ``` enum eventType { singleTouch }; enum eventType type; ``` ... and changed it to: ``` enum eventType { singleTouch } type; ```
In pure C, the following code: ``` int; typedef int; ``` elicits the following warnings from GCC with no warning options set: ``` x.c:1: warning: useless keyword or type name in empty declaration x.c:1: warning: empty declaration x.c:2: warning: useless keyword or type name in empty declaration x.c:2: warning: empty declaration ``` Maybe you have something analogous in your code?
warning: declaration does not declare anything
[ "", "c++", "iphone", "objective-c", "xcode", "" ]
Today I got into a very interesting conversation with a coworker, of which one subject got me thinking and googling this evening. Using C++ (as opposed to C) in an embedded environment. Looking around, there seems to be some good [trades](http://www.informit.com/articles/article.aspx?p=101167) for and against the features C++ provides, but others [Meyers](http://www.aristeia.com/c++-in-embedded.html) clearly support it. So, I was wondering who would be able to shed some light on this topic and what the general consensus of the community was.
It sort of depends on the particular nature of your embedded system and which features of C++ you use. The language itself doesn't necessarily generate bulkier code than C. For example, if memory is your tightest constraint, you can just use C++ like "C with classes" -- that is, only using direct member functions, disabling RTTI, and not having any virtual functions or templates. That will fit in pretty much the same space as the equivalent C code, since you've no type information, vtables, or redundant functions to clutter things up. I've found that templates are the biggest thing to avoid when memory is really tight, since you get one copy of each template function for each type it's specialized on, and that can rapidly bloat code segment. In the console video games industry (which is sort of the beefy end of the embedded world) C++ is king. Our constraints are hard limits on memory (512mb on current generation) and realtime performance. Generally virtual functions and templates are used, but not exceptions, since they bloat the stack and are too perf-costly. In fact, one major manufacturer's compiler doesn't even support exceptions at all.
The fear of C++ among embedded developers is largely a thing of the past, when C++ compilers were not as good as C compilers (optimizations and code quality wise). This applies especially to modern platforms with 32 bit architectures. But, C is certainly still the preferred choice for more confined environments (as is assembler for 8 bit or 4 bit targets). So, it really boils down to the resources your target platform provides, and how much of these resources you are likely to actually require, i.e. if you can afford the 'luxury' of doing embedded development in C++ (or even Java for that matter), because you know that you'll hardly have any issues regarding memory or CPU constraints. Nowadays, many modern embedded platforms (think gaming consoles, mobile phones, PDAs etc), have really become very capable targets, with RISC architectures, several MB of RAM, and 3D hardware acceleration. It would be a poor decision, to program such platforms using just C or even assembler out of uninformed performance considerations, on the other hand programming a 16 bit PIC in C++ would probably also be a controversial decision. So, it's really a matter of asking yourself how much of the power, you'll actually need and how much you can afford to sacrifice, in order to improve the development experience (high level language, faster development, less tedious/redundant tasks).
Using C++ in an embedded environment
[ "", "c++", "embedded", "" ]
I'm handling both the click and dblclick event on a DOM element. Each one carries out a different command, but I find that when double clicking on the element, in addition to firing the double click event, the click event is also fired twice. What is the best approach for preventing this behavior?
In a comment, you said, > I delay the click handler by 300 ms (a noticeable and annoying delay) and even ... So it sounds like what you want is that when you click then the DOM should geneate a click event immediately, except not if the click is the first click of a double-click. To implement this feature, when you click, the DOM would need to be able to predict whether this is the final click or whether it's the first of a double-click (however I don't think is possible in general for the DOM to predict whether the user is about to click again). --- What are the two distinct actions which you're trying to take on click and double-click? IMO, in a normal application you might want both events: e.g. single-click to focus on an element and then double-click to activate it. When you must separate the events, some applications use something other than double-click: for example, they use right-click, or control-click.
In case anyone else stumbles on this (as I did) looking for an answer, the absolute best solution that I could come up with is the following: ``` $node.on('click',function(e){ if(e.originalEvent.detail > 1){ return; /* if you are returning a value from this function then return false or cancel the event some other way */ } }); ``` Done. If there is more than one click back to back, the second, third,etc. will not fire. I definitely prefer this to using any sort of timers. I got myself pointed in this direction by reading [this](http://www.simonbattersby.com/blog/2010/10/preventing-doubleclick-firing-two-clicks-with-jquery/). --- *Incidentally: I was first researching this problem because I accidentally double clicked a paginated link, and the event fired and finished twice before the callback could happen.* *Before coming up with the code above, I had* ``` if e.originalEvent.detail === 2 //return ``` *however, I was able to click on the link 3 times (a triple click), and though the second click didn't fire, the third did*
Prevent click event from firing when dblclick event fires
[ "", "javascript", "dom-events", "" ]
I have an issue with a class that I'm trying to test. I've declared a private enum and I'm using that in a generic dictionary in the code. This enum has no meaning outside of this class but it's used in a private method. When I generated the code the accessor is written into the generic dictionary type, but throws an invalid cast exception when I try to use the test. ``` MyClass_Accessor target = new MyClass_Accessor(); Dictionary<MyClass_Accessor.MyEnum, long> dictionary = new Dictionary<MyClass_Accessor.MyEnum, long>(); dictionary.Add(MyClass_Accessor.Myenum.EnumValue, 1); target.Method(dictionary); //Throws invalid cast exception here. ``` The exception is that the generic dictionary of accessor => enum, long cannot be converted to Myclass => enum, long. *Other than altering my working class*, is there a way that I can test this method?
You can use the InternalsVisibleTo assembly attribute, and change your privates to internals. (If you can't change your private enum to an internal enum, then this won't work, but usually its an acceptable trade off.) Assuming you have an assembly called AssemblyA that is being unit tested by AssemblyATest, and integration tested by AssemblyAIntegTest, you can stick the following in your AssemblyInfo.cs file: ``` using System.Runtime.CompilerServices; // ... [assembly: InternalsVisibleTo("AssemblyATest")] [assembly: InternalsVisibleTo("AssemblyAIntegTest")] ``` If you sign your primary assemblies, you will also need to sign your test assemblies, and provide fully qualified, cultured, and primary keyed assembly names.
I'll readily admit that under your circumstances this is a test that you may need to perform, in which case jrista's answer is the one to follow (InternalsVisibleTo). When unit-testing however I don't think you are normally supposed to test the non-public API of classes. If this enum is private to the class, and therefore only used internally to the class, then it should not occur in any unit tests either. The purpose of unit tests it to establish that the public (including virtual/abstract protected) API of your class performs as expected. By including tests that rely on an implementation detail such as this private enum, you essentially make it impossible to change the implementation in the future (for example into one that may not need an enum).
How to use generics containing private types with Visual Studio Unit Tests
[ "", "c#", "unit-testing", "generics", "" ]
Is it possible to somehow shorten this statement? ``` if (obj != null) obj.SomeMethod(); ``` because I happen to write this a lot and it gets pretty annoying. The only thing I can think of is to implement **Null Object** pattern, but that's not what I can do every time and it's certainly not a solution to shorten syntax. And similar problem with events, where ``` public event Func<string> MyEvent; ``` and then invoke ``` if (MyEvent != null) MyEvent.Invoke(); ```
From C# 6 onwards, you can just use: ``` MyEvent?.Invoke(); ``` or: ``` obj?.SomeMethod(); ``` The `?.` is the null-propagating operator, and will cause the `.Invoke()` to be short-circuited when the operand is `null`. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem. === Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example: ``` public static void SafeInvoke(this Action action) { if(action != null) action(); } ``` now this is valid: ``` Action act = null; act.SafeInvoke(); // does nothing act = delegate {Console.WriteLine("hi");} act.SafeInvoke(); // writes "hi" ``` In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need: ``` var handler = SomeEvent; if(handler != null) handler(this, EventArgs.Empty); ``` but with: ``` public static void SafeInvoke(this EventHandler handler, object sender) { if(handler != null) handler(sender, EventArgs.Empty); } ``` we can use simply: ``` SomeEvent.SafeInvoke(this); // no race condition, no null risk ```
What you're looking for is the [Null-Conditional](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-) (not "coalescing") operator: **`?.`**. It's available as of C# 6. Your example would be `obj?.SomeMethod();`. If obj is null, nothing happens. When the method has arguments, e.g. `obj?.SomeMethod(new Foo(), GetBar());` the arguments are not evaluated if `obj` is null, which matters if evaluating the arguments would have side effects. And chaining is possible: `myObject?.Items?[0]?.DoSomething()`
Method call if not null in C#
[ "", "c#", "null", "" ]
Should I do something along the lines of this? I'm thinking of all my controllers inheriting from `BaseController`. Does this break the design pattern of IoC? What else should I do instead? ``` public class BaseController: Controller { protected ICookieService CookieService { get { return ServiceResolver.Resolve<ICookieService>(new { HttpContext = HttpContext }); } } protected IDateTimeService DateTimeService { get { return ServiceResolver.Resolve<IDateTimeService>(); } } protected ISettingsService SettingsService { get { return ServiceResolver.Resolve<ISettingsService>(); } } } ```
It would be a lot simpler to go with constructor injection and have a controllerfactory inject it for you. If you can, don't use a service locator (your ServiceResolver ) if you can get away with constructor injection. There's some info on it on [Adding a controller factory to ASP MVC](https://stackoverflow.com/questions/568137/adding-a-controller-factory-to-asp-mvc) The link shows how to do it with StructureMap and it looks like you're using Unity, but it should be straightforward to adapt.
I'm assuming that the protected interfaces you have are dependencies for the controller. Its possible to set up an IoC container to inject the dependencies for you. It can certainly be done with Castle Windsor. You would need to change you BaseController class to have a constructor with the required dependencies, as long as the IoC container knows about the other services it'll be able to inject them.
IoC and ASP.NET MVC Controllers
[ "", "c#", "asp.net-mvc", "inversion-of-control", "" ]
I'm currently working on a legacy app (win32, Visual C++ 2005) that allocates memory using LocalAlloc (in a supplied library I can't change). The app keeps very large state in fixed memory (created at the start with multiple calls to LocalAlloc( LPTR, size)). I notice that in release mode I run out of memory at about 1.8gb but in debug it happily goes on to over 3.8gb. I'm running XP64 with the /3gb switch. I need to increase the memory used in the app and I'm hitting the memory limit in release (debug works ok). Any ideas?
You probably have the Debug configuration linking with /LARGEADDRESSAWARE and the Release configuration linking with /LARGEADDRESSAWARE:NO (or missing altogether). Check Linker->System->Enable Large Addresses in the project's configuration properties.
Sounds like your Release build is also compiled as x86. If not, than there must be something in your code which treats pointer as signed 32-bit integers and this code is only active in Release. How does the running out of memory manifests itself? Also, there is no reason to use /3gb flag for XP64 when running 64-bit applications: it doesn't change anything in this scenario
WIN32 memory issue (differences between debug/release)
[ "", "c++", "c", "winapi", "" ]
I'd like to split a comma separated value into pairs: ``` >>> s = '0,1,2,3,4,5,6,7,8,9' >>> pairs = # something pythonic >>> pairs [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] ``` What would *# something pythonic* look like? How would you detect and handle a string with an odd set of numbers?
Something like: ``` zip(t[::2], t[1::2]) ``` Full example: ``` >>> s = ','.join(str(i) for i in range(10)) >>> s '0,1,2,3,4,5,6,7,8,9' >>> t = [int(i) for i in s.split(',')] >>> t [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> p = zip(t[::2], t[1::2]) >>> p [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] >>> ``` If the number of items is odd, the last element will be ignored. Only complete pairs will be included.
How about this: ``` >>> x = '0,1,2,3,4,5,6,7,8,9'.split(',') >>> def chunker(seq, size): ... return (tuple(seq[pos:pos + size]) for pos in xrange(0, len(seq), size)) ... >>> list(chunker(x, 2)) [('0', '1'), ('2', '3'), ('4', '5'), ('6', '7'), ('8', '9')] ``` This will also nicely handle uneven amounts: ``` >>> x = '0,1,2,3,4,5,6,7,8,9,10'.split(',') >>> list(chunker(x, 2)) [('0', '1'), ('2', '3'), ('4', '5'), ('6', '7'), ('8', '9'), ('10',)] ``` P.S. I had this code stashed away and I just realized where I got it from. There's two very similar questions in stackoverflow about this: * [What is the most “pythonic” way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) * [How do you split a list into evenly sized chunks in Python?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) There's also this gem from the [Recipes](http://docs.python.org/library/itertools.html#recipes) section of `itertools`: ``` def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) ```
Pythonic way to split comma separated numbers into pairs
[ "", "python", "tuples", "" ]
I don't want a search for the string value to be case insensitive. I want to do a search for the node without regard for case sensitivity. If the XML looks like this: ``` <items> <ITEM>My text!</ITEM> </items> ``` I need something like this to work: ``` $someXmlDoc->xpath("/items/item/text()"); ``` Currently, only this works: ``` $someXmlDoc->xpath("/items/ITEM/text()"); ```
There is no case conversion in xpath 1.0 as supported by php (see <http://jp.php.net/manual/en/class.domxpath.php>) you *could* use the translate function, shown below in a very limited sense. note: not recommended as it won't work for non-english characters ``` /items/*[translate(node(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz') = 'item']/text() ``` Upd:If node() will not work, try name() you could also do a union as below ``` /items/ITEM/text() | /items/item/text() ```
This is weird. XML tags are case-sensitive (<http://www.w3schools.com/xml/xml_syntax.asp>), so `<item>` and `<ITEM>` are two different tags. Thus. `"/items/item/text()"` and `/items/ITEM/text()` are two different paths. ``` <items> <ITEM>My text!</ITEM> <item>Your text!</item> </items> ``` "My text" and "Your text" have different `xpath`s
How do I perform a case insensitive search for a node in PHP xpath?
[ "", "php", "xpath", "" ]
Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently? Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.
You can use sum() to sum the values of an array. ``` a = [1,9,12] print sum(a) ```
Yet another way to sum up a list with the loop time: ``` s = reduce(lambda x, y: x + y, l) ```
Faster way to sum a list of numbers than with a for-loop?
[ "", "python", "algorithm", "for-loop", "" ]
I like to cleanly separate public and domain *objects* (so, nHibernate isn't going to help here) from each other which ends up forcing me to write a lot of code to map one object to another. What tools/plugins are out there to take the tedium of having to do manually do this mapping in .NET?m Whenever I Google this, it thinks I'm wanting to do ORM, which is *not* what I'm looking for. Thanks! EDIT 19:33CST: OK, I wrote a very basic application (very quickly written code) that demonstrates what I'm looking for. I'm just wondering if there is a VS plugin that will do this for me. [VS2008 Solution](http://waynehartman.com/downloads/OTOM.zip)
So, seemingly dissatisfied with a runtime solution, I have written a small utility that will create the mappings in code. You can download the source below and write better error handling, etc., etc. I'd appreciate any cool modifications you make, this was made in haste, but works. Please respect that the code is being released under the [LGPL](http://www.gnu.org/licenses/lgpl.txt). [Object To Object Mapping Utility Source Code](http://waynehartman.com/download?file=d2333998-c0cc-4bd4-8f02-82bef57d463c) **UPDATE 23 JUN 2009**: I made some updates to the code that cleaned it up (a little bit) and also added the ability to save a mapping to a file so that you can later modify it.
You might want to give [AutoMapper](https://github.com/AutoMapper/AutoMapper) a try. It sounds like what you're looking for.
Object to Object Mapping Utility
[ "", "c#", ".net", "visual-studio", "oop", "" ]
I am writing a program in C++ using Eclipse. I want to compile it as a library for Linux, somthing like a DLL in Windows. How I can do this? Do you know any tutorials on how libraries are created? I just want to understand that is the analog of a DLL for Linux and how to create it. I will be thankful for a small example.
In Linux, DLL's equivalents are (kind of anyway) shared objects (.so). You need to do something like this: ``` $ g++ -c -fPIC libfile1.cpp $ g++ -c -fPIC libfile2.cpp $ g++ -shared -o libyourlib.so libfile1.o libfile2.o ``` Take a look at some open source C++ library projects for more information. [GTKMM](http://www.gtkmm.org/) is one of them. Of course, instead of compiling everything manually it's highly recommended to use a **make file** or an **IDE** (such as [Eclipse](http://www.eclipse.org/) with [CDT](http://www.eclipse.org/cdt/) or [KDevelop](http://www.kdevelop.org/) or {*pick your favorite here*}) that will create one for you behind the scenes.
In UNIX/Linux world DLLs are called `shared libraries` and typically have `.so` or `.o` extension. See Linux [HOWTO](http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html) on shared libs.
Creating dynamically loaded Linux libraries using Eclipse
[ "", "c++", "c", "linux", "eclipse", "" ]
I have been passed a piece of work that I can either do in my application or perhaps in SQL: I have to get a date out of a string that may look like this: ``` 1234567-DSP-01/01-VER-01/01 ``` or like this: ``` 1234567-VER-01/01-DSP-01/01 ``` but may look like this: ``` 00 12345 DISCH 01/01-VER-01/01 XXX X XXXXX ``` Yay. if it is a `"DSP"` then I want that date, if a `"DISCH"` then that date. I am pulling the data out in a SQL Server view and would be happy to have the view transform the data for me. My application could do it but would add processor time. I could also see if the data could be manipulated before it is entered into the DB, I suppose. Thank you for your time.
An option would be to check for the presence of DSP or DISCH then substring out the date as necessary. For example (I don't have sqlserver today so I can verify syntax, sorry) ``` select date = case date_attribute when charindex('DSP',date_attribute) > 0 then substring(date_attribute,beg,end) when charindex('DISCH',date_attribute) > 0 then substring(date_attribute,beg,end) else 'unknown' end from myTable ```
If you do it in the view your adding processing time on SQL which in general a more expensive resource then an app, web or some other type of client. I'd recommend you try and format the data out when you insert the data, or you handle in the application tier. Scaling horizontally an app tier is so much easier then scalling your SQL. **Edit** I am talking the database server's physical resources are usually more expensive then a properly designed applications server's physical resources. This is because it is very easy to scale an application horizontally, it is in my opinion an order of magnitude more expensive to scale a DB server horizontally. Especially if your dealing with a transactional database and need to manage merging I am not saying it is not possible just that scaling a database server horizontally is a much more difficult task, hence it's more expensive. The only reason I pointed this out is the OP raised a concern about using CPU cycles on the app server vs the database server. Most applications I have worked with have been data centric applications which processed through GB's of data to get a user an answer. We initially put everything on the database server because it was easier then doing it in classic asp and vb6 at the time. Over time the DB server was more and more loaded until scaling veritcally was no longer an option. Database Servers are also designed at retrieving and joining data together. You should leave the formating of the data to the application and business rules (in general of course)
SQL server string manipulation in a view... Or in XSLT
[ "", "sql", "sql-server", "xslt", "string", "" ]
I have a Linq to Sql Model generated by VS ORD, but I want to make a changes to it to work around a couple of issues. I can change the `designer.cs` generated code , but if I ever need to recreate a table within the model, then I delete it and drag it back to the ORD. This however loses all of my customisations. Is there another way? I have seen reference to [sqlMetal.exe](http://msdn.microsoft.com/en-us/library/bb386987.aspx), but not sure how I would use this to get around the issue. For information my customisations are as follows: 1. I am using `Guid`'s and want the db to default these values, therefore I want to change the default linqtosl behaviour to add the attribute `[Column(IsDbGenerated= true)]` to the ID properties. 2. the Default Model Binding for MVC is not working for a collection (`EntitySet<T>`). To work around this I need to change the setter for these collections slightly. Neither of these changes are particularly big, but my database could change considerably over time, and I need to remember to do each customisation each time.
I've had this same question and was hoping to see an answer appear here that solves both of the points you mention. (I found another workaround to your item #2, although your idea of using OnCreated() in a partial seems nicer than what I'm currently doing.) I did run across an article recently (which I'll link to below) which might be an applicable solution to achieve these goals. This article describes how the author (1) uses SQLMetal to generate a dbml file, (2) runs a custom process which parses and modifies this dbml file to suit his needs, then (3) uses SQLMetal again, this time feeding in the modified dbml file, in order to generate code. It may be a lot of work for small projects/schemas, but I could see how this might be a handy workaround on large projects. Here's the link: <http://www.onedotnetway.com/enum-support-with-linq-to-sql-and-sqlmetal/> Best of luck! -Mike
This is [what "partial" classes are all about](http://msdn.microsoft.com/en-us/library/wa80x488%28VS.80%29.aspx). L2SQL creates your entity classes as "partial", so you never have to edit the designer-generated code, even if you recreate yur entity model.
Recreate Linq to Sql code when table changes where customised
[ "", "c#", "asp.net-mvc", "visual-studio-2008", "linq-to-sql", "" ]
Is there any way to do it?
The ~~best~~ easiest way would be to remove the corresponding element from the model.
There is the `RowFilter<DefaultTableModel, Object>` class you can use to filter out rows. The DefaultTableModel can be replaced by your own model. To filter, implement the method ``` @Override public boolean include(Entry entry) { // All rows are included if no filter is set if (filterText.isEmpty()) return true; // If any of the column values contains the filter text, // the row can be shown for (int i = 0; i < entry.getValueCount(); i++) { String value = entry.getStringValue(i); if (value.toLowerCase().indexOf(filterText) != -1) return true; } return false; } ``` When accessing rows, for instance listening to ListSelectionEvents, do not forget to translate the visible row index to the complete row index in your model. Java provides a function for this as well: ``` public void valueChanged(ListSelectionEvent e) { ListSelectionModel lsm = (ListSelectionModel) e.getSource(); int visibleRowIndex = ... // Get the index of the selected row // Convert from the selection index based on the visible items to the // internal index for all elements. int internalRowIndex = tableTexts .convertRowIndexToModel(visibleRowIndex); ... } ```
How can I hide (make invisible) row in JTable?
[ "", "java", "jtable", "row", "" ]
Im trying to access a Sql CE 2005 database on a windows mobile device from two different applciations. From the information I found online it should work but when I open the second connection I get a file sharing violation error ``` "There is a file sharing violation. A different process might be using the file. [ \\\Program Files\xx\DB.sdf ]" ``` Any ideas on what I'm doing wrong??
The problem was the connection string ..... `"Data Source=\\\Program Files\xx\DB.sdf"` apparently opens the database as a single user using `"Data Source=Program Files\xx\DB.sdf"` opens the database normally...
SQL Compact [does support multiple connections to the database](http://msdn.microsoft.com/en-us/library/ms171959.aspx), [even back with version 3.0](http://blogs.msdn.com/stevelasker/archive/2006/04/10/SqlEverywhereInfo.aspx). How is the first process opening the database? For example, the mobile Query Analyzer from 3.0 and 3.1 did open the database exclusively, effectively locking it from any other process.
Sql ce 3.0 Database multiuser
[ "", "c#", "windows-mobile", "sql-server-ce", "" ]
I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is. I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. The two ways to do this I can see are: * Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library. * Write or use an existing nose plugin to capture the output and verify it. If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module. Looking forward to your hints and tips on this one...
I used to mock loggers, but in this situation I found best to use logging handlers, so I wrote this one based on [the document suggested by jkp](http://www.fubar.si/2009/3/4/mocking-logging-python-module-for-unittests)(now dead, but cached on [Internet Archive](https://web.archive.org/web/20090416104408/http://www.fubar.si/2009/3/4/mocking-logging-python-module-for-unittests)) ``` class MockLoggingHandler(logging.Handler): """Mock logging handler to check for expected logs.""" def __init__(self, *args, **kwargs): self.reset() logging.Handler.__init__(self, *args, **kwargs) def emit(self, record): self.messages[record.levelname.lower()].append(record.getMessage()) def reset(self): self.messages = { 'debug': [], 'info': [], 'warning': [], 'error': [], 'critical': [], } ```
From python 3.4 on, the standard *unittest* library offers a new test assertion context manager, `assertLogs`. From the [docs](https://docs.python.org/3.4/library/unittest.html#unittest.TestCase.assertLogs): ``` with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) ```
How should I verify a log message when testing Python code under nose?
[ "", "python", "unit-testing", "mocking", "nose", "" ]
I'm trying to dynamically create and remove items from a list, it works just fine... sort of, I can remove items, and create items, but once an item has been created, I cannot remove it again, but I can remove the items present when the page loads. Here is my code ``` <div class="list"> <div class="item"> <input type="text" value="" /> <a href="" class="removeitem">Remove this item</a> </div> <div class="item"> <input type="text" value="" /> <a href="" class="removeitem">Remove this item</a> </div> <a href="" class="additem">Add item to list</a> </div> <script type="text/javascript"> // Add item to list $('.additem').click(function(){ var template = $($(this).prev().get(0)).clone(); template.insertBefore($(this)); return false; }); // Remove item from list $('.removeitem').click(function(){ $(this).prev().parent().remove(); return false; }); </script> ``` I can remove the 2 original items, but when I create new ones, they cannot be removed
You need to use [live events](http://docs.jquery.com/Events/live) rather than the normal style you are using at the moment. The click events are bound on load, at which point only the original items are present to be bound. You would use live events like this: ``` <script type="text/javascript"> // Add item to list $('.additem').click(function(){ var template = $($(this).prev().get(0)).clone(); template.insertBefore($(this)); return false; }); // Remove item from list $('.removeitem').live("click", function(){ $(this).prev().parent().remove(); return false; }); </script> ``` There is an overhead to using live events (it has to monitor all events in the DOM and check if they match I believe). Therefore, only use them when necessary.
Change: ``` $('.removeitem').click(function(){ $(this).prev().parent().remove(); return false; }); ``` to: ``` $('.removeitem').live("click", function(){ $(this).prev().parent().remove(); return false; }); ```
Removing dynamically inserted html with jQuery
[ "", "javascript", "jquery", "" ]
e.g. so that these would both work - is it possible? ``` (val,VAL2) = func(args) val = func(args) ``` Where **val** is **not a tuple** For example I'd like these to work for my custom object **something** ``` for item in something: do_item(item) #where again item - is not a tuple for (item,key) in something: do_more(key,item) ``` I thought that I need to implement next() function in two different ways... **edit:** as follows from the answers below, this should not really be done.
If you mean, can the function act differently based on the return types the caller is expecting, the answer is no (bar seriously nasty bytecode inspection). In this case, you should provide two different iterators on your object, and write something like: ``` for item in something: # Default iterator: returns non-tuple objects do_something(item) for (item,key) in something.iter_pairs(): # iter_pairs returns different iterator do_something_else(item, key) ``` eg. see the dictionary object, which uses this pattern. `for key in mydict` iterates over the dictionary keys. `for k,v in mydict.iteritems()` iterates over (key, value) pairs. **[Edit]** Just in case anyone wants to see what I mean by "seriously nasty bytecode inspection", here's a quick implementation: ``` import inspect, opcode def num_expected_results(): """Return the number of items the caller is expecting in a tuple. Returns None if a single value is expected, rather than a tuple. """ f = inspect.currentframe(2) code = map(ord, f.f_code.co_code) pos = f.f_lasti if code[pos] == opcode.opmap['GET_ITER']: pos += 1 # Skip this and the FOR_ITER if code[pos] > opcode.EXTENDED_ARG: pos +=5 elif code[pos] > opcode.HAVE_ARGUMENT: pos +=3 else: pos += 1 if code[pos] == opcode.opmap['UNPACK_SEQUENCE']: return code[pos+1] + (code[pos+2] << 8) return None ``` Usable something like: ``` class MagicDict(dict): def __iter__(self): if num_expected_results() == 2: for k,v in self.iteritems(): yield k,v else: for k in self.iterkeys(): yield k d=MagicDict(foo=1, bar=2) print "Keys:" for key in d: print " ", key print "Values" for k,v in d: print " ",k,v ``` **Disclaimer:** This is incredibly hacky, insanely bad practice, and *will* cause other programmers to hunt you down and kill you if they ever see it in real code. Only works on cpython (if that). **Never** use this in production code (or for that matter, probably any code).
Have you tried that? It works. ``` def myfunction(data): datalen = len(data) result1 = data[:datalen/2] result2 = data[datalen/2:] return result1, result2 a, b = myfunction('stuff') print a print b c = myfunction('other stuff') print c ``` In fact there is no such thing as "return signature". All functions return a single object. It seems that you are returning more than one, but in fact you wrap them into a container tuple object.
how to program functions with alternative return value signatures in python? (next() for alternative iterators)
[ "", "python", "" ]
I want to add some rows to a database using Linq to SQL, but I want to make a "custom check" before adding the rows to know if I must add, replace or ignore the incomming rows. I'd like to keep the trafic between the client and the DB server as low as possible and minimize the number of queries. To do this, I want to fetch as little information as required for the validation, and only once at the beginning of the process. I was thinking of doing something like this, but obviously, it doesn't work. Anyone have an idea? ``` Dictionary<int, DateTime> existingItems = (from ObjType ot in TableObj select (new KeyValuePair<int, DateTime>(ot.Key, ot.TimeStamp)) ) ``` What I'd like to have at the end would be a Dictionary, without having to download the whole ObjectType objects from TableObject. I also considered the following code, but I was trying to find a proper way: ``` List<int> keys = (from ObjType ot in TableObj orderby ot.Key select ot.Key).ToList<int>(); List<DateTime> values = (from ObjType ot in TableObj orderby ot.Key select ot.Value).ToList<int>(); Dictionary<int, DateTime> existingItems = new Dictionary<int, DateTime>(keys.Count); for (int i = 0; i < keys.Count; i++) { existingItems.Add(keys[i], values[i]); } ```
Try using [the `ToDictionary` method](https://msdn.microsoft.com/en-us/library/bb548657(v=vs.90).aspx) like so: ``` var dict = TableObj.Select( t => new { t.Key, t.TimeStamp } ) .ToDictionary( t => t.Key, t => t.TimeStamp ); ```
Looking at your example, I think this is what you want: ``` var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp); ```
Convert Linq Query Result to Dictionary
[ "", "c#", "linq", "linq-to-sql", "" ]
I have a 2 processes to perform in my swing application, one to fill a list, and one to do operations on each element on the list. I've just moved the 2 processes into Swingworker threads to stop the GUI locking up while the tasks are performed, and because I will need to do this set of operations to several lists, so concurrency wouldn't be a bad idea in the first place. However, when I just ran > fillList.execute(); > doStuffToList.execute(); the doStuffToList thread to ran on the empty list (duh...). How do I tell the second process to wait until the first one is done? I suppose I could just nest the second process at the end of the first one, but i dunno, it seems like bad practice.
Something like this would do it, I think? ``` boolean listIsFull=false; class FillListWorker extends SwingWorker<Foo,Bar> { ... protected void done() { synchronized (listYouveBeenFilling) { listIsFull=true; listYouveBeenFilling.notifyAll(); } } ... } class DoStuffToListListWorker extends SwingWorker<Foo,Bar> { ... protected Foo doInBackground() { synchronized (listYouveBeenFilling) { while (!listIsFull) { try { listYouveBeenFilling.wait(); } catch (InterruptedException ie) { // Don't worry, we'll just wait again } } } } ... } ```
> How do I tell the second process to wait until the first one is done? I suppose I could just nest the second process at the end of the first one, but i dunno, it seems like bad practice. Have you looked into using callables & futures instead? They sound like a good match for this sort of thing (letting the doStuffToList work on a Future.get() instead of the actual list, so it'll be ready when get is called), apart from the whole swingworker business.. (Consider this a suggestion rather than an answer)
Scheduling Swingworker threads
[ "", "java", "swing", "concurrency", "scheduling", "swingworker", "" ]
I am writing algorithms that work on series of numeric data, where sometimes, a value in the series needs to be null. However, because this application is performance critical, I have avoided the use of nullable types. I have perf tested the algorithms to specifically compare the performance of using nullable types vs non-nullable types, and in the best case scenario nullable types are 2x slower, but often far worse. The data type most often used is double, and currently the chosen alternative to null is double.NaN. However I understand this is not the exact intended usage for the NaN value, so am unsure whether there are any issues with this I cannot foresee and what the best practise would be. I am interested in finding out what the best null alternatives are for the following data types in particular: double/float, decimal, DateTime, int/long (although others are more than welcome) Edit: I think I need to clarify my requirements about performance. Gigs of numerical data are processed through these algorithms at a time which takes several hours. Therefore, although the difference between eg 10ms or 20ms is usually insignificant, in this scenario it really does makes a significant impact to the time taken.
Well, if you've ruled out `Nullable<T>`, you are left with domain values - i.e. a magic number that you treat as null. While this isn't *ideal*, it isn't uncommon either - for example, a lot of the main framework code treats `DateTime.MinValue` the same as null. This at least moves the damage far away from common values... **edit to highlight only where no NaN** So where there is no `NaN`, maybe use `.MinValue` - but just remember what evils happen if you accidentally *use* that same value meaning the same number... Obviously for unsigned data you'll need `.MaxValue` (avoid zero!!!). Personally, I'd try to use `Nullable<T>` as expressing my intent more safely... there may be ways to optimise your `Nullable<T>` code, perhaps. And also - by the time you've checked for the magic number in all the places you need to, perhaps it won't be much faster than `Nullable<T>`?
I somewhat disagree with Gravell on this specific edge case: a Null-ed variable is considered 'not defined', it doesn't have a value. So whatever is used to signal that is OK: even magic numbers, but with magic numbers you have to take into account that a magic number will always haunt you in the future when it becomes a 'valid' value all of a sudden. With Double.NaN you don't have to be afraid for that: it's never going to become a valid double. Though, you have to consider that NaN in the sense of the sequence of doubles can only be used as a marker for 'not defined', you can't use it as an error code in the sequences as well, obviously. So whatever is used to mark 'undefined': it has to be clear in the context of the set of values that that specific value is considered the value for 'undefined' AND that won't change in the future. If Nullable give you too much trouble, use NaN, or whatever else, as long as you consider the consequences: the value chosen represents 'undefined' and that will stay.
Alternatives to nullable types in C#
[ "", "c#", "nullable", "nan", "non-nullable", "" ]
I am converting a room editor I had made in AJAX to Flash where users can move furniture around where they want, but I am running into some issues with the x,y coordinates. With the Javascript/AJAX setup, I recorded the X,Y coordinates of the furniture image, and it worked fine from the top left corner of the image. However, now trying to make it work, and load the same setups into Flash instead of with AJAX, the placement is all off. It appears that X,Y coordinates that are returned to me are from the center of the image instead of from the top left (if I drag something to the top left corner of a "room," it shows X & Y as being half of the width and height). Any reason why this would be? I as under the impression the X,Y coordinates worked the same in both Javascript and Flash.
I would assume that you are doing all of this with the Flash IDE, because had you loaded this all at runtime with purely code, you would have went out of your way to force these to center by specifying an x and y that is half it's height and width. This all leads me to believe that you have put these into movieclips that you created with a centered registration. You need to check the x,y of the bitmaps you are using as furniture. Make sure that they are at 0,0 inside their parent movieclips. Then you simply move the parent around. If your bitmaps have negative values of half their width and height as their x and y values, this would center your bitmap in the middle of the MovieClip/Sprite as opposed to having a top-left registration. If you created a movieclip with centered registration, you do not have to destroy it a make a new one with another registration; Merely open the movieclip and set the bitmap/asset that is inside to a position of X: 0, Y: 0, then leave from inside the movieclip and once on the outside you will have to adjust it accordingly.
Ensure that each object's registration point is at its top left corner, and not at its center. More information: * [Adobe](http://help.adobe.com/en_US/Flash/10.0_UsingFlash/WSd60f23110762d6b883b18f10cb1fe1af6-7deea.html) * [Flash CS4: The Missing Manual](http://books.google.com/books?id=5lbgLdoGcusC&pg=PA234&lpg=PA234&source=bl&ots=QngiNs3-Vf&sig=cKfASaHe6kuoFfP_00-Kpq3Fsh4&hl=en&ei=5nooStPiPIqMtgeouejfBQ&sa=X&oi=book_result&ct=result&resnum=8)
X,Y coordinates seem to be generated from the middle of an object instead of the top left in flash
[ "", "javascript", "flash", "actionscript-3", "" ]
A client would like me to add their Twitter stream to their website homepage, using a custom solution built in PHP. The Twitter API obviously has a limited number of calls you can make to it per hour, so I can't automatically ping Twitter every time someone refreshes my client's homepage. The client's website is purely HTML at the moment and so there is **no database** available. My solution must therefore only require PHP and the local file system (e.g. saving a local XML file with some data in it). So, given this limited criteria, what's the best way for me to access the Twitter API - via PHP - without hitting my API call limit within a few minutes?
It will be quite easy, once you can pull down a timeline and display it, to then add some file-based-caching to it. ``` check age of cache Is it more than 5 mins old? fetch the latest information regenerate the HTML for output save the finished HTML to disk display the cached pre-prepared HTML ``` [PEAR's Cache\_Lite](http://pear.php.net/package/Cache_Lite) will do all you need on the caching layer.
You may want to use TweetPHP by Tim Davies. <http://lab.lostpixel.net/classes/twitter/> - This class has lots of features including the one you want, showing your clients time line. The page shows good examples on how to use it. You can then put the output of this in a file or database. If you want the site visitor to update the database or the file like every 5 minutes so, you can set a session variable holding a timestamp and just allow another update if the timestamp was at least 5 minutes ago. Hope this helps
What's the best way to use the Twitter API via PHP?
[ "", "php", "twitter", "" ]
is using TinyMCE a top choice for WYSIWYG editor on a webpage? What are good alternatives? some comparison seems to show that TinyMCE is one of the most compatible across browsers: <http://geniisoft.com/showcase.nsf/WebEditors>
TinyMCE is a great choice. I've used it in commercial offerings with good results. I'm also looking at FCKEditor for a new project specifically because of the integrated file upload and rumors that it has better XSS protection. Frankly, I'm not sure either one is sufficient to protect against XSS (you may have to supplement with something like <http://htmlpurifier.org/> if that is a concern).
I've been using FCKEditor with ASP.NET for years and have found it very easy to customize and configure. It's very stable and the intergrated upload feature is a plus. <http://www.fckeditor.net/>
is using TinyMCE a top choice for WYSIWYG editor on a webpage? What are good alternatives?
[ "", "javascript", "editor", "wysiwyg", "" ]
Is it possible to find out / get some information about the connecting client when using remoting on .net 2.0? I like to know get some information about the connecting client on the server side, so I can act accordingly? This is a small and very local application that Never will have more then max 10 simultaneously connecting/requesting clients. pass client reference in each function? (or some identifier)? I could do it this way, but I would prefer to just get the information from the request/connecting client. Ip-address or similar would be nice. Regards
Take a look at the answer I provided for a [similar question](https://stackoverflow.com/questions/527676/identifying-the-client-during-a-net-remoting-invocation): [Identifying the client during a .NET remoting invocation (Answer)](https://stackoverflow.com/questions/527676/identifying-the-client-during-a-net-remoting-invocation/527756#527756)
This [question](https://stackoverflow.com/questions/66363/get-external-ip-address-over-remoting-in-c) might have the answer you're looking for. I stripped out the parts that probably don't matter to you and left the part that actually grabs the IPAddress. ``` public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; } ```
remoting - information about the client. c#
[ "", "c#", "remoting", "" ]
For small logical programs that can be done in a text editor, for tracing I use the classic `System.out.println()`. I guess you all know how frustrating it is to use that in a block of high number of iterations. Why is it so slow? What's the reason behind it?
This has nothing whatsoever to do with the JVM. Printing text to screen simply involves a lot of work for the OS in drawing the letters and especially scrolling. If you redirect System.out to a file, it will be much faster.
This is very OS-dependent. For example, in Windows, writing to the console is a blocking operation, and it's also slow, and so writing lots of data to the console slows down (or blocks) your application. In unix-type OSes, writing to the console is buffered, so your app can continue unblocked, and the console will catch up as it can.
Java: What's the reason behind System.out.println() being that slow?
[ "", "java", "performance", "console", "stdout", "" ]
I'm writing a function that exponentiates an object, i.e. given a and n, returns an. Since a needs not be a built-in type, the function accepts, as a keyword argument, a function to perform multiplications. If undefined, it defaults to the objects `__mul__` method, i.e. the object itself is expected to have multiplication defined. That part is sort of easy: ``` def bin_pow(a, n, **kwargs) : mul = kwargs.pop('mul',None) if mul is None : mul = lambda x,y : x*y ``` The thing is that in the process of calculating an the are a lot of intermediate squarings, and there often are more efficient ways to compute them than simply multiplying the object by itself. It is easy to define another function that computes the square and pass it as another keyword argument, something like: ``` def bin_pow(a, n, **kwargs) : mul = kwargs.pop('mul',None) sqr = kwargs.pop('sqr',None) if mul is None : mul = lambda x,y : x*y if sqr is None : sqr = lambda x : mul(x,x) ``` The problem here comes if the function to square the object is not a standalone function, but is a method of the object being exponentiated, which would be a very reasonable thing to do. The only way of doing this I can think of is something like this: ``` import inspect def bin_pow(a, n, **kwargs) : mul = kwargs.pop('mul',None) sqr = kwargs.pop('sqr',None) if mul is None : mul = lambda x,y : x*y if sqr is None : sqr = lambda x : mul(x,x) elif inspect.isfunction(sqr) == False : # if not a function, it is a string sqr = lambda x : eval('x.'+sqr+'()') ``` It does work, but I find it an extremely unelegant way of doing things... My mastery of OOP is limited, but if there was a way to have sqr point to the class' function, not to an instance's one, then I could get away with something like `sqr = lambda x : sqr(x)`, or maybe `sqr = lambda x: x.sqr()`. Can this be done? Is there any other more pythonic way?
You can call unbound methods with the instance as the first parameter: ``` class A(int): def sqr(self): return A(self*self) sqr = A.sqr a = A(5) print sqr(a) # Prints 25 ``` So in your case you don't actually need to do anything specific, just the following: ``` bin_pow(a, n, sqr=A.sqr) ``` Be aware that this is early binding, so if you have a subclass B that overrides sqr then still A.sqr is called. For late binding you can use a lambda at the callsite: ``` bin_pow(a, n, sqr=lambda x: x.sqr()) ```
here's how I'd do it: ``` import operator def bin_pow(a, n, **kwargs) : pow_function = kwargs.pop('pow' ,None) if pow_function is None: pow_function = operator.pow return pow_function(a, n) ``` That's the fastest way. See also [`object.__pow__`](http://docs.python.org/reference/datamodel.html#object.__pow__) and the [`operator`](http://docs.python.org/library/operator.html) module documentations. Now, to pass an object method you can pass it directly, no need to pass a string with the name. In fact, never use strings for this kind of thing, using the object directly is much better. If you want the unbound method, you can pass it just as well: ``` class MyClass(object): def mymethod(self, other): return do_something_with_self_and_other m = MyClass() n = MyClass() bin_pow(m, n, pow=MyClass.mymethod) ``` If you want the class method, so just pass it instead: ``` class MyClass(object): @classmethod def mymethod(cls, x, y): return do_something_with_x_and_y m = MyClass() n = MyClass() bin_pow(m, n, pow=MyClass.mymethod) ```
Referencing a class' method, not an instance's
[ "", "python", "" ]
I have a lot of shared C++ code that I'd like to use in my iPhone app. I added the .cpp and .h files to my Xcode project and used the classes in my Objective-C++ code. The project compiles fine with 0 errors or warnings. However, when I run it in the simulator I get the following error when I attempt to access an STL method in my objective-c code (such as `.c_str()`): ``` Program received signal: “EXC_BAD_ACCESS”. Unable to disassemble std::string::c_str. ``` Here's an example of the code that causes the error: ``` [name setText:[[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str()]]; ``` where `name` is an NSTextField object and `cppname` is a std::string member of `myCPlusPlusObject`. Am I going about this the right way? Is there a better way to use STL-laden C++ classes in Objective-C++? I would like to keep the common C++ files untouched if possible, to avoid having to maintain the code in two places. Thanks in advance!
Make sure the string isn't empty before passing it to the `initWithCString` function. Also the function you're using has been deprecated, [use this one instead](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/initWithCString:encoding:).
Note also that this line of code: ``` [name setText:[[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str()]]; ``` leaks the created string. Go back and read the memory management rules at <http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>. The main issue is there you have allocated the string, therefore you have taken ownership of it, and you then never release it. You should do one of the following: ``` [name setText:[[[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str() encoding:NSUTF8StringEncoding] autorelease]]; ``` or ``` NSString* myCPlusPlusString = [[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str() encoding:NSUTF8StringEncoding]; [name setText:myCPlusPlusString]; [myCPlusPlusString release]; ``` or ``` [name setText:[NSString stringWithCString:myCPlusPlusObject->cppname.c_str() encoding:NSUTF8StringEncoding]]; ``` The latter is the best as far as code simplicity is concerned. The middle one is the best as far as memory usage is concerned, which is frequently an issue on the iPhone. The first one is likely identical to the last one - I say "likely" because there is no guarentee that stringWithCString returns an autoreleased object. It probably does, but whether it does or not is not your concern, all that matters to you is that you do not take ownership of the string because the method name does not begin with “alloc” or “new” or contains “copy” and so you are not responsible for releaing it.
Using shared C++/STL code with Objective-C++
[ "", "c++", "iphone", "objective-c", "xcode", "stl", "" ]
We have an application that produces a database on disk. The database is made of thousand of files. The application can have from 500 to 3000 file's handle opened at the same time. These handle are kept opened and data is continuously written to. Up until now, it worked really well on local hard drive, but when trying to put the database on a shared disk, we encountered a lot of problems. Is it simply a bad idea or it can work if we change the design of the database engine to open/close file handle on demand? **EDIT** At this time, we only have one client "connected" to the database.
Based on experience with "shared file" databases (dBase, Paradox and the like) this doesn't scale well. It can also be very sensitive to network errors and bad hardware.
> "Is it simply a bad idea or it can work if we change the design of the database engine to open/close file handle on demand?" Yes it is simply a bad idea. If you want to share your database I would suggest refactoring to a standard database designed to scale well and work with multi-user access.
How reliable is file sharing on Windows when using it for a database?
[ "", "c++", "windows", "networking", "" ]
We have bunch of autogenerated classes which are mostly Axis2 stubs, skeletons etc. For some complicated wsdls, Axis2 generates a TON of java-beans, stubs etc. And I am sure there are other cases too when auto generation is used. For now we treat these as other first class members of our code-base and they are stored in the same packages. However when doing refactoring, cleanups etc it becomes hard to weed out the warnings that are coming from these auto-generated classes. For example, if I am trying to clean up the code so as to use Java1.5 generics, there is no good way to know how many of these offending classes are ours vs being auto-generated. Should I be separating these autogenerated parts out into a different package? How do you guys store such artifacts in the repository? EDIT: I see 'generate during build process' in quite a few answers below. While I see the benefits of doing that, I dont quite see how I can get away from a repository checkin. My code has compile time dependencies on some of these classes and for me, a build during development is a 'ctrl-s' in eclipse. We use ant-scripts to generate the compile, run tests and generate deliverables.
You can keep the same packages but use a different source folder (something like generated-src), which is what we do. I'm actually on the fence about the whole idea of saving generated code in the source code repository. We do it as a convenience for other developers on the project, but it usually makes sense to regenerate the source code as part of the build process. If this generated code is unlikely to change, then using a separate project and generating a jar might be more practical.
Summary of best practices: * Make it repeatable + Create generated code as part of a build process. + Don't check generated code into source control. (Do check in the source. e.g. WSDL) * Keep generated code separate from managed code + Use a different source folder for generated output. + Deliver a separate .jar so that this generated code becomes a dependency. + Consider using a different IDE project (or maven module)
A good place to put autogenerated code?
[ "", "java", "code-generation", "apache-axis", "axis", "" ]
Are there non obvious differences between NVL and Coalesce in Oracle? The obvious differences are that coalesce will return the first non null item in its parameter list whereas nvl only takes two parameters and returns the first if it is not null, otherwise it returns the second. It seems that NVL may just be a 'Base Case" version of coalesce. Am I missing something?
`COALESCE` is more modern function that is a part of `ANSI-92` standard. `NVL` is `Oracle` specific, it was introduced in `80`'s before there were any standards. In case of two values, they are synonyms. However, they are implemented differently. `NVL` always evaluates both arguments, while `COALESCE` usually stops evaluation whenever it finds the first non-`NULL` (there are some exceptions, such as sequence `NEXTVAL`): ``` SELECT SUM(val) FROM ( SELECT NVL(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val FROM dual CONNECT BY level <= 10000 ) ``` This runs for almost `0.5` seconds, since it generates `SYS_GUID()`'s, despite `1` being not a `NULL`. ``` SELECT SUM(val) FROM ( SELECT COALESCE(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val FROM dual CONNECT BY level <= 10000 ) ``` This understands that `1` is not a `NULL` and does not evaluate the second argument. `SYS_GUID`'s are not generated and the query is instant.
NVL will do an implicit conversion to the datatype of the first parameter, so the following does not error ``` select nvl('a',sysdate) from dual; ``` COALESCE expects consistent datatypes. ``` select coalesce('a',sysdate) from dual; ``` will throw a 'inconsistent datatype error'
Oracle Differences between NVL and Coalesce
[ "", "sql", "oracle", "coalesce", "nvl", "" ]
How do I include a JavaScript file inside another JavaScript file, similar to `@import` in CSS?
The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed. But since 2015 (ES6), JavaScript has had the [ES6 modules](http://exploringjs.com/es6/ch_modules.html) standard to import modules in Node.js, which is also supported by [most modern browsers](https://caniuse.com/#feat=es6-module). For compatibility with older browsers, build tools like [Webpack](https://webpack.github.io/) and [Rollup](https://rollupjs.org/) and/or transpilation tools like [Babel](https://babeljs.io/) can be used. # ES6 Modules ECMAScript (ES6) modules have been [supported in Node.js](https://nodejs.org/api/esm.html) since v8.5, with the `--experimental-modules` flag, and since at least Node.js v13.8.0 without the flag. To enable "ESM" (vs. Node.js's previous CommonJS-style module system ["CJS"]) you either use `"type": "module"` in `package.json` or give the files the extension `.mjs`. (Similarly, modules written with Node.js's previous CJS module can be named `.cjs` if your default is ESM.) Using `package.json`: ``` { "type": "module" } ``` Then `module.js`: ``` export function hello() { return "Hello"; } ``` Then `main.js`: ``` import { hello } from './module.js'; let val = hello(); // val is "Hello"; ``` Using `.mjs`, you'd have `module.mjs`: ``` export function hello() { return "Hello"; } ``` Then `main.mjs`: ``` import { hello } from './module.mjs'; let val = hello(); // val is "Hello"; ``` ## ECMAScript modules in browsers Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) [since](https://jakearchibald.com/2017/es-modules-in-browsers/) Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at [caniuse](https://caniuse.com/#feat=es6-module). There is no need to use Node.js' `.mjs` extension; browsers completely ignore file extensions on modules/scripts. ``` <script type="module"> import { hello } from './hello.mjs'; // Or the extension could be just `.js` hello('world'); </script> ``` ``` // hello.mjs -- or the extension could be just `.js` export function hello(text) { const div = document.createElement('div'); div.textContent = `Hello ${text}`; document.body.appendChild(div); } ``` Read more at <https://jakearchibald.com/2017/es-modules-in-browsers/> ### Dynamic imports in browsers Dynamic imports let the script load other scripts as needed: ``` <script type="module"> import('hello.mjs').then(module => { module.hello('world'); }); </script> ``` Read more at <https://developers.google.com/web/updates/2017/11/dynamic-import> # Node.js require The older CJS module style, still widely used in Node.js, is the [`module.exports`/`require`](https://nodejs.org/api/modules.html) system. ``` // mymodule.js module.exports = { hello: function() { return "Hello"; } } ``` ``` // server.js const myModule = require('./mymodule'); let val = myModule.hello(); // val is "Hello" ``` There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing. # AJAX Loading You could load an additional script with an AJAX call and then use `eval` to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using `eval` also opens the door to bugs, hacks and security issues. # Fetch Loading Like Dynamic Imports you can load one or many scripts with a `fetch` call using promises to control order of execution for script dependencies using the [Fetch Inject](https://www.npmjs.com/package/fetch-inject) library: ``` fetchInject([ 'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js' ]).then(() => { console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`) }) ``` # jQuery Loading The [jQuery](http://jquery.com/) library provides loading functionality [in one line](http://api.jquery.com/jQuery.getScript/): ``` $.getScript("my_lovely_script.js", function() { alert("Script loaded but not necessarily executed."); }); ``` # Dynamic Script Loading You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution. The script can even reside on a different server. Furthermore, the browser evaluates the code. The `<script>` tag can be injected into either the web page `<head>`, or inserted just before the closing `</body>` tag. Here is an example of how this could work: ``` function dynamicallyLoadScript(url) { var script = document.createElement("script"); // create a script DOM node script.src = url; // set its src to the provided URL document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead) } ``` This function will add a new `<script>` tag to the end of the head section of the page, where the `src` attribute is set to the URL which is given to the function as the first parameter. Both of these solutions are discussed and illustrated in [JavaScript Madness: Dynamic Script Loading](http://unixpapa.com/js/dyna.html). # Detecting when the script has been executed Now, there is a big issue you must know about. Doing that implies that *you remotely load the code*. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.) It means that if you use these tricks directly, *you won't be able to use your newly loaded code the next line after you asked it to be loaded*, because it will be still loading. For example: `my_lovely_script.js` contains `MySuperObject`: ``` var js = document.createElement("script"); js.type = "text/javascript"; js.src = jsFilePath; document.body.appendChild(js); var s = new MySuperObject(); Error : MySuperObject is undefined ``` Then you reload the page hitting `F5`. And it works! Confusing... **So what to do about it ?** Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example: ``` function loadScript(url, callback) { // Adding the script tag to the head as suggested before var head = document.head; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = callback; script.onload = callback; // Fire the loading head.appendChild(script); } ``` Then you write the code you want to use AFTER the script is loaded in a [lambda function](http://en.wikipedia.org/wiki/Anonymous_function): ``` var myPrettyCode = function() { // Here, do whatever you want }; ``` Then you run all that: ``` loadScript("my_lovely_script.js", myPrettyCode); ``` Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line `script.async = false;`. There's a [great article on Javascript loading in general](http://www.html5rocks.com/en/tutorials/speed/script-loading/) which discusses this. # Source Code Merge/Preprocessing As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.
If anyone is looking for something more advanced, try out [RequireJS](http://requirejs.org/). You'll get added benefits such as dependency management, better concurrency, and avoid duplication (that is, retrieving a script more than once). You can write your JavaScript files in "modules" and then reference them as dependencies in other scripts. Or you can use RequireJS as a simple "go get this script" solution. Example: Define dependencies as modules: **some-dependency.js** ``` define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) { //Your actual script goes here. //The dependent scripts will be fetched if necessary. return libraryObject; //For example, jQuery object }); ``` **implementation.js** is your "main" JavaScript file that depends on **some-dependency.js** ``` require(['some-dependency'], function(dependency) { //Your script goes here //some-dependency.js is fetched. //Then your script is executed }); ``` Excerpt from the [GitHub](https://github.com/jrburke/requirejs) README: > RequireJS loads plain JavaScript files as well as more defined > modules. It is optimized for in-browser use, including in a Web > Worker, but it can be used in other JavaScript environments, like > Rhino and Node. It implements the Asynchronous Module API. > > RequireJS uses plain script tags to load modules/files, so it should > allow for easy debugging. It can be used simply to load existing > JavaScript files, so **you can add it to your existing project without > having to re-write your JavaScript files.** > > ...
How do I include a JavaScript file in another JavaScript file?
[ "", "javascript", "file", "import", "include", "" ]
In my Java application I am renaming files to a file name provided in a String parameter. There is a method ``` boolean OKtoRename(String oldName, String newName) ``` which basically checks whether the newName isn't already taken by some other file, as I wouldn't want to bury existing ones. It now occurred to me that perhaps the newName String will not denote a valid file name. So I thought to add this check to the method: ``` if (new File(newName).isFile()) { return false; } ``` Which obviously isn't the right way to do it, since in most cases the newFile does not yet exist and therefore although it *is* OKtoRename, the function returns false. I was wondering, is there a method (I know there isn't for the java.io.File objects) like `canExist()`? Or would I have to resort to regex to make sure the newFile String does not contain invalid characters (e.g. ?, \*, ", :)? I wonder if there is perhaps a function hidden somewhere in the JDK that would tell me if a string could possibly denote a valid file name.
Use [`createNewFile()`](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createNewFile()), which will atomically create the file only if it doesn't yet exist. If the file is created, the name is valid and it is not clobbering an existing file. You can then open the files and efficiently copy data from one to the other with `FileChannel.transferXXX` operations. An important thing to keep in mind that, in general, the check and the creation should be atomic. If you first check whether an operation is safe, then perform the operation as a separate step, conditions may have changed in the meantime, making the operation unsafe. Additional food for thought is available at this related post: ["Move/Copy operations in Java."](https://stackoverflow.com/questions/300559/move-copy-file-operations-in-java) --- *Update:* Since this answer, the NIO.2 APIs have been introduced, which add more interaction with the file system. Suppose you have an interactive program, and want to validate after each keystroke whether the file is potentially valid. For example, you might want to enable a "Save" button only when the entry is valid rather than popping up an error dialog after pressing "Save". Creating and ensuring the deletion of a lot of unnecessary files that my suggestion above would require seems like a mess. With NIO.2, you can't create a `Path` instance containing characters that are illegal for the file system. An `InvalidPathException` is raised as soon as you try to create the `Path`. However, there isn't an API to validate illegal names comprised of valid characters, like "PRN" on Windows. As a workaround, experimentation showed that using an illegal file name would raise a distinct exception when trying to access attributes (using `Files.getLastModifiedTime()`, for example). If you specify a legal name for a file that does exist, you get no exception. If you specify a legal name for a file that does not exist, it raises `NoSuchFileException`. If you specify an illegal name, `FileSystemException` is raised. However, this seems very kludgey and might not be reliable on other operating systems.
I assembled a list of illegal filename characters (considering UNIX, Mac OS X and Windows systems) based on some online research a couple of months ago. If the new filename contains any of these, there's a risk that it might not be valid on all platforms. ``` private static final char[] ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' }; ``` **EDIT:** I would like to stress, that this is **not a complete solution**: as a commenter pointed out, even though it passes this test your file name could still be a Windows specific keyword like COM, PRN, etc. However, if your file name contains any of these characters, it will certainly cause trouble in a cross-platform environment.
Java - How to find out whether a File name is valid?
[ "", "java", "file", "" ]
I've seen that you can manipulate [private and internal members using reflection](http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx). I've also seen it said that a ['sealed' class is more secure that one that isn't](http://www.allinterview.com/showanswers/4887.html). Are the modifiers "public, protected, internal, private, abstract, sealed, readonly" anything more than a gentleman's agreement about design and API use, that can be broken as long as you have access to reflection? And if a hacker is already is running code that calls your API, the game is already lost, right? Is the following anymore secure than any other class? ``` //private class sealed class User { private string _secret = "shazam"; public readonly decimal YourSalary; public string YourOffice{get;}; private DoPrivilegedAction() { } } ```
First, to answer your question: The security system is designed to protect **GOOD USERS from BAD CODE**; it is explicitly not designed to protect **GOOD CODE from BAD USERS**. Your access restrictions mitigate **attacks on your users** by **partially trusted hostile code**. They do not mitigate **attacks on your code** from **hostile users**. If the threat is hostile users getting your code, then you have a big problem. The security system does not mitigate that threat at all. Second, to address some of the previous answers: understanding the full relationship between reflection and security requires careful attention to detail and a good understanding of the details of the CAS system. The previously posted answers which state that there is no connection between security and access because of reflection are misleading and wrong. Yes, reflection allows you to override "visibility" restrictions (sometimes). That does not imply that there is no connection between access and security. The connection is that the right to use reflection to override access restrictions is deeply connected to the CAS system in multiple ways. First off, in order to do so *arbitrarily*, code must be granted private reflection permission by the CAS system. This is typically only granted to fully trusted code, which, after all, could already do *anything*. Second, in the new .NET security model, suppose assembly A is granted a superset of the grant set of assembly B by the CAS system. In this scenario, code in assembly A is allowed to use reflection to observe B's internals. Third, things get really quite complicated when you throw in dynamically generated code into the mix. An explanation of how "Skip Visibility" vs "Restricted Skip Visibility" works, and how they change the interactions between reflection, access control, and the security system in scenarios where code is being spit at runtime would take me more time and space than I have available. See Shawn Farkas's blog if you need details.
Access modifiers aren't about security, but good design. Proper access levels for classes and methods drives/enforces good design principles. Reflection should, ideally, only be used when the convenience of using it provides more utility than the cost of violating (if there is one) best design practices. Sealing classes only serves the purpose of preventing developers from extending your class and "breaking" it's functionality. There are different opinions on the utility of sealing classes, but since I do TDD and it's hard to mock a sealed class, I avoid it as much as possible. If you want security, you need to follow coding practices that prevent the bad guys from getting in and/or protect confidential information from inspection even if a break in occurs. Intrusion prevention, intrusion detection, encryption, auditing, etc. are some of the tools that you need to employ to secure your application. Setting up restrictive access modifiers and sealing classes has little to do with application security, IMO.
Do the access levels and modifiers (private, sealed, etc) serve a security purpose in C#?
[ "", "c#", "security", "sealed", "" ]
I was browsing some old books and found a copy of "Practical Java" by Peter Hagger. In the performance section, there is a recommendation to set object references to `null` when no longer needed. In Java, does setting object references to `null` improve performance or garbage collection efficiency? If so, in what cases is this an issue? Container classes? Object composition? Anonymous inner classes? I see this in code pretty often. Is this now obsolete programming advice or is it still useful?
It depends a bit on when you were thinking of nulling the reference. If you have an object chain A->B->C, then once A is not reachable, A, B and C will all be eligible for garbage collection (assuming nothing else is referring to either B or C). There's no need, and never has been any need, to explicitly set references A->B or B->C to null, for example. Apart from that, most of the time the issue doesn't really arise, because in reality you're dealing with objects in collections. You should generally always be thinking of removing objects from lists, maps etc by calling the appropiate remove() method. The case where there **used to be** some advice to set references to null was specifically in a **long scope where a memory-intensive object ceased to be used partway through the scope**. For example: ``` { BigObject obj = ... doSomethingWith(obj); obj = null; <-- explicitly set to null doSomethingElse(); } ``` The rationale here was that because *obj* is still in scope, then without the explicit nulling of the reference, it does not become garbage collectable until after the *doSomethingElse()* method completes. And this is the advice that **probably no longer holds on modern JVMs**: it turns out that the JIT compiler can work out at what point a given local object reference is no longer used.
No, it's not obsolete advice. Dangling references are still a problem, especially if you're, say, implementing an expandable array container (`ArrayList` or the like) using a pre-allocated array. Elements beyond the "logical" size of the list should be nulled out, or else they won't be freed. See Effective Java 2nd ed, Item 6: Eliminate Obsolete Object References.
Does setting Java objects to null do anything anymore?
[ "", "java", "garbage-collection", "performance", "" ]
I've had no need to send mails on my 2 sites hosted at the UK Fasthosts provider. But since I've added some email features to one of my sites I've tried to send mail via the Email Component of CakePHP and it doesn't leave the server, even if the send returns success. I've tried with plain mail() function and with the smtp option and got nowhere. Any ideas?
I had the same problem with Fasthosts. They have made it so you have to add `-f` in front of your "sent from" email address so this is what my mail function call looks like: ``` mail($email_to, $email_subject, $email_message, $headers, '-f'.$email_from); ``` You can get more info from page on Fasthots help: <http://www.fasthosts.co.uk/knowledge-base/?article_id=65>
I am not familiar with that hosting service but I've had similar experiences with other providers. The one thing that's worked across them all is the SwiftMailer library. Check it out and see if it works for you. <http://swiftmailer.org/>
How to send mail via PHP and/or CakePHP on a Fasthosts account
[ "", "php", "email", "cakephp", "smtp", "" ]
I saw some existing code in the PHP scripts doing a ``` system('hostname'); ``` how big can the performance impact on the server be if using this method?
Running external processes can be a real performance hit when you have thousands of clients trying to connect to your web server. That's why people ended up ditching CGI (common gateway interface, the act of web servers calling external processes to dynamically create content) and incorporating code directly into their web servers, such as mod\_perl. You won't notice it when you're testing your little web application at home but, when the hordes that make up the Internet swarm down to your site, it will collapse under the load. You'd be far better trying to figure out a way to cache this information within PHP itself (how often does it change, really?). For your particular example, you could use the `"php_uname('n')"` call to retrieve the full name (e.g., `"localhost.example.com"` and (optionally) strip off the domain part, but I've assumed you want the question answered in a more general sense. --- *Update:* Since someone has requested benchmarks, here's a C program that does three loops of 1,000 iterations each. The first does nothing within the loop, the second gets an environment variable (one other possibility for having PHP get its hostname), the third runs a `system()` command to execute hostname: ``` #include <stdio.h> #include <time.h> #define LOOP1 1000 int main (int c, char *v[]) { time_t t1, t2, t3, t4; int i; t1 = time(NULL); for (i = 0; i < LOOP1; i++) { } t2 = time(NULL); for (i = 0; i < LOOP1; i++) { getenv ("xxhostname"); } t3 = time(NULL); for (i = 0; i < LOOP1; i++) { system ("hostname >/dev/null"); } t4 = time(NULL); printf ("Loop 1 took %d seconds\n", t2-t1); printf ("Loop 2 took %d seconds\n", t3-t2); printf ("Loop 3 took %d seconds\n", t4-t3); return 0; } ``` The results are: ``` Cygwin (gcc): Loop 1 took 0 seconds Loop 2 took 0 seconds Loop 3 took 103 seconds Linux on System z (gcc): Loop 1 took 0 seconds Loop 2 took 0 seconds Loop 3 took 5 seconds Linux on Intel (gcc): Loop 1 took 0 seconds Loop 2 took 0 seconds Loop 3 took 5 seconds Linux on Power (gcc): Loop 1 took 0 seconds Loop 2 took 0 seconds Loop 3 took 4 seconds Windows on Intel (VS2008, and using "ver >nul:", not "hostname"): Loop 1 took 0 seconds Loop 2 took 0 seconds Loop 3 took 45 seconds ``` However you slice'n'dice it, that's quite a discrepancy on loop number 3. It probably won't cause any problems if you're getting one hit a week on your site but, if you hold any hope of surviving in the real world under load, you'd be best to avoid `system()` calls as much as possible.
Errm, you are aware of [php\_uname](https://www.php.net/manual/en/function.php-uname.php) and [posix\_uname](https://www.php.net/manual/en/function.posix-uname.php), right? ``` <?php echo "php_uname: " . php_uname('n') . "\n"; $ar = posix_uname(); echo "posix_uname: $ar[nodename]\n"; ?> ``` should both work. In PHP 5.3, there is also a `gethostname`.
how big is the performance impact of using system('hostname') in PHP?
[ "", "php", "performance", "" ]
I'm getting an NPE while trying to read in an image file, and I can't for the life of me figure out why. Here is my line: ``` BufferedImage source = ImageIO.read(new File(imgPath)); ``` imgPath is basically guaranteed to be valid and right before it gets here it copies the file from the server. When it hits that line, I get this stack trace: ``` Exception in thread "Thread-26" java.lang.NullPointerException at com.ctreber.aclib.image.ico.ICOReader.getICOEntry(ICOReader.java:120) at com.ctreber.aclib.image.ico.ICOReader.read(ICOReader.java:89) at javax.imageio.ImageIO.read(ImageIO.java:1400) at javax.imageio.ImageIO.read(ImageIO.java:1286) at PrintServer.resizeImage(PrintServer.java:981) <---My function <Stack of rest of my application here> ``` Also, this is thrown into my output window: Can't create ICOFile: Can't read bytes: 2 I have no idea what is going on, especially since the File constructor is succeeding. I can't seem to find anybody who has had a similar problem. Anybody have any ideas? (Java 5 if that makes any difference)
I poked around some more and found that you can specify which ImageReader ImageIO will use and read it in that way. I poked around our codebase and found that we already had a function in place for doing EXACTLY what I was trying to accomplish here. Just for anybody else who runs into a similar issue, here is the crux of the code (some of the crap is defined above, but this should help anybody who tries to do it): ``` File imageFile = new File(filename); Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("jpeg"); if ( imageReaders.hasNext() ) { imageReader = (ImageReader)imageReaders.next(); stream = ImageIO.createImageInputStream(imageFile); imageReader.setInput(stream, true); ImageReadParam param = imageReader.getDefaultReadParam(); curImage = imageReader.read(0, param); } ``` Thanks for the suggestions and help all.
The File constructor will almost certainly succeed, *regardless of whether it points to a valid/existing file*. At the very least, I'd check whether your underlying file exists via the `exists()` method.
NullPointerException using ImageIO.read
[ "", "java", "nullpointerexception", "javax.imageio", "" ]
I've got a CakePHP site that is stuck in a redirect loop. I've removed every piece of code that does a redirect & I've turned off autoRedirect on the Auth object. This occurred when I logged out of the site and has persisted even after deleting all cookies and just trying to load the homepage. The index action is in `$this->Auth->allow`. I should not, it keeps trying to redirect me to /users/login which then redirect loops. The login action is also in the allowed list Does anyone have any ideas what could cause this?
Your `<cake>/app/app_controller` should have a `beforeFilter()` method with all behaviors of **Auth** component. One of those behaviors is where to send when a user is not logged in. you will be looking for something like: ``` // If cake should redirect automatically or you will do it in the User.login() $this->Auth->autoRedirect = true; // And if the autoRedirect is true, where to redirect $this->Auth->loginRedirect = '/user/login'; ``` G'luck
This also occurs in CakePHP 1.3 if you add a custom component that extends **Component** instead of **Object**.
How do I troubleshoot a CakePHP application stuck in a redirect loop?
[ "", "php", "cakephp", "redirect", "" ]
OK, I am considering of getting into c++ development in coming months (there is no set date). I am vaguely familiar with the language (primarily C), as well as some basics of OO, MI, templates, exceptions, patterns, used STL. And now I am at the point in time where I would like to master the language in depth. And the natural question is whether I should start with current **C++03** or **C++0x** standard. Please suggest what the best way to go from a user to guru, given that new standard is almost here, and likely to remain for many years to come. Thanks
My recommendation is to start out in the middle. Start with C++03, but check the features and C++0x libs that some compilers are already offering each so often. As of now, C++03 is THE standard (not only formally, but most code you will find will be strictly C++03). Now, if you intend on learning go for the best: start quickly with STL basics and jump into Boost libraries right away. Learn templates the whole way, read on metaprogramming. Modern C++03 usage will get you right on track for C++0x.
Learn the older standard C++03. C++0X is still a couple years away (at least) from even being ratified as a standard. Once it's standardized, it'll take time before *any* conforming implementations appear that support all of its features, and it'll take an even *longer* time before C++0X implementations become significantly popular and oft-used.
Should I learn C++ based on new or old standard (specification)?
[ "", "c++", "c++11", "" ]
In my program (a program that assists with pathfinding), i need to store a list that contains entries consisting of a start node and an end node. A dictionary won't work as i cannot guarantee that the "key" (a node of course) will be unique. What is the best way to store this manner of data? Edit: i use C# and .Net 3.5.
You might be better off simply using an array of structs. Or a vector of structs. This allows for non-unique nodes in your list. Vectors are a standard template in C++, but if C# doesn't support it, then an array should work fine.
Would it be possible for you to use a List of KeyValuePair objects? Like this? ``` List<KeyValuePair<ObjectA, ObjectB>> list = new List<KeyValuePair<ObjectA, ObjectB>>(); ``` I don't have VS in front of me right now, so I'm not sure if I have the syntax 100% right, but hopefully this helps.
How to store related data
[ "", "c#", "list", "" ]
Consider the following C# code: ``` IEnumerable numbers = Enumerable.Range(0, 10); var evens = from num in numbers where num % 2 == 0 select num; ``` Is this pure syntactic sugar to allow me to write a `for` or `foreach` loop as a one-liner? Are there any compiler optimizations under the covers that make the list comprehension above more efficient than the loop construct? How does this work under the hood?
As Jason said, your code is equivalent to: ``` Enumerable.Range(0, 10).Where(n => n % 2 == 0); ``` Note the lambda will be transformed to a function call which is done for every element. This is probably the largest part of the overhead. I did a test, which indicates LINQ is about 3 times slower (mono gmcs version 1.2.6.0) on this exact task ``` Time for 10000000 for loop reps: 00:00:17.6852560 Time for 10000000 LINQ reps: 00:00:59.0574430 Time for 1000000 for loop reps: 00:00:01.7671640 Time for 1000000 LINQ reps: 00:00:05.8868350 ``` EDIT: Gishu reports that VS2008 and framework v3.5 SP1 gives: ``` Time for 1000000 loop reps: :00.3724585 Time for 1000000 LINQ reps: :00.5119530 ``` LINQ is about 1.4 times slower there. It compares a for-loop and a list to LINQ (and whatever structure it uses internally). Either way, it converts the result to an array (necessary to force LINQ to stop being "lazy"). Both versions repeat: ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; public class Evens { private static readonly int[] numbers = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; private static int MAX_REPS = 1000000; public static void Main() { Stopwatch watch = new Stopwatch(); watch.Start(); for(int reps = 0; reps < MAX_REPS; reps++) { List<int> list = new List<int>(); // This could be optimized with a default size, but we'll skip that. for(int i = 0; i < numbers.Length; i++) { int number = numbers[i]; if(number % 2 == 0) list.Add(number); } int[] evensArray = list.ToArray(); } watch.Stop(); Console.WriteLine("Time for {0} for loop reps: {1}", MAX_REPS, watch.Elapsed); watch.Reset(); watch.Start(); for(int reps = 0; reps < MAX_REPS; reps++) { var evens = from num in numbers where num % 2 == 0 select num; int[] evensArray = evens.ToArray(); } watch.Stop(); Console.WriteLine("Time for {0} LINQ reps: {1}", MAX_REPS, watch.Elapsed); } } ``` Past performance tests on similar tasks (e.g. [LINQ vs Loop - A performance test](http://ox.no/posts/linq-vs-loop-a-performance-test)) corroborate this.
You can simplify the code further by ``` var evens = Enumerable.Range(0, 10).Where(n => n % 2 == 0); ``` One advantage of this form is that the execution of this expression is deferred until `evens` is iterated over (`foreach(var n in evens) { ... }`). The above statement merely tells the compiler to capture the idea of how to enumerate the even numbers between 0 and 10, but do not execute on that idea until absolutely necessary.
C# List Comprehensions = Pure Syntactic Sugar?
[ "", "c#", "linq", "optimization", "compiler-construction", "list-comprehension", "" ]
I want to supply unknown "object" and return the value of one of its members. Response is required in C#. Generically I guess I'm looking for the code to this method public static object GetObjectMemberValue (object myObject, string memberName) More specifically I'm doing this for resource strings in Silverlight and need to write this method. It resides in a common project is used against a few different Resx dictionaries, thus I don't have access to the type information. public static string GetString (object StringResources, string ResourceId) Thank you!
This will get your value... Can you give me more info in the resx part of the question? ``` public static object GetObjectMemberValue(object myObject, string memberName) { PropertyInfo dateProperty = myObject.GetType().GetProperty(memberName); return dateProperty.GetValue(myObject, null); } ```
if you know the objects type, then cast to it? Or it should at least implement an interface if you don't know the explicit type? ``` MyType value = (MyType)objectGetter() //this is the function that returns the unknown. value.GetMember() ```
Easy Reflection question C#
[ "", "c#", ".net", "reflection", "" ]
To put it in a nutshell - In an oracle db, I want to make a column varchar2(16) which is now varchar2(8), without affecting the values presnet. I have already tried this and it does weird things. The query I tried was - alter table SOME\_TABLE modify (SOME\_COL varchar2(16)); But the values(some not all) already present in the table get '\0' appended to them when I run the above query. So, what is the right way of doing what I want?
The command you are executing is correct. Are you sure the additional characters you are seeing are not already present?
It's very doubtful that the raw data in the table is being changed. Since some of your comments imply you are using tools and applications other than SQLPlus to look at and process the data, I think you need to look at whether they are mishandling the data in some way. Here's an example where I tried to reproduce what you did in straight SQLPlus. No null bytes are appended to the existing data: ``` SQL> create table foo (bar varchar2(8)); Table created. SQL> insert into foo 2 select lpad(to_char(level),level) 3 from dual 4 connect by level <=8; 8 rows created. SQL> commit; Commit complete. SQL> select bar,dump(bar) from foo; BAR -------- DUMP(BAR) -------------------------------------------------------------------------------- 1 Typ=1 Len=1: 49 2 Typ=1 Len=2: 32,50 3 Typ=1 Len=3: 32,32,51 4 Typ=1 Len=4: 32,32,32,52 5 Typ=1 Len=5: 32,32,32,32,53 6 Typ=1 Len=6: 32,32,32,32,32,54 7 Typ=1 Len=7: 32,32,32,32,32,32,55 8 Typ=1 Len=8: 32,32,32,32,32,32,32,56 8 rows selected. SQL> alter table foo modify (bar varchar2(16)); Table altered. SQL> select bar,dump(bar) from foo; BAR ---------------- DUMP(BAR) -------------------------------------------------------------------------------- 1 Typ=1 Len=1: 49 2 Typ=1 Len=2: 32,50 3 Typ=1 Len=3: 32,32,51 4 Typ=1 Len=4: 32,32,32,52 5 Typ=1 Len=5: 32,32,32,32,53 6 Typ=1 Len=6: 32,32,32,32,32,54 7 Typ=1 Len=7: 32,32,32,32,32,32,55 8 Typ=1 Len=8: 32,32,32,32,32,32,32,56 ```
how to change a column's attribute without affecting the values already present?
[ "", "sql", "database", "oracle", "alter-table", "" ]
``` public class PhotoList : ObservableCollection<ImageFile> { public PhotoList() { } **//this is the line that I dont recognise!!!!!!!!!!** public PhotoList(string path) : this(new DirectoryInfo(path)) { } public PhotoList(DirectoryInfo directory) { _directory = directory; Update(); } public string Path { set { _directory = new DirectoryInfo(value); Update(); } get { return _directory.FullName; } } public DirectoryInfo Directory { set { _directory = value; Update(); } get { return _directory; } } private void Update() { foreach (FileInfo f in _directory.GetFiles("*.jpg")) { Add(new ImageFile(f.FullName)); } } DirectoryInfo _directory; } ```
This is called *constructor chaining* - constructors can call other constructors within the same type with this syntax (using **`this`** for sibling constructors and **`base`** for base constructors). Here is a simple example that shows how it works: ``` using System; class Program { static void Main() { Foo foo = new Foo(); } } class Foo { public Foo() : this("hello") { Console.WriteLine("world"); } public Foo(String s) { Console.WriteLine(s); } } ``` **Output:** > `hello` > `world`
It calls the other constructor in the class that takes a DirectoryInfo as argument. Lets see how the caller of this class can be used ``` //The empty ctor() PhotoList list = new PhotoList(); //The ctor that takes a DirectoryInfo PhotoList list2 = new PhotoList(new DirectoryInfo("directory")); //Would do the same as the code above since this constructor calls another constructor via the this() keyword PhotoList list3 = new PhotoList("directory"); ```
What does a constructor with an empty body and inheritance-like syntax do?
[ "", "c#", "constructor", "constructor-chaining", "" ]
I am having a hard time figuring out how to code a series of "if" statements that search through different dropdownlists for a specific value entered in a textbox. I was able to write code that finds a specific value in each dropdownlist; but, before this happens, I need to add an "if" statement saying, "if dropdownlist doesn't contain the specific value, go to next if statement, and so on". The following is an example of what I have so far: ``` if (dropdownlist1.SelectedValue == textbox1) { dropdownlist1.SelectedIndex = dropdownlist1.items.indexof(dorpdownlist1.items.findbyvalue(textbox1.text) ... if (dropdownlist2.SelectedValue == textbox1) { dropdownlist2.SelectedIndex = dropdownlist2.items.indexof(dorpdownlist2.items.findbyvalue(textbox1.text) ... etc... ``` What this does is reads or scans the first value or index in each dropdownlist, based off of my entry in textbox1. Unfortunately, it only identifies the first value or index. I need to figure out how to scan through the entire dropdownlist for all values per each "if" statement to find the matching textbox1 value. Does anyone have any suggestions? Thank you, DFM
``` foreach (ListItem li in dropdownlist1.Items) { if (li.Value == textBox1.text) { // The value of the option matches the TextBox. Process stuff here. } } ``` That is my suggestion for how to see if the value is in the dropdownlist.
The [DropDownList](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx) inherits the [Items](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.items.aspx) collection from the [ListControl](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.aspx). Since Items is an Array, you can use this syntax: dropdownlist1.Items.Contains(textbox1.Text) as a boolean.
How to Search Through a C# DropDownList Programmatically
[ "", "c#", "search", "drop-down-menu", "" ]
I didn't find it, yet. Did I miss something? I know a factorial method is a common example program for beginners. But wouldn't it be useful to have a standard implementation for this one to reuse? I could use such a method with standard types (Eg. int, long...) and with BigInteger / BigDecimal, too.
I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. [Here is a handful of implementations.](http://www.luschny.de/math/factorial/FastFactorialFunctions.htm)
[Apache Commons Math](http://commons.apache.org/math/userguide/utilities.html) has a few factorial methods in the [MathUtils](http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math4/util/MathUtils.html) class.
Is there a method that calculates a factorial in Java?
[ "", "java", "" ]
I'm new to the MVC framework and have just run through the NerdDinner sample project. I'm loving this approach over form-based asp.net. I'd like to spin of a more sizable side project using this same approach. Do you see anything in that project that would prevent me from enlarging the basic structure to a more complex website? Examples of things that make me wary: 1) The NerdDinner sample accesses a db of only two tables, my db has around 30. 2) The NerdDinner project uses the LinqToSQL classes directly... all the way from the model, through the controller, to the view... is that kosher for a larger project? Do you see any other parts of the NerdDinner framework that might cause me future grief?
I would add a service layer between the repositories and controllers. The service layer will contain all of your business logic leaving your controllers to deal mainly with processing form inputs and page flow. Within the repositories I map LinqToSql classes and fields to domain models and then use the domain models within the service layer, controllers and views. For a larger system the extra layers will prove their worth in the long run.
I agree with others that the model should be the only place you use linq2sql and my little addendum to that is only use linq2sql in models in small projects. For larger sites it might be worth the overhead to create a separate Web Service project that does all the talking to the database and utilize the web service in your Model. I never fully checked out the Nerd Diner example but other best practices include Typed Views and using a datamodeler that allows for easy validation (see [xval](http://www.codeplex.com/xval) or the [DataAnnotations](http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html) model binder). To me these are 2 of the most important best practices/ Stephen Walter has alot of excellent tips on his [website](http://stephenwalther.com/blog/category/10.aspx) that are worth checking out and taking into account when setting up a new MVC project.
Can I use the NerdDinner sample project as a base template for a larger project?
[ "", "c#", "asp.net-mvc", "linq-to-sql", "architecture", "" ]
We have a teradata database that is filled with BIGINT datatypes. SAS is the primary analytic engine for the organization. The SAS access library chokes on BIGINT and therefore forces all code to cast variables into a integer or decimal before returning them to SAS. Example: ``` proc sql; connect to database (blah blah); create table sas_dataset as select * from connection to database( select cast(bigint_var as integer), varchar_var, char_var, from some_table ); disconnect from database; quit; ``` Does anyone know a way to fix this? Possibly a macro for casting variables or SAS access fix? Keep in mind that there are literally thousands of variables in this database that are bigint and making changes to the database is out of the question.
If you can't fix it on the SAS side, you can always create a set of views on the Teradata side to do the casting. Then have SAS access the views: ``` create view sas_cast_db.some_table as select col1, col2, cast(bigint_var as decimal(18)), col3 from real_db.some_table; ``` Since you have lots of tables, it may be possible to write some SQL to auto-generate these from the data dictionary.
The issue is that SAS can only handle a maximum of 15 digits for a BIGINT data type. SAS have provided a few work-arounds for SAS 9.2 (one mentioned above) for this issue. You can also get your SAS Platform Admin to arrange for the SAS server to be updated so that it truncates the BIGINT fields to 15 digits (obvious caveats apply), or update your LIBNAME statement to set all BIGINTs to be cast automatically. <http://support.sas.com/kb/39/831.html>
Teradata and SAS with BigInt's
[ "", "sql", "teradata", "proc-sql", "" ]
We all know that in C# we can't cast bool to int. I wanted to see what is the binary representation of true with bitmask, but I can't use (bool & int).. I think the problem is the architecture desicion "true is true, not any number != 0" (C++) and I was wondering what the benefits of such an architecture are? What is so bad with the C true/false concept?
It's clearer to the programmer when an integer can't be used for `true` or `false`. `if (5 > 0)` is easier to understand rather than `if(5)` It's the same reason why they don't allow fall through conditions in switch statements. It's too easy to make a mistake.
In C integers are frequently doubly used as a normal number and a boolean, such as for loops that run while a certain number is not zero. That's a use which clearly has its merits for concise code, like a naïve strlen routine: ``` const char *s; for (s = str; *s; ++s) ; return (s - str); ``` but while short it masks the true purpose of that snippet, which essentially says "loop while the character I am looking at is not the null character". But written down it just says "treat it as a boolean when I feel like it, and as a number in some other cases". This kind of double nature allegedly frequently leads to problems and it makes the code less readable (since you have to judge from the context whether a given usage of an `int` is intended as `int` or `bool`). If you absolutely need to use a boolean as an integer you can either use ``` Convert.ToInt32(someBool) ``` as [Noldorin mentioned](https://stackoverflow.com/questions/946688/c-cant-cast-bool-to-int/946718#946718) or roll your own with ``` someBool ? 1 : 0 ``` Both of which clearly say that you are using an `int` (and not a `bool`).
C# can't cast bool to int
[ "", "c#", ".net", "" ]
How can I do something like this in NUnit? ``` class Foo { int Value { get; set; } ... } ... ICollection<Foo> someFoos = GetSomeFoos(); Expect(List.Map(someFoos).Property("Value"), Has.Some.EqualTo(7)); ``` `List.Map()` only accepts `ICollection`, not `ICollection<T>`.
Well, you could convert your `ICollection<T>` to something that implements `ICollection`. Array for instance: ``` ICollection<Foo> someFoos = GetSomeFoos(); var array = new Foo[10]; someFoos.CopyTo(array); Expect(List.Map(array).Property("Value"), Has.Some.EqualTo(7)); ```
well, you could conceptually use linq to objects extensions, something like: Expect(someAs.Count(), Has.Some.EqualTo(7));
How does one test generic collections in nunit?
[ "", "c#", ".net", "nunit", "" ]
I've often heard that using `system("PAUSE")` is bad practice and to use `std::cin.get()` instead. Now my understanding of system calls is that they take a string which they enter into a system command line and talk with the OS, so PAUSE is a DOS command that pauses the output in the command window. I assume this works similarly with Mac and unix with different keywords, and using system calls is discouraged because of a lack of cross OS compatibility. (If I'm wrong with any of this, please correct me) my question is this: When is it appropriate to use system() calls? How should they be applied? When should they NOT be applied?
`system("PAUSE")` is certainly less than ideal. using a call to system creates a subprocess, which on windows is fairly expensive and in any case not terribly cheap on any operating system. On embedded systems the memory overhead is significant. If there is any way to do it without much pain natively then do it. In the case of waiting for the user to press a single button, cin.get() will be very hard to beat. In this case, your applications process will just block on stdin, setting only a few flags visible to the kernel, and most importantly, allocates no new memory and creates no new scheduling entities, not even an interrupt handler. Additionally, it will work the same on all operating systems with all c++ compilers, since it uses only a very basic feature of a very standard part of the language, rather than depend on anything the OS provides. EDIT: predicting your concern that it doesn't matter if it's expensive because the whole *idea* is to pause. Well, first off, if its expensive, then it's going to hurt performance for anything else that might be going on. Ever notice (on windows) when one application is launching, other, already open apps become less responsive too? Additionally, your user might not be a live human, but rather another program working on behalf of a human user (Say, a shell script). The script already knows what to do next and can pre-fill stdin with a character to skip over the wait. If you have used a subprocess here, the script will experience a (noticeable to a human) delay. If the script is doing this hundreds (or hundreds of millions!) of times, a script that could take seconds to run now takes days or years. EDIT2: when to use `system()`: when you need to do something that another process does, that you can't do easily. `system()` isn't always the best candidate because it does two things that are somewhat limiting. First, the only way to communicate with the subprocess is by command line arguments as input and return value as output. The second is that the parent process blocks until the child process has completed. These two factors limit the cases in which system is useable. on unixy systems, most subprocesses happen with `fork` because it allows the same program to continue in the same place as two separate processes, one as a child of the other (which is hardly noticeable unless you ask for it from the OS). On Linux, this is especially well optimized, and about as cheap as creating a pthread. Even on systems where this is not as fast, it is still very useful (as demonstrated by the apache process-pool methodology) (unavailable on windows/[link to unix docs](http://linux.die.net/man/2/fork)) other cases (on windows too!) are often handled by `popen` or `exec` family of functions. `popen` creates a subprocess and a brand new pipe connecting to the subprocesses' stdin or stdout. Both parent and child processes can then run concurrently and communicate quite easily. ([link to windows docs](http://msdn.microsoft.com/en-us/library/96ayss4b.aspx)/[link to unix docs](http://linux.die.net/man/3/popen)) `exec`\* family of functions (there are several, execl, execv and so on) on the other hand causes the current program to be replaced by the new program. The original program exits invisibly and the new process takes over. When then new process returns, it will return to whatever called the original process, as if that process had returned at that point instead of vanishing. The advantage of this over `exit(system("command"))` is that no new process is created, saving time and memory (though not always terribly much) ([link to windows docs](http://msdn.microsoft.com/en-us/library/431x4c1w.aspx) /[link to unix docs](http://linux.die.net/man/3/exec)) `system` could plausibly be used by some scripted tool to invoke several steps in some recipe action. For example, at a certain point, a program could use `system` to invoke a text editor to edit some configuration file. It need not concern itself too much with what happens, but it should certainly wait until the user has saved and closed the editor before continuing. It can then use the return value to find out if the editing session was successful, in the sense that the editor actually opened the requested file (and that the editor itself existed at all!), but will read the actual results of the session from the edited file directly, rather than communicating with the subprocess. ([link to windows docs](http://msdn.microsoft.com/en-us/library/277bwbdz.aspx)/[link to unix docs](http://linux.die.net/man/3/system))
System calls are sent to the shell or command line interpreter of the OS (dos, bash, etc) and its up to the shell to do what it wants with this command. You would avoid using these kind of calls as it would reduce your programs portability to work with other operating systems. I would think only when you are absolutely sure that your code is targeting a specific OS that you should use such calls.
System() calls in C++ and their roles in programming
[ "", "c++", "windows", "operating-system", "system", "dos", "" ]
``` // CMyDialog inherits from CDialog void CMyFrame::OnBnClickedCreate() { CMyDialog* dlg = new CMyDialog(); dlg->Create( IDD_MYDIALOG, m_thisFrame ); dlg->ShowWindow( SW_SHOW ); } ``` I'm pretty sure this leaks. What I'm really asking is: is there any "magic" in MFC that does dialog cleanup when the dialog is destroyed. How would it work if dlg wasn't a pointer but declared on the stack - wouldn't the destructor destroy the window when dlg goes out of scope.
Yes, it is memory leak in your case but you can avoid memory leak in cases where modeless dialog allocated on the heap by making use of overriding `PostNcDestroy`. Dialogs are not designed for auto-cleanup ( where as Main frame windows, View windows are). In case you want to provide the auto-cleanup for dialogs then you must override the `PostNcDestroy` member function in your derived class. To add auto-cleanup to your class, call your base class and then do a `delete this`. To remove auto-cleanup from your class, call `CWnd::PostNcDestroy` directly instead of the `PostNcDestroy` member in your direct base class. ``` void MyDialog::PostNcDestroy() { CDialog::PostNcDestroy(); delete this; } ``` How this works (from MSDN): > When destroying a Windows window, the > last Windows message sent to the > window is WM\_NCDESTROY. The default > CWnd handler for that message > (CWnd::OnNcDestroy) will detach the > HWND from the C++ object and call the > virtual function PostNcDestroy. Some > classes override this function to > delete the C++ object. > > "delete this" will free any C++ > memory associated with the C++ object. > Even though the default CWnd > destructor calls DestroyWindow if > m\_hWnd is non-NULL, this does not lead > to infinite recursion since the handle > will be detached and NULL during the > cleanup phase. You can also refer MSDN ([Destroying Window Objects](https://msdn.microsoft.com/en-us/library/5zba4hah.aspx) ) for further details. **Note:** This works for modeless dialog that can be allocated on the **heap**.
Yes, that's a leak. And yes, the window would be destroyed if the object was stack-allocated. Using dialogs as stack-allocated objects is typical for modal dialogs - you call a method for showing a dialog as a modal window and that method only returns when the dialog is closed and the object is destroyed after that.
Is this a memory leak in MFC
[ "", "c++", "mfc", "memory-leaks", "" ]
Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.
[Here](http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/) is a useful solution that works for various operating systems, including Linux, Windows, etc.: ``` import psutil process = psutil.Process() print(process.memory_info().rss) # in bytes ``` Notes: * do `pip install psutil` if it is not installed yet * handy one-liner if you quickly want to know how many MiB your process takes: ``` import os, psutil; print(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2) ``` * with Python 2.7 and psutil 5.6.3, it was `process.memory_info()[0]` instead (there was a change in the API later).
For Unix based systems (Linux, Mac OS X, Solaris), you can use the `getrusage()` function from the standard library module [`resource`](https://docs.python.org/library/resource.html). The resulting object has the attribute `ru_maxrss`, which gives the *peak* memory usage for the calling process: ``` >>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss 2656 # peak memory usage (kilobytes on Linux, bytes on OS X) ``` The [Python docs](https://docs.python.org/library/resource.html#resource-usage) don't make note of the units. Refer to your specific system's [`man getrusage.2`](http://man7.org/linux/man-pages/man2/getrusage.2.html) page to check the unit for the value. On Ubuntu 18.04, the unit is noted as kilobytes. On Mac OS X, it's bytes. The `getrusage()` function can also be given `resource.RUSAGE_CHILDREN` to get the usage for child processes, and (on some systems) `resource.RUSAGE_BOTH` for total (self and child) process usage. If you care only about Linux, you can alternatively read the `/proc/self/status` or `/proc/self/statm` file as described in other answers for this question and [this](https://stackoverflow.com/questions/897941/) one too.
Total memory used by Python process?
[ "", "python", "memory-management", "" ]
from the free dinner book for asp.net MVC ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection formValues) { Dinner dinner = dinnerRepository.GetDinner(id); UpdateModel(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerID }); } ``` how to convert this line into vb.net? ``` return RedirectToAction("Details", new { id = dinner.DinnerID }); ``` more the **new { id = dinner.DinnerID }** part thanks
Try this ``` Return RedirectToAction("Details", New With { .id = dinner.DinnerID}) ``` In VB the anonymous type declaration syntax, as well as normal object initializers, needs a "." prefix on all of the property names. This is consistent with other VB features such as the With context.
That is using an [anonymous type](http://msdn.microsoft.com/en-us/library/cc468406.aspx), so it will look like this: ``` Return RedirectToAction("Details", New With { .id = dinner.DinnerID }) ```
how to convert this line into vb.net
[ "", "c#", "asp.net-mvc", "vb.net", "anonymous-types", "" ]
This is related to conventions used in C#. I've got a method that has two parameters (X and Y coordinates). These coordinates represent the position at which a "tile" may reside. If a tile resides at these coordinates, the method returns its number. If no tile resides at these coordinates, I'm wondering how the method should behave. I see three options: 1. Use exceptions. I may raise an exception every time Method finds no tile. However, as this situation is not rare, this option is the worst one. 2. Do it the old fashioned C++ way and return -1 if there is no tile. 3. Make the tile number a reference parameter and change the return type of method to boolean to show whether there is a tile or not. But this seems a bit complicated to me. So, what should I do?
Return -1. This is not just a C++ convention, it's also common in the .NET Framework - e.g. methods like String.IndexOf or properties like SelectedIndex for controls that represent lists. **EDIT** Just to elaborate, of the three options in your question (Exception, return -1, out parameter), returning -1 is the way to go. Exceptions are for exceptional situations, and the Microsoft coding guidelines recommends avoiding out parameters where possible. In my view returning -1 (provided it's always going to be an invalid value), returning a nullable int, or returning a Tile object are all acceptable solutions, and you should choose whichever is most consistent with the rest of your app. I can't imagine any developer would have the slightest difficulty with any of the following: ``` int tileNumber = GetTile(x,y); if (tileNumber != -1) { ... use tileNumber ... } int? result = GetTile(x,y); if (result.HasValue) { int tileNumber = result.Value; ... use tileNumber ... } Tile tile = GetTile(x,y); if (tile != null) { ... use tile ... } ``` I'm not sure I understand Peter Ruderman's comment about using an int being "much more efficient than returning a nullable type". I'd have thought any difference would be negligible.
You can return null, and check for this on the calling code. Of course you'd have to use a nullable type: ``` int? i = YourMethodHere(x, y); ```
Which style of return should I use?
[ "", "c#", "return-value", "conventions", "" ]
First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application. This code works, it shows the menu (I don't connect the exit action and so on to keep it simple) ``` import sys from PyQt4 import QtGui def main(): app = QtGui.QApplication(sys.argv) trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") trayIcon.setContextMenu(menu) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` But this doesn't: ``` import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") self.setContextMenu(menu) def main(): app = QtGui.QApplication(sys.argv) trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` I probably miss something. There are no errors but in the second case when I click with the right button it doesn't show the menu.
Well, after some debugging I found the problem. The QMenu object it is destroyed after finish `__init__` function because it doesn't have a parent. While the parent of a QSystemTrayIcon can be an object for the QMenu it has to be a Qwidget. This code works (see how QMenu gets the same parent as the QSystemTrayIcon which is an QWidget): ``` import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) menu = QtGui.QMenu(parent) exitAction = menu.addAction("Exit") self.setContextMenu(menu) def main(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), w) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ```
I think I would prefer the following as it doesn't seem to depend upon QT's internal garbage collection decisions. ``` import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) self.menu = QtGui.QMenu(parent) exitAction = self.menu.addAction("Exit") self.setContextMenu(self.menu) def main(): app = QtGui.QApplication(sys.argv) style = app.style() icon = QtGui.QIcon(style.standardPixmap(QtGui.QStyle.SP_FileIcon)) trayIcon = SystemTrayIcon(icon) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ```
PyQt: Show menu in a system tray application
[ "", "python", "menu", "pyqt", "system-tray", "" ]
I'm looking for recommendations for open-source projects written in C++ that will help me "get my chops back". A little background: * I've been working heavily in Java for the last three years, doing a lot of back-end development and system design, but with a fair amount of work in the presentation layer stuff, too. * The last C++ projects I worked on were a Visual C++ 6 project (designed to interact with Visual Basic) for mobile devices and several projects using the GNU toolchain circa gcc versions 2.x to 3.2 * I'm looking to get back up to speed on the language and learn some of the popular frameworks, specifically the basics of boost (although boost seems fairly sprawling to me, similar to the kitchen-sink feel of Spring in the java space) and test driven development in C++. **What I'm looking for:** Specific recommendations for small to mid-size open source projects to poke through and perhaps contribute to as I level my C++ skills back up. The problem domain isn't important, except that I would like to work on something in a new area to broaden my experience. **Edit:** A few people have commented that it's difficult to provide a recommendation without some indication of the problem domain I'd like to work in. So, I've decided that I'm most interested in graphics applications or games, two areas which I haven't worked in before.
If you like visual stuff, openFrameworks is a C++ Framework for doing Processing-type applications. <http://www.openframeworks.cc/> I'm not sure how viable it still is, but it looked pretty cool. It's hard to suggest something like this, you really don't have any itches you want to scratch??
I would personally be working on [Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan) if I wasn't absurdly busy starting my own personal venture. Dynamic language optimisation looks pretty cool to me.
Recommendations for an open-source project to help an experienced developer practice C++
[ "", "c++", "unit-testing", "open-source", "boost", "" ]
What JavaScript Mobile development tool would you use based on momentum, existing documentation and functionality, and ability to get passed the App Stores strict policies?
I found Phonegap to be the easiest to use. However Quickconnect seems to be more ambitious in terms of multi-platform support, the author tells me that Quickconnect has been used in many apps (but couldn't disclose which). Supposedly Phonegap apps were being rejected because those submitting were loading the entire apps off the web, however the framework does seem sluggish. Apple has not replied to the Phonegap team about the app rejection. If I had to make a choice it would be Phonegap at this stage, but unless you really want the app on multiple platforms I don't see why you wouldn't use the great tools provided by Apple for native development.
Current PhoneGap release (0.8.0) released 2009-10-13 is tagged "Apple approved for App Store submissions". [This blog post](http://nachbaur.com/blog/phonegap-officially-permitted-on-the-app-store) has more details.
QuickConnect vs Phonegap
[ "", "javascript", "iphone", "android", "cordova", "xui", "" ]
Let's say I have an object `Employee_Storage` that contains a database connection data member. Should this data member be stored as a pointer or as a reference? * If I store it as a reference, I don't have to do any `NULL` checking. (Just how important is NULL checking anyway?) * If I store it as a pointer, it's easier to setup `Employee_Storage` (or `MockEmployee_Storage`) for the purposes of testing. Generally, I've been in the habit of always storing my data members as references. However, this makes my mock objects difficult to set up, because instead of being able to pass in `NULL`s (presumably inside a default constructor) I now must pass in true/mock objects. Is there a good rule of thumb to follow, **specifically with an eye towards testability?**
It's only preferable to store references as data members if they're being assigned at construction, and there is truly no reason to ever change them. Since references cannot be reassigned, they are very limited. In general, I typically store as pointers (or some form of templated smart pointer). This is much more flexible - both for testing (as you mentioned) but also just in terms of normal usage.
It is almost never prefereable to store references as data members, and a lot of the time it is impossible. If the objects must be assignable (as they must to be stored in a standard library container), references cannot be used. Also, references cannot be reseated, so once a reference is initialised with an object, it cannot be made to refer to a different object. See this question [Should I prefer pointers or references in member data?](https://stackoverflow.com/questions/892133/should-i-prefer-pointers-or-references-in-member-data) for a more detailed discussion of the issue.
When is it preferable to store data members as references instead of pointers?
[ "", "c++", "tdd", "reference", "mocking", "pointers", "" ]