Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Quick question regarding how memory is allocated. If someone were to allocate 20 chars like this: ``` char store[20]; ``` does this mean that it allocated 20 char type blocks of memory, or that it allocated char type blocks of memory starting with 0 and ending with 20. The difference is that the first example's range would be from store[0] to store[19], whereas the second example's range would be from store[0] to store[20].
It means it allocated one block of memory large enough to hold 20 chars (from index 0 to 19)
[0] to [19] (20 elements, that is)
Array Allocation Subscript Number
[ "", "c++", "c", "arrays", "" ]
Let's say I have this query in PHP. ``` $a = mysql_query("SELECT * FROM `users` WHERE `id` = '1' "); ``` Which is nice and all, but I have a problem. How do I view the contents of $a, which I presume is an array like so: ``` Index | Value ID | 1 Username | Foo Password | Bar ... ```
``` while ($row = mysql_fetch_assoc($a)) { echo $row['id']; echo $row['username']; echo $row['password']; } ```
Use [`mysql_fetch_assoc`](https://www.php.net/mysql_fetch_assoc): ``` while($row = mysql_fetch_assoc($a)) { echo $row['index'] . ' | ' . $row['ID'] . ' | ' . $row['username'] . ' | ' . $row['password']; } mysql_free_result($a); ``` I prefere `mysql_fetch_assoc` to [`mysql_fetch_row`](https://www.php.net/manual/en/function.mysql-fetch-row.php) since it's not appreciably slower, and it gives you the ability to call fields by name (e.g.-`$row['index']). You could also use [`mysql_fetch_array`](https://www.php.net/manual/en/function.mysql-fetch-array.php) if you wanted the flexibility of referring to the row by index or by name. Really, just preference.
MySQL Result Array in PHP
[ "", "php", "mysql", "arrays", "" ]
I'm trying to figure out how to get the CPU usage for a particular process but can only find information relating to **overall** CPU usage. Does anyone know how to extract the **current CPU usage in percentage terms for a specific application?**
Performance Counters - Process - % Processor Time. Little sample code to give you the idea: ``` using System; using System.Diagnostics; using System.Threading; namespace StackOverflow { class Program { static void Main(string[] args) { PerformanceCounter myAppCpu = new PerformanceCounter( "Process", "% Processor Time", "OUTLOOK", true); Console.WriteLine("Press the any key to stop...\n"); while (!Console.KeyAvailable) { double pct = myAppCpu.NextValue(); Console.WriteLine("OUTLOOK'S CPU % = " + pct); Thread.Sleep(250); } } } } ``` **Notes for finding the instance based on Process ID**: I do not know of any better way, and hopefully somebody does. If not, here is one way you can find the right instance name for your process given the Process ID and process name. There is another Performance Counter (PC) called `"ID Process"` under the `"Process"` family. It returns the PID for the instance. So, if you already know the name (i.e. "chrome" or "myapp"), you can then test each instance until you find the match for the PID. The naming is simple for each instance: "myapp" "myapp#1" "myapp#2" ... etc. ``` ... new PerformanceCounter("Process", "ID Process", appName, true); ``` Once the PC's value equals the PID, you found the right `appName`. You can then use that `appName` for the other counters.
A method to calculate processor usage for a single process without using PerformanceCounter. ``` using System; using System.Diagnostics; namespace cpuusage { class Program { private static DateTime lastTime; private static TimeSpan lastTotalProcessorTime; private static DateTime curTime; private static TimeSpan curTotalProcessorTime; static void Main(string[] args) { string processName = "OUTLOOK"; Console.WriteLine("Press the any key to stop...\n"); while (!Console.KeyAvailable) { Process[] pp = Process.GetProcessesByName(processName); if (pp.Length == 0) { Console.WriteLine(processName + " does not exist"); } else { Process p = pp[0]; if (lastTime == null || lastTime == new DateTime()) { lastTime = DateTime.Now; lastTotalProcessorTime = p.TotalProcessorTime; } else { curTime = DateTime.Now; curTotalProcessorTime = p.TotalProcessorTime; double CPUUsage = (curTotalProcessorTime.TotalMilliseconds - lastTotalProcessorTime.TotalMilliseconds) / curTime.Subtract(lastTime).TotalMilliseconds / Convert.ToDouble(Environment.ProcessorCount); Console.WriteLine("{0} CPU: {1:0.0}%",processName,CPUUsage * 100); lastTime = curTime; lastTotalProcessorTime = curTotalProcessorTime; } } Thread.Sleep(250); } } } } ``` You could loop through the processes to pick which one, or if you already know the id, simply use this command instead of GetProcessesByName() ``` Process p = Process.GetProcessById(123); ```
c# calculate CPU usage for a specific application
[ "", "c#", "process", "cpu-usage", "" ]
After reading another question about the use of macros, I wondered: What *are* they good for? One thing I don't see replaced by any other language construct very soon is in diminishing the number of related words you need to type in the following: ``` void log_type( const bool value ) { std::cout << "bool: " << value; } void log_type( const int value ) { std::cout << "int: " << value; } ... void log_type( const char value ) { std::cout << "char: " << value; } void log_type( const double value ) { std::cout << "int: " << value; } void log_type( const float value ) { std::cout << "float: " << value; } ``` as opposed to ``` #define LOGFN( T ) void log_type( const T value ) { std::cout << #T ## ": " << value; } LOGFN( int ) LOGFN( bool ) ... LOGFN( char ) LOGFN( double ) LOGFN( float ) ``` Any other 'irreplaceables'? EDIT: trying to summarize the reasons-why encountered in the answers; since that's what I was interested in. Mainly because I have a feeling that most of them are due to us still programming in raw text files in, still, poorly supporting environments. * flexibility of code-to-be compiled (e.g. `#ifdef DEBUG`, platform issues) (SadSido, Catalin, Goz) * debug purposes (e.g. `__LINE__, __TIME__`); I also put 'stringifying' under this reason (SadSido, Jla3ep, Jason S) * replacing e.g. PHP's `require` vs. `include` feature (`#pragma once`) (SadSido, Catalin) * readability enhancement by replacing complicated code (e.g. `MESSAGEMAP`, `BOOST_FOREACH`) (SadSido, fnieto) * DRY principle (Jason S) * an inline replacement (Matthias Wandel, Robert S. Barnes) * stringifying (Jason S)
* compile different code under different conditions ( `#ifdef __DEBUG__` ); * guards to include each header once for each translation unit ( `#pragma once` ); * `__FILE__` and `__LINE__` - replaced by the current file name and current line; * structuring the code to make it more readable (ex: `BEGIN_MESSAGE_MAP()` ); See interesting macro discussion at gotw here: <http://www.gotw.ca/gotw/032.htm> <http://www.gotw.ca/gotw/077.htm>
Most useful - header file guarding: ``` #ifndef MY_HEADER_GUARD #define MY_HEADER_GUARD // Header file content. #endif ``` Later add [**Windows only**] Exporting classes to DLL: ``` #ifdef EXPORT_MY_LIB #define MY_API __declspec( dllexport) #else #define MY_API __declspec( dllimport) #endif ``` Sample class: ``` class MY_API MyClass { ... }; ```
What are preprocessor macros good for?
[ "", "c++", "macros", "" ]
Can someone tell me how to get the handle of a Windows console application in C#? In a Windows Forms application, I would normally try `this.Handle`.
Not sure it works, but you can try that : ``` IntPtr handle = Process.GetCurrentProcess().MainWindowHandle; ```
* The aforementioned [`Process.MainWindowHandle` method](https://stackoverflow.com/a/1277609/648265) [only works for the process that started the console](https://stackoverflow.com/questions/1277563/how-do-i-get-the-handle-of-a-console-applications-window/28616832#comment7926605_1277609) * The [`FindWindowByCaption` method](https://stackoverflow.com/a/4895594/648265) is inherently unreliable Here's a robust way to do this: The related functions from the [Console Win32 API](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682073%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396) are: ``` [DllImport("kernel32.dll", SetLastError = true)] static extern bool AttachConsole(uint dwProcessId); [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow(); [DllImport("kernel32.dll", SetLastError=true, ExactSpelling=true)] static extern bool FreeConsole(); ``` * For the console the current process is attached to, just `GetConsoleWindow()` is enough * For the console another process is attached to, attach to it as well with `AttachConsole`, call `GetConsoleWindow`, them immediately detach with `FreeConsole`. For the extra cautious, register a console event handler before attaching (and unregister it after detaching) as well so you don't accidentally get terminated if a console event happens in the tiny time frame you're attached to the console: ``` [DllImport("kernel32.dll")] static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add); delegate Boolean ConsoleCtrlDelegate(CtrlTypes CtrlType); enum CtrlTypes : uint { CTRL_C_EVENT = 0, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT = 5, CTRL_SHUTDOWN_EVENT } bool is_attached=false; ConsoleCtrlDelegate ConsoleCtrlDelegateDetach = delegate(CtrlType) { if (is_attached = !FreeConsole()) Trace.Error('FreeConsole on ' + CtrlType + ': ' + new Win32Exception()); return true; }; ``` --- Making changes to the current process just to read something is rather ugly (when this is a console process, this gets really ugly since it requires a helper process to avoid terminating the current console). Nevertheless, further investigation shows that there's no other way short of injecting into the `csrss` process or the target process. Console correspondence information is located in and managed by `csrss.exe` (or a multitude of those, one for each session, since Vista), so it can't be retrieved with the likes of `ReadProcessMemory`. All that `csrss` exposes is the [CSRSS LPC API](http://j00ru.vexillium.org/?p=349). There's only one relevant function in the full API list, `SrvGetConsoleWindow`. And it doesn't accept a PID but determines that of the calling party as seen in [an alternative implementation](http://doxygen.reactos.org/d6/dc4/frontendctl_8c_source.html#l00272) or the function's disassembly in `winsrv.dll`.
How do I get the handle of a console application's window
[ "", "c#", "console", "hwnd", "window-handles", "" ]
I am making a method so your password needs at least one captial and one symbol or number. I was thinking of splitting the string in to lose chars and then use preggmatch to count if it contains one capital and symbol/number. however i did something like this in action script but can't figure out how this is called in php. i cant find a way to put every char of a word in a array. AS3 example ``` for(var i:uint = 0; i < thisWordCode.length -1 ; i++) { thisWordCodeVerdeeld[i] = thisWordCode.charAt(i); //trace (thisWordCodeVerdeeld[i]); } ``` Thanks, Matthy
You can access characters in strings in the same way as you would access an array index, e.g. ``` $length = strlen($string); $thisWordCodeVerdeeld = array(); for ($i=0; $i<$length; $i++) { $thisWordCodeVerdeeld[$i] = $string[$i]; } ``` You could also do: ``` $thisWordCodeVerdeeld = str_split($string); ``` However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.
you can convert a string to array with [str\_split](http://php.net/manual/en/function.str-split.php) and use foreach ``` $chars = str_split($str); foreach($chars as $char){ // your code } ```
PHP: Split a string in to an array foreach char
[ "", "php", "arrays", "split", "passwords", "validation", "" ]
I have a template class defined as follow : ``` template <class T1, class T2> class MyClass { }; ``` In this class, I need a struct that contains one member of type T1. How can I do that ? I tried the following, but it didn't work : ``` template <class T1, class T2> class MyClass { typedef struct { T1 templateMember; // rest of members } myStruct; // rest of class definition }; ``` EDIT: As requested, I use VS2008 and get the following error : ``` 'MyClass<T1,T2>::myStruct' uses undefined class 'T1' ```
Just remove typedef: ``` template <class T1, class T2> class MyClass { struct myStruct{ T1 templateMember; // rest of members } ; }; ```
``` template <class T1> struct myStruct{ T1 templateMember; // rest of members }; template <class T1, class T2> class MyClass { myStruct<T1> mystruct; // rest of class definition }; ```
Mix of template and struct
[ "", "c++", "templates", "struct", "" ]
Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use `gsub`: ``` >> key = "cd baz ; ls -l" => "cd baz ; ls -l" >> newkey = key.gsub(/[^\w\d]/, "") => "cdbazlsl" ``` What would the equivalent function be in Python?
``` import re re.sub(pattern, '', s) ``` [Docs](http://docs.python.org/library/re.html#re.sub)
The answers so far have focused on doing the same thing as your Ruby code, which is exactly the reverse of what you're asking in the English part of your question: the code removes character that DO match, while your text asks for > a simple way to remove all characters > from a given string that fail to match For example, suppose your RE's pattern was `r'\d{2,}'`, "two or more digits" -- so the non-matching parts would be all non-digits plus all single, isolated digits. Removing the NON-matching parts, as your text requires, is also easy: ``` >>> import re >>> there = re.compile(r'\d{2,}') >>> ''.join(there.findall('123foo7bah45xx9za678')) '12345678' ``` **Edit**: OK, OP's clarified the question now (he did indeed mean what his code, not his text, said, and now the text is right too;-) but I'm leaving the answer in for completeness (the other answers suggesting `re.sub` are correct for the question as it now stands). I realize you probably mean what you "say" in your Ruby code, and not what you say in your English text, but, just in case, I thought I'd better complete the set of answers!-)
Python - Use a Regex to Filter Data
[ "", "python", "regex", "" ]
I'm trying to understand a historical stored procedure I need to fix. I found this **DRVTBL** key word, and I couldn’t find out what it means??? (This is a sql2000 database) ``` SELECT ... FROM ( ...) ) DRVTBL ```
DRVTBL is an alias for the subquery that precedes it. When you use a subquery within a SELECT like this, you have to give it an alias. If you remove DRVTBL, you will get an error. It doesn't then have to go on and be used anywhere else.
`DRVTBL`, from the query you have posted, looks like an alias. The work like temporary tables in your T-SQL Query. SQL Server 2005 has a little bit advanced version of this functionality, called [Common Table Expressions](http://msdn.microsoft.com/en-us/library/ms190766.aspx). An example - ``` SELECT * FROM ( SELECT Id, Name FROM Employee WHERE Name LIKE 'A%' ) EmployeeA WHERE EmployeeA.Name = 'Albert' ``` This will create an aliased table containing all the `Employee`s whose name starts with `A`, and the outer query will, in turn, select the employees with the name `Albert`. Same can be written using CTE as - ``` WITH EmployeeA AS ( SELECT Id, Name FROM Employee WHERE Name LIKE 'A%' ) SELECT * FROM EmployeeA WHERE EmployeeA.Name = 'Albert' ```
SQL 2000 - DRVTBL?
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2000", "" ]
We are working with a code repository which is deployed to both Windows and Linux - sometimes in different directories. How should one of the modules inside the project refer to one of the non-Python resources in the project (CSV files, etc.)? If we do something like: ``` thefile = open('test.csv') ``` or: ``` thefile = open('../somedirectory/test.csv') ``` It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like: ``` path = getBasePathOfProject() + '/somedirectory/test.csv' thefile = open(path) ``` Is it possible?
Try to use a filename relative to the current files path. Example for './my\_file': ``` fn = os.path.join(os.path.dirname(__file__), 'my_file') ``` In Python 3.4+ you can also use [pathlib](https://docs.python.org/3/library/pathlib.html): ``` fn = pathlib.Path(__file__).parent / 'my_file' ```
If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package\_resources. In your case the example would be ``` import pkg_resources my_data = pkg_resources.resource_string(__name__, "foo.dat") ``` Which of course reads the resource and the read binary data would be the value of my\_data If you just need the filename you could also use ``` resource_filename(package_or_requirement, resource_name) ``` Example: ``` resource_filename("MyPackage","foo.dat") ``` The advantage is that its guaranteed to work even if it is an archive distribution like an egg. See <http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api>
How to refer to relative paths of resources when working with a code repository
[ "", "python", "path", "relative-path", "" ]
So according to cplusplus.com when you set the format flag of an output stream to scientific notation via `of.setf(ios::scientific)` you should see 3 digits plus and a sign in the exponent. However, I only seem to get 2 in my output. Any ideas? Compiled on Mac OS using GCC 4.0.1. Here's the actual code I am using: ``` of.setf(ios::scientific); of.precision(6); for (int i=0;i<dims[0];++i) { for (int j=0;j<dims[1];++j) { of << setw(15) << data[i*dims[1]+j]; } of << endl; } ``` and an example line of output: ``` 1.015037e+00 1.015037e+00 1.395640e-06 -1.119544e-06 -8.333264e-07 ``` Thanks
I believe cplusplus.com is incorrect, or at least is documenting a particular implementation - I can't see any other online docs which specifically state the number of exponent digits which are displayed - I can't even find it in the C++ specification. *Edit*: The [C++ Standard Library: A Tutorial and Reference](http://books.google.com/books?id=n9VEG2Gp5pkC&lpg=PA27&ots=Rdibsm35UV&dq=C%2B%2B%20standard%20library%20specification&pg=PA624#v=onepage&q=two%20concrete%20values&f=false) doesn't explicitly state the number of exponent digits; but all it's examples display two exponent digits.
It's implementation specific.
Only 2 digits in exponent in scientific ofstream
[ "", "c++", "scientific-notation", "" ]
I had a working program (Windows Forms Project) complete with buttons, labels, textboxes e.t.c. and the underlying code. In an attempt to shortcut my work, I decided to add tab controls and move everything in my main form into tab 1 (cut and pasted). As you can imagine it didn't work. I then got rid of the tab conrol and pasted everything back into the main form but the program doesn't work anymore. Can someone tell me what's wrong please? I'm working in MS V studio 2008 express Thanks.
The event handlers that you coded are still there. However, they are not associated with the control any more. I'm not sure if you're using VB.Net or C#, but the fix is the same - it's manual and tedious if you have a bunch of controls, but not too difficult. Here are the instructions for fixing a single button control, and you'll have to apply the concepts across the board. These instructions are specific to C#. I can give you VB instructions as well as I've done this plenty of times. Double click on the button to generate a new event handler. If the button is named Button1, the original event handler was probably called Button1\_Click. Now it should be Button1\_Click1. Delete the Button1\_Click1 function and compile. You'll get errors and if you doible-click on the error in the error pane it will take you to the form,designer.cs file to a line that looks like: ``` this.Button1.Click += new System.EventHandler(this.Button1_Click1); ``` Change this to ``` this.Button1.Click += new System.EventHandler(this.Button1_Click); ``` to point to the previously existing event handler, and the event handler will be fixed.
I have done this many times, but I usually just drag them into the TabControl. Maybe in the cut and paste operation your controls have become unwired from the event declarations.
How do I conserve program functionality and code after moving all controls into a tab control?
[ "", "c#", ".net", "visual-studio", "" ]
If I try a marshal a string that is really a NULL pointer, what will happen?
From native to managed, you get a null string object. From managed to native, you get a null pointer. It's fairly intuitive. :-)
A NULL value when typed as a string will be translated to the respective language representation of NULL when marshalled in either direction (NULL for C and null for C#)
What happens if I marshal a null pointer using the [MarshalAs(UnmanagedType.LPStr)]
[ "", "c#", "interop", "null", "marshalling", "" ]
My small utility application asks the user for an output directory via a GUI file selector. Then it creates a lot of files in this output directory after some processing. I need to check if the application has write access so that it informs the user and does not continue with the processing (which might take a long time) My first attempt was the **canWrite()** method of **java.io.File**. But this does not work since it deals with the directory entry itself and not its contents. I have seen at least one instance of a Windows XP folder that can be renamed or deleted but no files may be created in it (because of permissions). This is actually my testcase. I finally settled with the following solution ``` //User places the input file in a directory and selects it from the GUI //All output files will be created in the directory that contains the input file File fileBrowse = chooser.getSelectedFile(); //chooser is a JFileChooser File sample = new File(fileBrowse.getParent(),"empty.txt"); try { /* * Create and delete a dummy file in order to check file permissions. Maybe * there is a safer way for this check. */ sample.createNewFile(); sample.delete(); } catch(IOException e) { //Error message shown to user. Operation is aborted } ``` However this does not feel elegant to me since it just tries to actually create a file and checks if the operation succeeds. I suspect that there must be a better way for this but all solutions I have found so far with Security Managers and stuff deal with Java Applets and not standalone applications. Am I missing something? What is the recommended way of checking for file access inside a directory before actually writing the files? I am using Java 5.
You could check the file permissions, make sure the directory exists, and do a lot of checking or find a library that does all that checking for you **BUT (!)** isn't the best way of checking to try ? If you check for permissions and the filesystem changes... you will have to change your code. But trying to write a file will ALWAYS tell you if you can write a file. Your solution doesn't have to be the most elegant one. It's not a cheap hard coded patch or something ugly. It's just normal code. And it will always work. But if you don't like to see that check in the code just separate it by putting it in class which only goal is to check for the possibly of writing. In fact, you should put it in a utility class wheter you like the elegance or not. The other solution would be to place your whole writing-to-the-hard-drive code, in the try. And if you can't write, the whole part will be skipped and you give feedback to the user with a message in the catch part.
it doesn't works even if you invoke `canWrite` on the **final path**? ``` File sample = new File(fileBrowse.getParent(),"empty.txt"); if (sample.canWrite()) { doSomethingUseful(sample); } else { notifyUser(); } ```
Checking for write access in a directory before creating files inside it
[ "", "java", "file", "permissions", "" ]
I was wondering, in the new HTML 5, we will get <audio> and <video> tags, but why not native editable combobox and built in local menu support? The reason I'm asking this is because these are the most common problems I face when I have to design a web solution to a typical table based application (e.g. order management app). On a proper client side app, I can use the OS to provide these facilities out of box (e.g. JPopupMenu, JComboBox). For a webapp, I have to look for javascript (libraries) to accomplish something like it. *Why are these not in HTML 5?* I know I should avoid discussion like questions, so here are some further questions: *Do you know libraries that can do the popup menu thing and editable combobox thing cheaply (perhaps with a small code sample)?*
Actually, an editable combobox or just combobox can be created using the new list attribute on the input element. It points to a datalist element that can provide a list of predefined options: ``` <input list=languages> <datalist id=languages> <option value="English"></option> <option value="Dutch"></option> </datalist> ``` For menus the old menu element has been reused. You can use at least datalist in IE >=10, Firefox >=37, Chrome >= 39, Opera >= 29. Data from [caniuse datalist](http://caniuse.com/#search=datalist). About menu element, only Firefox seems to have a partial support for it.
The state of form and input controls on in browsers is a big mess in general. * There's no consistency to implementation. Some use OS native controls (Safari), some use bespoke controls (Opera), and some use a mix of both (IE) * Because of the above, styling/branding a form is not reliable * Again because of the above, we suffer(ed) with z-index issues. * Even on browsers where you can apply style, it's inconsistent. Ever add a CSS border to `input` only to see squares around your radio buttons? In general, I tend to agree with you. We've been living with the same form controls [since HTML 3](http://htmlhelp.com/reference/html40/new.html). So us web developers are left to create more rich and advanced controls on our own. And while these can work, they rely heavily on DHTML and can have significant usability implications. It would be nice to see advancement in this area.
Why does HTML 5 not have editable combobox or local menus built in?
[ "", "javascript", "html", "" ]
I have been a Python programmer for almost two years, and I am used to writing small scripts to automate some repetitive tasks I had to do at the office. Now, apparently my colleagues noticed this, and they want those scripts too. Some of them have Macs, some Windows; I made these on windows. I investigated the possibility of using py2exe or even py2app to make natives of my script, but they never satisfied me... I came to know that all of them have JVM on their systems, so can I give them one single executable JAR file of my script using something like Jython may be? How feasible is this... I mean, I had no idea how to write scripts for Jython, neither did I care about it when I wrote them... what kind of problems will it give?
The best current techniques for distributing your Python files in a jar are detailed in this article on Jython's wiki: <http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts> For your case, I think you would want to take the jython.jar file that you get when you install Jython and zip the Jython Lib directory into it, then zip your .py files in, and then add a `__run__.py` file with your startup logic (this file is treated specially by Jython and will be the file executed when you call the jar with "java -jar"). This process is definitely more complicated then in ought to be, and so we (the Jython developers) need to come up with a nice tool that will automate these tasks, but for now these are the best methods. Below I'm copying the recipe at the bottom of the above article (modified slightly to fit your problem description) to give you a sense of the solution. Create the basic jar: ``` $ cd $JYTHON_HOME $ cp jython.jar jythonlib.jar $ zip -r jythonlib.jar Lib ``` Add other modules to the jar: ``` $ cd $MY_APP_DIRECTORY $ cp $JYTHON_HOME/jythonlib.jar myapp.jar $ zip myapp.jar Lib/showobjs.py # Add path to additional jar file. $ jar ufm myapp.jar othermanifest.mf ``` Add the `__run__.py` module: ``` # Copy or rename your start-up script, removing the "__name__ == '__main__'" check. $ cp mymainscript.py __run__.py # Add your start-up script (__run__.py) to the jar. $ zip myapp.jar __run__.py # Add path to main jar to the CLASSPATH environment variable. $ export CLASSPATH=/path/to/my/app/myapp.jar:$CLASSPATH ``` On MS Windows, that last line, setting the CLASSPATH environment variable, would look something like this: ``` set CLASSPATH=C:\path\to\my\app\myapp.jar;%CLASSPATH% ``` Or, again on MS Windows, use the Control Panel and the System properties to set the CLASSPATH environment variable. Run the application: ``` $ java -jar myapp.jar mymainscript.py arg1 arg2 ``` Or, if you have added your start-up script to the jar, use one of the following: ``` $ java org.python.util.jython -jar myapp.jar arg1 arg2 $ java -cp myapp.jar org.python.util.jython -jar myapp.jar arg1 arg2 $ java -jar myapp.jar -jar myapp.jar arg1 arg2 ``` The double -jar is kind of annoying, so if you want to avoid that and get the more pleasing: ``` $ java -jar myapp.jar arg1 ``` You'll have to do a bit more work until we get something like this into a future Jython [Update: JarRunner is part of Jython 2.5.1]. Here is some Java code that looks for the `__run__.py` automatically, and runs it. Note that this is my first try at this class. Let me know if it needs improvement! ``` package org.python.util; import org.python.core.imp; import org.python.core.PySystemState; public class JarRunner { public static void run(String[] args) { final String runner = "__run__"; String[] argv = new String[args.length + 1]; argv[0] = runner; System.arraycopy(args, 0, argv, 1, args.length); PySystemState.initialize(PySystemState.getBaseProperties(), null, argv); imp.load(runner); } public static void main(String[] args) { run(args); } } ``` I put this code into the org.python.util package, since that's where it would go if we decide to include it in a future Jython. To compile it, you'll need to put jython.jar (or your myapp.jar) into the classpath like: ``` $ javac -classpath myapp.jar org/python/util/JarRunner.java ``` Then you'll need to add JarRunner.class to your jar (the class file will need to be in org/python/util/JarRunner.class) calling jar on the "org" directory will get the whole path into your jar. ``` $ jar uf org ``` Add this to a file that you will use to update the manifest, a good name is manifest.txt: ``` Main-Class: org.python.util.JarRunner ``` Then update the jar's manifest: ``` $ jar ufm myapp.jar manifest.txt ``` Now you should be able to run your app like this: ``` $ java -jar myapp.jar ```
I experienced a similar issue in that I want to be able to create simple command line calls for my jython apps, not require that the user go through the jython installation process, and be able to have the jython scripts append library dependencies at runtime to sys.path so as to include core java code. ``` # append Java library elements to path sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "lib", "poi-3.8-20120326.jar")) ``` When running the 'jython' launcher explicitly on the command line, on Unix systems, it just runs a big shell script to properly form a java command line call. This jython launcher seems to have a dependency on reaching back to a core install of jython, and by some way of magic allows the proper handling of .jar files being added to the sys.path at runtime from within my .py scripts. You can see what the call is and block execution by the following: ``` jython --print run_form.py java -Xmx512m -Xss1024k -Dfile.encoding=UTF-8 -classpath /Applications/jython2.5.2/jython.jar: -Dpython.home=/Applications/jython2.5.2 -Dpython.executable=/Applications/jython2.5.2/bin/jython org.python.util.jython run_form.py ``` But it's still just firing up a JVM and running a class file. So my goal was to be able to make this java call to a standalone jython.jar present in my distribution's lib directory so users would not need to do any additional installation steps to start using my .py scripted utilities. ``` java -Xmx512m -Xss1024k -classpath ../../lib/jython.jar org.python.util.jython run_form.py ``` Trouble is that the behavior is enough different that I would get responses like this: ``` File "run_form.py", line 14, in <module> import xls_mgr File "/Users/test/Eclipse/workspace/test_code/py/test/xls_mgr.py", line 17, in <module> import org.apache.poi.hssf.extractor as xls_extractor ImportError: No module named apache ``` Now you might say that I should just add the jar files to the -classpath, which in fact I tried, but I would get the same result. The suggestion of bundling all of your .class files in a jython.jar did not sound appealing to me at all. It would be a mess and would bind the Java/Python hybrid application too tightly to the jython distribution. So that idea was not going to fly. Finally, after lots of searching, I ran across bug #1776 at jython.org, which has been listed as critical for a year and a half, but I don't see that the latest updates to jython incorporate a fix. Still, if you're having problems with having jython include your separate jar files, you should read this. <http://bugs.jython.org/issue1776> In there, you will find the temporary workaround for this. In my case, I took the Apache POI jar file and unjar'ed it into its own separate lib directory and then modified the sys.path entry to point to the directory instead of the jar: ``` sys.path.append('/Users/test/Eclipse/workspace/test_code/lib/poi_lib') ``` Now, when I run jython by way of java, referencing my local jython.jar, the utility runs just peachy. Now I can create simple scripts or batch files to make a seamless command line experience for my .py utilities, which the user can run without any additional installation steps.
Distributing my Python scripts as JAR files with Jython?
[ "", "python", "jython", "executable-jar", "" ]
I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception: ``` class MyException(Exception): def __init__(self, message): self.message = message def __str__(self): return repr(self.message) ``` This is the warning: ``` DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 self.message = message ``` What's wrong with this? What do I have to change to get rid of the deprecation warning?
## Solution - almost no coding needed Just inherit your exception class from `Exception` and pass the message as the first parameter to the constructor Example: ``` class MyException(Exception): """My documentation""" try: raise MyException('my detailed description') except MyException as my: print my # outputs 'my detailed description' ``` You can use `str(my)` or (less elegant) `my.args[0]` to access the custom message. ## Background In the newer versions of Python (from 2.6) we are supposed to inherit our custom exception classes from Exception which ([starting from Python 2.5](http://docs.python.org/library/exceptions.html#exceptions.Exception)) inherits from BaseException. The background is described in detail in [PEP 352](http://www.python.org/dev/peps/pep-0352/). ``` class BaseException(object): """Superclass representing the base of the exception hierarchy. Provides an 'args' attribute that contains all arguments passed to the constructor. Suggested practice, though, is that only a single string argument be passed to the constructor.""" ``` `__str__` and `__repr__` are already implemented in a meaningful way, especially for the case of only one arg (that can be used as message). You do not need to repeat `__str__` or `__init__` implementation or create `_get_message` as suggested by others.
Yes, it's deprecated in Python 2.6 because it's going away in Python 3.0 BaseException class does not provide a way to store error message anymore. You'll have to implement it yourself. You can do this with a subclass that uses a property for storing the message. ``` class MyException(Exception): def _get_message(self): return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) ``` Hope this helps
BaseException.message deprecated in Python 2.6
[ "", "python", "exception", "deprecated", "" ]
I have a table that contains a column named views. Each time the user refreshes the page, it updates the view count +1. What im trying to do, is create a mysql query to output the list of rows based on their views count, from highest to lowest. this is what i thought would work ``` SELECT * FROM picdb ORDER BY views DESC LIMIT 10 ``` even when i view it ASCENDING, its all out of whack. thoughts? **EDIT** the column type is TEXT **SOLVED** changed column type to INT and it works fine now. Thanks for pointing it out.
If your column type is TEXT, the default sorting behavior treats the data as strings, and therefore sorts them alphabetically (not numerically). Change your column type to a number type, and it will sort correctly.
``` SELECT * FROM tbl ORDER BY CAST(views AS UNSIGNED) DESC LIMIT 10 ``` Might do the trick. The real question is why you have a column containing integers with the text type?
mysql show rows in order from highest value to lowest value
[ "", "sql", "mysql", "" ]
In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of `get; set;` like: ``` private int myInt; public int MyInt { get { return myInt; } set { myInt = value } } ``` My question is: how does this differ from: ``` public int MyInt; ``` and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!
See this article <http://blog.codinghorror.com/properties-vs-public-variables/> Specifically * Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties. * You can't databind against a variable. * Changing a variable to a property is a breaking change.
Three reasons: 1. You cannot override fields in subclasses like you can properties. 2. You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API. 3. Convention. That's just the way it's done. I'm sure there are more reasons that I'm just not thinking of. In .Net 3.x you can use automatic properties like this: ``` public int Age { get; set; } ``` instead of the old school way with declaring your private fields yourself like this: ``` private int age; public int Age { get { return age; } set { age = value; } } ``` This makes it as simple as creating a field, but without the breaking change issue (among other things).
Should I use public properties and private fields or public fields for data?
[ "", "c#", ".net", "coding-style", "properties", "" ]
How can I use memcache in Joomla? I'm a newbie in this field so please be descriptive with your answer.
You will need to install memcached on your server and will probably need root access to do so. You can get memcached from <http://www.danga.com/memcached/>. It requires libevent, which can be downloaded here: <http://www.monkey.org/~provos/libevent/> Finally, you'll need to get the PHP PECL extension for memcache. To install this, you need to go to the server where PHP is installed and run this command: ``` pecl install memcache ``` Again, you will most likely need root access to your server to do this. After you have libevent, memcached, and the PECL extensions installed, go to the Global Configuration in Joomla and choose `Memory Cache` as the Cache Handler under Cache Settings. After you save the Global Configuration, open it again and more inputs should appear underneath the Cache Handler input. Set Memory Chache Server to `localhost` and the port to `11211`. This should match the parameters you use to run `memcached` from the command line. EDIT: You can also use XCache not only to store data in a way similar to Memcache, but it will also cache the opcode generated by PHP. This way, instead of reading the PHP code from disk and parsing it each time, it will hold the code in memory for the next request. Be sure to select `XCache` as the Cache Handler in Global Configuration. Read this for information on installing XCache: <http://xcache.lighttpd.net/wiki/InstallFromSource>
In order to make Joomla to use memcache for session caching you need to manually edit the configuration.php and change this line: ``` public $session_handler = 'database'; ``` to this one: ``` public $session_handler = 'memcache'; ``` And this is what is missing everywhere, you need to add a new option memcache\_settings: ``` public $memcache_settings = 'a:3:{s:10:"persistent";s:1:"0";s:11:"compression";s:1:"0";s:7:"servers";a:1:{i:0;a:2:{s:4:"host";s:9:"127.0.0.1";s:4:"port";s:5:"11211";}}}'; ``` This is a serialized multy-dimentianal array. I use this code to generate the above string: ``` $a = array( "persistent" => "0", "compression" => "0", "servers" => array( "0" => array( "host" => "127.0.0.1", "port" => "11211") ) ); echo(serialize($a)); ``` If you don't add the memcache\_settings option your sessions will never work with memcache.
How to use memcached with Joomla
[ "", "php", "mysql", "joomla", "memcached", "" ]
All of the constructors methods here do the same thing. I mostly use method2 but saw method3 for the first time today. Have seen method1 in some places but dont know what are the exact differences between them ? Which one is the best way to define constructors and why ? Is there any performance issues involved ? ``` 1 class Test 2 { 3 private: 4 int a; 5 char *b; 6 public: 7 Test(){}; 8 9 // method 1 10 Test(int &vara, char *& varb) : a(vara), b(varb){} 11 12 // method 2 13 Test(int &vara, char *& varb) 14 { 15 a = vara; 16 b = varb; 17 } 18 19 //method 3 20 Test(int &vara, char *& varb) 21 { 22 this->a = vara; 23 this->b = varb; 24 } 25 26 ~Test(){} 27 }; ``` I have here used simple fields int and char\*,what will happen if I have many fields or complex types like struct ?? Thanks
For the types you use, there will probably be no difference in performance. However for non-POD data (classes with constructors) the form: ``` Test(int &vara, char *& varb) : a(vara), b(varb){} ``` will be the most efficient. This is because non-POD data will be initialised whther you provide an initialisation list or not. The other forms, which use assignment, will take the hit for initialisation, and then another hit for assignment.
Probably not a HUGE difference in terms of performance, but in method 1, you're constructing a and b using a copy constructor. In method 2, you're constructing a and b automatically, THEN using the assignment operator. That *could* be slower for more complex types than int and char\*. Method 3 is exactly the same thing as method 2.
C++ constructor definition
[ "", "c++", "" ]
I need advice on keyboard event handling with SDL. I have a 1st person camera, and can walk fwd, back, strafe left and right and use the mouse to look around which is great. Here is my processEvents function: ``` void processEvents() { int mid_x = screen_width >> 1; int mid_y = screen_height >> 1; int mpx = event.motion.x; int mpy = event.motion.y; float angle_y = 0.0f; float angle_z = 0.0f; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: quit = true; break; case SDLK_w: objCamera.Move_Camera( CAMERASPEED); break; case SDLK_s: objCamera.Move_Camera(-CAMERASPEED); break; case SDLK_d: objCamera.Strafe_Camera( CAMERASPEED); break; case SDLK_a: objCamera.Strafe_Camera(-CAMERASPEED); break; default: break; } break; case SDL_MOUSEMOTION: if( (mpx == mid_x) && (mpy == mid_y) ) return; SDL_WarpMouse(mid_x, mid_y); // Get the direction from the mouse cursor, set a resonable maneuvering speed angle_y = (float)( (mid_x - mpx) ) / 1000; angle_z = (float)( (mid_y - mpy) ) / 1000; // The higher the value is the faster the camera looks around. objCamera.mView.y += angle_z * 2; // limit the rotation around the x-axis if((objCamera.mView.y - objCamera.mPos.y) > 8) objCamera.mView.y = objCamera.mPos.y + 8; if((objCamera.mView.y - objCamera.mPos.y) <-8) objCamera.mView.y = objCamera.mPos.y - 8; objCamera.Rotate_View(-angle_y); break; case SDL_QUIT: quit = true; break; case SDL_VIDEORESIZE: screen = SDL_SetVideoMode( event.resize.w, event.resize.h, screen_bpp, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE ); screen_width = event.resize.w; screen_height = event.resize.h; init_opengl(); std::cout << "Resized to width: " << event.resize.w << " height: " << event.resize.h << std::endl; break; default: break; } } } ``` now while this is working, it has some limitations. The biggest one and the purpose of my question is that it seems to only process the latest key that was pressed. So if I am holding 's' to walk backwards and I press 'd' to strafe right, I end up strafing right but not going backwards. Can someone point me in the right direction for better keyboard handling with SDL, support for multiple keypresses at once, etc?
A good approach will be to write a keyboard ("input") handler that will process input events and keep the event's state in some sort of a structure (associative array sounds good - key[keyCode]). Every time the keyboard handler receives a 'key pressed' event, it sets the key as enabled (true) and when it gets a key down event, it sets it as disabled (false). Then you can check multiple keys at once without pulling events directly, and you will be able to re-use the keyboard across the entire frame without passing it around to subroutines. Some fast pseudo code: ``` class KeyboardHandler { handleKeyboardEvent(SDL Event) { keyState[event.code] = event.state; } bool isPressed(keyCode) { return (keyState[keyCode] == PRESSED); } bool isReleased(keyCode) { return (keyState[keyCode] == RELEASED); } keyState[]; } ... while(SDL Pull events) { switch(event.type) { case SDL_KEYDOWN: case SDL_KEYUP: keyHandler.handleKeyboardEvent(event); break; case SDL_ANOTHER_EVENT: ... break; } } // When you need to use it: if(keyHandler.isPressed(SOME_KEY) && keyHandler.isPressed(SOME_OTHER_KEY)) doStuff(TM); ```
SDL keeps track of the current state of all keys. You can access this state via: [SDL\_GetKeyState()](http://sdl.beuc.net/sdl.wiki/SDL_GetKeyState) So, each iteration you can update the movements based on the key state. To make the movement smooth you should update the movement magnitude based on the time elapsed between updates.
How to handle multiple keypresses at once with SDL?
[ "", "c++", "linux", "opengl", "ubuntu", "sdl", "" ]
`XmlRoot` does not seem to work with classes that are contained within a collection. Here are the classes I have defined: ``` [XmlRoot("cars")] public class CarCollection : Collection<Car> { } [XmlRoot("car")] public class Car { [XmlAttribute("make")] public String Make { get; set; } [XmlAttribute("model")] public String Model { get; set; } } ``` Here is the code I am using to serialize these objects: ``` CarCollection cars = new CarCollection(); cars.Add(new Car { Make = "Ford", Model = "Mustang" }); cars.Add(new Car { Make = "Honda", Model = "Accord" }); cars.Add(new Car { Make = "Toyota", Model = "Tundra" }); using (MemoryStream memoryStream = new MemoryStream()) { XmlSerializer carSerializer = new XmlSerializer(typeof(CarCollection)); carSerializer.Serialize(memoryStream, cars); memoryStream.Position = 0; String xml = null; using (StreamReader reader = new StreamReader(memoryStream)) { xml = reader.ReadToEnd(); reader.Close(); } memoryStream.Close(); } ``` The xml after serialization looks like this: ``` <cars xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Car make="Ford" model="Mustang" /> <Car make="Honda" model="Accord" /> <Car make="Toyota" model="Tundra" /> </cars> ``` Notice the "C" in car is not lowercase. What do I need to change to make this happen? If I serialize the Car directly it comes out as I would expectg. UPDATE: I found another workaround. I am not sure how much I like it but it will work for my case. If I create a custom class (see below) and have CarCollection derive from it the serialization works as I expected. ``` public class XmlSerializableCollection<T> : Collection<T>, IXmlSerializable { public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) { return; } XmlSerializer serializer = new XmlSerializer(typeof(T)); while (reader.NodeType != XmlNodeType.EndElement) { T t = (T)serializer.Deserialize(reader); this.Add(t); } if (reader.NodeType == XmlNodeType.EndElement) { reader.ReadEndElement(); } } public void WriteXml(XmlWriter writer) { XmlSerializer reqSerializer = new XmlSerializer(typeof(T)); foreach (T t in this.Items) { reqSerializer.Serialize(writer, t); } } } ```
Can't you just markup the car with XmlType? ``` [XmlType("car")] public class Car { } ```
`XmlRootAttribute` only applies if the element is the root of the object graph being serialized, ie. the object you pass to the `XmlSerializer` instance. To control serialization of collections, you would normally use the `XmlElementAttribute` to specify the element name to serialize the child objects with. Unfortunately, this attribute can only be applied to a field or property and not a class. If you can expose your collection as a property of a class, you can use the attribute as follows: ``` [XmlRoot("cars")] public class CarList { [XmlElement("car")] public CarCollection Cars { get; set; } } ``` With your code sample, produces the following result: ``` <cars xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <car make="Ford" model="Mustang" /> <car make="Honda" model="Accord" /> <car make="Toyota" model="Tundra" /> </cars> ``` It's a bit of a work-around, but it's the closest you can get without lots of custom code.
Xml Serialization inside a collection
[ "", "c#", ".net", "xml-serialization", "" ]
I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server? So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA. **\* EDIT \*** The data to be shared is a list of 1 million tuples.
Without some deep and dark rewriting of the Python core runtime (to allow forcing of an allocator that uses a given segment of shared memory and ensures compatible addresses between disparate processes) there is no way to "share objects in memory" in any general sense. That list will hold a million addresses of tuples, each tuple made up of addresses of all of its items, and each of these addresses will have be assigned by pymalloc in a way that inevitably varies among processes and spreads all over the heap. On just about every system except Windows, it's possible to spawn a subprocess that has essentially read-only access to objects in the parent process's space... as long as the parent process doesn't alter those objects, either. That's obtained with a call to `os.fork()`, that in practice "snapshots" all of the memory space of the current process and starts another simultaneous process on the copy/snapshot. On all modern operating systems, this is actually very fast thanks to a "copy on write" approach: the pages of virtual memory that are not altered by either process after the fork are not really copied (access to the same pages is instead shared); as soon as either process modifies any bit in a previously shared page, poof, that page is copied, and the page table modified, so the modifying process now has its own copy while the other process still sees the original one. This extremely limited form of sharing can still be a lifesaver in some cases (although it's extremely limited: remember for example that adding a reference to a shared object counts as "altering" that object, due to reference counts, and so will force a page copy!)... except on Windows, of course, where it's not available. With this single exception (which I don't think will cover your use case), sharing of object graphs that include references/pointers to other objects is basically unfeasible -- and just about any objects set of interest in modern languages (including Python) falls under this classification. In extreme (but sufficiently simple) cases one can obtain sharing by renouncing the native memory representation of such object graphs. For example, a list of a million tuples each with sixteen floats could actually be represented as a single block of 128 MB of shared memory -- all the 16M floats in double-precision IEEE representation laid end to end -- with a little shim on top to "make it look like" you're addressing things in the normal way (and, of course, the not-so-little-after-all shim would also have to take care of the extremely hairy inter-process synchronization problems that are certain to arise;-). It only gets hairier and more complicated from there. Modern approaches to concurrency are more and more disdaining shared-anything approaches in favor of shared-nothing ones, where tasks communicate by message passing (even in multi-core systems using threading and shared address spaces, the synchronization issues and the performance hits the HW incurs in terms of caching, pipeline stalls, etc, when large areas of memory are actively modified by multiple cores at once, are pushing people away). For example, the multiprocessing module in Python's standard library relies mostly on pickling and sending objects back and forth, not on sharing memory (surely not in a R/W way!-). I realize this is not welcome news to the OP, but if he does need to put multiple processors to work, he'd better think in terms of having anything they must share reside in places where they can be accessed and modified by message passing -- a database, a memcache cluster, a dedicated process that does nothing but keep those data in memory and send and receive them on request, and other such message-passing-centric architectures.
``` mmap.mmap(0, 65536, 'GlobalSharedMemory') ``` I think the tag ("GlobalSharedMemory") must be the same for all processes wishing to share the same memory. <http://docs.python.org/library/mmap.html>
Possible to share in-memory data between 2 separate processes?
[ "", "python", "" ]
Suppose I have `'/srv/www/site.com/htdocs/system/application/views/'` and want to test it against a regexp that matches each directory name in the path? *Something* like this pattern: `'(/[^/])'` That yields an array with `'srv','www','site.com'...` etc. PS: the regexp syntax I wrote is just to illustrate, it's not tested and surely wrong, but just to give an idea. PS2: I know there's `explode()` but let's see if we can do this with a regexp (it's useful for other languages and frameworks which don't have explode).
[`preg_match_all`](http://dk.php.net/manual/en/function.preg-match-all.php): ``` $str = '/srv/www/site.com/htdocs/system/application/views/'; preg_match_all('/\/([^\/]+)/', $str, $matches); // $matches[0] contains matching strings // $matches[1] contains first subgroup matches print_r($matches[1]); ``` Output: ``` Array ( [0] => srv [1] => www [2] => site.com [3] => htdocs [4] => system [5] => application [6] => views ) ```
There is [`preg_split`](http://us.php.net/manual/en/function.preg-split.php) for splitting files on regular expressions similar to explode, and then there is [`preg_match_al`l](http://us.php.net/manual/en/function.preg-match-all.php) which does what you want.
Can preg_match() (or other php regex function) match a variable number of parenthesized subpatterns?
[ "", "php", "regex", "preg-match", "" ]
I'm a little confused over a ManualResetEvent that I'm using which doesn't appear to be unblocking. Anyone know why this might be the case? The scenario I've got is something along these lines. The real situation is quite complicated and I've not managed to isolate a section of code that's reasonable to post to reproduce the issue. **EDIT** I've updated the code example below. This is execute in a number of different dialogs and I have noticed that one of them hits the this.mre.WaitOne(); Then what happens is I get a "Server Busy" dialog, where I need to press 'switch to' or 'retry', which will then allow my code to step passed the WaitOne() call and all will work. I'm not sure how its relevant, but obviously its of some important. ``` public class A { ManualResetEvent mre; public void Start(ThreadClass tc) { this.mre = new ManualResetEvent(false); tc.Begin(); WebClient wc = new WebClient(); // progress events are pumped to the ThreadClass which then update the Form2. wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted); wc.DownloadFileAsync("Src", "Tgt"); this.mre.WaitOne(); } void void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { try { // Do Stuff } finally { this.mre.Set(); } } } public class ThreadClass { Begin() { Thread t = new Thread(new ThreadStart(DoWork)); t.Start(); } private void DoWork() { Form f = new Form2(); f.ShowDialog(); // Sits waiting on another ResetEvent to determine when to close the thread. } } ```
Webclient runs in the same thread as your caller, so that thread is blocked at the WaitOne, it doesn't actually create a new thread for you. Move your code into a BackgroundWorker or simply, don't block but wait for the DownloadComplete event to be raised.
Check that the MRE you're setting is actually the same MRE you're waiting on. You say this is a simplified example - is it possible that in the *real* code you're creating two different reset events? That would fairly obviously break things :)
ManualResetEvent WaitOne not unblocking
[ "", "c#", "multithreading", "manualresetevent", "" ]
Relating to a previous question, [how let OSGi to reuse your configuration via Config Admin](https://stackoverflow.com/questions/1221951/how-let-osgi-config-admin-persist-reuse-your-configuration), I am still trying to solve this problem in the Equinox Framework. [Pavol Juhos](https://stackoverflow.com/users/3358/pavol-juhos) wrote: > Equinox Config Admin (org.eclipse.equinox.cm) stores the configuration data in the persistent storage area provided by the Framework. And that happens to be the "local bundle cache" directory by default for Equinox. So i read up on this topic and found that there are several [runtime options](http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html) for Equinox (among other things osgi.configuration.area). What I want is to change the configuration, in order that the local bundle cache won't be droped or cleaned, so the next time I'll run the Framework, the last entered configuration (for any bundle) will be used.
There is also the `osgi.clean` property. If you set this to true, the OSGi container must delete the existing bundle cache (and all related data) on startup and reload the bundles into the runtime cache. If you set this to false then your bundle cache should survive a restart. This is documented in the Eclipse SDK Equinox Runtime Options.
CM was not design to persist data after you stop the container. If you want to do that you must use the Preferences Service. So your application, at initialization, must get data from you persistent store managed by PS and 'pass it' to the CM do it works.
Configure Equinox to modify the management of the "local bundle cache"
[ "", "java", "configuration", "osgi", "equinox", "" ]
``` SELECT a, b FROM products WHERE (a = 1 OR b = 2) ``` or... ``` SELECT a, b FROM products WHERE NOT (a != 1 AND b != 2) ``` Both statements should achieve the same results. However, the second one avoids the infamously slow "OR" operand in SQL. Does that make the 2nd statement faster?
Traditionally the latter was easier for the optimiser to deal with in that it could easily resolve an `and` to a [s-arg](http://www.zen-coding.org/index.php?article=wtf_is_sarg_1), which (loosely speaking) is a predicate that can be resolved using an index. Historically, query optimisers could not resolve `OR` statements to s-args and queries using OR predicates could not make effective use of indexes. Thus, the recommendation was to avoid it and re-cast the query in terms like the latter example. More recent optimisers are better at recognising OR statements that are amenable to this transform, but complex OR statements may still confuse them, resulting in unnecessary table scans. This is the origin of the 'OR is slow' meme. The performance is nothing to do with the efficiency of processing the expression but rather the ability of the optimiser to recognise opportunities to make use of indexes.
No, a != 1 and b != 2 is identical to a = 1 or b = 2. The query optimizer will run the same query plan for both, at least in any marginally sophisticated implementation of Sql.
Which conditional statement is faster in SQL?
[ "", "sql", "optimization", "conditional-statements", "" ]
Is there a PHP function to remove certain array elements from an array? E.g., I have an array (`A`) with values and another array (`B`) from which a need to remove values. Want to remove the values in array `A` from array `B`?
Use [`array_diff()`](https://www.php.net/manual/en/function.array-diff.php) ``` $new_array = array_diff($arrayB, $arrayA); ``` will return an array with all the elements from `$arrayB` that are **not** in `$arrayA`. To do this with associative arrays use [`array_diff_assoc()`](https://www.php.net/manual/en/function.array-diff-assoc.php). To remove a single value use: ``` unset($array[$key]); ``` You can of course loop that to do the equivalent of the array functions but there's no point in that.
It depends on what you mean by "remove". You can use the unset() function to remove keys from your array, but this will not reindex it. So for example, if you have: ``` $a = array(1 => 'one', 2 => 'two', 3 => 'three'); ``` and you then call ``` unset($a[2]); ``` You'll end up with something like ``` (1 => 'one', 3 => 'three'); ``` If you need the array to be sequentially indexed, you can take the unsetted array and feed it into array\_values(), which will return a new array with sequentially indexed keys. Returning to your original scenario, as others observe, array\_diff will do the job for you, but note that it doesn't do an index check. If you need that, use array\_diff\_assoc, instead.
How to remove values from an array in PHP?
[ "", "php", "" ]
This is only a minor annoyance but if I can figure this out I'll be very happy. Is it possible to change the default project directory in Netbeans 7? I don't know if it's relevant but I have the PHP Netbeans distro. Thanks!
In new netbeans 7 search file: **D:\Users\YourWindowsUserName\.netbeans\7.0\config\Preferences\org\netbeans\modules\projectui.properties** Delete: \**RecentProjectsDisplayNames.*\*8, \**RecentProjectsIcons.*\*8, \**recentProjectsURLs.*\*8 for cleaning recent projects. Change **projectsFolder** for default projects folder when creating new one To find out the location of the projectui.properties file for the latest versions of NetBeans for various operating systems: <http://wiki.netbeans.org/FaqWhatIsUserdir>
Under Linux, you can change it in the Netbeans configuration directory: .netbeans/6.8/config/Preferences/org/netbeans/modules/projectui.properties
How to change the default Netbeans 7 project directory?
[ "", "php", "netbeans", "" ]
I started out with [this question](https://stackoverflow.com/questions/1262736/only-one-expression-can-be-specified-in-the-select-list-when-the-subquery-is-not), which I sort of answered [there](https://stackoverflow.com/questions/1262736/only-one-expression-can-be-specified-in-the-select-list-when-the-subquery-is-not/1262794#1262794), and now I'm asking the more fundamental question here. I've simplified the query down to this: ``` var q = from ent in LinqUtils.GetTable<Entity>() from tel in ent.Telephones.DefaultIfEmpty() select new { Name = ent.FormattedName, Tel = tel != null ? tel.FormattedNumber : "" // this is what causes the error }; ``` `tel.FormattedNumber` is a property that combines the `Number` and `Extension` fields into a neatly formatted string. And here's the error that results: ``` System.InvalidOperationException: Could not translate expression 'Table(Entity).SelectMany(ent => ent.Telephones.DefaultIfEmpty(), (ent, tel) => new <>f__AnonymousType0`2(Name = ent.FormattedName, Tel = IIF((tel != null), tel.FormattedNumber, "")))' into SQL and could not treat it as a local expression. ``` If I change the reference above from `FormattedNumber` to just plain `Number`, everything works fine. But I do want the formatted number to display nicely in my list. What do you recommend as the neatest, cleanest way of doing so?
You could use `AsEnumerable` on the entity, but that would force it to bring back all the columns (even if not used); perhaps instead something like: ``` var q1 = from ent in LinqUtils.GetTable<Entity>() from tel in ent.Telephones.DefaultIfEmpty() select new { Name = ent.FormattedName, Number = (tel == null ? null : ent.Number), Extension = (tel == null ? null : ent.Extension) }; var q2 = from row in q1.AsEnumerable() select new { row.Name, FormattedNumber = FormatNumber(row.Number, row.Extension) }; ``` where `FormatNumber` is some method that takes the two and merges them, presumably re-used from your other (property) code. With LINQ-to-SQL, another option is to expose a UDF on the data-context that does the formatting inside the database; a slightly different example: ``` var qry = from cust in ctx.Customers // and tel select new { cust.Name, FormattedNumber = ctx.FormatNumber(tel.Number, tel.Extension) }; ``` (which will do the work at the database; whether or not that is a good idea ;-p)
The clean way is to state the fields you actually want in expression, put them in your mid-tier objects and then use any auxiliary functions to modify them latter. I'm not sure if you realize that a class representing SQL table for LINQ is a DTO class - it defines the grammar used by LINQ-SQL translator. Injecting a property into a DTO which is not mapped to the SQL table is not even supported - meaning that translator can fire at will. Attributes define the grammar and anything not defined by them doesn't exist for expression translator. Entities named in the from clause are not objects - they are just symbols used to help spelling out actual table fields that will be fetched. A field not named explicitly in select is a field not fetched - at least that's the goal of the translator, it may have to let a few slip through. For example if that ent.FormattedName is not declared, that's a slip and can explode latter. So, that FormattedNumber property injected into DTO class doesn't even exist in the grammar. It's not a "calculated field" - that term is strictly for SQL table definitions and if you had one it would be in DTO's grammar. Notice that error said very precisely "local expression" - very limited scope. You could try to cheat it by a nested lambda expression invoking a static function on the whole "tel" which might triger fetching of the whole record - or throwing another exception. Other LINQ-s, which are not translators, can have relaxed rules. LINQ-SQL has to be either very strict or very slow and it's already slow enough :-)
Linq "Could not translate expression... into SQL and could not treat it as a local expression."
[ "", "c#", "linq", "linq-to-sql", "" ]
Is there any sure-fire way to ensure *threads* remain isolated from one another, in Java? I've had an issue for a week and a half, where *threads* implementing various 3rd party source code keep colliding due to static variables and other such things that are really beyond my control. I know a single system can run as many instances of the project I'm working on, as it wants. But when trying to incorporate everything into a threaded, single executable, there are always errors and exceptions. I'm almost at the point of just launching a new *process* for each instance of this program that I want, but I'd really rather not go down this route (it would eliminate a lot of real-time data I gather, as well as hinder my ability to kill a targeted process). Suggestions? Thanks!
If the authors of the library you want to use have not designed their code to be thread safe, then there's little you can easily do except to prevent two of your threads calling it at the same time. You can pull some tricks with classloaders, but this tends to lead to a whole new world of complexity. To elaborate, it's possible to load the same class twice (or more times) into the same JVM, if you use different classloaders - hence you could effectively get independent copies of static variables. This use of separate classloaders is exploited by some Java EE Application Servers. That in turn leads to questions of which classloader and classpath gets used when the libraries themselves start to do some reflection and dynamic classloading. I would not recommend this approach unless your need is very great. By preferences would be: 1). Have a single-threaded worker for the unsafe code. Try to do as much work as possible out in your mulit-threaded app, dropping into the Worker as little as you can. 2). If the worker is the major part of your processing and so you really need parallel execution pull the worker out into mulitple separate processes, use some IPC communication to share the work out. This feels like a JMS queueing solution might work nicely. 3). If you can't afford the [IPC](https://stackoverflow.com/tags/ipc/info) overhead try to find a thread-safe alternative to the libraries, or if you have influence with the authors get them to fix the code. It really should not be that hard to increase their parallelism.
> *Threads implementing various 3rd party source code keep colliding due to static variables and other such things that are really beyond my control.* If that's really the case then I think you have to go down that road of having separate processes. If the code you call is not thread-safe then all you can do is to make sure that this code is only called by one process at a time. Which basically eliminates the advantages of running it in a different thread. > *as well as hinder my ability to kill a targeted process* I don't see your point here. Only with processes you can safely kill the processing, it is not possible to do this in a safe way with threads if you don't have complete control over all the code that is run. See also [this question](https://stackoverflow.com/questions/1218790/how-to-isolate-your-program-from-calls-to-a-bad-api) for a discussion of a similar problem.
Thread isolation in Java
[ "", "java", "multithreading", "process", "isolation", "" ]
I have a C# application that serializes its DTOs to JSON and sends them accros the wire to be processed by Ruby. Now the format of the serialized date is like so: ``` /Date(1250170550493+0100)/ ``` When this hits the Ruby app I need to cast this string representation back to a date/datetime/time (whatever it is in Ruby). Any ideas how I would go about this? Cheers, Chris.
You could parse out the milliseconds since the epoch, something like: ``` def parse_date(datestring) seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i / 1000.0 return Time.at(seconds_since_epoch) end parse_date('/Date(1250170550493+0100)/') ``` You'd still need to handle the timezone info (the `+0100` part), so this is a starting point.
You can use [`Time.strptime`](https://ruby-doc.org/stdlib-2.1.1/libdoc/time/rdoc/Time.html#method-c-strptime) to parse this to a `Time` object with the correct time zone: ``` Time.strptime(string, "/Date(%Q%z)/") ``` For example: ``` string = "/Date(1250170550493+0100)/" Time.strptime(string, "/Date(%Q%z)/") #=> 2009-08-13 14:35:50 +0100 ```
c# serialized JSON date to ruby
[ "", "c#", "ruby", "json", "serialization", "" ]
I [read that you do not need to validate or sanitize user's input](http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html) if you use prepared statements. This however does not make sense to me in the following example. The user gives his email address. I normally run this **Validation code** ``` // to validate data if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { header("Location: index.php"); die("Wrong email-address"); } ``` The statement says that we do not need to validate data if we use prepared statements, as follows **Code without the validation code** ``` // to get email-address nad passhash from the db $result = pg_prepare($dbconn, "query2", 'SELECT email, passhash_md5 FROM users WHERE email = $1 AND passhash_md5 = $2;'); $result = pg_execute($dbconn, "query2", array($_POST['email'], $_POST['password'])); if(!$result) { echo "An error occurred"; exit; } ``` I am not sure if we need the validation code or not in the last code, since we use `pg_prepare` and `pg_execute`. **Do you need to consider validating and sanitizing user's input if you use prepared statements?**
You still have to validate your data but you do not have to sanitize it. Using prepared statements prevents insertion of malicious code but does not check if its form makes sense.
It's important to separate validating and sanitizing. *Validating* is making sure that the user has entered the correct type or format of data. For example, on a web form someone could hack the response of a select input to submit a value that doesn't appear in the selection you provided. Validating could catch this error, and provide a suitable error message back to the user. The user could also enter a string into a field that expects a number value. If you do not check this before attempting the query, the query may fail and it will be tougher to determine the cause and provide the user with an error message, or the query may succeed silently with bad data. *Sanitizing* is making sure that the data will not cause harm when added to the database (or later displayed on the website, causing an XSS attack or such). The query `INSERT INTO people (names) VALUES('$name')` will fail if `$name = "O'Reilly"`, but a prepared statement will automatically escape the single quote when binding the string as a parameter. When using different character sets this is especially important, as there may be more than just the quote and slash characters that can cause problems, possibly allowing an SQL injection attack. In order to check that the user is actually entering an email address, you need to keep the validation code, since PostgreSQL has no idea that the data entered is supposed to be an email address, and will store any string you provide to it.
To understand the validation of user's data for prepared statements
[ "", "php", "database", "" ]
I am using JDK1.6\_14. This is a generic question though. When to go for error handling and when to go for exception handling? For example, when I carry a division operation out, I can either check if the denominator is zero and throw an error or just handle `ArithmeticException`. But when to go for which method? Thanks.
There are these cases: 1. Something can go wrong and you can do something about it (say the user supplied an invalid value in the GUI). 2. Something can go wrong but there is little you can do (example: some server on the Internet died) 3. Something can go wrong and the existing exception doesn't carry enough information to find out what happened (think `IOException("Can't read file")` vs. `IOException("Can't read file "+file)` vs. `IOException("Can't read file "+file.getAbsolutePath())`). Solutions: 1. Use `try-catch` to handle the error and take the appropriate action to solve the issue. In the example, show a message somewhere and select the field in the GUI with the illegal value. 2. Throw the exception up in the hope that the code further up in the stack can do something about it or, as a last resort, present the exception to the user. In the example, ask the user to try again later. 3. If it would be hard for the user/developer to figure out what happened when seeing the exception message, enrich it. So when `File.delete()` fails, wrap it in a `RuntimeException` which says *which* file couldn't be deleted.
In general, avoid provoking an exception which you could easily have avoided by execution-time testing and which could be a problem for reasons other than a bug elsewhere in your code. If you're going to divide by something and you have no reason to trust that the divisor is 0 (e.g. if it was user entered) then check the input first. If, however, the divisor should never be zero for other reasons (e.g. it's the size of a collection which should definitely be non-empty) then it's at least *more* reasonable to let that bubble up as an exception. In that case you shouldn't be *handling* that specific exception though, as you're not expecting it to go wrong. You may want to defensively guard against the possibility anyway - but if you spot an error like that, you're probably going to want to throw some other kind of exception to indicate the bug. Again, this shouldn't be "handled" other than near the top of the stack where you might be catching general exceptions (e.g. so that a server can keep going even if a single request fails). In general you should only be *handling* exceptions which you can't reasonably predict - e.g. an I/O failure, or a web service not being present etc.
Errors and Exceptions
[ "", "java", "exception", "error-handling", "" ]
Could there be any obvious reason why a Java program I run from the Eclipse IDE's output is different from what I get if I do the same with the command line in Windows (XP)? I am using the JDK 1.6.0\_04 and Eclipse 3.4.0 The program creates threads and then tests a locking algorithm. In Eclipse, the threads do not interfere with each other. However, using javac, the threads interrupt each other.
One thing that might be the cause of different behaviour is, if you have ie. two jars that provide the same functionality (ie. two versions of the same jar). Depending on how you specify the classpath the code from one jar can override the other. Now in eclipse the order might just be different than on commandline - thus you actually call different code which results in different output.
If you're playing with threads, the console output could vary wildly from machine to machine, and I'm sure eclipse does something to affect threading in some way.
Eclipse and Command Line's Java output differs
[ "", "java", "eclipse", "command-line", "compilation", "" ]
I have a container div which i add to external websites using a bookmarklet to do some functions, the problem i face that this div contains some elements and each element has its inline style, but when i put in the external site, sometimes it overrides styles from the site CSS. There is a way to stop any overrides on this div?
you can define css properites within the element to be able to display your div properly e.g. ``` <div style="margin:0;border:1px solid red;"> ``` Or additionally you can supply your css styles with your Div html as well. I know its a pain when the "external" site has css global rules; e.g ``` ul ( margin-left: 5px; } ``` the best I could do was to reset all these things for my div id. UPDATE: Yes, I understand that he has inline styles but the problem is caused by global rules. So e.g. if @Amr ElGarhy's div has ULs, they will all get left margin of 5px (as I exampled above). and Amr ElGarhy has to reset this margin in inline styles as well.
The host site should have it's CSS properties defined with the **!important** notice (color: red !important;). Or you could append your styles to the DIV using JavaScript (**jQuery**). You can check if the DIV already has styling so you can decide to add or not to add any of your styling.
How to stop all CSS overrides on a container DIV?
[ "", "javascript", "html", "css", "" ]
I am having trouble understanding a question. The question asks first to write a C++ class to represent a stack of integers, and that much is done. Here are my prototypes: ``` class Stack{ private: int top; int item[100]; public: Stack() {top = -1;} ~Stack(); void push(int x) {item[++top] = x;} int pop() {return item[top--];} int empty(int top); }; ``` The second part of the question says "Using the stack for storage purposes, write a C++ class to represent a queue of integers". My queue is as follows: ``` class Queue{ private: int * data; int beginning, end, itemCount; public: Queue(int maxSize = 100); Queue(Queue &OtherQueue); ~Queue(); void enqueue(int x); void dequeue(); int amount(); }; ``` I don't understand how I am meant to use a stack for storage purposes for a queue.
I don't agree with the existing answer. *Typically*, a queue is [First In First Out](http://en.wikipedia.org/wiki/FIFO_%28computing%29), while a stack is obviously [Last In First Out](http://en.wikipedia.org/wiki/LIFO_%28computing%29). I can only think of an implementation using two stacks, popping the whole thing and adding all but the last item to the second stack. Seems like a silly thing to do, but I guess it's for the sake of the exercise. As commented below, it is possible to do in [amortized](http://en.wikipedia.org/wiki/Amortized_analysis) O(1), because the second stack will be in the right order. You can just take elements from the second stack, until you run out, in which case you move everything from the original stack to the second stack. A FIFO queue would just be a stack with `Enqueue` being `Push` and `Dequeue` being `Pop`. That doesn't make any sense as an exercise, so I'd definitely assume a FIFO queue was intended. *Edit*: added some links, something not easily done on my phone :)
Take two stacks, *in* and *out*. * To `enqueue` an element, `push` it on stack *in*. * To `dequeue` an element, 1. `pop` an element from stack *out* if *out* is not empty; otherwise, 2. `pop` and `push` all elements from *in* to *out*, then serve the top element of *out*. It is important that you perform step 2 only if necessary. Note that `enqueue` has complexity *O(1)*, and `dequeue` has [amortized](http://en.wikipedia.org/wiki/Amortized_analysis) complexity *O(1)*, provided your implementations of `pop` and `push` are *O(1)*.
Queue that uses a Stack
[ "", "c++", "stack", "queue", "" ]
I have a script that copies table cells from the browser into the user's clipboard. I loop through each cell and when a new line is needed I use ``` text += "\n"; ``` If I paste the text into excel, it formats correctly and fills in the proper rows, however if I paste into notepad, it shows a symbol instead of creating a new line: 123□456□789 instead of: 123 456 789 Is there something else I can use that notepad will recognize as a line break?
that's because you need a carriage return and line feed. ``` text += "\r\n"; ``` **The non programming way** open up in WordPad save open in notepad
You can use the following: ``` text += "\r\n"; ```
How do I create a new line using javascript that shows correctly in notepad?
[ "", "javascript", "newline", "notepad", "" ]
I want to log how long something takes in real walltime. Currently I'm doing this: ``` startTime = time.time() someSQLOrSomething() print "That took %.3f seconds" % (time.time() - startTime) ``` But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running. I don't want to just benchmark it. I want to log it in a live application in order to see trends on a live system. I want something like clock\_gettime(CLOCK\_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock\_gettime().
That function is simple enough that you can use ctypes to access it: ``` #!/usr/bin/env python __all__ = ["monotonic_time"] import ctypes, os CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h> class timespec(ctypes.Structure): _fields_ = [ ('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long) ] librt = ctypes.CDLL('librt.so.1', use_errno=True) clock_gettime = librt.clock_gettime clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)] def monotonic_time(): t = timespec() if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0: errno_ = ctypes.get_errno() raise OSError(errno_, os.strerror(errno_)) return t.tv_sec + t.tv_nsec * 1e-9 if __name__ == "__main__": print monotonic_time() ```
In Python 3.3+ there is [time.monotonic](https://docs.python.org/3/library/time.html?highlight=monotonic#time.monotonic) (see also [PEP 418](http://www.python.org/dev/peps/pep-0418/#time-monotonic)).
How do I get monotonic time durations in python?
[ "", "python", "linux", "benchmarking", "clock", "" ]
what is good practice for generating verbose output? currently, i have a function ``` bool verbose; int setVerbose(bool v) { errormsg = ""; verbose = v; if (verbose == v) return 0; else return -1; } ``` and whenever i want to generate output, i do something like ``` if (debug) std::cout << "deleting interp" << std::endl; ``` however, i don't think that's very elegant. so i wonder what would be a good way to implement this verbosity switch?
The simplest way is to create small class as follows(here is Unicode version, but you can easily change it to single-byte version): ``` #include <sstream> #include <boost/format.hpp> #include <iostream> using namespace std; enum log_level_t { LOG_NOTHING, LOG_CRITICAL, LOG_ERROR, LOG_WARNING, LOG_INFO, LOG_DEBUG }; namespace log_impl { class formatted_log_t { public: formatted_log_t( log_level_t level, const wchar_t* msg ) : fmt(msg), level(level) {} ~formatted_log_t() { // GLOBAL_LEVEL is a global variable and could be changed at runtime // Any customization could be here if ( level <= GLOBAL_LEVEL ) wcout << level << L" " << fmt << endl; } template <typename T> formatted_log_t& operator %(T value) { fmt % value; return *this; } protected: log_level_t level; boost::wformat fmt; }; }//namespace log_impl // Helper function. Class formatted_log_t will not be used directly. template <log_level_t level> log_impl::formatted_log_t log(const wchar_t* msg) { return log_impl::formatted_log_t( level, msg ); } ``` Helper function `log` was made template to get nice call syntax. Then it could be used in the following way: ``` int main () { // Log level is clearly separated from the log message log<LOG_DEBUG>(L"TEST %3% %2% %1%") % 5 % 10 % L"privet"; return 0; } ``` You could change verbosity level at runtime by changing global `GLOBAL_LEVEL` variable.
``` int threshold = 3; class mystreambuf: public std::streambuf { }; mystreambuf nostreambuf; std::ostream nocout(&nostreambuf); #define log(x) ((x >= threshold)? std::cout : nocout) int main() { log(1) << "No hello?" << std::endl; // Not printed on console, too low log level. log(5) << "Hello world!" << std::endl; // Will print. return 0; } ```
What is good practice for generating verbose output?
[ "", "c++", "verbosity", "" ]
Well, i need to do some calculations in PHP script. And i have one expression that behaves wrong. ``` echo 10^(-.01); ``` Outputs 10 ``` echo 1 / (10^(.01)); ``` Outputs 0 ``` echo bcpow('10', '-0.01') . '<br/>'; ``` Outputs 1 ``` echo bcdiv('1', bcpow('10', '0.01')); ``` Outputs 1.000.... I'm using `bcscale(100)` for BCMath calculations. Excel and Wolfram Mathematica give answer ~0,977237. Any suggestions?
The caret is the bit-wise [XOR operator](http://php.net/manual/en/language.operators.bitwise.php) in PHP. You need to use [`pow()`](http://php.net/manual/en/function.pow.php) for integers.
PHP 5.6 finally introduced an innate power operator, notated by a double asterisk (`**`) - not to be confused with `^`, the bitwise XOR operator. Before 5.6: ``` $power = pow(2, 3); // 8 ``` 5.6 and above: ``` $power = 2 ** 3; ``` An assignment operator is also available: ``` $power = 2 ** 2; $power **= 2; // 8 ``` Through many discussions and voting, it was decided that the operator would be right-associative (not left) and its operator precedence is above the *bitwise not operator* (`~`). ``` $a = 2 ** 3 ** 2; // 512, not 64 because of right-associativity $a = 2 ** (3 ** 2); // 512 $b = 5 - 3 ** 3; // -22 (power calculated before subtraction) ``` Also, for some reason that does not make much sense to me, the power is calculated before the negating *unary operator* (`-`), thus: ``` $b = -2 ** 2; // -4, same as writing -(2 ** 2) and not 4 ```
Raising to power in PHP
[ "", "php", "math", "exponent", "exponentiation", "bcmath", "" ]
This page: <http://blog.ostermiller.org/convert-java-outputstream-inputstream> describes how to create an InputStream from OutputStream: ``` new ByteArrayInputStream(out.toByteArray()) ``` Other alternatives are to use PipedStreams and new threads which is cumbersome. I do not like the idea of copying many megabytes to new in memory byte array. Is there a library that does this more efficiently? EDIT: By advice from Laurence Gonsalves, i tried PipedStreams and it turned out they are not that hard to deal with. Here's the sample code in clojure: ``` (defn #^PipedInputStream create-pdf-stream [pdf-info] (let [in-stream (new PipedInputStream) out-stream (PipedOutputStream. in-stream)] (.start (Thread. #(;Here you write into out-stream))) in-stream)) ```
If you don't want to copy all of the data into an in-memory buffer all at once then you're going to have to have your code that uses the OutputStream (the producer) and the code that uses the InputStream (the consumer) either alternate in the same thread, or operate concurrently in two separate threads. Having them operate in the same thread is probably much more complicated that using two separate threads, is much more error prone (you'll need to make sure that the consumer *never* blocks waiting for input, or you'll effectively deadlock) and would necessitate having the producer and consumer running in the same loop which seems way too tightly coupled. So use a second thread. It really isn't that complicated. The page you linked to had reasonable example. Here's a somewhat modernized version, which also closes the streams: ``` try (PipedInputStream in = new PipedInputStream()) { new Thread(() -> { try (PipedOutputStream out = new PipedOutputStream(in)) { writeDataToOutputStream(out); } catch (IOException iox) { // handle IOExceptions } }).start(); processDataFromInputStream(in); } ```
There is another Open Source library called *[EasyStream](http://io-tools.sourceforge.net/easystream/index.html)* that deals with pipes and thread in a transparent way. That isn't really complicated if everything goes well. Problems arise when (looking at Laurence Gonsalves example) > class1.putDataOnOutputStream(out); Throws an exception. In that example the thread simply completes and the exception is lost, while the outer `InputStream` might be truncated. Easystream deals with exception propagation and other nasty problems I've been debugging for about one year. (I'm the mantainer of the library: obviously my solution is the best one ;) ) Here is an example on how to use it: ``` final InputStreamFromOutputStream<String> isos = new InputStreamFromOutputStream<String>(){ @Override public String produce(final OutputStream dataSink) throws Exception { /* * call your application function who produces the data here * WARNING: we're in another thread here, so this method shouldn't * write any class field or make assumptions on the state of the outer class. */ return produceMydata(dataSink) } }; ``` There is also a nice [introduction](http://io-tools.sourceforge.net/easystream/OutputStream_to_InputStream.html) where all other ways to convert an OutputStream into an InputStream are explained. Worth to have a look.
Most efficient way to create InputStream from OutputStream
[ "", "java", "io", "stream", "inputstream", "bytearrayoutputstream", "" ]
I have a struct for which i want to define a relative order by defining < , > , <= and >= operators. actually in my order there won't be any equality, so if one struct is not smaller than another, it's automatically larger. I defined the first operator like this: ``` struct MyStruct{ ... ... bool operator < (const MyStruct &b) const {return (somefancycomputation);} }; ``` now i'd like to define the other operators based on this operator, such that <= will return the same as < and the other two will simply return the oposite. so for example for the > operator i'd like to write something like ``` bool operator > (const MyStruct &b) const {return !(self<b);} ``` but i don't know how to refere to this 'self' since i can refere only to the fields inside the current struct. whole is in C++ hope my question was understandable :) thank you for the help!
Self is `*this`. That is, `this` is a pointer to the current object, so you need to dereference it to get the actual object.
If you are providing an `operator<` with all the appropriate logic then (whether or not it is implemented as a free function) you can implement the other operators in terms of it as free functions. This follows the rule of preferring non-members over members where possible and free functions will have identical behaviour w.r.t. conversions of the left and right operands, whereas operators implemented as member functions don't. e.g. ``` inline bool operator>(const MyStruct& a, const MyStruct&b) { return b < a; } inline bool operator<=(const MyStruct& a, const MyStruct&b) { return !(b < a); } inline bool operator>=(const MyStruct& a, const MyStruct&b) { return !(a < b); } ```
how to refer to the current struct in an overloaded operator?
[ "", "c++", "struct", "operators", "operator-overloading", "" ]
I have a login system requiring a username and a password. I want to display a captcha after a certain amount of failed login attempts. What is the proper way to implement this? I've read around on this site and some solutions suggest having a 'failed-attempts-count' added to the users table. However, I need the failed attempts to not be tied to a certain user - i.e. I'd like the captcha to be displayed regardless of whether or not the username that was entered exists in the system. Would storing this in a session variable be ok (I am using PHP)? If so, is there no downside to just throwing data as needed into session variables? I already have any a session id for every visitor on the site (either logged in or not) so I could create a table that relates login-attempts to this session id...any ideas on what the best / most secure approach is? Thanks. **Update:** from the answers thus far, it seems like session ID is not the best idea since the hacker could simply clear his/her cache (but is this really an issue because wouldnt this slow down the brute force attack enough to render it useless?). The other option is by IP...but I am hesitant for users under an intranet or proxy since failed attempts will be shared....I can't really think of any other methods..can you?
The danger of using a session ID is that someone who writes a brute force attack can just clear his cookies with each attempt and thus giving him a new session. Keep in mind that an automated brute force attack can be written in a scripting language outside of a browser that could manipulate the cookies sent for each request. Another way to do this would be to create a table with user source IP's and add the counter there. This will inconvenience users using a proxy server though. But at least you will catch those trying to repeatedly guess passwords from the same location. UPDATE: Having to clear cookies during successive brute force attempts would not slow down the attack as this process would be automated and happen almost instantly. Cookie manipulation in these types of attacks is quite common. Modifying a cookie is not the same as clearing your browser's cache (which typically takes a while because it needs to delete a bunch of files). All the attacker needs to do is prevent a cookie from being sent.
install APC <http://www.php.net/apc> or memcache(d) <http://www.php.net/memcache> or here <http://www.php.net/memcached> (memcache also needs a memcached server to be installed, see here <http://www.danga.com/memcached/>), then use the appropriate increment commands for bad login attempts from an IP address with a timeout of whatever suites you (5 minutes, 30 minutes, etc...). this will allow you to QUICKLY determine if a brute force attempt is happening (without worries of race conditions) and automatically expire the block after a determinate amount of time. APC example: ``` $max_attempts = 5; // max attempts before captcha $attempts = apc_fetch('login_attempts_'.$ip)); if($attempts and $attempts>$max_attempts){ // block code here or redirect, captcha etc... also suggest a short sleep time to delay answer, slow down bot }else{ // check login here, run next code if login fails if($login_failed){ if(!$attempts){ apc_store('login_attempts_'.$ip,1,$timeout); }else{ // function NOT currently documented on php.net, increments number stored in key apc_inc('login_attempts_'.$ip); } } } ``` of course it is a very rough example... but you get the idea
Limiting login attempts regardless of user?
[ "", "php", "security", "codeigniter", "" ]
I've been brooding over a design issue (smelly code kinda thing) for a couple days now. Maybe you can help. I have a "Login" Method in my RegistrationService, and currently it looks simplified like this: ``` public Boolean Login(String username, String password, out String successRedirectUrl, out IValidationDictionary validationResults) { successRedirectUrl = ""; if (!Validator.IsValid(username) || !Validator.IsValid(password)) return false; // Other logic // Distributed login requests etc. // Build Redirect Url if login was successful etc. } ``` Okay, let me explain above code. The method's main return value (Boolean) is supposed to tell the caller whether or not the login request was successful. Now, IF it was successful, I need to redirect the user to a different Url (thus, the "out" parameter successRedirectUrl). If it was NOT successful, I need to tell the user in the view what was wrong - thus the ValidationDictionary (Modelstate). This code is really ugly and hard to maintain though. I thought of getting rid of the Boolean return type (returning the successRedirectUrl directly and checking on the caller side if it is empty) but I felt things became even more unclear. Any idea how to do this better? Thank you!
How about this?? ``` public class LoginOutput{ private bool _isLoginSuccess=false; public bool IsLoginSuccess{/*Usual get set block*/} private string _successRedirectUrl = String.Empty(); public string SuccessRedirectUrl{/*Usual get set block*/} public IValidationDictionary ValidationResultDict{/*Usual get set block*/} } //your method now could be public LoginOutput Login(string username, string password){ // your logic goes here } ```
Make a custom class to hold all three values, and return it. Get rid of the "out" parameters.
ASP.NET MVC: Ugly code needs refactoring (returning three values)
[ "", "c#", "asp.net-mvc", "refactoring", "" ]
I am trying to polish off a nav menu by having a script that fetches the current page name (via $\_SERVER["PHP\_SELF"]) and then in JavaScript finds the relevant name (i.e. from /contact.php finds just contact) and searches for an element with that id (my list items have ids that match their target). Now I want to swap the id of the element for "cur", which will confer upon it the relevant styling, making the tab of the current page display differently. But I am having problems, despite tryin replaceNode and replaceChild using the appropriate syntax. Here is the script in its longwinded form: ``` function setCurPage() { var CurPage = "<?php echo $_SERVER["PHP_SELF"]; ?>"; // equates to "/contact.php" var CurRaw = CurPage.substr(1); var Cur = CurRaw.split(".")[0]; var oldNode = document.getElementById(Cur); var newNode = document.createElement("li"); newNode.id = "cur"; var innards = document.getElementById(Cur).children; while(innards.length > 0) { newNode.insertBefore(innards[0]); } oldNode.parentNode.replaceChild(newNode, oldNode); } ``` I've tried various alerts and I know that the node creation lines are correct, but any alerts break after the replaceChild line. Anyone have any ideas?
You want to use something like the following: ``` var newNode = oldNode.cloneNode(true); newNode.id = "cur"; oldNode.parentNode.replaceChild(newNode, oldNode); ```
``` oldNode.id = "cur"; ``` ought to do all you need. If you want to be strict about it, you can use ``` oldNode.setAttribute("id", "cur"); ```
Changing node id by replacing the node
[ "", "javascript", "dom", "replace", "" ]
I need to load a PHP file into a variable. Like `include();` I have loaded a simple HTML file like this: ``` $Vdata = file_get_contents("textfile.txt"); ``` But now I need to load a PHP file.
I suppose you want to get the **content generated by PHP**, if so use: ``` $Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php'); ``` Otherwise if you want to get the **source code of the PHP file**, it's the same as a .txt file: ``` $Vdata = file_get_contents('path/to/YOUR/FILE.php'); ```
``` ob_start(); include "yourfile.php"; $myvar = ob_get_clean(); ``` [ob\_get\_clean()](https://secure.php.net/manual/en/function.ob-get-clean.php)
How do I load a PHP file into a variable?
[ "", "php", "file", "" ]
I'm just getting my head around regular expressions, and I'm using the Boost Regex library. I have a need to use a regex that includes a specific URL, and it chokes because obviously there are characters in the URL that are reserved for regex and need to be escaped. Is there any function or method in the Boost library to escape a string for this kind of usage? I know there are such methods in most other regex implementations, but I don't see one in Boost. Alternatively, is there a list of all characters that would need to be escaped?
``` . ^ $ | ( ) [ ] { } * + ? \ ``` Ironically, you could use a regex to escape your URL so that it can be inserted into a regex. ``` const boost::regex esc("[.^$|()\\[\\]{}*+?\\\\]"); const std::string rep("\\\\&"); std::string result = regex_replace(url_to_escape, esc, rep, boost::match_default | boost::format_sed); ``` (The flag [`boost::format_sed`](http://www.boost.org/doc/libs/1_56_0/libs/regex/doc/html/boost_regex/ref/match_flag_type.html) specifies to use the replacement string format of sed. In sed, an escape `&` will output whatever matched by the whole expression) Or if you are not comfortable with sed's replacement string format, just change the flag to `boost::format_perl`, and you can use the familiar `$&` to refer to whatever matched by the whole expression. ``` const std::string rep("\\\\$&"); std::string result = regex_replace(url_to_escape, esc, rep, boost::match_default | boost::format_perl); ```
Using code from Dav (+ a fix from comments), I created ASCII/Unicode function `regex_escape()`: ``` std::wstring regex_escape(const std::wstring& string_to_escape) { static const boost::wregex re_boostRegexEscape( _T("[.^$|()\\[\\]{}*+?\\\\]") ); const std::wstring rep( _T("\\\\&") ); std::wstring result = regex_replace(string_to_escape, re_boostRegexEscape, rep, boost::match_default | boost::format_sed); return result; } ``` For ASCII version, use `std::string`/`boost::regex` instead of `std::wstring`/`boost::wregex`.
How to escape a string for use in Boost Regex
[ "", "c++", "regex", "boost", "escaping", "" ]
Is it possible to incrementally increase the amount of allocated memory on a free store that a pointer points to? For example, I know that this is possible. ``` char* p = new char; // allocates one char to free store char* p = new char[10]; // allocates 10 chars to free store ``` but what if I wanted to do something like increase the amount of memory that a pointer points to. Something like... ``` char input; char*p = 0; while(cin >> input) // store input chars into an array in the free store char* p = new char(input); ``` obviously this will just make p point to the new input allocated, but hopefully you understand that the objective is to add a new char allocation to the address that p points to, and store the latest input there. Is this possible? Or am I just stuck with allocating a set number.
You can do this using the function realloc(), though that may only work for memory allocated with malloc() rather than "new" having said that, you probably don't want to allocate more memory a byte at a time. For efficiency's sake you should allocate in blocks substantially larger than a single byte and keep track of how much you've actually used.
The C solution is to use malloc instead of new -- this makes realloc available. The C++ solution is to use std::vector and other nice containers that take care of these low-level problems and let you work at a much higher, much nicer level of abstraction!-)
Way to increase memory allocated on free store
[ "", "c++", "heap-memory", "" ]
I have xml files that I read in at runtime, is is possible to validate the xml against an xsd file at runtime? using c#
Try this: ``` public void ValidateXmlDocument( XmlReader documentToValidate, string schemaPath) { XmlSchema schema; using (var schemaReader = XmlReader.Create(schemaPath)) { schema = XmlSchema.Read(schemaReader, ValidationEventHandler); } var schemas = new XmlSchemaSet(); schemas.Add(schema); var settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = schemas; settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += ValidationEventHandler; using (var validationReader = XmlReader.Create(documentToValidate, settings)) { while (validationReader.Read()) { } } } private static void ValidationEventHandler( object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Error) { throw args.Exception; } Debug.WriteLine(args.Message); } ```
I GOT CODE TOO! I use this in my tests: ``` public static bool IsValid(XElement element, params string[] schemas) { XmlSchemaSet xsd = new XmlSchemaSet(); XmlReader xr = null; foreach (string s in schemas) { // eh, leak 'em. xr = XmlReader.Create( new MemoryStream(Encoding.Default.GetBytes(s))); xsd.Add(null, xr); } XDocument doc = new XDocument(element); var errored = false; doc.Validate(xsd, (o, e) => errored = true); if (errored) return false; // If this doesn't fail, there's an issue with the XSD. XNamespace xn = XNamespace.Get( element.GetDefaultNamespace().NamespaceName); XElement fail = new XElement(xn + "omgwtflolj/k"); fail.SetAttributeValue("xmlns", xn.NamespaceName); doc = new XDocument(fail); var fired = false; doc.Validate(xsd, (o, e) => fired = true); return fired; } ``` This one takes in the schemas as strings (file resources within the assembly) and adds them to a schema set. I validate and if its not valid I return false. If the xml isn't found to be invalid, I do a negative check to make sure my schemas aren't screwed up. Its not guaranteed foolproof, but I have used this to find errors in my schemas.
Possible to validate xml against xsd using code at runtime?
[ "", "c#", "xml", "xsd", "schema", "xml-validation", "" ]
I have written the small test with sole purpose to better understand transactions in jdbc. And though I did all according to the documentation, the test does not wish to work normally. Here is table structure: ``` CREATE TABLE `default_values` ( `id` INT UNSIGNED NOT auto_increment, `is_default` BOOL DEFAULT false, PRIMARY KEY(`id`) ); ``` Test contains 3 classes: ``` public class DefaultDeleter implements Runnable { public synchronized void deleteDefault() throws SQLException { Connection conn = null; Statement deleteStmt = null; Statement selectStmt = null; PreparedStatement updateStmt = null; ResultSet selectSet = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost/xtest", "root", ""); conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); // Deleting current default entry deleteStmt = conn.createStatement(); deleteStmt.executeUpdate("DELETE FROM `default_values` WHERE `is_default` = true"); // Selecting first non default entry selectStmt = conn.createStatement(); selectSet = selectStmt.executeQuery("SELECT `id` FROM `default_values` ORDER BY `id` LIMIT 1"); if (selectSet.next()) { int id = selectSet.getInt("id"); // Updating found entry to set it default updateStmt = conn.prepareStatement("UPDATE `default_values` SET `is_default` = true WHERE `id` = ?"); updateStmt.setInt(1, id); if (updateStmt.executeUpdate() == 0) { System.err.println("Failed to set new default value."); System.exit(-1); } } else { System.err.println("Ooops! I've deleted them all."); System.exit(-1); } conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } throw e; } finally { try { selectSet.close(); } catch (Exception e) {} try { deleteStmt.close(); } catch (Exception e) {} try { selectStmt.close(); } catch (Exception e) {} try { updateStmt.close(); } catch (Exception e) {} try { conn.close(); } catch (Exception e) {} } } public void run() { while (true) { try { deleteDefault(); } catch (SQLException e) { e.printStackTrace(); System.exit(-1); } try { Thread.sleep(20); } catch (InterruptedException e) {} } } } public class DefaultReader implements Runnable { public synchronized void readDefault() throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost/xtest", "root", ""); conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); stmt = conn.createStatement(); rset = stmt.executeQuery("SELECT * FROM `default_values` WHERE `is_default` = true"); int count = 0; while (rset.next()) { count++; } if (count == 0) { System.err.println("Default entry not found. Fail."); System.exit(-1); } else if (count > 1) { System.err.println("Count is " + count + "! Wtf?!"); } conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { try { conn.rollback(); } catch (Exception ex) { ex.printStackTrace(); } throw e; } finally { try { rset.close(); } catch (Exception e) {} try { stmt.close(); } catch (Exception e) {} try { conn.close(); } catch (Exception e) {} } } public void run() { while (true) { try { readDefault(); } catch (SQLException e) { e.printStackTrace(); System.exit(-1); } try { Thread.sleep(20); } catch (InterruptedException e) {} } } } public class Main { public static void main(String[] args) { try { Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver") .newInstance(); DriverManager.registerDriver(driver); Connection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost/xtest", "root", ""); System.out.println("Is transaction isolation supported by driver? " + (conn.getMetaData() .supportsTransactionIsolationLevel( Connection.TRANSACTION_SERIALIZABLE) ? "yes" : "no")); } finally { try { conn.close(); } catch (Exception e) {} } (new Thread(new DefaultReader())).start(); (new Thread(new DefaultDeleter())).start(); System.in.read(); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } } ``` I have written script, which fills table with 100k records (where one of them is default) for each run. But every time I run this test, output is: > Is transaction isolation supported by driver? yes > > Default entry not found. Fail. What's wrong with this code?
Please make sure you're creating InnoDB tables, MyISAM (the default) doesn't support transactions. You can change your db create to this: ``` CREATE TABLE `default_values` ( `id` INT UNSIGNED NOT auto_increment, `is_default` BOOL DEFAULT false, PRIMARY KEY(`id`) ) Engine=InnoDB; ``` another example: [MySQL transaction with accounting application](https://stackoverflow.com/questions/292706/mysql-transaction-with-accounting-application)
If you allow the container to manage transactions, you can do something like: ``` @Resource private UserTransaction utx; ``` and then just use it in your code: ``` utx.begin(); // atomic operation in here utx.commit(); ``` Then you don't need to worry about the intricacies of transaction management. Edit: @Gris: Yes, you're correct on that. I had assumed you were developing a web app. as pjp said, spring is a nice alternative in this case. Or -- depending on the size and complexity of the application -- you could get by with managing your own transactions.
Java sql transactions. What am I doing wrong?
[ "", "java", "jdbc", "transactions", "" ]
I am using [MySQL](http://en.wikipedia.org/wiki/MySQL) and [PHP](http://en.wikipedia.org/wiki/PHP). In my database I have this table called `users`, and inside the `users` table have a record: username: admin password: password In my login page, I tried login as (password: password): * username : ADMIN -> result : can login * username : admin -> result : can login I store the username in my database as "admin", all lowercase. In my PHP authentication page, I didn't include the strtolower() function. Does it mean, in PHP the username form field that I submitted is not case sensitive?
It's not PHP. It's your database query that is not case sensitive. You can either make one of the operands binary string. For example: ``` SELECT 'abc' LIKE 'ABC'; ``` This will return `1` or `true`. While ``` SELECT 'abc' LIKE BINARY 'ABC'; ``` will return `0` or `false`.
Yup, as Randell said, it's the database that is case-sensitive. Check this article, for *[Can we make MySQL to be case sensitive for SELECT queries and can we force a column in MySQL to be always lowercase?](http://mysqldatabaseadministration.blogspot.com/2006/09/case-sensitive-mysql.html)*.
Is PHP not case sensitive?
[ "", "php", "forms", "case-insensitive", "" ]
I'm creating a non-intrusive popup window to notify the user when processing a time-consuming operation. At the moment I'm setting its transparency by calling `SetLayeredWindowAttributes` which gives me a reasonable result: [alt text http://img6.imageshack.us/img6/3144/transparentn.jpg](http://img6.imageshack.us/img6/3144/transparentn.jpg) However **I'd like the text and close button to appear opaque** (it doesn't quite look right with white text) while keeping the background transparent - is there a way of doing this?
In order to do "proper" alpha in a layered window you need to supply the window manager with a PARGB bitmap by a call to `UpdateLayeredWindow`. The cleanest way to achieve this that I know of is the following: 1. Create a GDI+ `Bitmap` object with the `PixelFormat32bppPARGB` pixel format. 2. Create a `Graphics` object to draw in this `Bitmap` object. 3. Do all your drawing into this object using GDI+. 4. Destroy the `Graphics` object created in step 2. 5. Call the `GetHBITMAP` method on the `Bitmap` object to get a Windows `HBITMAP`. 6. Destroy the `Bitmap` object. 7. Create a memory DC using `CreateCompatibleDC` and select the `HBITMAP` from step 5 into it. 8. Call UpdateLayeredWindow using the memory DC as a source. 9. Select previous bitmap and delete the memory DC. 10. Destroy the `HBITMAP` created in step 5. This method should allow you to control the alpha channel of everything that is drawn: transparent for the background, opaque for the text and button. Also, since you are going to be outputting text, I recommend that you call `SystemParametersInfo` to get the default antialiasing setting (`SPI_GETFONTSMOOTHING`), and then the `SetTextRenderingHint` on the Graphics object to set the antialiasing type to the same type that is configured by the user, for a nicer look.
I suspect you'll need two top level windows rather than one - one that has the alpha blend and a second that is display above the first with the opaque text and button but with a transparent background. To accomplish this with a single window you'll need to use the [UpdateLayeredWindow](http://msdn.microsoft.com/en-us/library/ms633556%28VS.85%29.aspx) API call, but using this will cause your buttons to not redraw when they are interacted with (hover highlights, focus etc.) It is possible that if this application is for Vista only there is a new API call that you can use, but I do not believe it is available in XP or earlier.
Transparent window containing opaque text and buttons
[ "", "c++", "winapi", "mfc", "gdi+", "gdi", "" ]
``` class NewList<T> : List<T> ``` Why can't I access it's internals like `T[] _items`, etc? Why aren't they protected, but private? Should I use composition for this?
They're private because the author (Microsoft) did not intend for you to access them, probably for safety reasons. You should use composition instead of inheritance. Make your class expose `IList<T>` instead of `List<T>` directly. `List<T>` should never be directly exposed in a public API (this is actually specified in the design guidelines). It should be used as an internal implementation detail only.
`List<T>` isn't designed to be a base class. You should use one of the classes in [System.Collections.ObjectModel](http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx) instead.
Why can't I access the class internals of List<T> when I derive from it?
[ "", "c#", ".net", "inheritance", "list", "" ]
I would like to extend ASP.NET MVC's TextBox so it conditionally switches its CSS value (based on data from the Model). However, I don't want to put that logic in my view (by conditionally changing htmlAttributes/via method call there), but instead extend the class so I don't clutter my view. Basically I want the TextBox on creation look at the Model to see if it has a dictionary entry with its own name, and then look up the associated CSS value if it finds it. The problems I encounter are: 1) How do I extend it? The TextBox itself is already an extension method and not a class so I can't "inherit"? 2) How would I communicate the conditions affecting the TextBox's attributes from my controller method to the TextBox?
Probably you should not couple your text box back to the model. Always it’s better idea to have dependencies just in one way. From model to view. So indirect answer is to have yet another extension method that will accept enum or boolean and depending on this will add or not class name. ``` <%= Html.StyledTextBox("myField", ViewData["ShouldBeStyled"]) %> ``` Also there is direct answer. To extend ASP.NET MVC, you should write your own extension methods. You can always call underline extension method. So your code could look like: ``` public static class MyCoolExtension { public static string TextBox(this HtmlHelper htmlHelper, string name) { // get data from htmlHelper.ViewData and call another extension methods of the HtmlHelper var className = htmlHelper.ViewData["someClass"]; return htmlHelper.TextBox("myField", "30", new { @class = className }); } } ```
One thing you could do is to use ViewData to pass the desired CSS class to your view, then the view wouldn't need to be aware of your logic to do this. To answer your specific questions, 1: You are right, you cannot extend this, but here are two alternatives: one is to avoid the need for extending this at all, and making use of what is provided (such as using ViewData), and the other is to implement your own. You can download the MVC source code and work directly from there if you'd like. 2: Consider something in your controller: ``` if (someCondition) { ViewData["someClass"] = "foo"; } else { ViewData["someClass"] = "snazzle"; } ``` and then in your view: ``` <%= Html.TextBox("myField", "30", new { @class = ViewData["someClass"] }) %> ``` Best of luck! -f!
ASP.NET MVC: 'Extend' Html.TextBox to conditionally have CSS value?
[ "", "c#", "asp.net", "asp.net-mvc", "extension-methods", "html-helper", "" ]
I was reading an article: [Optimizing JavaScript for Execution Speed](http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5) And there is a section that says: **Use this code:** ``` for (var i = 0; (p = document.getElementsByTagName("P")[i]); i++) ``` **Instead of:** ``` nl = document.getElementsByTagName("P"); for (var i = 0; i < nl.length; i++) { p = nl[i]; } ``` **for performance reasons.** I always used the "wrong" way, according the article, but, am I wrong or is the article wrong?
If you look at it from a language like C#, you'd expect the second statement to be more efficient, however C# is not an interpreter language. As the guide states: your browser is optimized to retrieved the right Nodes from live lists and does this a lot faster than retrieving them from the "cache" you define in your variable. Also you have to determine the length each iteration, with might cause a bit of performance loss as well. Interpreter languages react differently from compiled languages, they're optimized in different ways.
**"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."** --*Donald Knuth* --- Personally i would use your way because it is more readable and easier to maintain. Then i would use a tool such as [YSlow](http://developer.yahoo.com/yslow/) to profile the code and iron out the performance bottlenecks.
Is it faster access an javascript array directly?
[ "", "javascript", "arrays", "performance", "" ]
Currently I get 3 rows back from a query, although the report only displays one of those rows. I need all three in the datatable, but only one row to be rendered. How can I choose that row specifically in the report. I'd rather not create another datatable in my dataset just to accommodate this. ``` =FormatCurrency(Fields!tip.Value, "DailySystemFinancialDataSet_tipsCount")) ``` That's what the field looks like, but I want to make sure the row it prints is where Fields!pay\_type = 'comp tip'. EDIT\*\*\* Like I said, I don't need to be manipulating these table rows.. the data is collected and calculated, I just need to get a specific row out of the table in the dataset. Everything is already passed to the report, so I'm using the report editor in design mode (vs2008) and I'd like a solution that works within those constraints. Thanks again.
I found the reporting services documentation, finally. <http://msdn.microsoft.com/en-us/library/ms157328.aspx> in particular, the RowNumber() function is exactly what I needed to solve the problem. Thanks ya'll.
You can use linq, first retrieve all your rows and make a select query in linq to return you the row you want to work with. ``` table.Select(t => t.Id==someId).FirstOrDefault() ```
need a specific row out of a datatable in a report
[ "", "c#", "reporting-services", "" ]
We have a long running server application running Java 5, and profiling it we can see the old generation growing slowly over time. It's correctly freed on a full GC, but I'd like to be able to look at the unreachable objects in Eclipse MAT using a heap dump. I've successfully obtained a heap dump using +XX:HeapDumpOnCtrlBreak, but the JVM always does a GC before dumping the heap. Apparently this doesn't happen on Java 6 but we're stuck on 5 for now. Is there any way to prevent this?
I suggest a 3rd-party profiler such as [YourKit](http://www.yourkit.com/overview/), which may allow you to take snapshots without kicking off the GC first. Added bonus, you can take a snapshot without the whole ctrl-break shenanigans.
use jconsole or visualvm or jmc or ... other jmx management console. open HotSpotDiagnostic in com.sun.management. select method [dumpHeap](https://docs.oracle.com/javase/8/docs/jre/api/management/extension/com/sun/management/HotSpotDiagnosticMXBean.html#dumpHeap-java.lang.String-boolean-) and input two parameters: * path to the dump file * (true/false) dump only live objects. use `false` to dump all objects. Note that the dump file will be written by the JVM you connected to, not by JVisualVM, so if the JVM is running on a different system, it will be written on that system. [![enter image description here](https://i.stack.imgur.com/81Gmp.gif)](https://i.stack.imgur.com/81Gmp.gif)
How can I take a heap dump on Java 5 without garbage collecting first?
[ "", "java", "garbage-collection", "heap-memory", "" ]
I want to apply a special class to the two last list items in an unordered list with jQuery. Like this: ``` <ul> <li>Lorem</li> <li>ipsum</li> <li>dolor</li> <li class="special">sit</li> <li class="special">amet</li> </ul> ``` How to? Should I use :eq somehow? Thanks in advance Pontus
Another approach, using [andSelf](http://docs.jquery.com/Traversing/andSelf) and [prev](http://docs.jquery.com/Traversing/prev): ``` $('ul li:last-child').prev('li').andSelf().addClass("special"); ```
You can use function [slice](http://api.jquery.com/slice/). It is very flexible. ``` $('ul li').slice(-2).addClass("special"); ```
jQuery: Getting the two last list items?
[ "", "javascript", "jquery", "css-selectors", "traversal", "" ]
Hello I'm currently creating an application which has the need to add server IP addresses to it, as there is no InputBox function in C# I'm trying to complete this using forms, but am very new to the language so not 100% as to what I should do. At the moment I have my main form and a form which will act as my inputbox which wants to hide on load. Then when the user clicks on the add IP Address on the main form I wish to open up the secondary form and return the IP address entered into a text box on the secondary form. So how would I go about doing this? Or is there any better ways to achieve similar results?
In your main form, add an event handler for the event **Click** of button Add Ip Address. In the event handler, do something similar as the code below: ``` private string m_ipAddress; private void OnAddIPAddressClicked(object sender, EventArgs e) { using(SetIPAddressForm form = new SetIPAddressForm()) { if (form.ShowDialog() == DialogResult.OK) { //Create a property in SetIPAddressForm to return the input of user. m_ipAddress = form.IPAddress; } } } ``` **Edit**: Add another example to fit with *manemawanna* comment. ``` private void btnAddServer_Click(object sender, EventArgs e) { string ipAdd; using(Input form = new Input()) { if (form.ShowDialog() == DialogResult.OK) { //Create a property in SetIPAddressForm to return the input of user. ipAdd = form.IPAddress; } } } ``` In your Input form, add a property: ``` public class Input : Form { public string IPAddress { get { return txtInput.Text; } } private void btnInput_Click(object sender, EventArgs e) { //Do some validation for the text in txtInput to be sure the ip is well-formated. if(ip_well_formated) { this.DialogResult = DialogResult.OK; this.Close(); } } } ```
You could just use the VB InputBox... 1. Add reference to Microsoft.VisualBasic 2. string result = Microsoft.VisualBasic.Interaction.InputBox("Title","text", "", 10, 20);
Creating an Inputbox in C# using forms
[ "", "c#", "winforms", "forms", "" ]
I had no idea to correctly form the title of this question, because I don't even know if what I'm trying to do has a name. Let's say I've got an external file (called, for instance, settings.txt) with the following in it: ``` template:'xaddict'; editor:'true'; wysiwyg:'false'; ``` These are simple name:value pairs. I would like to have php take care of this file in such a way that I end up with php variables with the following values: ``` $template = 'xaddict'; $editor = 'true'; $wysiwyg = 'false'; ``` I don't know how many of these variables I'll have. How should i go and do this? The data inside the file is in simple name:value pairs. No nesting, no complex data. All the names need to be converted to $name and all the values need to be converted to 'value', disregarding whether it is truly a string or not.
Do you want 'true' in "editor:'true'" to be interpreted as a string or as a boolean? If sometimes string, sometimes boolean, how do you know which? If you have "number='9'" do you want '9' interpreted as a string or an as an integer? Would '09' be a decimal number or octal? How about "number='3.14'": string or float? If sometimes one, sometimes the other, how do you know which? If you have "'" (single quote) inside a value is it escaped? If so, how? Is there any expectation of array data? Etc. Edit: This would be the simplest way, imo, to use your example input to retrieve your example data: ``` $file = 'test.csv'; $fp = fopen($file, 'r'); while ($line = fgetcsv($fp, 1024, ':')) { $$line[0] = $line[1]; } ```
``` $settings = json_decode(file_get_contents($filename)); ``` assuming your file is in valid JSON format. If not, you can either massage it so it is or you'll have to use a different approach.
how do i use php to read an external file and put insides into variables?
[ "", "php", "json", "variables", "external", "" ]
I am having the URL <http://somesubdomain.domain.com> (subdomains may vary, domain is always the same). Need to take subdomain and reload the page with something like domain.com/some/path/here/somesubdomain using greasemonkey (or open a new window with URL domain.com/some/path/here/somesubdomain, whatever).
``` var full = window.location.host //window.location.host is subdomain.domain.com var parts = full.split('.') var sub = parts[0] var domain = parts[1] var type = parts[2] //sub is 'subdomain', 'domain', type is 'com' var newUrl = 'http://' + domain + '.' + type + '/your/other/path/' + subDomain window.open(newUrl); ```
The answer provided by Derek will work in the most common cases, but will not work for "xxx.xxx" sub domains, or "host.co.uk". (also, using window.location.host, will also retrieve the port number, which is not treated : <http://www.w3schools.com/jsref/prop_loc_host.asp>) To be honest I do not see a perfect solution for this problem. Personally, I've created a method for host name splitting which I use very often because it covers a larger number of host names. This method splits the hostname into `{domain: "", type: "", subdomain: ""}` ``` function splitHostname() { var result = {}; var regexParse = new RegExp('([a-z\-0-9]{2,63})\.([a-z\.]{2,5})$'); var urlParts = regexParse.exec(window.location.hostname); result.domain = urlParts[1]; result.type = urlParts[2]; result.subdomain = window.location.hostname.replace(result.domain + '.' + result.type, '').slice(0, -1);; return result; } console.log(splitHostname()); ``` This method only returns the subdomain as a string: ``` function getSubdomain(hostname) { var regexParse = new RegExp('[a-z\-0-9]{2,63}\.[a-z\.]{2,5}$'); var urlParts = regexParse.exec(hostname); return hostname.replace(urlParts[0],'').slice(0, -1); } console.log(getSubdomain(window.location.hostname)); // for use in node with express: getSubdomain(req.hostname) ``` These two methods will work for most common domains (including co.uk) **NOTE**: the `slice` at the end of sub domains is to remove the extra dot. I hope this solves your problem.
Get subdomain and load it to url with greasemonkey
[ "", "javascript", "url", "greasemonkey", "" ]
I would like to ask if there is a more elegant way to do this: ``` List<char> unallowed = new List<char>(); for (char c = '\u0000'; c <= '\u0008'; c++) { unallowed.Add(c); } for (char c = '\u000B'; c <= '\u000C'; c++) { unallowed.Add(c); } // And so on... ``` I have to add to the list a few contiguous ranges of Unicode characters and the only thing that I can think of to refactor the code above is to create my own method to avoid typing the for cycles repeatedly. And I'm not even too sure it's worth it.
Well, you could do something like: ``` List<char> chars = new List<char>(); chars.AddRange(Enumerable.Range(0x0000, 9).Select(i => (char)i)); chars.AddRange(Enumerable.Range(0x000B, 2).Select(i => (char)i)); ``` Not sure it is worth it, though - especially given the need to use "count" rather than "end". Probably easier to write your own extension method... ``` static void AddRange(this IList<char> list, char start, char end) { for (char c = start; c <= end; c++) { list.Add(c); } } static void Main() { List<char> chars = new List<char>(); chars.AddRange('\u0000', '\u0008'); chars.AddRange('\u000B', '\u000C'); } ``` --- Re your comment; extension methods **aren't** a .NET 3.5 feature. They are a C# 3.0 feature. So as long as you compile the code set to target .NET 2.0 / 3.0 (as appropriate), it doesn't matter if the client doesn't have .NET 3.5; you do, however, need to defined the `ExtensionAttribute` - a few lines of code only: ``` namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] public sealed class ExtensionAttribute : Attribute { } } ``` Or just go for broke and download [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) and use all of LINQ-to-Objects in .NET 2.0.
Adding a method to add the range is probably the simplest refactoring, and I think it *would* be worth it, just because it makes the ranges themselves easier to read. Using [MiscUtil](http://pobox.com/~skeet/csharp/miscutil)'s `Range` class you could do something like: ``` list.AddRange('\u000b'.To('\u000c').Step(1)) ``` but that would still be less clear than having an extra method (possibly an extension method on `List<char>`?) and writing: ``` list.AddCharRange('\u000b', '\u000c'); ``` The extra cruft is okay for one or two calls, but if you're repeating this a number of times you *really* want to get rid of as much extraneous text as possible, to make the useful data stand out. It's a shame that extension methods aren't considered by collection initializers, as otherwise that would make a really neat solution. Do you *definitely* need a `List<char>` though due to other restrictions? This *sounds* like you really want a `Predicate<char>` to say whether or not a character is allowed - and that could be implemented by combining ranges etc.
.NET Adding a range of characters to a list
[ "", "c#", ".net", "list", "refactoring", "" ]
I have implemented a custom allocator (to be used by STL containers within my memory debugging utility, without them using my overridden new operator). Within the memory debugger I use an instance of the same allocator class to allocate the objects I need to keep track of 'normal' memory allocations. It's all working fine, but I'm not sure if the way I'm using the allocator interface is correct. Here are the utility methods as they currently stand (correct initialization parameters for the entry will be added soon): ``` iidebug::CMemoryDebugger::CEntry* iidebug::CMemoryDebugger::NewEntry() { CEntry* pEntry = m_entryAllocator.allocate(1); if (0 != pEntry) { new(pEntry) CEntry(0, 0, __FILE__, 0, 0, 0); } return pEntry; } void iidebug::CMemoryDebugger::DeleteEntry( iidebug::CMemoryDebugger::CEntry* pEntry ) { if (0 != pEntry) { destruct(pEntry); m_entryAllocator.deallocate(pEntry, 1); } } ``` This just seems very messy, but I can't see how I can improve it.
You can actually overload new and delete to take an allocator parameter, like so: ``` inline void *operator new(size_t sizeT, Allocator *&a) { return a->allocate(sizeT); } inline void operator delete(void * mem, Allocator *&a) { a->release(mem); } int main() { Allocator * a = new Allocator; C *c = new(a) C; c->~C(); operator delete(c, a); return 0; } ``` See the [wikipedia article](http://en.wikipedia.org/wiki/Placement_syntax) for more detail. It's still a bit messy because you have to be sure not to call the regular delete operator if your allocator does something special.
Just for reference in case anyone struggles to use Drew's code, it needed a few tweaks. The following is what I ended up using: ``` template <typename T> void* operator new(SizeT iSize, SimpleAllocator<T>& rAllocator) { return rAllocator.allocate(1); } template <typename T> void operator delete(void* pvMemory, SimpleAllocator<T>& rAllocator) { ((T*)pvMemory)->~T(); rAllocator.deallocate(pvMemory, 1); } ``` And actually using it is as simple as: ``` // SimpleAllocator<CFoo> fooAllocator = ... CFoo* pFoo = new(fooAllocator) CFoo(param1, param2, ...); // Do stuff with pFoo... operator delete(pFoo, fooAllocator); ```
What is the correct way to instantiate an object with an allocator?
[ "", "c++", "memory", "" ]
Basically, I'd like to have an input that when blur'd, will check the input to make sure it's in the format... [24hour] : [minutes] So for example 13:00, or 15:30. So I guess I have to split it up into three parts, check the first bit is between 0 and 24, then check it has the semi-colon, then check it has a number between 0 and 60. Going more complicated than that, it'd be fantastic to have it so if the user enters 19 it'll complete it as 19:00 for example. I am using jQuery fwiw, but regular code is fine, for example I'm using this little piece of code so far which works fine, to convert . inputs to : ``` tempval = $(this).val().replace(".", ":"); $(this).val(tempval); ``` Not sure where to start with this, if anyone could recommend me some reading that'd be fantastic, thank you!
I suggest using [masked input](http://digitalbush.com/projects/masked-input-plugin/) That way the wrong input will be prevented in the first place. Disclaimer: I haven't used that plugin myself, just found it by keywords "masked input"
([0-1 ]?[0-9]|2[0-3]):([0-5][0-9]) I think that's the regex you're looking for (not specifically for javascript though). <http://www.regular-expressions.info/> This site has an excellent amount of info for language-specific regular expressions! Cheers!
Check that the user is entering a time format? eg 13:00
[ "", "javascript", "jquery", "" ]
I identified a bug in my code and I'm baffled as to how it could have occurred in the first place. My question is, I found a skip in the database ID fields (it is an incremented identity field), indicating some records weren't inserted - which means my SQL sprocs (probably) threw an error. Thinking backwards from there, that means that my business object should have caught that error and thrown it, exiting immediately and returning back to the page's codebehind (instead it continued right on to the second stored procedure). I don't understand why or how this is possible. What's going on in respect to the code execution skipping my try catches? **Page code behind:** ``` protected void submitbutton_click(object sender, EventArgs e){ try{ mybusinessobject.savetodatabase() } catch( Exception ex) { Response.Redirect("Error.aspx"); } } ``` **business object code:** ``` public static void savetodatabase(){ int ID1=-1; int ID2=-1; //store the billing contact SqlCommand cmd1 = new SqlCommand("SaveInfo1", con); cmd1.CommandType = CommandType.StoredProcedure; //... cmd1.Parameters.Add("@Ret", SqlDbType.Int); cmd1.Parameters["@Ret"].Direction = ParameterDirection.ReturnValue; try { con.Open(); cmd1 .ExecuteNonQuery(); ID1 = Convert.ToInt32(cmd1.Parameters["@Ret"].Value); } catch (Exception ex) { throw ex; } finally { con.Close(); } if (ID1 > 0) { SqlCommand cmd = new SqlCommand("SaveInfo2", con); cmd.CommandType = CommandType.StoredProcedure; //... try { con.Open(); cmd.ExecuteNonQuery(); ID2= Convert.ToInt32(cmd.Parameters["@Ret"].Value); } catch (Exception ex) { throw ex; } finally { con.Close(); } } } ``` **SQL Code:** ``` PROCEDURE [dbo].[SaveInfo1] ( -- ... parameters ... ) AS INSERT INTO Table1 ( ... ) Values ( ... ) RETURN SCOPE_IDENTITY PROCEDURE [dbo].[SaveInfo2] ( -- ... parameters ... ) AS DECLARE @SpecialID INT INSERT INTO Table2 ( ... ) Values ( ... ) SET @SpecialID = SCOPE_IDENTITY() INSERT INTO Table3 ( [ID], ... ) Values ( @SpecialID, ... ) RETURN SCOPE_IDENTITY() ```
Your exception handling is horrible. **Never** do this: ``` catch (Exception ex) { throw ex; } ``` All that accomplishes is to screw up the stack trace in the exception. It makes it look like the exception originated at the point of the `throw`. **Never** do this: ``` try{ mybusinessobject.savetodatabase() } catch( Exception ex) { Response.Redirect("Error.aspx"); } ``` You don't know what exception happened. You have no idea whether or not it's safe to redirect, and on top of it all, you lose *all* information about what the exception was! You should also get into the habit of implementing `using` blocks: ``` public static void savetodatabase() { using (SqlConnection con = new SqlConnection("Connectionstring")) { int ID1; //store the billing contact using (SqlCommand cmd1 = new SqlCommand("SaveInfo1", con)) { cmd1.CommandType = CommandType.StoredProcedure; //... cmd1.Parameters.Add("@Ret", SqlDbType.Int); cmd1.Parameters["@Ret"].Direction = ParameterDirection.ReturnValue; con.Open(); cmd1.ExecuteNonQuery(); ID1 = Convert.ToInt32(cmd1.Parameters["@Ret"].Value); } if (ID1 <= 0) { return; } int ID2 = -1; using (SqlCommand cmd = new SqlCommand("SaveInfo2", con)) { cmd.CommandType = CommandType.StoredProcedure; //... con.Open(); cmd.ExecuteNonQuery(); ID2 = Convert.ToInt32(cmd.Parameters["@Ret"].Value); } } } ``` A `using` block will ensure that the resource will have its `Dispose` method called, whether or not an exception is thrown.
Isn't the more likely scenario that someone just deleted some records from the table?
asp.net/sql server try catch what is going on?
[ "", "asp.net", "sql", "exception", "" ]
If I have the following XML segment: ``` <Times> <Time>1/1/1900 12:00 AM</Time> <Time>1/1/1900 6:00 AM</Time> </Times> ``` What should the corresponding property look like that, when deserialization occurs, accepts the above XML into a list of DateTime objects? This works to deserialize the XML segment to a list of `string` objects: ``` [XmlArray("Times")] [XmlArrayItem("Time", typeof(string))] public List<string> Times { get; set; } ``` But when I use DateTime as the type instead of string (for both the List type and XmlArrayItem type), I get the following error: `The string '1/1/1900 12:00 AM' is not a valid AllXsd value.` Thanks!
With `DateTime`, I expect that a large part of the problem is that the format of the xml is wrong; that isn't the xsd standard for dates... can you influence the xml at all? Otherwise, you might have to stick with strings and process it afterwards. More standard xml would be: ``` <Times> <Time>1900-01-01T00:00:00</Time> <Time>1900-01-01T06:00:00</Time> </Times> ``` For example: ``` using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; public class Data { [XmlArray("Times")] [XmlArrayItem("Time")] public List<DateTime> Times { get; set; } static void Main() { XmlReader xr = XmlReader.Create(new StringReader(@"<Data><Times> <Time>1900-01-01T00:00:00</Time> <Time>1900-01-01T06:00:00</Time> </Times></Data>")); XmlSerializer ser = new XmlSerializer(typeof(Data)); Data data = (Data) ser.Deserialize(xr); // use data } } ```
The easiest way is to create a new property which is serialized instead of the Times property, and handles the formatting : ``` [XmlIgnore] public IList<DateTime> Times { get; set; } [XmlArray("Times")] [XmlArrayItem("Time")] public string[] TimesFormatted { get { if (this.Times != null) return this.Times.Select((dt) => dt.ToString("MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture)).ToArray(); else return null; } set { if (value == null) this.Times = new List<DateTime>(); else this.Times = value.Select((s) => DateTime.ParseExact(s, "MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture)).ToList(); } } ```
How can I deserialize a list of DateTime objects?
[ "", "c#", ".net", "xml-serialization", "" ]
I've been searching for while now and I can't find a simple example of how to capture a webcam stream with FMJ. Are there any tutorials or examples available which could help me?
I have been working with FMJ for a while and I haven't found many examples to start with either. What I would do is to explore the FmjStudio class that has the webcam functionality integrated and its pretty straight forward. For bob: What you want is FMJ. FMJ uses an DataSource implementation for civil to use it with JMF. I would recommend you to go to <http://fmj-sf.net/> download the latest source and explore FmjStudio aswell since it uses civil to capture. For theDude: You are right, you can use JMF aswell but the same code you use for JMF will most likely work with FMJ (maybe with a coupla changes) and the performance will be much better, specially if you want a wide range of different webcams to work with your software.
I know this isn't what you want to hear, but I've used JMF for this task and it works very well. There are enough examples online to get a simple web cam capture app running pretty easily. I'll post more if you're interested.
FMJ Webcam capture example
[ "", "java", "webcam", "capture", "fmj", "" ]
Is it as easy as $ENV{'HTTP\_REFERER'}? or is there something else that I need to do? Example: My Site: sample.php Calling Site w/iFrame: somesite.com I want sample.php when it loads to be able to use "somesite.com" for input as a variable.
There is no difference between an inline frame and a normal page. And loading an inline frame initially with `src` will send the HTTP referer.
First of all, your page must not **depend** on the Referer being present nor correct : it is an information that is sent by the browser, and can either : * be disabled (some firewall/antivirus remove that information, for instance -- or did sometime ago) * or be altered / faked (if you search a bit, there must be some firefox extension that allow you to fake this pretty easily, for instance) For more informations, see, for instance : * [Determining Referer in PHP](https://stackoverflow.com/questions/165975/determining-referer-in-php) * [How do you get the ‘referer’ header in PHP?](https://stackoverflow.com/questions/1031162/how-do-you-get-the-referer-header-in-php) These posts both "agree" with me ^^ Now, you can enventually use it to add some feature ; but you must not **rely** on it for your website to work ;-)
How do I get the siteURL calling my page when it is loaded in an iFrame?
[ "", "php", "iframe", "http-referer", "" ]
I'm trying to create a text box using the vales retrieved from the database. But instead of a text box, a select box (drop down box) is created. I do not understand why. I have given the type as text only, then why a select box is being created? ``` echo $form->input($r['Attribute']['label'], array('label' => $r['Attribute']['label'].' * ', 'class' => 'required', 'id' => $r['Attribute']['id'], 'name' => $r['Attribute']['label'], 'type' => 'text', 'style' => 'width:' . $r['Attribute']['size'] . 'px')); ``` This is the Attributes table with a few records. ``` id form_id label type size sequence_no required 2 1 Name text 200 1 true 3 1 Age number 200 2 true ``` The output of $form->input is ``` <div class="input select"> <label for="4">Name * </label> <select id="4" class="required" style="width: 200px;" name="data[Name]"> </select> </div> ``` instead of ``` <div class="input text"> <label for="4">Name * </label> <input id="4" class="required" style="width: 200px;" name="data[Name]"> </input> </div> ``` How does the input type get saved as "select" even when I explicitly mention it as "text"?
Because the value of Attribute.label is capitalised, CakePHP thinks it is a reference to another model along the lines of a belongsTo relationship, and so it tries to give you the list automatically. Try replacing: ``` $form->input($r['Attribute']['label'], ``` with something like: ``` $form->input('Attribute.'.$r['Attribute']['id'].'.label', ``` which should output: ``` <div class="input text"> <label for="4">Name * </label> <input id="4" class="required" style="width: 200px;" name="data[Attribute][2][label]" /> </div> ``` This will give you all the information you need in a structure that CakePHP will recognise. Edit: Oh, and change the line that has `'id' => $r['Attribute']['id'],` because that is just going to generate nonsensical HTML attributes. Something like `'id' => 'Attribute'.$r['Attribute']['id']` should be more useful.
The only thing I could think of is, if you have a field named, say, "name", and you also have a variable in your view named `"$names"`, and this variable is an array, by naming convention Cake may think these belong together. Looking through the FormHelper, there's actually this piece of code: ``` $types = array('text', 'checkbox', 'radio', 'select'); if (!isset($options['options']) && in_array($options['type'], $types)) { // ... looks for corresponding variable in the view ... $options['type'] = 'select'; ``` This seems to be the special case where Cake may change the input type by itself. Looks like setting `'options' => null` in the `$form->input()` arguments should help.
Why is CakePHP is rendering a drop-down instead of a text box in my form?
[ "", "php", "cakephp", "textbox", "drop-down-menu", "" ]
I've created a simple Attribute: ``` [AttributeUsage(AttributeTargets.Method)] public class InitAttribute : System.Attribute { public InitAttribute() { Console.WriteLine("Works!"); } } ``` and I apply it to a simple method: ``` static class Logger { public static string _severity; public static void Init(string severity) { _severity = severity; } [Init()] public static void p() { Console.WriteLine(_severity); } } ``` What is going on is pretty straightforward. Only, I expect the attribute to perform an action (printing "Works!"), but this does not happen. Additionally, printing "Works!" is of course just for debugging purposes: I'd like to access the *instance*'s property `_severity` (to check if is `!= null`, for example), but everything I keep reading about regarding attributes (that is pretty new to me) is about accessing the *class*' methods or properties and so on via reflection. Once I've evaluated `_severity`, how can I modify the behavior of the decorated method (in this case, raise an exception "Logger is not initialized" and do not execute it)? Any help appreciated.
If you need to perform an action as control enters a method, you should look at [aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming) and frameworks such as [PostSharp](http://www.postsharp.org/). Attributes are not designed to perform anything by themselves. They are just a bunch of data (or metadata if you will) attached to stuff in IL assemblies that can be queried at runtime.
Attributes only allow decoration of types and members, but the attribute itself cannot acces the decorated object. You will have to use the constructor parameters of the attribute to pass in any data you require to work with within the attribute. If you wish to use attributes to automatically alter the behaviour of their target objects, you will have to look at AOP solutions like [PostSharp](http://www.postsharp.org/).
Why does my .NET Attribute not perform an action?
[ "", "c#", "reflection", "attributes", "" ]
I'm trying to set flag that causes the `Read Only` check box to appear when you `right click \ Properties` on a file. Thanks!
Two ways: ``` System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); fileInfo.IsReadOnly = true/false; ``` or ``` // Careful! This will clear other file flags e.g. `FileAttributes.Hidden` File.SetAttributes(filePath, FileAttributes.ReadOnly/FileAttributes.Normal); ``` The `IsReadOnly` property on `FileInfo` essentially does the bit-flipping you would have to do manually in the second method.
To **set** the read-only flag, in effect making the file non-writeable: ``` File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.ReadOnly); ``` To **remove** the read-only flag, in effect making the file writeable: ``` File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly); ``` To **toggle** the read-only flag, making it the opposite of whatever it is right now: ``` File.SetAttributes(filePath, File.GetAttributes(filePath) ^ FileAttributes.ReadOnly); ``` This is basically bitmasks in effect. You set a specific bit to set the read-only flag, you clear it to remove the flag. Note that the above code will not change any other properties of the file. In other words, if the file was hidden before you executed the above code, it will stay hidden afterwards as well. If you simply set the file attributes to `.Normal` or `.ReadOnly` you might end up losing other flags in the process.
Best way to make a file writeable in c#
[ "", "c#", ".net", "file", "file-attributes", "" ]
I have a non databound DGV (no datasource, etc; rows added manually). To filter it I'd been doing a check in a loop and setting the rows visible property appropriately. This worked well with smaller test sets, but fails utterly in performance with larger ones. 1k rows filtered at 5000/sec. 10k rows filtered at only ~250/sec. 50k at a mere 40/sec. My assumption about what's going on is that each time i change a rows visibility the DGV rebuilds a list of displayed rows turning the filtering process into an O(n^2) operation. While even 10k rows indicates that the user is abusing the system; badly behaved users need to be accounted for so I need to do something differently. Is there a faster way to filter a large number of rows than what I'm doing now without using data binding, or do I need to fall back on clearing/recreating all the rows (for reasonable amounts of data this is significantly slower)? ``` //psuedocode. runs slowly if more than a few thousand rows. foreach (DataGridViewRow row in myDGV) { row.Visible = CalculateFilter(row); } ```
I had this issue a few years ago (before I knew about databindings) and found a bug post at Microsoft, saying that this is confirmed, but the issue will propably not be fixed. However, there are a few possibilities to solve this. 1. Insted of adding rows to the datagridview, add rows to a datatable and bind it to the datagridview. ``` DataTable table = new DataTable(); table.Columns.Add("Name", typeof(String)); table.Columns.Add("...", typeof(String)); foreach (var element in list) table.Rows.Add(element.Name, element.Something); dataGridView1.DataSource = table1; table.DefaultView.RowFilter = "Name Like '...'"; ``` 2. Create a Class that inherits from BindingList and implements IBindingList. Then bind it to your DataGridView. 3. Set DataGridView VirtualMode to true. Method two is more complicated, because you have to add your own logic to implement the FindCore Method. And you should look here: <http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/68c8b93e-d273-4289-b2b0-0e9ea644623a>
The overall performance should greatly improve if you temporarily remove the rows from the dataGridView while filtering. 1. Create a windows forms app 2. Drop a DataGridView and four buttons to the form 3. Copy and paste this code (don't forget to add event handlers for the button events) ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Stopwatch watch = new Stopwatch(); private void Form1_Load(object sender, EventArgs e) { // populate dataGridView for (int i = 0; i < 10000; i++) dataGridView1.Rows.Add("Column", i+1, 10000 - i); for (int i = 0; i < 10000; i = i + 2) dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red; } // remove filter private void button1_Click(object sender, EventArgs e) { watch.Reset(); watch.Start(); foreach (DataGridViewRow row in dataGridView1.Rows) row.Visible = true; watch.Stop(); MessageBox.Show(watch.ElapsedMilliseconds.ToString()); } // add filter (hide all odd rows) private void button2_Click(object sender, EventArgs e) { watch.Reset(); watch.Start(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (Convert.ToInt32(row.Cells[1].Value) % 2 != 0) row.Visible = false; } watch.Stop(); MessageBox.Show(watch.ElapsedMilliseconds.ToString()); } // remove filter (improved) private void button3_Click(object sender, EventArgs e) { watch.Reset(); watch.Start(); List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (DataGridViewRow row in dataGridView1.Rows) { rows.Add(row); } dataGridView1.Rows.Clear(); foreach (DataGridViewRow row in rows) row.Visible = true; dataGridView1.Rows.AddRange(rows.ToArray()); watch.Stop(); MessageBox.Show(watch.ElapsedMilliseconds.ToString()); } // add filer (improved) private void button4_Click(object sender, EventArgs e) { watch.Reset(); watch.Start(); List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (DataGridViewRow row in dataGridView1.Rows) { rows.Add(row); } dataGridView1.Rows.Clear(); foreach (DataGridViewRow row in rows) { if (Convert.ToInt32(row.Cells[1].Value) % 2 != 0) { row.Visible = false; } } dataGridView1.Rows.AddRange(rows.ToArray()); watch.Stop(); MessageBox.Show(watch.ElapsedMilliseconds.ToString()); } } ```
Filtering an DataGridView that doesn't have databinding
[ "", "c#", "datagridview", "filter", "" ]
Here's my code: ``` public void VerifyIfFirstTimeRun() { if (System.Configuration.ConfigurationSettings.AppSettings["FirstTimeRunning"] == "true") { //Do bla bla bla //Then do bla bla bla System.Configuration.ConfigurationSettings.AppSettings["FirstTimeRunning"] = "false"; } } ``` Problem is, I'm testing this with the F5 key, it boots up and sure enough using a breakpoint shows that it is indeed going inside the If Condition, but when I "Stop" the application and press F5 again it goes inside the If Condition AGAIN. Is this standard operational procedures? If so, how can I test if its working?
This is going against the spirit of what the App.config file is used for ... but to answer your question, you need to do System.Configuration.Configuration.Save(). Edit: App.config is typically used to configure database connections, providers, etc. And is usually set once at installation. It's suggested that user settings go into a separate config file user.config. See [this](http://msdn.microsoft.com/en-us/library/a65txexh%28VS.80%29.aspx) for the explanation. Edit: [System.Configuration.Configuration](http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx) class. Note - now that I read why you're using these settings, may I suggest another way? You should probably just check if the file is there: ``` if (!File.Exists("thefilepath")) { AlertUserOfMissingFile(); ChooseNewFile(); } ``` It's safer this way anyhow because having a setting set to true doesn't necessarily mean the file is where you think it is.
I'm not sure you should *expect* this to save; you can, however, have a settings file that has a setting (a `bool` in this case) in the *user's* context, which saves (when you ask it to) via `Settings.Default.Save()`.
My App.Config file isn't saving anything I modify
[ "", "c#", "app-config", "" ]
A fellow developer suggested we store a selection of days of the week as 7-character string of 1’s and 0’s, i.e. “1000100” for Monday and Friday. I preferred (and strongly suggested) a solution with a Flags enum and bitwise operations, I think it's a cleaner way of doing this, and it should be easier to understand for other developers. ``` [Flags()] public enum Weekdays : int { Monday = 1, Tuesday = 2, Wednesday = 4, Thursday = 8, Friday = 16, Saturday = 32, Sunday = 64 } ``` However, as I started to implement a sample solution, I realized that maybe the simple string approach was easier after all: Certainly the bit-string is more obvious than “17” if you’re just looking at the data. And I find the C# bitwise operations counter-intuitive and extremely verbose: ``` Weekdays workDays = Weekdays.Monday | Weekdays.Tuesday; if ((workDays & Weekdays.Monday) == Weekdays.Monday) {...} ``` Of course this could be wrapped nicely into extension methods, but then we suddenly end up with at least the same number of lines of code as with the string-solution, and I can hardly argue the bitwise code is easier to read. That being said, I still would go with a flags enum and bitwise operations. The key benefits I can think of are * Better performance * Less space needed for storage So how do I sell the bitwise solution to my colleagues? Should I? What are the other benefits of using this method over strings? After completing the sample project, I found that the team still opted for the string-based solution. I need some better/stronger arguments. Why should you use Flags enums rather than simple bit-strings?
**Benefits of using Flags enum:** * Standard approach: ["They are the correct design to use when multiple enumeration values can be specified at the same time."](http://msdn.microsoft.com/en-us/library/ms229062.aspx) * Intent is clear * Maintainable -- new programmers should pick this up easily * Easily extensible -- support for new flag combinations (e.g. weekend) * Fast **Negatives of using Flags enum:** * Data representation for humans hard to understand (e.g. what flags are set for 17?) **Benefits of using string of bits:** * Easy for programmers to see which bits are set in string **Negatives of using string of bits:** * Non-standard approach * Harder to understand for programmers unfamiliar with your design * Potentially easier to set "garbage" values (e.g. stringValue = "Sunday") * Needless string creation * Needless string parsing * Additional development work * Reinventing the wheel (but not even a round wheel) How important is it really to be able to look at the string of bits to see what is set? If it's hard to know that 17 is Monday and Friday, you can always use calculator and convert to binary. Or add some sort of string representation for "display" (or debugging) use. It's not *that* difficult. It also seems to me that if you are going to make the string of bits approach solid then you will need to do quite a bit of encapsulation to bring it up to a level of abstraction that the Flags enum already provides. If the approach is to simply manipulate the string of bits directly then that is going to be hard to read (and understand) and probably error prone. e.g. you may end up seeing this: ``` days = "1000101"; // fixed bug where days were incorrectly set to "1010001" ```
You shouldn't be creating non-standard datastructures to replace a standard data structure (in this case, the DayOfWeek builtin enum). Instead, extend the existing structure. This works essentially the same way as the bit flags method you were talking about. ``` namespace ExtensionMethods { public static class Extensions { /* * Since this is marked const, the actual calculation part will happen at * compile time rather than at runtime. This gives you some code clarity * without a performance penalty. */ private const uint weekdayBitMask = 1 << Monday | 1 << Tuesday | 1 << Wednesday | 1 << Thursday | 1 << Friday; public static bool isWeekday(this DayOfWeek dayOfWeek) { return 1 << dayOfWeek & weekdayBitMask > 0; } } } ``` Now you can do the following: ``` Thursday.isWeekday(); // true Saturday.isWeekday(); // false ```
Flags enum & bitwise operations vs. “string of bits”
[ "", "c#", "bit-manipulation", "enum-flags", "" ]
Currently I'm developing a spatial data processing server. Here are requirements: 1. Server must be able to receive and handle about 150-200 small messages per sec(gps fix, some additional data). 2. It must be scalable. For example to run on several machines and balance load itself(without nlb) Currently I have tested this kind of architecture: 1. Incoming messages service,responsible only for getting messages into (without msmqwcf binding) 2. Message parser service. Gets messages from msmq, parses them and writes to db, also sends notification to next service(again with plain MSMQ interop). This one is able to work on several PCs 3. Data publisher service. Contains small cache and responsible for getting requested data from db. Sends notifications to clients using TCP binding via wcf. Also all services have methods for configuration and some other tasks which are called via WCF TCP binding. Small performance tests shown that it works quite fast, but i wonder is this a best way to use those MSMQ and WCF together for this specific app. Or maybe someone can give me a direction where to look?
I am not really sure of the specific question you have, seems like more of a general design question, but as I love MSMQ I'll chime in here. MSMQ does have some drawbacks, specifically about load balancing transactional messages, but on whole its pretty awesome. However, none of your requirements mentioned any specific reason to use MSMQ: durability, recoverable messaging, disconnected clients, etc.. so I am assuming you have some of these requirements, but that they are not explicitly called out. Requirement #1 should be easy to meet/beat, especially if these are small messages and there is no apparent logic being performed on them (e.g. just vanilla inserts/updates) and MSMQ handles competing consumers very well. Requirement #2 unless your using transactional messaging with MSMQ, its not impossible to load balance MSMQ to enable scaling, but it has some caveats. How are you load balancing MSMQ? See [How to Load-Balancing MSMQ: A Brief Discussion](http://blogs.msdn.com/johnbreakwell/archive/2009/03/19/load-balancing-msmq-a-brief-discussion.aspx) for some details if you don't already have them. Barring potential snafu's with load-balancing MSMQ, none of which are insurmountable, there is nothing wrong with this approach. **Scaling MSMQ** MSMQ scales very well vertically (same machine) and moderately horizontally (many machines). However, it is difficult to make MSMQ truly highly available, which may or may not be a concern. See the links already in this answer for thoughts on making it highly available. ***Scaling Vertically*** When scaling MSMQ vertically, there are many instances of the queue reader(s) running on a single machine, reading from a single queue. MSMQ handles this very well. All of our queue data is in a temporal store on the local machine. *What happens if we lose the machine hosting the queue?* Clients can send and messages will stack up in the outgoing queue of the client, but we can't receive them until the server comes back up. *What happens to the messages in the queue?* Without the introduction of some sort of highly available backed disk subsystem they are likely gone. Even so, getting another queue 'hooked up' to that data file can be a challenge. In theory, you can get them back. In practice, its likely easier to resend the message from the edge system. Depending on transaction volumes, the queue may be empty the majority of the time so the risk of data loss needs to be weighed with the effort/cost of making it highly available. ***Scaling Horizontally*** When scaling MSMQ horizontally, there is an instance of a queue on each processing machine. Each machine may have [n] readers for that queue running on the machine receiving messages from the queue. All of our queue data is in temporal stores on several machines. You can use any of the methods described in the documentation for load-balancing MSMQ, however, my experience has almost always been with application load balancing, described as software load-balancing: the client has a list of available msmq end points to deliver to. Each server hosting the queue is subject to the same availability problems as the single queue. Also might want to check out [Nine Tips to Enterprise-proof MSMQ](http://www.devx.com/enterprise/Article/22314/0/page/1) for some additional MSMQ related information.
Just listening in on the conversation really, but am i right to think that MSMQ will actually help with the concurrency problem by buffering messages. So the server reading from the queue will never get flooded? That would change the problem on the component that is processing the messgaes from 'event based' concurrency (like on a webserver) to a much simpler pull mechanism. If you're still in a greenfield design stage you might also want to look at CCR & DSS, these could also help with the concurrency. Very impressive stuff, but then again if you only need to store the messages in a DB it's probably not going to help you much.
Hi load server with load balancing, using WCF and MSMQ
[ "", "c#", "wcf", "msmq", "" ]
We use strongly typed DataSets in our application. When importing data we use the convenient `DataSet.Merge()` operation to copy DataRows from one DataSet to another. ``` StringCollection lines = ReadFromFile(fileName); foreach (string line in lines) { DataRow dr = ImportRow(line); dataSet1.Merge( new DataRow[] { dr } ); } DoAdditionalCalculationsWith(dataset1); SaveToDatabase(dataSet1); ``` Unfortunately this doesn't scale. For larger imports the Merge takes up 80% of our total import time (according to our profiler). Is there a faster way to do this? **Edit:** We can't just add the rows because they might already be in the DataSet and doing it in the database is also not an option, because our import logic is quite complex.
You've probably already tried this, but just in case: DataSet.Merge takes an array or DataRows as a parameter. Have you tried batching the merge, i.e. doing the following? ``` dataSet1.Merge(lines.Select(line=>ImportRow(line)).ToArray()); ``` However, it's quite possibly the case that you cannot improve performance - maybe you can avoid the need to Merge in the first place somehow - such as by doing the merge in the DB, as Sklivvz suggests.
The obvious answer is 'do it in the DB' -- I'll assume it's not applicable in your case. You should try to use a row loop. This can be quite performant if the tables you are merging are sorted. <http://en.wikipedia.org/wiki/Merge_algorithm>
Faster (more scalable) DataSet.Merge?
[ "", "c#", "ado.net", "" ]
I'm having trouble deciding whether not this code should compile or if just both compilers I tried have a bug (GCC 4.2 and Sun Studio 12). In general, if you have a static class member you declare in a header file you are required to define it in some source file. However, an exception is made in the standard for static const integrals. For example, this is allowed: ``` #include <iostream> struct A { static const int x = 42; }; ``` With no need to add a definition of x outside the class body somewhere. I'm trying to do the same thing, but I also take the address of x and pass it to a template. This results in a linker error complaining about a lack of definition. The below example doesn't link (missing a definition for A::x) even when it's all in the same source file: ``` #include <iostream> template<const int* y> struct B { static void foo() { std::cout << "y: " << y << std::endl; } }; struct A { static const int x = 42; typedef B<&x> fooness; }; int main() { std::cout << A::x << std::endl; A::fooness::foo(); } ``` Which is bizarre since it works as long as I don't pass the address to a template. Is this a bug or somehow technically standards compliant? Edit: I should point out that &A::x is *not* a runtime value. Memory is set aside for statically allocated variables at compile time.
To be a well formed program you stil have to have the defintion of the static variable (without an initializer in this case) if it actually gets used, and taking the address counts as a use: * C++2003 Standard: 9.4.2 Static data members Paragraph 4 (bold added) > If a static data member is of const > integral or const enumeration type, > its declaration in the class > definition can specify a > constant-initializer which shall be an > integral constant expression (5.19). > In that case, the member can appear in > integral constant expressions. **The > member shall still be defined in a > namespace scope if it is used in the > program and the namespace scope > definition shall not contain an > initializer**
You are trying to pass a runtime value to a template, that's not possible. The only allowed template parameters are types (class/typename) or integral constant values (int/bool/etc).
Is it legal C++ to pass the address of a static const int with no definition to a template?
[ "", "c++", "templates", "static", "standards", "constants", "" ]
Does anyone know what MySQL statement I would use to return results containing a list of all the tables in a database and the number of rows in each one?
try this ``` SELECT Table_name,Table_rows FROM information_schema.tables WHERE TABLE_SCHEMA = 'yourdatabase' ```
show tables - for list of tables show table status - should give you the name, number of rows, and a list of extra info
List of all tables in database, and number of rows in each one?
[ "", "php", "mysql", "database", "" ]
What is ``` Type<Type> type; ``` called (opposed to) ``` Type type; ``` You know, where you put the angle brackets around the type? I use this a lot, but don't know the name - it's bugging me. It's very hard to search for - Google ignores the `<>` characters. (note: this is Java)
Generics! :)
Generics: <http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html>
What is Type<Type> called?
[ "", "java", "generics", "" ]
**How can you convert the following while loop to a for -loop in PHP?** ``` while( $row2 = pg_fetch_row( $result_tags ) ``` While -loops are a source of errors for me. I see the while -loop as follows. ``` for ( $i = 0 ; $i < count(pg_fetch_row( $result_tags )) ; $i++ ) ```
You can't convert that `while` to a `for`. `for` loops are used for incremental loops. `while` loops are used to execute code until a condition is `false`. While most `for` loops can be easily converted to `while` loops (`for` loops are just a syntactical enhancements of `while` loops), the opposite is not always possible. Consider the following loop: ``` while($row = pg_fetch_row($result)) { } ``` This loop will execute until `pg_fetch_row()` returns a [falsy value](http://php.net/empty). > **Note:** The proper syntax for such a loop would be: > > `while(($row = pg_fetch_row($result)) !== FALSE) { }` Unfortunately, the closest you can come to using a `for` loop is the following: ``` for(; $row = pg_fetch_row($result) ;) {} ``` Which will behave exactly the same as the `while` loop anyway. > **Note:** Again, the proper syntax for such a loop would be: > > `for(; ($row = pg_fetch_row($result)) !== FALSE ;) { }` I think you should go back in your code and find exactly the cause of your problem instead of blaming the use of the `while` loop. `pg_fetch_row()` returns an array of columns, so you cannot use `count()` on it. The closest you can come to using a `for` loop would be using `pg_num_rows` as such: ``` for($i = 0; $i < pg_num_rows($result); $i++) { $row = pg_fetch_row($result); } ``` But personally I find that unnecessarily verbose and open to more problems.
Going in the other direction, a for loop: ``` for (init; test; incr) {body;} ``` is equivalent to: ``` init; while (test) { body; incr; } ``` That is, a for loop is a special kind of while loop. Personally, I don't see how converting the while loop you give to a for loop will reduce errors.
To convert PHP's while loop to a for -loop
[ "", "php", "for-loop", "while-loop", "" ]
We know that C++ doesn't allow templated virtual function in a class. Anyone understands why such restriction?
Short answer: Virtual functions are about not knowing who called whom until at run-time, when a function is picked from an already compiled set of candidate functions. Function templates, OTOH, are about creating an arbitrary number of different functions (using types which might not even have been known when the callee was written) at compile-time from the callers' sides. That just doesn't match. Somewhat longer answer: Virtual functions are implemented using an additional indirection (the Programmer's General All-Purpose Cure), usually implemented as a table of function pointers (the so-called virtual function table, often abbreviated "vtable"). If you're calling a virtual function, the run-time system will pick the right function from the table. If there were virtual function templates, the run-time system would have to find the address of an already compiled template instance with the exact template parameters. Since the class' designer cannot provide an arbitrary number of function template instances created from an unlimited set of possible arguments, this cannot work.
How would you construct the vtable? Theoretically you could have an infinite number of versions of your templated member and the compiler wouldn't know what they might be when it creates the vtable.
Templatized Virtual function
[ "", "c++", "" ]
I create a listview and the number of columns are determined at runtime. I have been reading texts on the web all over about listview( and I still am) but I wish to know how to add items to a specific column in listview I thought something like: ``` m_listview.Items.Add("1850").SubItems.Add("yes"); ``` would work assuming the **"1850"** which is the text of the column would be the target column.
ListViewItems aren't aware of your ListView columns. In order to directly reference the column, you first need to add all the columns to the ListViewItem. So... lets say your ListView has three columns A, B and C; This next bit of code will only add data to column A: ``` ListViewItem item = new ListViewItem(); item.Text = "Column A"; m_listView.Items.Add(item); ``` To get it to add text to column C as well, we first need to tell it it has a column B... ``` ListViewItem item = new ListViewItem(); item.Text = "Column A"; item.SubItems.Add(""); item.SubItems.Add("Column C"); m_listView.Items.Add(item); ``` So now we'll have columns A, B and C in the ListViewItem, and text appearing in the A and C columns, but not the B. Finally... now that we HAVE told it it has three columns, we can do whatever we like to those specific columns... ``` ListViewItem item = new ListViewItem(); item.Text = "Column A"; item.SubItems.Add(""); item.SubItems.Add("Column C"); m_listView.Items.Add(item); m_listView.Items[0].SubItems[2].Text = "change text of column C"; m_listView.Items[0].SubItems[1].Text = "change text of column B"; m_listView.Items[0].SubItems[0].Text = "change text of column A"; ``` hope that helps!
I'm usially inherit ListViewItem as : ``` public class MyOwnListViewItem : ListViewItem { private UserData userData; public MyOwnListViewItem(UserData userData) { this.userData = userData; Update(); } public void Update() { this.SubItems.Clear(); this.Text = userData.Name; //for first detailed column this.SubItems.Add(new ListViewSubItem(this, userData.Surname)); //for second can be more } } ``` where ``` public class UserData { public string Name; public string Surname; } ``` using ``` listView1.Items.Add(new MyOwnListViewItem(new UserData(){Name="Name", Surname = "Surname"})); ```
How do I add to a specific column in Listview item?
[ "", "c#", ".net", "winforms", "listview", "user-interface", "" ]
How can i list the contents of a windows share using PHP? ``` $SearchFolder = "\\\\192.168.1.100\\pdfoutput\\"; if (is_dir($SearchFolder)) { if ($Directory = opendir($SearchFolder)) { while (($File = readdir($Directory)) !== false) { if(filetype($SearchFolder.$File) == "file") { $this->Attachments[] = new Attachment($SearchFolder.$File); } } closedir($Directory); } } ``` Print(opendir($SearchFolder)); gives this error: > Warning: > opendir(\192.168.1.100\pdfoutput) > [function.opendir]: failed to open > dir: No error in > C:\Users\gary\Webserver\QuickMail\maildetails.php > on line 227 This is not working as expected. Any thoughts?
I've found a good alternative to using local network paths and that is using an FTP server. This works great also considering i needed to display some images from this directory as well. The FTP server i've used is very light and allows access to this directory from the entire LAN without any security or permissions errors. ``` $SearchFolder = "ftp://192.168.0.104/PDFOutput/"; if (is_dir($SearchFolder)) { if ($Directory = opendir($SearchFolder)) { while (($File = readdir($Directory)) !== false) { if(filetype($SearchFolder.$File) == "file") { $this->Attachments[] = new Attachment($SearchFolder.$File); } } closedir($Directory); } } ```
Take a look at the user comments for the opendir function at <https://www.php.net/function.opendir> . It looks like there may be some information that will help you. Specifically, this bit of code by DaveRandom may solve your problem: ``` <?php // Define the parameters for the shell command $location = "\\servername\sharename"; $user = "USERNAME"; $pass = "PASSWORD"; $letter = "Z"; // Map the drive system("net use ".$letter.": \"".$location."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1"); // Open the directory $dir = opendir($letter.":/an/example/path") ?> ```
How to walk a directory over a local network using PHP?
[ "", "php", "directory-walk", "" ]
I have a set of web service methods returning a ActionResult class holding the following properties: ``` object returnValue bool success string message ``` the returnValue is used to hold different types of return values depending on the web methods used. The problem I have on the client is that if a web method is returning an internal class in the returnValue I can't cast it due to the client don't recognize the type. I can fejk methods to be able to expose the class "Issue" I need. Ex: ``` Issue ExposeIssueType() { return null; } ``` But isn't there any other way?
While I'm waiting for your answer to my comment, I'll tell you that this is a very bad web service design. Each web service operation should return the data it is meant to return. There is no point in creating a class that can hold all possible return values. Additionally, you should not be using a string message to return errors from a web service. The SOAP protocol has a "SOAP Fault" mechanism for that purpose. Since you're using WCF, you have complete support for SOAP Faults. Example: In the service contract: ``` [FaultContract(typeof(GeneralFault))] [OperationContract] int Divide(int a, int b); ``` In the service: ``` public int Divide(int a, int b) { if (b == 0) { throw new FaultException<GeneralFault>( new GeneralFault {Message = "Attempt to divide by zero"}); } return a / b; // Note - operation can focus on its job } ``` Data contract for the data returned in the fault: ``` [DataContract] public class GeneralFault { [DataMember] public string Message {get;set;} } ```
Create your type in a shared DLL (mark it as Serializable), reference both sides of the wire.
How to return an Object with an Object Property from a WCF Service?
[ "", "c#", "wcf", "web-services", "" ]
I notice that a snapshot of the Java 7 API [has been up](http://java.sun.com/javase/7/docs/api/) on java.sun.com for some time, but I only just had a look through it just now, looking specifically for the promised JodaTime-inspired Date/Time API. Alas, I can find no mention of it in the published docs. Is this because it simply hasn't been done yet, and this published API is an early, incomplete snapshot, or because the idea has been quietly dropped?
[Alex Miller is running a very informative website about jdk7 features](http://tech.puredanger.com/java7). [JSR 310](http://jcp.org/en/jsr/detail?id=310) is **still not confirmed** [according to this page](http://tech.puredanger.com/java7#jsr310).
Last I heard, JSR 310 was [running behind](https://jsr-310.dev.java.net/servlets/ReadMsg?list=dev&msgNo=1389) and might not get into Java 7. And yes, that's a huge shame - although at least we've got Joda Time as a stopgap until then.
Java 7 Date/Time API
[ "", "java", "datetime", "java-7", "" ]
i received a small problem to resolve in my free time regarding changing an objects behavior and also the class behavior at runtime in C++. I read a little bit and found this link, really useful for me. <http://www.vollmann.ch/en/pubs/meta/meta/meta.html> Mr. Volmann made a Meta object protocol(MOP) for defining classes at runtime, more exactly their properties. I tried to add methods in the same matter, at runtime, with dynamically loading dlls but the objects weren't aware about their new added behaviors. i saved the details about the methods in the dlls in xml files, and when i wanted to add a new behavior to a class/object i parsed the xml files and loaded only the DLL i needed, but this wasn't flexible enough.. this is just a study case, so if you have any guidance to give please do. I don't have much experience in C++ but i liked the challenge. Thank you in advance.
You could try to create some kind of base class for all of your classes. This class has some kind of add method for function pointers. Each fp is assigned some kind of handle or string. Later you can then call the added function via some kind of generic call method. for the arguments of the function - you'll need some way to pass this to the function for referencing the data of the class. Perhaps you'll encapsule the data in some kind of struct and pass a reference/pointer to the struct. For other arguments, you could use some list of pointers or take a look at bind. Be aware - this is a major undertaking as C++ is not created with these kind of things in mind.
Tobias L's method above is the only solution I see as possible, the real difficulty comes (as TL says) in passing and binding the arguments to the new methods - it seems to me that most of the very technical code might be helped a long a lot by by using standard boost library functionality. Specifically boost::bind and function/functional stuff seems to provide a lot of what you might need to make 'methods' following the framework of Mr Volmann's 'attributes'.
Metaclasses and Reflection in C++
[ "", "c++", "reflection", "" ]
Okay i know that it's important for your website to work fine with javascript disabled. In my opinion one way to start thinking about how to design such websites is to detect javascript at the homepage and if it's not enabled redirect to another version of website that does not javascript code and works with pure html (like gmail) Another method that i have in mind is that for example think of a X (close button) on a dialog box on a webpage. What if pressing the X without any javascript interference lead to sending a request to the server and in the server side we hide that dialog next time we are rendering the page, And also we bind a javascript function to onclick of the link and in case of the javascript enabled it will hide the dialog instantly. What do you think of this? How would you design a website to support both?
One way to deal with this is to : * First, create the site, without any javascript * Then, when every works, add javascript enhancements where suitable This way, if JS is disabled, the "first" version of the site still works. You can do exactly the same with CSS, naturally -- there is even one "[CSS Naked Day](http://naked.dustindiaz.com/)" each day, showing what websites look like without CSS ^^ One example ? * You have a standard HTML form, that POSTs data to your server when submitted, and the re-creation of the page by the server displays a message like "thanks for subscriving" * You then add some JS + Ajax stuff : instead of reloading the whole page while submitting the form, you do an Ajax request, that only send the data ; and, in return, it displays "thanks for subscribing" without reloading the page In this case, if javascript is disabled, the first "standard" way of doing things still works. This is (part of) what is called [Progressive enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement)
The usual method is what's called [progressive enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement). Basically you take a simple HTML website, with regular forms. The next enhancement is CSS - you make it look good. Then you can enhance it further with Javascript - you can add or remove elements, add effects and so on. The basic HTML is always there for old browsers (or those with script blockers, for example). For example a form to post a comment might look like this: ``` <form action="post-comment.php" method="post" id="myForm"> <input type="text" name="comment"> </form> ``` Then you can enhance it with javascript to make it AJAXy ``` $('#myForm').submit(...); ``` Ideally the AJAX callback should use the same code as post-comment.php - either by calling the same file or via `include`, then you don't have to duplicate code.
Designing a website for both javascript script support and not support
[ "", "javascript", "jquery", "html", "progressive-enhancement", "graceful-degradation", "" ]
I would like to do something like this: <http://javascript.about.com/library/blcmarquee1.htm> The script I referenced however seems to be a bit laggy (outdated?), so I was wondering if anyone knew of a better solution. (jQuery solutions welcome.)
Just found this — jQuery-driven, and has images. I’m intending to use it for a current project. <http://logicbox.net/jquery/simplyscroll/> UPDATE: I have now used this in production code. The plugin is capable of looping 70+ 150×65px images pretty smoothly - which a number of another plugin I tried similar to this were failing on. NOTE it reeked havoc with `z-index` issues in IE 6 / 7 and was not showing up etc. - But this might also have been partly due to my CSS. To anyone having trouble with it not showing up at all in IE check out the standard IE `z-index` fixes: <http://www.google.com/search?q=ie+z+index+issues> LATEST UPDATE: Addition things to consider when implementing plug-ins like these: * The number of items and type of content to scroll. I found a number that would start to glitch as soon as you had more than say 15 images to scroll. * I found a number of these plugins that were tied to old versions of jquery * If scrolling images ARE THEY ALL THE SAME SIZE again a number of the plug-ins I experimented with only worked if all the images were the same size but did not make this clear in the tutorials. I believe then the plugins run then set a string of li tags that are all x wide then calculate the total distance of them all chained together to manage the scrolling. * Effects - some would continuously scroll others would move one image pause for a second then move another image I have now also found these two scroller plugins to be very good as well. <http://caroufredsel.frebsite.nl/> <http://sorgalla.com/jcarousel/>
[The Silky-Smooth jQuery Marquee](http://remysharp.com/2008/09/10/the-silky-smooth-marquee/) and [Giva Labs' Marquee](http://www.givainc.com/labs/marquee_example.htm)
Continuously scrolling horizontal ticker containing images in jQuery?
[ "", "javascript", "jquery", "marquee", "scroller", "ticker", "" ]
For C, we use `char[]` to represent strings. For C++, I see examples using both `std::string` and `char` arrays. ``` #include <iostream> #include <string> using namespace std; int main () { string name; cout << "What's your name? "; getline(cin, name); cout << "Hello " << name << ".\n"; return 0; } ``` ``` #include <iostream> using namespace std; int main () { char name[256]; cout << "What's your name? "; cin.getline(name, 256); cout << "Hello " << name << ".\n"; return 0; } ``` (Both examples adapted from <http://www.cplusplus.com>.) What is the difference between these two types in C++? (In terms of performance, API integration, pros/cons, ...)
A char array is just that - an array of characters: * If allocated on the stack (like in your example), it will always occupy eg. 256 bytes no matter how long the text it contains is * If allocated on the heap (using malloc() or new char[]) you're responsible for releasing the memory afterwards and you will always have the overhead of a heap allocation. * If you copy a text of more than 256 chars into the array, it might crash, produce ugly assertion messages or cause unexplainable (mis-)behavior somewhere else in your program. * To determine the text's length, the array has to be scanned, character by character, for a \0 character. A string is a class that contains a char array, but automatically manages it for you. Most string implementations have a built-in array of 16 characters (so short strings don't fragment the heap) and use the heap for longer strings. You can access a string's char array like this: ``` std::string myString = "Hello World"; const char *myStringChars = myString.c_str(); ``` C++ strings can contain embedded \0 characters, know their length without counting, are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they're more readable and easier to use. --- However, C++ strings are not (very) suitable for usage across DLL boundaries, because this would require any user of such a DLL function to make sure he's using the exact same compiler and C++ runtime implementation, lest he risk his string class behaving differently. Normally, a string class would also release its heap memory on the calling heap, so it will only be able to free memory again if you're using a shared (.dll or .so) version of the runtime. In short: use C++ strings in all your internal functions and methods. If you ever write a .dll or .so, use C strings in your public (dll/so-exposed) functions.
Arkaitz is correct that `string` is a managed type. What this means for *you* is that you never have to worry about how long the string is, nor do you have to worry about freeing or reallocating the memory of the string. On the other hand, the `char[]` notation in the case above has restricted the character buffer to exactly 256 characters. If you tried to write more than 256 characters into that buffer, at best you will overwrite other memory that your program "owns". At worst, you will try to overwrite memory that you do not own, and your OS will kill your program on the spot. Bottom line? Strings are a lot more programmer friendly, char[]s are a lot more efficient for the computer.
Difference between string and char[] types in C++
[ "", "c++", "string", "types", "" ]
I put a **Yes/No/Cancel Messagebox** in **FormClosing** Method of my form. and now this is Message box text: *Do You Want to Save Data?* I am not a profesional and not know how to handle if user clicked **Cancel** Button? Exactly the result of clicking on Cancel Button must be The form remain open. How to prevent Closing my form in **FormClosing** method? I wrote So far: ;) ``` DialogResult dr = MessageBoxFarsi.Show("Do You Want to Save Data?","",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning); //... else if (dr == DialogResult.Cancel) { ??? } ``` Please Help me to complete my code! Thanks
FormClosing has a Boolean parameter which, if set to True when the function returns, will cancel closing the form, IIRC. EDIT: For example, ``` private void Form1_FormClosing(Object sender, FormClosingEventArgs e) { // Set e.Cancel to Boolean true to cancel closing the form } ``` [See here](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx).
Actually I think you are missing Event handler, oh you can not turn to that even without an even handler. You must add an event with an event handler like this. ``` private void myform_Closing(object sender, FormClosingEventArgs e) { DialogResult dr = MessageBoxFarsi.Show("Do You Want to Save Data?","",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning) if (dr == DialogResult.Cancel) { e.Cancel = true; return; } else if (dr == DialogResult.Yes) { //TODO: Save } } //now add a default constructor public myform() // here use your form name. { this.FormClosing += new FormClosingEventHandler(myform_Closing); } ``` Forgive me if there are some wrongs spellings in this code because i didn't write it in c# and copy paste here. I just wrote it in here. :)
Handling Cancel Button in Yes/No/Cancel Messagebox in FormClosing Method
[ "", "c#", ".net", "messagebox", "" ]
I am running a regex in a java function to parse a document and return true if it has found the string specified by the regex and return false if it hasn't. But the problem is that when the document doesn't contain the string specified by the regex It takes a very long time to return false and I want to terminate that function if it takes more than 6 seconds to execute. How can I set a time limit of 6 seconds on that function so as to forcibly terminate that if it takes more than 6 seconds. I am calling a method "method 1" of class 2 from class 1. The "method 1" calls "method 2" of the same class i.e. "class 2". Method 2 runs the regex code over a document. If it finds the string specified by the regex, then it returns the result to the method 1 which in turn return the result to the method in "class 1" which called the "method 1" of class 2. Now the problem is that the execution time of both the method1 and method2 of class 2 should be not more than 6 seconds. So, I made a new RegexpThread class in the same file, in which my class2 was. Then I move the method2 of the class2 into class RegexpThread. Then whenever the method 1 is called, it instantiates the RegexpThread class as follows: ``` RegexpThread rt = new RegexpThread() { public void run() { method 2(m, urlCopy, document); } }; rt.start(); try { rt.join(6 * 1000); } catch (InterruptedException e) { return "y"; } if(rt.getResultXml().equals("")) { return "g"; } resultXml.append(rt.getResultXml()); return resultXml.toString(); ``` The code shown is in the method 1 of class2. The method 2 in the RegexpThread class perform some regex search over a document. There is a private field named "resultXml" in the RegexpThread class. If the method 2 has found the string specified by the regex then it assigns the result to the private field "resultXml". If not then the "resultXml" contains its default value i.e empty string. So, in the above "if block", it is checking the "resultXml" field against empty string. If it is an empty string then that means the regex has not found its string in the document. But if it is not an empty string then that means the regex has found the string in the document and has assigned the result to the "resultXml" field. so, look at this and tell me what to do...
What you've done kind of looks fine to me here's how I'd modify it: ``` final AtomicReference<String> resultXml = new AtomicReference<String>(); RegexpThread rt = new RegexpThread() { public void run() { method2(m, urlCopy, document, resultXml); } }; rt.start(); try { rt.join(6 * 1000); } catch (InterruptedException e) { return "y"; } if(resultXml.get() == null) { rt.interupt(); return "g"; } resultXml.append(resultXml.get()); return resultXml.toString(); ```
I might be mistaken here, but I think all ways to terminate a thread [have been deprecated for some time](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html). The recommended way is to use a shared `isRunning` variable that your worker thread periodically checks and gracefully exits when it's been set. This will not work in your case, but it looks to me like you're treating the symptom - not the real problem. You should post the code of your regexp function, that takes 6 seconds to execute. If it's the regexp itself, the execution time may be a case of [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html).
How to set a time limit on a java function running a regex
[ "", "java", "multithreading", "" ]
There is a possiblity that this may be a dupicate question. I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
If you use ``` if (x == null) ``` you will *not* get a `NullPointerException`. I suspect you're doing: ``` if (x.y == null) ``` which is throwing because `x` is null, not because `x.y` is null. If that doesn't explain it, please post the code you're using to test for nullity.
I guess you are doing something like this, ``` String s = null; if (s.equals(null)) ``` You either check for null like this ``` if (s == null) ``` A better approach is to ignore the null and just check for the expected value like this, ``` if ("Expected value".equals(s)) ``` In this case, the result is always false when s is null.
Nullpointer exception
[ "", "java", "nullpointerexception", "" ]
Here are my two questions: 1. I am now learning to manage my code with CVS, and I just want to make a repository for my C++ files, Makefile and bash and python scripts only, not the object files and executables. So I made several subdirectories under my project directory: src, bin, scripts, results and data. I put C++ files and Makefile under ~/myproject/src, Bash and Python scripts under ~/myproject/scripts and object and executables under ~/myproject/bin. I am hoping only the files under src and scripts will be updated via CVS. I wonder how you organize your projects? Just hope to follow some good habits. 2. Since I put my C++ files and Makefile into ~/myproject/src and object and executable files into ~/myproject/bin, I have to specify the directories in Makefile. Here is what I am doing Makefile: ``` ... BIN_DIR=/home/myproject/bin/ all: $(BIN_DIR)myexecutable TAGS TAGS: *.cc *.h etags --members --declarations -l c++ *.cc *.h $(BIN_DIR)myexecutable: $(BIN_DIR)myobject.o $(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS) Makefile.depend: *.h *.cc Makefile $(CXX) -M $(CXXFLAGS) *.cc > Makefile.depend clean: \rm -f $(BIN_DIR)myexecutable $(BIN_DIR)*.o Makefile.depend TAGS` ``` However this will give error > make: \*\*\* No rule to make target `/home/myproject/bin/myobject.o', needed by` /home/myproject/bin/myexecutable'. How to specify a different directory for object and executable files from C++ files in Makefile?
1. You can keep your files in different directories if you like, but that isn't necessary. Add a file or directory to the CVS repository once, and CVS will retain it indefinitely. From then on you can update it, check it in, whatever. If you don't add an object file to the repository, CVS won't touch it. If you want to add a whole directory tree, and you're in the habit of keeping objects there, just make clean before you do it. 2. Make is a wonderful tool, but it has some glaring faults. What you're describing is one of the classic problems: Make is good at using a source *there* to make something *here*, but not the other way around. Here are a couple of ways to do what you're trying to do. A) Run make in your binary directory: ``` ... all: myexecutable TAGS myexecutable: myobject.o $(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS) VPATH = /home/myproject/src ... ``` cd ~/myproject/bin make -f ../src/makefile B) Put the objects on the bin directory by brute force: ``` $(BIN_DIR)%.o: %.cc $(CXX) $(CXXFLAGS) -c -o $@ $^ ``` This will give you a problem with Makefile.depend, which you can approach several ways. C) Learn some more advanced Make techniques. You probably shouldn't try this yet.
If you want to learn make, the [GNU make manual](http://www.gnu.org/software/make/manual/make.html) is very good, both as a reference and a tutorial. You might want to consider using the **patsubst** command. The following is a chopped down version of one of my own makefiles that uses it: ``` OUT = bin/csvfix.exe CC = g++ IDIR = inc ODIR = obj SDIR = src INC = -Iinc -I../alib/inc LIBS = ../alib/lib/alib.a -lodbc32 _OBJS = csved_atable.o \ csved_case.o \ csved_cli.o \ csved_command.o \ csved_date.o \ OBJS = $(patsubst %,$(ODIR)/%,$(_OBJS)) $(ODIR)/%.o: $(SDIR)/%.cpp $(CC) -c $(INC) -o $@ $< $(CFLAGS) $(OUT): $(OBJS) $(CC) -o $@ $^ $(CFLAGS) $(LIBS) strip $(OUT) clean: rm -f $(ODIR)/*.o $(OUT) ```
organize project and specify directory for object files in Makefile
[ "", "c++", "project-management", "makefile", "cvs", "" ]
I know [Wt](http://www.webtoolkit.eu/) is the most stable of them, but it's a bit uncomfortable to use. [CppCMS](http://art-blog.no-ip.info/cppcms/blog) sounds good but how stable is it? How secure is it? I have encountered [C++ Server Pages](http://www.tntnet.org/index.html) as well but there's nothing about their security in there. Has anyone had some experience with any of those libraries and can enlight me?
First of all, several differences: 1. Wt is GUI like framework, it is quite far from traditional web development. So, if you want to develop a code as if it was GUI it is for you. 2. CppCMS is traditional MVC framework optimized for performance, it has many features like template engines, forms processing, i18n support, sessions, efficient caching and so on, support of various web server APIs: FastCGI, SCGI and CGI. If you come for Django world, you would find yourself at home. 3. I'm less familiar with the third project, but it feels more like PHP -- you put the C++ code inside templates and has no clear separation of View and Controller. Stability, I can tell only about CppCMS, it is stable, and there are applications running it 7/24, the authors blog and the Wiki with documentation of CppCMS are written in CppCMS. So, there shouldn't be major critical bugs. *Disclosure:* I'm developer of CppCMS.
I am the developper of [libapache2-mod-raii](http://blackmilk.fr/www/cms/dev/libapache2_mod_raii_en) and I am very disappointed we did not recommend this library for production work... Cause I do ! :) I also like to point out that the project page is also available in English. On the other hand, I do not agree with Steve about the fact that servlets are not compiled on the fly, as they are ! Otherwise, on the lacks of prefork support is not my point of view, although I was looking on the issue.
CppCMS vs. C++ Server Pages vs. Wt
[ "", "c++", "cgi", "wt", "" ]
I'm messing around with game loops and going to create some games as practice. Currently I have a steady game loop up where the game is updated as fast as possible and the rendering is updated x times a second (25 currently) The rendinging method is basically a draw + Console.Clear() and at very high updates the display becomes very jittery since it's not finished drawing when Console.Clear() hits. Is there a better way of doing something like this? Can I write whatever data to the console and then replace it with some other data?
Assuming you Write a full screen from topleft again in every loop you could simply replace the Clear() with: ``` Console.SetCursorPosition(0, 0); ``` And overwrite the previous screen.
Since you're in C# anyway, you might want to look into the [XNA Framework](http://msdn.microsoft.com/en-us/xna/default.aspx). I'm guessing your problem arises from `Console.Clear()` not being optimized for this kind of use, as XNA uses a similar method (`Clear()` is called on a `GraphicsDevice`). If you don't want to try using XNA, then it may possibly be faster to draw a rectangle (solid black or gray or whatever) rather than call `Clear()` to 'blank' out the screen and then draw over it.
Is there a better way to make console games than with Console.Clear()?
[ "", "c#", "console", "game-loop", "" ]
I'm trying to apply a class to a link only if the current page equals that link. I find the current page with: ``` var pathname = window.location.pathname.split("/")[window.location.pathname.split("/").length - 1]; ``` This grabs the url of the page and saves whatever is after the last /, which in the case of my page is 'index.html'. Now, I'm using links (anchor tags with display: block) that have a background color change when you mouse over them. My goal is to have those links already colored, as if they were hovered, when you visit the page that the link links to. So I used: ``` if (pathname == $(".linkclass").attr("href")){ $(this).addClass("linkHover"); } ``` Now obviously the "this" modifier doesn't work, but how do I tell it to apply this class to only whichever instance of linkClass passes the if statement? (And not EVERY instance of .linkclass, of which there are multiple). Thanks!
I figured it out, but I'll answer it in case someone comes across a similar issue. Instead of the if statement, I figured jquery could handle the comparison using it's own selection engine. At first I looked for .equals or something, but I figured it out with: ``` var pathname = window.location.pathname.split("/")[window.location.pathname.split("/").length - 1]; $(".linkClass[href='" +pathname+ "']").addClass("linkHover"); ``` You can use variables in jquery selectors, and select against attributes, so this works perfectly.
Maybe try something like this: ``` $("#a.linkClass").each( function() { if (pathname == $(".linkclass").attr("href")) { $(this).addClass("linkHover"); } } ); ``` Or similar. The idea is selecting all the menu link anchors, then cycle through them and perform your test using the `each()` function.
JQuery - Parsing through classes then using an if statement to modify just one
[ "", "javascript", "jquery", "css", "arrays", "" ]
Through trying to explain the [Monty Hall problem](http://en.wikipedia.org/wiki/Monty_Hall_problem) to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this: ``` import random as r #iterations = int(raw_input("How many iterations? >> ")) iterations = 100000 doors = ["goat", "goat", "car"] wins = 0.0 losses = 0.0 for i in range(iterations): n = r.randrange(0,3) choice = doors[n] if n == 0: #print "You chose door 1." #print "Monty opens door 2. There is a goat behind this door." #print "You swapped to door 3." wins += 1 #print "You won a " + doors[2] + "\n" elif n == 1: #print "You chose door 2." #print "Monty opens door 1. There is a goat behind this door." #print "You swapped to door 3." wins += 1 #print "You won a " + doors[2] + "\n" elif n == 2: #print "You chose door 3." #print "Monty opens door 2. There is a goat behind this door." #print "You swapped to door 1." losses += 1 #print "You won a " + doors[0] + "\n" else: print "You screwed up" percentage = (wins/iterations) * 100 print "Wins: " + str(wins) print "Losses: " + str(losses) print "You won " + str(percentage) + "% of the time" ``` My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough? The problem I have with it is that the all choices are kind of hard coded in. **Is this a good or bad 'simulation' for the Monty Hall problem? How come?** **Can you come up with a better version?**
Your solution is fine, but if you want a stricter simulation of the problem as posed (and somewhat higher-quality Python;-), try: ``` import random iterations = 100000 doors = ["goat"] * 2 + ["car"] change_wins = 0 change_loses = 0 for i in xrange(iterations): random.shuffle(doors) # you pick door n: n = random.randrange(3) # monty picks door k, k!=n and doors[k]!="car" sequence = range(3) random.shuffle(sequence) for k in sequence: if k == n or doors[k] == "car": continue # now if you change, you lose iff doors[n]=="car" if doors[n] == "car": change_loses += 1 else: change_wins += 1 print "Changing has %s wins and %s losses" % (change_wins, change_loses) perc = (100.0 * change_wins) / (change_wins + change_loses) print "IOW, by changing you win %.1f%% of the time" % perc ``` a typical output is: ``` Changing has 66721 wins and 33279 losses IOW, by changing you win 66.7% of the time ```
You mentioned that all the choices are hardcoded in. But if you look closer, you'll notice that what you think are 'choices' are actually not choices at all. Monty's decision is without loss of generality since he always chooses the door with the goat behind it. Your swapping is always determined by what Monty chooses, and since Monty's "choice" was actually not a choice, neither is yours. Your simulation gives the correct results..
Is this a good or bad 'simulation' for Monty Hall? How come?
[ "", "python", "language-agnostic", "probability", "" ]
When and Why does some one decide that they need to create a View in their database? Why not just run a normal stored procedure or select?
A view provides several benefits. **1. Views can hide complexity** If you have a query that requires joining several tables, or has complex logic or calculations, you can code all that logic into a view, then select from the view just like you would a table. **2. Views can be used as a security mechanism** A view can select certain columns and/or rows from a table (or tables), and permissions set on the view instead of the underlying tables. This allows surfacing only the data that a user needs to see. **3. Views can simplify supporting legacy code** If you need to refactor a table that would break a lot of code, you can replace the table with a view of the same name. The view provides the exact same schema as the original table, while the actual schema has changed. This keeps the legacy code that references the table from breaking, allowing you to change the legacy code at your leisure. These are just some of the many examples of how views can be useful.
Among other things, it can be used for security. If you have a "customer" table, you might want to give all of your sales people access to the name, address, zipcode, etc. fields, but not credit\_card\_number. You can create a view that only includes the columns they need access to and then grant them access on the view.
Why do you create a View in a database?
[ "", "sql", "sql-server", "database", "t-sql", "" ]