Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I play back sound with Java's SourceDataLine but whenever I try to adjust the volume (gain), there is a 0.2-0.5 second delay between the action and the response in the speaker. The audio data is written in 4k-16k chunks (16bit mono, 22kHz ~ 44k/s). How can I make this volume adjustment more real-time? Does the `write(byte[], int, int)` lock out the gain adjustment of the FloatControl? Do I need to revert back to a DSP way of concurrent adjustment of the sound buffer data volume or submit smaller chunks? JDK7, Decent Windows PC
Sound system takes the data from SourceDataLine in chunks of a few (hundred...) kilobytes and buffers them. If you change params for it, it won't take effect until system playback buffer is empty and new data is read from SDL. What you need to do is to hack somewhere around changing system playback volume (which has immediate effect) rather than modyfing data you provide to it.
Have you tried using a custom (lower) buffer size when calling SourceDataLine.open()? ``` SourceDataLine.open( AudioFormat format, int bufferSize ) ``` That should decrease latency. The master playback volume solution is still probably going to be faster though.
Real-time java sound volume adjustment
[ "", "java", "audio", "" ]
There seems to be a conflict with the windows headers between the mysql c-api and boost::asio. If I include mysql first I get: > boost/asio/detail/socket\_types.hpp(27) : fatal error C1189: #error : WinSock.h has already been included ``` #if defined(BOOST_WINDOWS) || defined(__CYGWIN__) # if defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_) # error WinSock.h has already been included # endif // defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_) ``` If I include boost::asio first I get: > include\config-win.h(24) : warning C4005: '\_WIN32\_WINNT' : macro redefinition ``` /* Defines for Win32 to make it compatible for MySQL */ #ifdef __WIN2000__ /* We have to do this define before including windows.h to get the AWE API functions */ #define _WIN32_WINNT 0x0500 #else /* Get NT 4.0 functions */ #define _WIN32_WINNT 0x0400 #endif ``` Is there some way around this, and why is mysql trying to force the windows version and boost trying to enforce that it include winsock its self anyway?
The macro redefinition is only a warning. Your code should still compile and link. I think your code will even work without any problem.
Try `#include "winsock2.h"` before including mysql and boost::asio
C++ mysql and boost asio header conflict
[ "", "c++", "mysql", "boost-asio", "" ]
In HTML forms, if you press 'enter' while in a text field the form will generally submit. I'm implementing a search panel in Java Swing, and I want to include the same functionality as I think users will be expecting this. I know that it's possible to use setAction on a JTextField to accomplish this, however I was wondering if there was an easier / better way than setting the action on every field. I've tried looking around but there doesn't seem to be a standard solution to this problem that I can find! **Edit**: There is getRootPane().setDefaultButton(...), but that only seems to set the default button for a frame. That wouldn't work for me as I'm using a tabbed pane, each panel of which has a form on it!
IIRC, adding an ActionListener to the JTextField will provide the functionality you want *quick google later...* Yep - and this appears to be the recommended way by Sun, as shown in the [text field trail...](http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html)
You may have to listen for the tab switch and reset the default button for the current tab using `getRootPane().setDefaultButton(...)`.
Java default form action or button
[ "", "java", "user-interface", "swing", "default", "action", "" ]
I have created a website in ASP.NET and have created a class and put it inside of the App\_Code folder. However I cannot access this from my other pages. Does something need to be configured to allow this? I have made it work in previous projects, but not in this one, somehow. ``` namespace CLIck10.App_Code { public static class Glob { ... } } ```
Right click on the `.cs` file in the `App_Code` folder and check its properties. Make sure the "Build Action" is set to "Compile".
Put this at the top of the other files where you want to access the class: ``` using CLIck10.App_Code; ``` OR access the class from other files like this: ``` CLIck10.App_Code.Glob ``` Not sure if that's your issue or not but if you were new to C# then this is an easy one to get tripped up on. Update: I recently found that if I add an App\_Code folder to a project, then I must close/reopen Visual Studio for it to properly recognize this "special" folder.
Classes residing in App_Code is not accessible
[ "", "c#", "asp.net", "" ]
I would like to have all variables accessible of the file *handler\_login.php* which I `include` in the file *handler\_question.php*. The *handler\_question.php* processes the data from the following form. **My form\_question.php** ``` <form method="post" action="handler-question.php"> <p>Title: <input name="question_title" type="text" cols="92" /> </p> <p>Question: <div id="wmd-container" class="resizable-textarea"> <textarea id="input" class="textarea" tabindex="101" rows="15" cols="92" name="question_body" /></textarea> </div> </p> <p>Tags: <input name="tags" type="text" cols="92" /> </p> <input type="submit" value="OK" /> </form> ``` The following file is what the last file includes **My handler\_login.php** ``` <?php // independent variables $dbHost = "localhost"; $dbPort = 5432; $dbName = "masi"; $dbUser = "masi"; $dbPassword = "123456"; $conn = "host=$dbHost port=$dbPort dbname=$dbName user=$dbUser password=$dbPassword"; // you can store the username and password to $_SESSION variable $dbconn = pg_connect($conn); if(!$dbconn) { exit; } $sql = "SELECT username, passhash_md5, email FROM users WHERE username = '{$_POST['username']}' AND email = '{$_POST['email']}' AND passhash_md5 = '{$_POST['password']}';"; $result = pg_query($dbconn, $sql); if(!$result) { exit; } $username = $_POST['username']; $passhash_md5 = md5($_POST['password']); // COOKIE setting /*{{{*/ /* $cookie may look like this: variables $username = "username" $passhash_md5 = "password-in-md5" before md5: "usernamepasshash_md5" after md5: "a08d367f31feb0eb6fb51123b4cd3cb7" */ $login_cookie = md5( $username . $passhash_md5 ); $sql3 = "SELECT passhash_md5 FROM users WHERE username=$_POST['username'];"; $password_data_original = pg_query($dbconn, $sql3); while ($row = pg_fetch_row($data)) { $password_original = $row[0]; } $login_cookie_original = md5( $username . $password_original ); // Check for the Cookie if (isset($_COOKIE['login']) ) { // Check if the Login Form is the same as the cookie if ( $login_cookie_original == $login_cookie ) { header("Location: index.php"); die("logged in"); } header("Location: index.php"); die("wrong username/password"); } // If no cookie, try logging them in else { //Get the Data // we do not want SQL injection so we use pg_escape_string $sql2 = sprintf("SELECT * from users WHERE passhash_md5='%s', pg_escape_string($login_cookie)); $raw_user_list = pg_query($dbconn, $sql2); if ($user = pg_fetch_row($row_user_list)) { setcookie ("login", $login_cookie); header("Location: index.php"); die("logged in"); } else { header("Location: index.php"); die("wrong username/password"); } } pg_close($dbconn); ?> ``` **and finally my handler\_question.php where the problem occurs** ``` <?php include 'handler-login.php'; // This is the problem $question_body = '{$_POST['question_body']}' // I get an error right from the beginning $question_title = '{$_POST['question_title']}' $sql_questions_question_id = "SELECT question_id FROM users WHERE username = $username;" // $username comes from handler_login.php $questions_question_id = pg_query($dbconn, $sql_questions_question_id); // to get tags to an array $tags = '{$_POST['question_tags']}'; $tags_trimmed = trim($tags); $tags_array = explode(",", $tags_trimmed); // to save the cells in the array to db $sql_tags_insert = "INSERT INTO tags (tag, questions_question_id) VALUES (for ($i = 0; $i < count($tags_array); $i++)" $sql = "SELECT username, passhash_md5, email FROM users WHERE username = '{$_POST['username']}' AND email = '{$_POST['email']}' AND passhash_md5 = '{$_POST['password']}';"; $result = pg_query($dbconn, $sql); if(!$result) { exit; } $username = $_POST['username']; $passhash_md5 = md5($_POST['password']); pg_close($dbconn); ?> ``` *How can you have all variables of handler\_login.php to be accessible by handler\_question.php?*
I know this is not the answer to the question you asked but since you tagged this beginner I would just like to say, you cannot trust **any** data from users. As soon as you do you open your site to the risk of sql injections and xss attacks. You need to validate all input and [escape](http://php.net/htmlentities) all output that comes from a user. Using unsanitized data from the user in your sql could unintentionally break the sql statement if quotes and other sql characters are used. But more importantly it could result in sql injection with **very** bad things like tables being dropped and admin accounts being comprised. Look at [typecasting](http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting), [validating and sanitizing](http://php.net/manual/en/book.filter.php) variables and using [PDO](http://php.net/pdo) with prepared statements. If [PDO](http://php.net/pdo) is not available to you use [pg\_escape\_string](http://php.net/pg_escape_string). Not [escaping](http://php.net/htmlentities) the output could result in an attacker inserting code into your site (xss) which for example could allow them to steal passwords and cookies from you and your users. They could also fill your site you with hidden spam links, if google finds out first the site will be blacklisted.
You have this code to include the file: ``` include 'handler-login.php'; ``` (with a dash in the filename) but you say your file is called `handler_login.php` (with an underscore). Is that just a typo in your question, or could it be the problem? (Also, this code looks broken to me: ``` $question_body = '{$_POST['question_body']}' ``` Did you mean this: ``` $question_body = $_POST['question_body']; ``` instead?)
To understand PHP's include -command
[ "", "php", "database", "postgresql", "include", "" ]
I'm trying to get a list of all top level desktop windows in an X11 session. Basically, I want to get a list of all windows that are shown in the window managers application-switching UI (commonly opened when the user presses ALT+TAB). I've never done any X11 programming before, but so far I've managed to enumerate through the entire window list, with code that looks something like this: ``` void CSoftwareInfoLinux::enumerateWindows(Display *display, Window rootWindow) { Window parent; Window *children; Window *child; quint32 nNumChildren; XTextProperty wmName; XTextProperty wmCommand; int status = XGetWMName(display, rootWindow, &wmName); if (status && wmName.value && wmName.nitems) { int i; char **list; status = XmbTextPropertyToTextList(display, &wmName, &list, &i); if (status >= Success && i && *list) { qDebug() << "Found window with name:" << (char*) *list; } status = XGetCommand(display, rootWindow, &list, &i); if (status >= Success && i && *list) { qDebug() << "... and Command:" << i << (char*) *list; } Window tf; status = XGetTransientForHint(display, rootWindow, &tf); if (status >= Success && tf) { qDebug() << "TF set!"; } XWMHints *pHints = XGetWMHints(display, rootWindow); if (pHints) { qDebug() << "Flags:" << pHints->flags << "Window group:" << pHints->window_group; } } status = XQueryTree(display, rootWindow, &rootWindow, &parent, &children, &nNumChildren); if (status == 0) { // Could not query window tree further, aborting return; } if (nNumChildren == 0) { // No more children found. Aborting return; } for (int i = 0; i < nNumChildren; i++) { enumerateWindows(display, children[i]); } XFree((char*) children); } ``` `enumerateWindows()` is called initially with the root window. This works, in so far as it prints out information about hundreds of windows - what I need, is to work out which property I can interrogate to determine if a given `Window` is a top-level Desktop application window (not sure what the official terminology is), or not. Can anyone shed some light on this? All the reference documentation I've found for X11 programming has been terribly dry and hard to understand. Perhaps someone could point be to a better resource?
I have a solution! Well, sort of. If your window manager uses the extended window manager hints (EWMH), you can query the root window using the "`_NET_CLIENT_LIST`" atom. This returna list of client windows the window manager is managing. For more information, see [here](http://standards.freedesktop.org/wm-spec/wm-spec-1.3.html#id2449346). However, there are some issues with this. For a start, the window manager in use must support the EWMH. KDE and GNOME do, and I'm sure some others do as well. However, I'm sure there are many that don't. Also, I've noticed a few issues with KDE. Basically, some non-KDE applications don't get included in the list. For example, if you run xcalc under KDE it won't show up in this list. If anyone can provide any improvements on this method, I'd be glad to hear them. For reference, the code I'm using is listed below: ``` Atom a = XInternAtom(m_pDisplay, "_NET_CLIENT_LIST" , true); Atom actualType; int format; unsigned long numItems, bytesAfter; unsigned char *data =0; int status = XGetWindowProperty(m_pDisplay, rootWindow, a, 0L, (~0L), false, AnyPropertyType, &actualType, &format, &numItems, &bytesAfter, &data); if (status >= Success && numItems) { // success - we have data: Format should always be 32: Q_ASSERT(format == 32); // cast to proper format, and iterate through values: quint32 *array = (quint32*) data; for (quint32 k = 0; k < numItems; k++) { // get window Id: Window w = (Window) array[k]; qDebug() << "Scanned client window:" << w; } XFree(data); } ```
To expand on the previous solution, if you want to then get the window names: ``` // get window Id: Window w = (Window) array[k]; char* name = '\0'; status = XFetchName(display, w, &name); if (status >= Success) { if (name == NULL) printf("Found: %ul NULL\n", w); else printf("Found: %ul %s\n", w, name); } XFree(name); ```
How to identify top-level X11 windows using xlib?
[ "", "c++", "x11", "xlib", "icccm", "ewmh", "" ]
I am implementing a notification system and seeing if these suggestions are valid to set up, if one is better than the other or a better solution is available: A notification is added to the database. A guest / identifiable user logs onto or uses the site. They are greeted with notifications they haven't seen before with the option to close or read later. * Notification table stores notification texts and Id. * **Option 1:** Alerts table stores all users who have read the notification * **Option 2:** Alerts table stores all users who have NOT read the notification Are these options much of a muchness, is it better to add potentially 100,000+ alerts and as those users discard or interact with the notice, their status is changed or the alert deleted. This could become a very large table... What's a more extensible set up for custom notifications based on user activity?
I wouldn't do it that way. I'd store a record for each (user,notification) and mark each record as read or unread. You can then record when they read it, which might be important depending on your application (eg if you needed an audit trail of some kind). 100k records is not very big. Don't worry about size until you get to at least 10 million records. If necessary archive them at some point. But you should do some estimates on how quickly you'll generate 10 million records. If it's 3 days, then yeah you have a problem. If it's 3 years then you don't. This option of course has the notification text in a separate table. This should also scale extremely well with even higher number of messages as you select the unread messages for a user (indexed) and can either join to get the notification text (if your table is in the tens of millions of records size) or select them and then separately select the messages. Partitioning the (user,notification) table is easy: you base it on user ranges. And when users delete messages, generally you should just mark it as deleted rather than actually deleting it. Most of the time there's not much reason to delete anything in a database.
I'm coding my our website and have the same question but I solved myself this way: 1. Store all record in a notifications table. 2. `Read/Unread = true/false` 3. CRON Job: delete old 10 notifications if user have more than 50 notifications. I think Facebook periodically runs a cron job to delete old notifications which we cannot see after our limit notification has been reached.
Suggestions for a user notification system in MySql and PHP
[ "", "php", "mysql", "notifications", "" ]
Hit a roadblock while implementing a [sub domain based language switcher](https://stackoverflow.com/questions/1170008/building-a-language-switcher-2-languages-only-asp-net-mvc) (en.domain.com loads English, jp.domain.com loads Japanese). **How do I get a single membership system to work across multiple sub domains (ASP.NET MVC C#)?** Saw something about adding `domain="domain.com"` to `<forms >` entry in web.config. Did that, but does that work when testing on local visual studio development web server?
Try creating the cookie yourself. In *AccountController* you'll find this: ``` FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); ``` that "creates and adds to the cookie collection". It doesn't allow modification of the domain (but does allow modification of the path, oddly). Instead create a cookie without adding to the collection, modify the necessary properties, then add to the collection: ``` var a = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie); //if you're debugging right here, a.Domain should be en.example.com; change it a.Domain = "example.com"; HttpContext.Current.Response.Cookies.Add(a); ``` James
You have to use dot prefix, like this. ``` <authentication mode="Forms"> <forms domain=".tv.loc" loginUrl="~/signin" timeout="2880" name="auth" /> </authentication> ```
ASP.NET MVC - cross sub domain authentication/membership
[ "", "c#", "asp.net-mvc", "authentication", "asp.net-membership", "subdomain", "" ]
I am try to read the following string, captured from a log4net UdpAppender. ``` <log4net:event logger="TestingTransmitter.Program" timestamp="2009-08-02T17:50:18.928+01:00" level="ERROR" thread="9" domain="TestingTransmitter.vshost.exe" username="domain\user"> <log4net:message>Log entry 103</log4net:message> <log4net:properties> <log4net:data name="log4net:HostName" value="machine" /> </log4net:properties> </log4net:event> ``` When trying to XElement.Parse or XDocument.Parse the content, it throws an exception: > 'log4net' is an undeclared namespace. > Line 1, position 2. I know I can search and replace "log4net:" in the original string and remove it, allowing me to parse the XML successfully, but is there a better way? This is the complete data captured (reformatted to allow reading), there are no xml namespace declarations made or removed..
First, create an instance of XmlNamespaceManager class, and add your namespaces to that, e.g. ``` XmlNamespaceManager mngr = new XmlNamespaceManager( new NameTable() ); mngr.AddNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" ); mngr.AddNamespace( "xsd", "http://www.w3.org/2001/XMLSchema" ); ``` To parse an XML string using those namespace mappings, call the following function, passing the instance of XmlNamespaceManager with the namespaces you've added to it: ``` /// <summary>Same as XElement.Parse(), but supports XML namespaces.</summary> /// <param name="strXml">A String that contains XML.</param> /// <param name="mngr">The XmlNamespaceManager to use for looking up namespace information.</param> /// <returns>An XElement populated from the string that contains XML.</returns> public static XElement ParseElement( string strXml, XmlNamespaceManager mngr ) { XmlParserContext parserContext = new XmlParserContext( null, mngr, null, XmlSpace.None ); XmlTextReader txtReader = new XmlTextReader( strXml, XmlNodeType.Element, parserContext ); return XElement.Load( txtReader ); } ```
You really only have two options: 1. Strip "log4net:" from the XML, as you suggested; 2. Modify the XML to declare the namespace, probably most easily accomplished by wrapping the fragment (via StringBuilder) in a root element that has the declaration. Strictly speaking, your example is malformed XML -- it's no surprise XDocument / XElement won't parse it.
XDocument or XElement parsing of XML element containing namespaces
[ "", "c#", "linq-to-xml", "log4net", "" ]
I have two indexed arrays $measurements[] and $diffs[] , $measurements[] is filled with values from a database and the $diffs[] gets values from a function which calculates the difference from two measurements. When I have a collection of different measurements in $measurements[] I want to add a value to just one array element in the $diffs[] array and then loop through it, then where the array element got updated check for corresponding index array element in the $measurements[] array en deduct it from there. What I'm trying to accomplish is to have a specific difference deducted from a corresponding measurement when I have a collection of measurments. Is this possible in php and how would I go about doing this. Edit: to make it more descriptive (english is not my first language nor is php) ``` $measurements Array ( [0] => 1469 [1] => 1465 [2] => 739 [3] => 849 ) $diffs Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ``` I would like to update $diffs array index [2] => 200 so it becomes ``` Array ( [0] => 0 [1] => 0 [2] => 200 [3] => 0 ) ``` and then subtract $diffs array index [2] from $measurements array index [2] in this case 739 - 200 I sincerely hope this makes it more clear.
I'm sure it's possible... it sounds like you need just a few [`foreach`](http://php.net/foreach)es and some basic arithmetic. But more specific than that, I can't help you. I can't understand your description of the problem. --- *Edit:* Now, with more information on the table, the code isn't all that complex. Here's how I would do it: ``` foreach ($measurements as $index => $measurement) { $measurements[$index] -= $diffs[$index]; // subtract the negative difference from the measurement. unset($diffs[$index]); // clear the modifier after use. } ``` This code iterates through each element in the `$measurements` array, and subtracts a number from the corresponding index in `$diffs`. This code doesn't require that `$diffs` has matching size with `$measurements`, because PHP will coerce a missing index-value to zero.
Maybe something like this if your array is 100. Syntax might be off and like previous poster not sure if I understood your problem. ``` for ( $counter = 0; $counter <= 100; $counter += 1) { $measurements[$counter] = $measurements[$counter] - $diff[$counter]; } ```
Is this possible with php
[ "", "php", "" ]
So I've got a SQL statement that pared down looks something like this: ``` SELECT column FROM table t (nolock) LEFT OUTER JOIN table2 (nolock) t2 on t.id = t2.id ``` This statement works on my SQL 2005 and SQL 2008 environments. It does not on a remote SQL 2005 environment. I've switched the last line to: ``` LEFT OUTER JOIN table2 t2 (nolock) on t.id = t2.id ``` This works in the remote environment. Putting aside issues of whether (nolock) is appropriate and that the syntax should remain internally consistent, any ideas why this happens? I attempted to search for hotfixes/KBs that dealt with this and came up with nothing. Is there a setting on SQL server that could cause this behavior?
Check your database compatibility level. It should be `90` for this syntax to work. Just checked: ``` sp_dbcmptlevel 'test', 80 DBCC execution completed. If DBCC printed error messages, contact your system administrator. SELECT TOP 100 * FROM master t (nolock) LEFT OUTER JOIN master (nolock) t2 on t.id = t2.id Сообщение 102, уровень 15, состояние 1, строка 3 Incorrect syntax near 't2'. ```
I am not sure but maybe it is caused by [compatibility level](http://msdn.microsoft.com/en-us/library/ms191137.aspx)? Since SQL 2005 by default correct syntax of hint is `WITH (NOLOCK)` and maybe this is the reason.
Order of (nolock) and table aliases on SQL Server
[ "", "sql", "sql-server", "sql-server-2005", "" ]
[boost::variant](http://www.boost.org/doc/libs/1_39_0/doc/html/boost/variant.html) claims that it is a value type. Does this mean that it's safe to simply write out the raw representation of a boost::variant and load it back later, as long as it only contains POD types? Assume that it will be reloaded by code compiled by the same compiler, and same version of boost, on the same architecture. Also, (probably) equivalently, can boost::variant be used in shared memory?
Regarding serialisation: It should work, yes. But why don't you use `boost::variant`'s visitation mechanism to write out the actual type contained in the variant? ``` struct variant_serializer : boost::static_visitor<void> { template <typename T> typename boost::enable_if< boost::is_pod<T>, void>::type operator()( const T & t ) const { // ... serialize here, e.g. std::cout << t; } }; int main() { const boost::variant<int,char,float,double> v( '1' ); variant_serializer s; boost::apply_visitor( s, v ); return 0; } ``` Regarding shared memory: `boost::variant` does not perform heap allocations, so you can place it into shared memory just like an `int`, assuming proper synchronisation, of course. Needless to say, as you said, the above is only valid if the variant can only contain POD types.
Try just including boost/serialization/variant.hpp; it does the work for you.
Is it safe to serialize a raw boost::variant?
[ "", "c++", "serialization", "boost", "shared-memory", "boost-variant", "" ]
I am using a FormView with an ObjectDataSource. When the save button is clicked, I would like to modify the data bound object before it gets set to the ObjectDataSources Update method. I tried the FormView's Updating event as well as the Object Data Source's Updating event but I can't figure out how to access the data bound object. FormView.DataItem is null in those events. Or in other words, I would like to intercept and modify the DataItem before it gets passed to the ObjectDataSource UpdateMethod. To give a little more detail on why I want to do this, there are some values on the form which can't be databound with the build in functionality. One of the controls is the checkbox list. I am using the DataBinding event to populate the checks, but now I also need a way to update my object to reflect the form values. There are also other controls with similar situations.
Why don't you just write your own business object (aka ObjectDataSource), and wrap the original ObjectDataSource object? You can then intercept anything you want, and modify it enroute to the original ObjectDataSource object's Save method.
I know this is an old question, but I had the same problem, and found the answer I think Bob's looking for. The solution is to use the ObjectDataSource Updating event on the Web Form. The Updating event includes the ObjectDataSourceMethodEventArgs object as a parameter. The ObjectDataSourceMethodEventArgs class includes a propery named "InputParameters", and you can use that to access the data object and modify the contents before the update occurs. You need to convert the InputParameters object to an OrderedDictionary type first (full namespace is System.Collections.Specialized.OrderedDictionary) It looks something like this: ``` protected void myObjectDataSource_Updating(object sender, ObjectDataSourceMethodEventArgs e) { OrderedDictionary parameters = (OrderedDictionary)e.InputParameters; MyDataObject updatedData = (MyDataObject)parameters[0]; DropDownList myDropDown = (DropDownList)FormView1.FindControl("myDropDown") updatedData.SomeDataValue = myDropDown.SelectedValue; } ```
How do you manually modify a bound object with a FormView?
[ "", "c#", "asp.net", "asp.net-2.0", "" ]
I am using SQL Server 2008 and I want to test the execution correctness of my SQL Server Agent job immediately to ignore the schedule. Any ideas? thanks in advance, George
In SSMS, under the "SQL Server Agent" node, open the "Jobs" subnode and find your job, right click on it and select "Start Job" - that'll start and run the job right away. [![alt text](https://i.stack.imgur.com/FJpno.jpg)](https://i.stack.imgur.com/FJpno.jpg) Marc
Create a stored procedure that encapsulates all the aspects of your job and then use that in SQL Agent. You can then just call the procedure from the command line to test it eg. `exec dbo.MyProcedure @param1 = 'foo'`
Any solutions to test SQL Agent Job immediately to ignore schedule
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "sql-server-agent", "" ]
I have a dictionary which is of type Dictionary [string,handler\_func] where handler\_func is a delegate of type ``` public delegate void HANDLER_FUNC(object obj, TcpClient client); ``` now I have an attribute class like so ``` [AttributeUsage(AttributeTargets.Method)] public class MessageHandlerAttribute : Attribute { public MessageHandlerAttribute(string s1, HANDLER_FUNC hf) { s1 = name; msgtype = hf; } private string name; public string HandlerName { get { return name; } set { name = value; } } private HANDLER_FUNC msgtype; public HANDLER_FUNC MessageName { get { return msgtype; } set { msgtype = value; } } } ``` The basic idea is I apply this attribute to a method in a class and somewhere I use reflection to fill up the Dictionary above problem is unless this method is static the atrribute is not working so ``` [MessageHandlerAttribute("HandleLoginResponse",HandleLoginResponse)] private void HandleLoginResponse(object obj, TcpClient client) ``` is causing the standard need an object thing So what are my options ( i do not want the handler method to be static ) Thanks
``` [MessageHandlerAttribute("HandleLoginResponse",HandleLoginResponse)] private void HandleLoginResponse(object obj, TcpClient client) ``` I don't understand why you need to specify the method in the attribute : since the attribute is applied to the method, you can already retrieve the method... You could do something like that : ``` [MessageHandlerAttribute("HandleLoginResponse")] private void HandleLoginResponse(object obj, TcpClient client) ... foreach(MethodInfo method in this.GetType().GetMethods()) { MessageHandlerAttribute attr = Attribute.GetCustomAttribute(method, typeof(MessageHandlerAttribute)) as MessageHandlerAttribute; if (attr != null) { HANDLER_FUNC func = Delegate.CreateDelegate(typeof(HANDLER_FUNC), this, method) as HANDLER_FUNC; handlers.Add(attr.HandlerName, func); } } ```
Attribute parameters are generated at compile time and stored in the assembly, so this won't work (HandleLoginResponse is a non-static method, so it is bound to an object, which is only available at runtime)
C# delegate and attributes syntax question
[ "", "c#", "syntax", "" ]
Entering my address via a traditional form drives me crazy: * Why do I have to enter my city, state, **and** zip code when my city and state can be inferred from my zip code? * Choosing your state from a dropdown list is a pain in the ass -- often you can't tab into it, you have to use the mouse, etc. [alt text http://img10.imageshack.us/img10/7404/traditionaladdressform.png](http://img10.imageshack.us/img10/7404/traditionaladdressform.png) Because I find this process so repulsive, when I designed my online store ([bombsheets.com](https://bombsheets.com)), I decided to build an auto-complete widget for addresses. As you type, we try to geocode your address (via Google Maps): [alt text http://img403.imageshack.us/img403/9333/addressautocomplete.png](http://img403.imageshack.us/img403/9333/addressautocomplete.png) In the best case, this works really well. If your address is "120 W 45th St, New York, NY 10036, USA", you can enter it by typing something as short as "120 w 45th st, nyc". However, as far as I know, we're the only online store that uses this interface. Rather than pat myself on the back for being such a genius, I'm curious whether its lack of use means that this idea is somehow flawed. A few potential issues: 1. Too foreign / unfamiliar. Customers are used to the old form, and switching things up on them is confusing. 2. You have to enter your apartment / floor number / whatever in a different field. This is confusing. 3. When our store blows up (good problem to have), we'll be hitting Google with too many Geocode requests for this to scale. 4. **EDIT:** This won't work for (the ~5% of) users with javascript disabled. 5. There's no significant issue here and this interface is the future. (This isn't so outlandish since, for example, many online stores force you to enter both your credit card number and your credit card type, when the latter is inferrable from the former). Anyway, basically I'm curious if this is an area in which I should be trying to innovate, or whether I should just use the traditional approach. (Thoughts about improving the usability of this new approach are of course appreciated as well).
The **multiple drop downs** vs **single text field** discussion raises some interesting usability discussions. The separate state and country fields are commonly used. So you may be breaking the rule of "don't make me think" but the auto complete helps explain what is required. Jakob Nielsen argues that single text fields for addresses are easier for users to use: > Such information is often hardwired > into users' fingers, and having to > select such options from a menu breaks > the standard paradigm for entering > information and can even create more > work for users (<http://www.useit.com/alertbox/20001112.html>) On the other hand selecting the information from fixed lists will mean less room for errors and some people prefer to use the mouse (for instance, those people go to the edit menu to access commands like copy and paste). You need to judge your target audience and make a call.
One concern is whether it works without JavaScript or not. If your customers for some reason or other (there are several of them) do not have JavaScript enabled, or doesn't even have browsers supporting it (e.g. on a cell phone), you could get malformed input that your site may not handle correctly.
Is an autocomplete text box for entering addresses a good idea?
[ "", "javascript", "ruby-on-rails", "autocomplete", "e-commerce", "street-address", "" ]
Is it feasible to use the yield keyword to implement a simple state machine [as shown here](http://en.wikipedia.org/wiki/Finite_State_Machine). To me it looks like the C# compiler has done the hard work for you as it internally implements a state machine to make the yield statement work. Can you piggy-back on top of the work the compiler is already doing and get it to implement most of the state machine for you? Has anyone done this, is it technically possible?
It's feasible but it is a bad idea. Iterator blocks were created to help you write custom iterators for collections, not for solving the general-purpose problem of implementing state machines. If you want to write a state machine, just write a state machine. It's not hard. If you want to write a lot of state machines, write a library of useful helper methods that let you cleanly represent state machines, and then use your library. But don't abuse a language construct intended for something completely different that just happens to use state machines as an implementation detail. That makes your state machine code hard to read, understand, debug, maintain and extend. (And incidentally, I did a double-take when reading your name. One of the designers of C# is also named Matt Warren!)
Yes, it's absolutely possible and easy to do. You can enjoy using control flow constructs (`for`, `foreach`, `while`, ... `goto` (using `goto` particularly suits this scenario ;))) along with `yield`s to build one. ``` IEnumerator<State> StateMachine (Func<int> currentInput /* gets current input from IO port */, Func<int> currentOutput) { for (;;) { if ((currentInput() & 1) == 0) yield return new State("Ready"); else { if (...) { yield return new State("Expecting more data"); SendOutput(currentOutput()); while ((currentInput() & 2) != 0) // while device busy yield return new State("Busy"); else if (...) { ... } } } } // consumer: int data; var fsm = StateMachine(ReadFromIOPort, () => data); // ... while (fsm.Current != "Expecting more data") fsm.MoveNext(); data = 100; fsm.MoveNext(); ```
implementing a state machine using the "yield" keyword
[ "", "c#", "yield", "state-machine", "fsm", "" ]
I would like to replace an object instance by another instance inside a method like this: ``` class A: def method1(self): self = func(self) ``` The object is retrieved from a database.
It is unlikely that replacing the 'self' variable will accomplish whatever you're trying to do, that couldn't just be accomplished by storing the result of func(self) in a different variable. 'self' is effectively a local variable only defined for the duration of the method call, used to pass in the instance of the class which is being operated upon. Replacing self will not actually replace references to the original instance of the class held by other objects, nor will it create a lasting reference to the new instance which was assigned to it.
As far as I understand, If you are trying to replace the current object with another object of same type (assuming `func` won't change the object type) from an member function. I think this will achieve that: ``` class A: def method1(self): newObj = func(self) self.__dict__.update(newObj.__dict__) ```
Is it safe to replace a self object by another object of the same type in a method?
[ "", "python", "" ]
I'd like to do some network socket programming in C++ and have found the [C++ Sockets library](http://www.alhem.net/Sockets/index.html). First, is this a good way to go in C++? Normally in C, I'd use some of the stuff beej describes in [his tutorial](http://beej.us/guide/bgnet/). Second, how do I compile the examples given on the site? I can't figure it out from their installation/configuration guide. So I download the tar.gz to my Linux box, then what? To have a specific example, how do I compile and run the [DisplaySocket example](http://www.alhem.net/Sockets/tutorial/using1a.html)? Thanks. --- EDIT: Thank you for the quick answers. A comment though. I'm not really looking into "understanding" network programming as I think I do that well enough already. I want to know if there's anything in particular to take advantage of in C++, and - if "the C++ Sockets Library" is a good choice - how to use it.
That's not "the" C++ sockets library, it's "a" C++ sockets library. Boost.asio has another (<http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio.html>). (Community Wiki since I can't actually help you with your question - I've never compiled the code you ask about, so I don't know at what point you might have tripped over a problem).
Network programming would be better understood by using basic socket api (BSD or WinSock) rather than a socket library which hides most of the intricacies about sockets and their behaviour.
How to use the C++ Sockets Library
[ "", "c++", "api", "sockets", "compilation", "" ]
I'm an Eclipse newbie and I'm trying to build a mixed AWT/SWT application. Here's my code: ``` public class HelloWorldSWT { public static void main(String[] args) { Frame frame = new Frame("My AWT Frame"); // java.awt.Frame frame.setLayout( new BorderLayout() ); Canvas canvas = new Canvas(); // java.awt.Canvas frame.add(canvas, BorderLayout.CENTER); frame.setVisible(true); Display display = new Display(); // display object to manage SWT lifecycle. Shell swtShell = SWT_AWT.new_Shell(display, canvas); Button m_button = new Button(swtShell, SWT.PUSH); m_button.setText( "button" ); // invoke the AWT frame rendering by making the frame visible // This starts the EDT frame.setVisible(true); // standard SWT dispatch loop while(!swtShell.isDisposed()) { if(!display.readAndDispatch()) display.sleep(); } swtShell.dispose(); } } ``` This compiles fine, but when I run it as application in Eclipse, I get the following error: > Exception in thread "main" > java.lang.UnsatisfiedLinkError: > sun.awt.SunToolkit.getAppContext(Ljava/lang/Object;)Lsun/awt/AppContext; > at > sun.awt.SunToolkit.getAppContext(Native > Method) at > sun.awt.SunToolkit.targetToAppContext(Unknown > Source) at > sun.awt.windows.WComponentPeer.postEvent(Unknown > Source) at > sun.awt.windows.WComponentPeer.postPaintIfNecessary(Unknown > Source) at > sun.awt.windows.WComponentPeer.handlePaint(Unknown > Source) at > sun.java2d.d3d.D3DScreenUpdateManager.repaintPeerTarget(Unknown > Source) at > sun.java2d.d3d.D3DScreenUpdateManager.createScreenSurface(Unknown > Source) at > sun.awt.windows.WComponentPeer.replaceSurfaceData(Unknown > Source) at > sun.awt.windows.WComponentPeer.replaceSurfaceData(Unknown > Source) at > sun.awt.windows.WComponentPeer.setBounds(Unknown > Source) at > sun.awt.windows.WWindowPeer.setBounds(Unknown > Source) at > sun.awt.windows.WComponentPeer.initialize(Unknown > Source) at > sun.awt.windows.WCanvasPeer.initialize(Unknown > Source) at > sun.awt.windows.WPanelPeer.initialize(Unknown > Source) at > sun.awt.windows.WWindowPeer.initialize(Unknown > Source) at > sun.awt.windows.WFramePeer.initialize(Unknown > Source) at > sun.awt.windows.WComponentPeer.(Unknown > Source) at > sun.awt.windows.WCanvasPeer.(Unknown > Source) at > sun.awt.windows.WPanelPeer.(Unknown > Source) at > sun.awt.windows.WWindowPeer.(Unknown > Source) at > sun.awt.windows.WFramePeer.(Unknown > Source) at > sun.awt.windows.WToolkit.createFrame(Unknown > Source) at > java.awt.Frame.addNotify(Unknown > Source) at > java.awt.Window.show(Unknown Source) > at java.awt.Component.show(Unknown > Source) at > java.awt.Component.setVisible(Unknown > Source) at > java.awt.Window.setVisible(Unknown > Source) at > HelloWorldSWT.main(HelloWorldSWT.java:20) What am I doing wrong?
Since version 3.3, SWT automatically finds its required platform-specific libraries, which are inside the swt.jar (at the top level of the JAR contents). So all you need is swt.jar in the classpath, and it works. One way to get an UnsatisifiedLinkError is if you're using a swt.jar for another platform -- they're all named "swt.jar"; for example, if you download the one for Linux, and try to use it on Windows. The project will compile OK since all the API-level code is the same Java for every platform, but it will fail when you run because the native libraries are wrong. However, since the error in this case happens in AWT, it might be something else, not directly related to SWT. First, make sure you've downloaded the Windows SWT release. When you import it into your workspace, it creates an Eclipse project named org.eclipse.swt, which contains the swt.jar. You then make org.eclipse.swt a required project for your project, and nothing else in the Build Path besides a valid, clean JRE (you can try defining a new one [Window -> Preferences -> Java -> Installed JREs], or just use a different one you might have installed). You can also test it from the shell/command window. Go to your project directory. The command should be as simple as: ``` java -cp bin;..\org.eclipse.swt\swt.jar HelloWorldSWT ``` I got your code to run (Vista-32, JDK 6\_15), but the window opened really small, and would not close. I don't know anything about the SWT-AWT bridge though, so good luck with that....
The UnsatisfiedLinkError is indicating that a native library that you are relying upon is not found when you are trying to run your app. If you are compiling this in your IDE, then the library is in your build path. If you are running this from with your IDE and getting this error, the libray is not in your Run path. Check your Run Dialog to see that the libraries you have in your build path are in your run path.
Java UnsatisfiedLinkError when mixing AWT and SWT?
[ "", "java", "eclipse", "swt", "awt", "" ]
I am building a website for a club that is part of a mother organisation. I am downloading (leeching ;) ) the images that where put on profile pages of the mother organisation to show on my own page. But their website has a nice white background, and my website has a nice gray gradient on the background. This does not match nicely. So my idea was to edit the images before saving them to my server. I am using GDI+ to enhance my images, and when I use the method MakeTransparent of Bitmap, it does work, and it does do what its supposed to do, but I still have these white jpeg artifacts all over the place. The artifacts makes the image so bad, I am better off not making the image transparent and just leaving it white, but thats really ugly on my own website. I can always at a nice border with a white background of course, but I rather change the background to transparent. So I was wondering if and how I can remove some simple JPEG artifacts in C#. Has anyone ever done this before? Thanks for your time. Example image: ![TB-5404](https://i466.photobucket.com/albums/rr27/Arcturus5404/tb5404_full.jpg) Transformed image: ![TB-5404 transformed](https://i466.photobucket.com/albums/rr27/Arcturus5404/transformed.png)
Well, I attempted something that is far from perfect, but I figure it might be useful to someone else. I have gotten to: ![alt text](https://codertao.com/images/test2.jpg) Problems encountered: the shadows are far enough from 'off white' that its difficult to auto convert them, and even if you did the shadow would still be in the image itself. The glare off the top... hub thing, is also closer to off white then the anti aliased bits. There are three to seven spots of white in the image which aren't connected to any of the primary corners; and finally there's still a bit of white on the edges (could probably get rid of it by tweaking the code, but not without taking off part of the glare top. C# inefficient code: ``` static void Main() { Bitmap bmp=new Bitmap("test.jpg"); int width = bmp.Width; int height = bmp.Height; Dictionary<Point, int> currentLayer = new Dictionary<Point, int>(); currentLayer[new Point(0, 0)] = 0; currentLayer[new Point(width - 1, height - 1)] = 0; while (currentLayer.Count != 0) { foreach (Point p in currentLayer.Keys) bmp.SetPixel(p.X, p.Y, Color.Black); Dictionary<Point, int> newLayer = new Dictionary<Point, int>(); foreach (Point p in currentLayer.Keys) foreach (Point p1 in Neighbors(p, width, height)) if (Distance(bmp.GetPixel(p1.X, p1.Y), Color.White) < 40) newLayer[p1] = 0; currentLayer = newLayer; } bmp.Save("test2.jpg"); } static int Distance(Color c1, Color c2) { int dr = Math.Abs(c1.R - c2.R); int dg = Math.Abs(c1.G - c2.G); int db = Math.Abs(c1.B - c2.B); return Math.Max(Math.Max(dr, dg), db); } static List<Point> Neighbors(Point p, int maxX, int maxY) { List<Point> points=new List<Point>(); if (p.X + 1 < maxX) points.Add(new Point(p.X + 1, p.Y)); if (p.X - 1 >= 0) points.Add(new Point(p.X - 1, p.Y)); if (p.Y + 1 < maxY) points.Add(new Point(p.X, p.Y + 1)); if (p.Y - 1 >= 0) points.Add(new Point(p.X, p.Y - 1)); return points; } ``` The code works by starting with two points; setting them to black, and then checking to see if any neighbors near them are near white; if they are they're added to a list which is then executed against. Eventually it runs out of white pixels to change. As an alternative, you might want to consider redesigning the site to use a white background.
Loop through each pixel in the image, if R,G and B is higher than, say, 230 then replace the color with your desired color(or transparent). Maybe even weight the new color depending on how far from 'true' white the old color is. Expect to get problems if the actual image is white also, otherwhise you will end up with a grey stormtrooper :)
JPEG artifacts removal in C#
[ "", "c#", "image-processing", "gdi+", "bitmap", "" ]
In C#, what's the syntax for declaring an indexer as part of an interface? Is it still **this[ ]**? Something feels odd about using the **this** keyword in an interface.
``` public interface IYourList<T> { T this[int index] { get; set; } } ```
It is - it's pretty odd syntax at other times if you ask me! But it works. You have to declare the `get;` and/or `set;` parts of it with no definition, just a semi-colon, exactly like ordinary properties in an interface.
Indexer as part of the interface in C#
[ "", "c#", "interface", "indexer", "" ]
I need to write a function to parse variables which contain domain names. It's best I explain this with an example, the variable could contain any of these things: ``` here.example.com example.com example.org here.example.org ``` But when passed through my function all of these must return either example.com or example.co.uk, the root domain name basically. I'm sure I've done this before but I've been searching Google for about 20 minutes and can't find anything. Any help would be appreciated. EDIT: Ignore the .co.uk, presume that all domains going through this function have a 3 letter TLD.
### Stackoverflow Question Archive: * [How to get domain name from url?](https://stackoverflow.com/questions/569137/how-to-get-domain-name-from-url/569219) * [Check if domain equals value?](https://stackoverflow.com/questions/1122261/php-check-if-domain-equals-value-then-perform-action) * [How do I get the base url?](https://stackoverflow.com/questions/1144856/how-do-i-split-serverhttpreferer-to-get-the-base-url) --- ``` print get_domain("http://somedomain.co.uk"); // outputs 'somedomain.co.uk' function get_domain($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false; } ```
If you want a fast simple solution, without external calls and checking against predefined arrays. Works for new domains like "www.domain.gallery" also, unlike the most popular answer. ``` function get_domain($host){ $myhost = strtolower(trim($host)); $count = substr_count($myhost, '.'); if($count === 2){ if(strlen(explode('.', $myhost)[1]) > 3) $myhost = explode('.', $myhost, 2)[1]; } else if($count > 2){ $myhost = get_domain(explode('.', $myhost, 2)[1]); } return $myhost; } ``` * domain.com -> domain.com * sub.domain.com -> domain.com * www.domain.com -> domain.com * www.sub.sub.domain.com -> domain.com * domain.co.uk -> domain.co.uk * sub.domain.co.uk -> domain.co.uk * www.domain.co.uk -> domain.co.uk * www.sub.sub.domain.co.uk -> domain.co.uk * domain.photography -> domain.photography * www.domain.photography -> domain.photography * www.sub.domain.photography -> domain.photography
PHP Getting Domain Name From Subdomain
[ "", "php", "dns", "subdomain", "" ]
When I type strange characters like é or ë and store it in a mysql dbase; the character will be converted to: é It probably will have to do something with my character set. But i don't now where to start. On top of the page i inserted: ``` <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> ``` The collocation of the field in the dbase is: utf8\_unicode\_ci Displaying the field in a webpage results in é and ë but displaying them in a textarea results in é How can i change this?
Make sure the collation for the columns, tables and the database are all set to `utf8_unicode_ci` or `utf8_general_ci` You also have to keep in mind, in addition to the `meta` directive that you already have, to extract and insert entries to and from the database in the same encoding. Include this line right after you've made the call to connect to the database: ``` mysql_query("set names 'utf8'"); ``` This will keep the character set properly as UTF-8 state as you manipulate and extract entries in the database. If you can for next time, [have everything in UTF-8 from the very start](http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html).
There are a two things you can do: * Look into PHP's UTF-8 functions: [utf8\_encode](http://us.php.net/utf8_encode) and [utf8\_decode](http://us.php.net/manual/en/function.utf8-decode.php) * Check your MySQL database character set: it should be UTF-8 as well. More on [unicode in MySQL](http://dev.mysql.com/tech-resources/articles/4.1/unicode.html).
Strange characters in mysql dbase
[ "", "php", "mysql", "character-encoding", "" ]
Hello fellow C++ programmers. I have, what I hope to be, a quick question about STL containers: ``` std::list<std::string> l; ``` This statement compiles fine when used in some C++ sourcefile (with the appropriate includes). But ``` std::list<const std::string> m; ``` or ``` std::list<std::string * const> n; ``` fails to compile when using gcc (gcc version 4.0.1 (Apple Inc. build 5484)). However, using the Visual Studio 2008 C++ compiler, no complaints arise. A little research unearths that elements in STL containers have to be `Assignable`. Is there a STL bug in the VC implementation (I'd say: 'unlikely') or do they use another concept of `Assignable`?
Technically, container elements do have to be assignable, however in `std::list`, list nodes are very rarely moved around, so once constructed they don't need to be copied (OK) or assigned (would cause an error). Unless a compiler goes out of its way to test assignability, it's likely that instantiating many list operations won't actually cause a compile error, even if it's not technically legal.
The things in a container must be assignable (i.e. not const), but the compiler does not have to instantiate all template methods unless they are actually used, at which point it can discover the const problem. Some compilers are better at doing this than others.
const pointers in STL containers
[ "", "c++", "stl", "const-correctness", "" ]
I would like to debug some templated code to understand it better. Unfortunately I'm new to template metaprogramming and it IS hard for me to get in. When I try to output the preprocessed source files I get 125 000 lines of code :/ So is there a way I can see the generated Code? (The library I'm using is [SeqAn](http://www.seqan.de/))
No it isn't. The preprocessor has nothing to do with template processing, which is performed by the compiler. Templates do not generate C++ code, any more than a function call does - they are an integral part of the C++ language itself.
Nope, in general, it can't be done. Templates are simply part of the C++ language, they're not a separate preprocessor, so they don't generate C++ code. The usual solution is to sprinkle your code with static asserts and other tests to verify that the right templates get instantiated in the right ways. Once you start getting lost in your metaprogramming, this simple trick can help you determine which type a template parameter really is: ``` // given a variable t of an unknown type T int*** i = t; ``` When the compiler encounters this, it'll print out a nice and simple error message, "Can not convert `<long, detailed typename>` to int\*\*\*", allowing you to easily verify that the template parameter T is actually the type you think it should be.
C++ Template Metaprogramming - Is it possible to output the generated code?
[ "", "c++", "templates", "metaprogramming", "seqan", "" ]
I'm wondering if there is a shorter way of inserting text in PHP than ``` <?php $city = "London"; ?> This website is a funky guide to <?php print $city; ?>!!! ``` For example, using ruby on rails, I could set ``` city = 'London' ``` somewhere in the code, and in my .erb file I could do ``` This website is a funky guide to <%= city %>!!! ``` I did read somewhere that `{$city}` could be used, but I tried it and it didn't. So is there a shorter form than `<?php print $var; ?>` ?
You could use [`short_open_tag`](http://fr.php.net/manual/en/ini.core.php#ini.short-open-tag), which have to be enabled in your configuration, but that's not considered as a good practice, as it only works if those are enabled -- and they are not always *(maybe not even by default)* Using long tags and echo/print might be longer, yes... But I would recommend using those, and not short tags. Also note that you might need to escape your data, when it comes from an un-trusted source and/or might contain HTML you don't want to get injected in the page, to avoid injections of HTML/JS *(see [htmlspecialchars](http://php.net/htmlspecialchars))* : --- **EDIT after the comments, to add couple of things about `short_open_tag` :** Why are short open tags considered *(at least by me ^^ )* bad practice ? First of all, after some checking, they are not enabled by default : **For PHP 5.3 :** ``` squale@shark:~/temp/php/php-5.3.0 $ grep 'short_open_tag' php.ini-development ; short_open_tag short_open_tag = Off squale@shark:~/temp/php/php-5.3.0 $ grep 'short_open_tag' php.ini-production ; short_open_tag short_open_tag = Off ``` Disabled by default in either "`development`" or "`production`" settings. **For PHP 5.2.10** *(most recent version of PHP 5.2)* : ``` squale@shark:~/temp/php/php-5.2.10 $ grep 'short_open_tag' php.ini-dist short_open_tag = On squale@shark:~/temp/php/php-5.2.10 $ grep 'short_open_tag' php.ini-recommended ; - short_open_tag = Off [Portability] short_open_tag = Off ``` Disabled by default in the "`recommended`" settings Considering these default settings are sometimes *(often ?)* kept by hosting services, it is dangerous to rely on `short_open_tag` being activated. *(I have myself run into problem with those being disabled... And when you are not admin of the server and don't have required privilegies to modify that, it's not fun ^^ )* If you want some numbers, you can take a look at [Quick survery: `short_open_tag` support on or off by default?](http://forums.zend.com/viewtopic.php?f=8&t=47) *(Not a scientific proof -- but show it could be dangerous to use those for an application you'd release to the public)* Like you said, those, when activated, conflict with XML declaration -- means you have to use something like this : ``` <?php echo '<?xml version="1.0" encoding="UTF-8" ?>'; ?> ``` Considering short open tags exists, and might be activated on the server you'll use, you should probable not use `<?xml` ever, though ; too bad **:-(** Actually, reading through the php.ini-recommended of PHP 5.2.10 : ``` ; Allow the <? tag. Otherwise, only <?php and <script> tags are recognized. ; NOTE: Using short tags should be avoided when developing applications or ; libraries that are meant for redistribution, or deployment on PHP ; servers which are not under your control, because short tags may not ; be supported on the target server. For portable, redistributable code, ; be sure not to use short tags. ``` The one from PHP 6 is even more interesting : ``` ; This directive determines whether or not PHP will recognize code between ; <? and ?> tags as PHP source which should be processed as such. It's been ; recommended for several years that you not use the short tag "short cut" and ; instead to use the full <?php and ?> tag combination. With the wide spread use ; of XML and use of these tags by other languages, the server can become easily ; confused and end up parsing the wrong code in the wrong context. But because ; this short cut has been a feature for such a long time, it's currently still ; supported for backwards compatibility, but we recommend you don't use them. ``` *(Might be the same in PHP 5.3 ; didn't check)* There have been [rumors](http://www.mail-archive.com/internals@lists.php.net/msg41839.html) short open tags could be removed from PHP 6 ; considering the portion of php.ini I just posted, it probably won't... but, still... To give an argument pointing to the other direction (I've gotta be honest, after all) : using short open tags **for template files** *(only)* is something that is often done in Zend Framework's examples that use template files : > In our examples and documentation, we > make use of PHP short tags: > > That said, many developers prefer to > use full tags for purposes of > validation or portability. For > instance, short\_open\_tag is disabled > in the php.ini.recommended file, and > if you template XML in view scripts, > short open tags will cause the > templates to fail validation. ([source](http://framework.zend.com/manual/en/zend.view.html#zend.view.introduction.shortTags)) On the contrary, for `.php` files : > Short tags are never allowed. For > files containing only PHP code, the > closing tag must always be omitted ([source](http://framework.zend.com/manual/en/coding-standard.coding-style.html#coding-standard.coding-style.php-code-demarcation)) I hope those informations are useful, and bring some kind of answer to your comment **:-)**
If you switch out of PHP mode, then the only way to print the variable is to switch back into it and print it like you have above. You could stay in PHP mode and use the {} construction you tried: ``` <?php $city = "London"; echo "This website is a funky guide to {$city}!!!"; ?> ```
What is the shortest way of inserting a variable into text with PHP?
[ "", "php", "ruby-on-rails", "shortcut", "" ]
I am upgrading a large build-system to use Maven2 instead of Ant, and we have two related requirements that I'm stuck on: 1. We need to generate a time-stamped artifact, so a part of the *package* phase (or wherever), instead of building ``` project-1.0-SNAPSHOT.jar ``` we should be building ``` project-1.0-20090803125803.jar ``` (where the `20090803125803` is just a `YYYYMMDDHHMMSS` time-stamp of when the jar is built). The only real requirement is that the time-stamp be a part of the generated file's filename. 2. The same time-stamp has to be included within a *version.properties* file inside the generated jar. This information is included in the generated *pom.properties* when you run, e.g., `mvn package` but is commented out: ``` #Generated by Maven #Mon Aug 03 12:57:17 PDT 2009 ``` Any ideas on where to start would be helpful! Thanks!
Maven versions 2.1.0-M1 or newer have built in special variable `maven.build.timestamp`. ``` <build> <finalName>${project.artifactId}-${project.version}-${maven.build.timestamp}</finalName> </build> ``` See Maven [documentation](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Available_Variables) for more details. --- For older Maven versions a look at [maven-timestamp-plugin](http://code.google.com/p/maven-timestamp-plugin/) or [buildnumber-maven-plugin](http://mojo.codehaus.org/buildnumber-maven-plugin/index.html). If you use maven-timestamp-plugin, you can use something like this to manipulate resulting artifact name. ``` <build> <finalName>${project.artifactId}-${project.version}-${timestamp}</finalName> </build> ``` And this configuration for buildnumber-maven-plugin should create a ${timestamp} property which contains the timestamp value. There doesn't seem to be a way to create the *version.properties* file directly with this plugin. ``` <configuration> <format>{0,date,yyyyMMddHHmmss}</format> <items> <item>timestamp</item> </items> </configuration> ``` [These](http://apollo.ucalgary.ca/tlcprojectswiki/index.php/Public/Project_Versioning_-_Best_Practices#Build_Versioning) [three](http://www.gadberry.com/aaron/2007/05/28/inject-build-time-timestamp-property-using-maven/) [sites](http://pteropus.blogspot.com/2007/03/from-maven-to-mvn-part-5.html) are also worth checking out.
If you use a version of Maven >= 2.1.0-M1, then you can use the ${maven.build.timestamp} property. For more info, see: <http://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Available_Variables>
How do I add time-stamp information to Maven artifacts?
[ "", "java", "maven-2", "ant", "upgrade", "" ]
I'm writing to a file as shown below. I am ONE HUNDRED % SURE there are no line breaks in the variables being written to the file. However, at an arbitrary character count in every line printed to Notepad of applicable length, a line break is created. However, pressing delete at the end of the file (even holding delete) to get rid of any non-printing character such as a line break has no effect. Pressing backspace before the first character of any line affected by this deletes the last character on the previous line, but does get rid of the line break. Writing after the last character is immediately moved to the next line. I have tested on a new line, holding a character just to see if i can get past the point at which the word wrap begins. I can, but not where the c# has written to. I have tried TYPE KEYWORDS.LOG in the command, and it does not print the line breaks, so I do not (think) it will effect my reading the file by line later. But is this a glitch in Notepad? In C#? In IO.StreamWriter? In my code? (I don't think so?) Is it simply a property I am unaware of? **OBVIOUSLY, WORD WRAP IS NOT ON. BUT THANKS. . .** resizing the window does not wrap the text, or change the effects I have described at all. ``` // OPEN STREAM TO KEYWORDS.LOG StreamWriter fileWrite = new StreamWriter("KEYWORDS.LOG"); for (int i=0;i<Referrals.Count();i++) { // FIRST THE URL Console.Write("\n\n{0}\n-", Referrals[i].URL); // NOW TO THE FILE! fileWrite.Write("{0}@", Referrals[i].URL); var SortedKeys = from k in Referrals[i].Keywords.Keys orderby Referrals[i].Keywords[k] descending select k; foreach (string Phrase in SortedKeys) { // NOW TO THE CONSOLE Console.Write("\t({0}) {1}\n", Referrals[i].Keywords[Phrase], Phrase); // NOW TO THE FILE! fileWrite.Write("##{0}##{1}", Referrals[i].Keywords[Phrase], Phrase); } // LINE BREAK FOR FILE! fileWrite.WriteLine(""); } // CLOSE FILE STREAM fileWrite.Close(); ```
It probably isn't arbitrary, you just haven't seen the reason. Have a look at [C# TextWriter inserting line break every 1024 characters](https://stackoverflow.com/questions/908119/c-textwriter-inserting-line-break-every-1024-characters/908135) The max length is 1024. Paste some example text if you can ;D
This is definitely not a word wrap issue. I encountered this issue in notepad using a previous version of windows (XP, I think) and the limit was 4096 characters. Today I tried it in windows 7's notepad and the limit is 1024 characters. Several other text editors I have tried impose a "characters per line" limit that is often undocumented. I rarely encounter a situation where I need more than a few hundred characters per line, but I see no reason to impose a limit. I first encountered the problem when creating ASCII stereograms. I wanted one that was big enough to print on a poster and I was looking at it in notepad. As soon as I generated one over 4096 characters wide, every line was wrapped. It looked awful. These text viewers are not actually inserting any line breaks into the text. They are just altering the way they display the text. That is why you can delete the last character of the "line" when your cursor is at the beginning of the next "line". I put "line" in quotes because it is not truly a line. You are actually deleting text somewhere in the middle of the real line of text. Assuming the text editor is well-behaved, when you save the file, it will still have the long line. If you later view the text in a viewer capable of displaying long enough lines, it should display correctly.
Writing to Notepad wraps at arbitrary point?
[ "", "c#", "word-wrap", "notepad", "" ]
I implemented dynamic loading of plugins in the following way: ``` function processPlugin( $plgFile, $db ) { require_once( $plgFile ); $plgin = new PlginImpl(); $plgin->setDb($db); $ret = $plgin->process(); return $ret; } ``` Each plugin defines a class named `PlginImpl`, which works fine. But it should be possible to call further plugins specified within within the return value of `process()`. That would call the same method specified above, but fails with: ``` Fatal error: Cannot redeclare class PlginImpl in .. ``` Please note that each plugin is a class, i.e.: ``` class PlginImpl extends Plugin implements PluginInterface ``` `Plugin` offer some useful functions while `PluginInterface` defines i.e. `process()`. I assume that the fact that all plugins are named PlginImpl causes the problem, hence my question: is there a way to unload a class (`PlginImpl`) after loading it with `require_once`? Or is there an entirely different approach I should follow? --- **EDIT** I tried without succeeding the following things: * unset `$plgin` after `process()` * calling `__destruct()` - it doesn't work neither within `processPlugin()` nor within the `process` method
Since you can't unload a class after you've loaded it, the only option you have is to rename each plugin. PluginX, PluginY, etc., but it shouldn't matter as you can just force them to use the plugin interface as you showed. To load a specific plugin, you could simply have something like solomongaby suggests, but instead of a filename, you pass it the name of the plugin.. something like this: ``` function loadPlugin($pluginName) { require_once $pluginName . '.php'; $plugin = new $pluginName; //do whatever with $plugin } ```
Another option, though I don't recommend it, is to use [runkit\_import](http://ca.php.net/manual/en/function.runkit-import.php).
Unload dynamic class in PHP
[ "", "php", "" ]
I am trying to build a Visual C++ 2008 DLL using SDL\_Mixer 1.2: <http://www.libsdl.org/projects/SDL_mixer/> This is supposedly from a build made for Visual C++, but when I include SDL\_mixer.h I get error **C2143**: "**syntax error : missing ';' before '['**". The problem line is: const char[] MIX\_EFFECTSMAXSPEED = "MIX\_EFFECTSMAXSPEED"; Is this because of the use of the dynamic array construct "char[]", instead of "char\*"? All the expressions in the file are wrapped by "`extern "C" {`".
My bad. Although the answers here are correct regarding C construct, the actual problem was that I had included a "D" language file instead of the C version.
move the square brackets after the variable name ``` const char MIX_EFFECTSMAXSPEED[] = "MIX_EFFECTSMAXSPEED"; ```
Syntax error compiling header containing "char[]"
[ "", "c++", "visual-c++", "" ]
I've got an idea for caching that I'm beginning to implement: [Memoizing function](http://en.wikipedia.org/wiki/Memoization)s and storing the return along with a hash of the function signature in [Velocity](http://en.wikipedia.org/wiki/Velocity). Using [PostSharp](http://www.postsharp.org/), I want to check the cache and return a rehydrated representation of the return value instead of calling the function again. I want to use attributes to control this behavior. Unfortunately, this could prove dangerous to other developers in my organization, if they fall in love with the performance gain and start decorating every method in sight with caching attributes, including some with *side effects*. I'd like to kick out a compiler warning when the memoization library suspects that a function may cause side effects. How can I tell that code may cause side effects using CodeDom or Reflection?
This is an extremely hard problem, both in practice and in theory. We're thinking hard about ways to either prevent or isolate side effects for precisely your scenarios -- memoization, [automatic parallelization](http://www.bluebytesoftware.com/blog/2009/07/27/OnEffectsAndUbiquitousParallelism.aspx), and so on -- but it's difficult and we are still far from a workable solution for C#. So, no promises. (Consider switching to Haskell if you really want to eliminate side effects.) Unfortunately, even if a miracle happened and you found a way to prevent memoization of methods with side effects, you've still got some *big* problems. Consider the following: 1) What if you memoize a function that is itself calling a memoized function? That's a good situation to be in, right? You want to be able to compose memoized functions. But memoization has a side effect: it adds data to a cache! So immediately you have a meta-problem: you want to tame side effects, but only "bad" side effects. The "good" ones you want to encourage, the bad ones you want to prevent, and it is hard to tell them apart. 2) What are you going to do about exceptions? Can you memoize a method which throws an exception? If so, does it always throw the same exception, or does it throw a new exception every time? If the former, how are you going to do it? If the latter, now you have a memoized function which has two different results on two different calls because two different exceptions are thrown. Exceptions can be seen as a side effect; it is hard to tame exceptions. 3) What are you going to do about methods which do not have a side effect but are nevertheless *impure* methods? Suppose you have a method GetCurrentTime(). That doesn't have a side effect; nothing is mutated by the call. But this is still not a candidate for memoization because any two calls are *required* to produce different results. **You don't need a side-effects detector, you need a purity detector.** I think your best bet is to solve the *human* problem via education and code reviews, rather than trying to solve the hard *technical* problem.
Simply speaking you can't with either CodeDom or Reflection. To accurately determine whether or not a method causes side effects you must understand what actions it is taking. For .Net that means cracking open the IL and interperting it in some manner. Neither Reflection or CodeDom give you this capability. * CodeDom is a method for generating code into an application and only has very limited inspection capabilities. It's essentially limited to the subset of the language understood by the various parsing enginse. * Reflections strength lies in it's ability to inspect metadata and not the underlying IL of the method bodies. MetaData can only give you a very limited set of information as to what does and does not cause side effects.
How can I programmatically detect side effects (compile time or run time)?
[ "", "c#", "memoization", "side-effects", "" ]
I'm trying to bind some data to a WPF listview. One of the properties of my data type is of type `byte[]` and I'd like it to be shown as a comma-delimited string, so for example `{ 12, 54 }` would be shown as `12, 54` rather than as `Byte[] Array`. I think I want to make a custom `DataTemplate` but I'm not sure. Is that the best way? If so, how do I do it? If not, what is the best way? EDIT: I only want to use this for one column - the other properties are displayed fine as they are.
I would suggest using a ValueConverter: ``` [ValueConversion(typeof(byte []), typeof(string))] public class ByteArrayConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { byte [] bytes = (byte [])value; StringBuilder sb = new StringBuilder(100); for (int x = 0; x<bytes.Length; x++) { sb.Append(bytes[x].ToString()).Append(" "); } return sb.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } #endregion } ``` In your xaml, you'd add it to your binding like this: ``` <Window.Resources> <local:ByteArrayConverter x:Key="byteArrayConverter"/> </Window.Resources> ... "{Binding ByteArrayProperty, Converter={StaticResource byteArrayConverter}}" ```
I would create a `ValueConverter` that creates the comma-delimited string. Then you can bind directly to the `byte[]`, but specify the converter in the binding. (No need for me to put code when Mark's answer is good.)
How do I get a WPF listview to format a byte array as a comma-delimited string?
[ "", "c#", "wpf", "data-binding", "listview", "datatemplate", "" ]
I am starting the process of writing an application, one part of which is to decode bar codes, however I'm off to a bad start. I am no bar code expert and this is not a common bar code type, so I'm in trouble. I cannot figure out what type of bar code this is, which I have to decode. I have looked on Wikipedia and some other sites with visual descriptions of different types of bar codes (and how to identify them), however I cannot identify it. Please note that I have tried several free bar code decoding programs and they have all failed to decode this. So here is a picture of that bar code: [alt text http://www.shrani.si/f/2B/4p/4UCVyP72/barcode.jpg](http://www.shrani.si/f/2B/4p/4UCVyP72/barcode.jpg) I hope one of you can recognize it. Also if anyone has worked with this before and knows of a library that can decode them (from an image), I'd love to hear about them. I'm very thankful for any additional pointers I can receive. Thank you.
zbar thinks it's Code 128 but the decoded string is suspiciously different than the barcode's own caption. Maybe it's a charset difference? ``` ~/src/zebra-0.5/zebraimg$ ./zebraimg ~/src/barcode/reader/barcode.jpg CODE-128:10657958011502540742 scanned 1 barcode symbols from 1 images in 0.04 seconds ``` My old copy was called zebra but the library is now called zbar. <http://sourceforge.net/projects/zbar/>
I don't recognize this bar code - but here are a few sites that might help you (libraries etc.) - assuming you use C# and .NET (you didn't specify in your question): * <http://www.idautomation.com/csharp/> * <http://www.bokai.com/barcode.net.htm>
What type of BarCode is this?
[ "", "c#", "barcode", "decoding", "" ]
Upon trying to start a Pinax app, I receive the following error: ``` Error: No module named notification ``` Below are the steps I took ``` svn co http://svn.pinaxproject.com/pinax/trunk/ pinax cd pinax/pinax/projects/basic_project ./manage.py syncdb ``` Any suggestions? --- **UPDATE:** Turns out there are some bugs in the SVN version. Downloading the latest release solved my problem. If any one has any other suggestions on getting the trunk working, they would still be appreciated.
I'd avoid the svn version all together. It's unmaintained and out of date. Instead, use the git version at <http://github.com/pinax/pinax> or (even better) the recently release 0.7b3 downloadable from <http://pinaxproject.com>
Two thoughts: 1. Check all of your imports to make sure that notification is getting into the namespace. 2. You may be missing quotes around an import path (eg. in your urls.py: (r'^test', 'mysite.notification') -- sometimes I forget the quotes around the view)
Error starting Django with Pinax
[ "", "python", "django", "pinax", "" ]
I'm trying to make changes to some legacy code. I need to fill a `char[] ext` with a file extension gotten using `filename.Right(3)`. Problem is that I don't know how to convert from a `CStringT` to a `char[]`. There has to be a really easy solution that I'm just not realizing... TIA.
Well you can always do this even in unicode ``` char str[4]; strcpy( str, CStringA( cString.Right( 3 ) ).GetString() ); ``` If you know you AREN'T using unicode then you could just do ``` char str[4]; strcpy( str, cString.Right( 3 ).GetString() ); ``` All the original code block does is transfer the last 3 characters into a non unicode string (CStringA, CStringW is definitely unicode and CStringT depends on whether the UNICODE define is set) and then gets the string as a simple char string.
If you have access to ATL, which I imagine you do if you're using CString, then you can look into the [ATL conversion classes](http://msdn.microsoft.com/en-us/library/87zae4a3%28VS.80%29.aspx) like CT2CA. ``` CString fileExt = _T ("txt"); CT2CA fileExtA (fileExt); ``` If a conversion needs to be performed (as when compiling for Unicode), then CT2CA allocates some internal memory and performs the conversion, destroying the memory in its destructor. If compiling for ANSI, no conversion needs to be performed, so it just hangs on to a pointer to the original string. It also provides an implicit conversion to `const char *` so you can use it like any C-style string. This makes conversions really easy, with the caveat that if you need to hang on to the string after the CT2CA goes out of scope, then you need to copy the string into a buffer under your control (not just store a pointer to it). Otherwise, the CT2CA cleans up the converted buffer and you have a dangling reference.
CStringT to char[]
[ "", "c++", "cstring", "" ]
Is there a way to make a HTML select element call a function each time its selection has been changed programmatically? Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example. Here's an example: ``` <body> <p> <select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select> <input type="button" onclick="test();" value="Add an option and select it." /> </p> <script type="text/javascript"> var inc = 1; var sel = document.getElementById('sel1'); function test() { inc++; var o = new Option('n'+inc, inc); sel.options[sel.options.length] = o; o.selected = true; sel.selectedIndex = sel.options.length - 1; } function myfunction() { document.title += '[CHANGED]'; } </script> </body> ``` Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)? Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?). Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed. as for the answer to your question > Is there any way to make test() call > myfunction() without changing test() > (or adding an event on the button)? yes, by using jquery AOP <http://plugins.jquery.com/project/AOP> , it gives an easy-ish solution. ``` <body> <p> <select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select> <input type="button" onclick="test();" value="Add an option and select it." /> </p> <script type="text/javascript"> var inc = 1; var sel = document.getElementById('sel1'); function test() { inc++; var o = new Option('n'+inc, inc); sel.options[sel.options.length] = o; o.selected = true; sel.selectedIndex = sel.options.length - 1; } function myfunction() { document.title += '[CHANGED]'; } //change to aop.after if you want to call afterwards jQuery.aop.before( {target: window, method: 'test'}, function() { myfunctino(); } ); </script> </body> ```
Define your own change function that calls the framework function and then calls a callback function. e.g.: ``` function change(callback) { frameworkchange(); callback(); } ```
Detect programmatical changes on a html select box
[ "", "javascript", "html", "events", "html-select", "" ]
In C++, I know that the compiler can choose to initialize static objects in any order that it chooses (subject to a few constraints), and that in general you cannot choose or determine the static initialization order. However, once a program has been compiled, the compiler has to have made a decision about what order to initialize these objects in. **Is there any way to determine, from a compiled program with debugging symbols, in what order static constructors will be called?** The context is this: I have a sizeable program that is suddenly segfaulting before main() when it is built under a new toolchain. Either this is a static initialization order problem, or it is something wrong with one of the libraries that it is loading. However, when I debug with gdb, the crash location is simply reported as a raw address without any symbolic information or backtrace. I would like to decide which of these two problems it is by placing a breakpoint at the constructor of the very first statically-initialized object, but I don't know how to tell which object that is.
Matthew Wilson provides a way to answer this question in [this section](http://my.safaribooksonline.com/0321228774/ch11#ch11lev2sec2) (Safari Books Online subscription required) of [*Imperfect C++*](https://rads.stackoverflow.com/amzn/click/com/0321228774). (Good book, by the way.) To summarize, he creates a `CUTrace.h` header that creates a static instance of a class that prints the filename of the including source file (using the nonstandard preprocessor macro `__BASE_FILE__`) when created, then he includes `CUTrace.h` in every source file. This requires a recompilation, but the #include "CUTrace.h" can easily be added and removed via a script, so it shouldn't be too hard to set up.
In G++ on Linux, static constructor and destructor ordering is determined by function pointers in the .ctors and .dtors sections. Note that with sufficient debugging available, you can actually get a backtrace: ``` (gdb) bt #0 0xb7fe3402 in __kernel_vsyscall () #1 0xb7d59680 in *__GI_raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64 #2 0xb7d5cd68 in *__GI_abort () at abort.c:88 #3 0x08048477 in foo::foo() () #4 0x0804844e in __static_initialization_and_destruction_0(int, int) () #5 0x0804846a in global constructors keyed to foo_inst () #6 0x0804850d in __do_global_ctors_aux () #7 0x08048318 in _init () #8 0x080484a9 in __libc_csu_init () #9 0xb7d4470c in __libc_start_main (main=0x8048414 <main>, argc=1, ubp_av=0xbfffcbc4, init=0x8048490 <__libc_csu_init>, fini=0x8048480 <__libc_csu_fini>, rtld_fini=0xb7ff2820 <_dl_fini>, stack_end=0xbfffcbbc) at libc-start.c:181 #10 0x08048381 in _start () at ../sysdeps/i386/elf/start.S:119 ``` This is with debugging symbols for libc and libstdc++ installed. As you can see, the crash here occured in the foo::foo() constructor for the static object foo\_inst. If you want to break into the initialization process, you could then set a breakpoint on \_\_do\_global\_ctors\_aux and step through its disassembly, I suppose. Or just wait for it to crash to get the backtrace like the above.
Determine static initialization order after compilation?
[ "", "c++", "gdb", "initialization", "g++", "segmentation-fault", "" ]
How do I construct a SQL query (MS SQL Server) where the "where" clause is case-insensitive? ``` SELECT * FROM myTable WHERE myField = 'sOmeVal' ``` I want the results to come back ignoring the case
In the default configuration of a SQL Server database, string comparisons **are** case-insensitive. If your database overrides this setting (through the use of an alternate collation), then you'll need to specify what sort of collation to use in your query. ``` SELECT * FROM myTable WHERE myField = 'sOmeVal' COLLATE SQL_Latin1_General_CP1_CI_AS ``` Note that the collation I provided is just an example (though it will more than likely function just fine for you). A more thorough outline of SQL Server collations can be found [here](http://msdn.microsoft.com/en-us/library/ms144250.aspx).
Usually, string comparisons are case-insensitive. If your database is configured to case sensitive collation, you need to force to use a case insensitive one: ``` SELECT balance FROM people WHERE email = 'billg@microsoft.com' COLLATE SQL_Latin1_General_CP1_CI_AS ```
SQL server ignore case in a where expression
[ "", "sql", "sql-server", "where-clause", "case-insensitive", "" ]
I have the following list item ``` public List<Configuration> Configurations { get; set; } public class Configuration { public string Name { get; set; } public string Value { get; set; } } ``` How can I pull an item in configuration where name = value? For example: lets say I have 100 configuration objects in that list. How can I get : Configurations.name["myConfig"] Something like that? **UPDATE: Solution for .net v2 please**
Using the [`List<T>.Find`](http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx) method in C# 3.0: ``` var config = Configurations.Find(item => item.Name == "myConfig"); ``` In C# 2.0 / .NET 2.0 you can use something like the following (syntax could be slightly off as I haven't written delegates in this way in quite a long time...): ``` Configuration config = Configurations.Find( delegate(Configuration item) { return item.Name == "myConfig"; }); ```
It seems like what you really want is a Dictionary (<http://msdn.microsoft.com/en-us/library/xfhwa508.aspx>). Dictionaries are specifically designed to map key-value pairs and will give you much better performance for lookups than a List would.
Getting an item in a list
[ "", "c#", "list", "" ]
I need to populate an ASP.NET menu control with hierarchical structure with menu items that can be constantly changed, from a database (categories with n levels of sub categories). There are some approaches for that and I would like to hear which one is the most efficient one. I have those in mind: 1. Retrieving data from database and converting it to xml then transforming it with customized XSLT file and binding it to Menu control 2. Retrieving data from database and while looping through (recursive), inserting menu items and children to the menu control 3. SQL Site Map Provider (thanks to Made4Print) 4. Something else?
The ASP.NET Menu Control can use a .SiteMap file through a SiteMapDataSource. You can implement your own SiteMapProvider, this way you can have your SiteMap heirarchy within your database and wireup the same components making things more dyanamic. Here is an example: <http://weblogs.asp.net/scottgu/archive/2006/01/11/435108.aspx> HTH
If you want to do this, I would definitely recommend option 2, since it contains one level of transformation less than option 1. If you already loop through the menu items and their hiearchies, you might as well build up the menu items and subitems directly - I don't see any big benefit from taking a detour over XML and then through XSLT into a menu structure, really. Marc PS: Option 3 (the SQL Sitemap provider) also sounds like a really good idea, if the site map structure and options are good enough for you (they usually should be). I would probably try that option first, and go from there.
Populating Menu from a database
[ "", "c#", "asp.net", "sql-server", "" ]
I want to create a pie chart in JavaScript. On searching I found the Google Charts API. Since we are using jQuery I found that there is [jQuery integration for Google Charts](http://www.maxb.net/scripts/jgcharts/include/demo) available. But my problem is here the actual data is sent to the Google server for creating the charts. Is there a way to prevent the data from being sent to Google? I am concerned about sending my data to a third party.
[jqPlot](http://www.jqplot.com/index.php) looks pretty good and it is open source. Here's a link to the most impressive and up-to-date [jqPlot examples](http://www.jqplot.com/deploy/dist/examples/).
# [Flot](http://www.flotcharts.org/) ## Limitations: lines, points, filled areas, bars, pie and combinations of these From an interaction perspective, Flot by far will get you as close as possible to Flash graphing as you can get with `jQuery`. Whilst the graph output is pretty slick, and great looking, you can also interact with data points. What I mean by this is you can have the ability to hover over a data point and get visual feedback on the value of that point in the graph. The trunk version of flot supports pie charts. Flot Zoom capability. On top of this, you also have the ability to select a chunk of the graph to get data back for a particular “zone”. As a secondary feature to this “zoning”, you can also select an area on a graph and zoom in to see the data points a little more closely. *Very cool*. --- # [Sparklines](http://omnipotent.net/jquery.sparkline/) ## Limitations: Pie, Line, Bar, Combination Sparklines is my favourite mini graphing tool out there. Really great for dashboard style graphs (think Google Analytics dashboard next time you login). Because they’re so tiny, they can be included in line (as in the example above). Another nice idea which can be used in all graphing plugins is the self-refresh capabilities. Their Mouse-Speed demo shows you the power of live charting at its best. --- # [Query Chart 0.21](http://www.reach1to1.com/sandbox/jquery/jqchart/) ## Limitations: Area, Line, Bar and combinations of these jQuery Chart 0.21 isn’t the nicest looking charting plugin out there it has to be said. It’s pretty basic in functionality when it comes to the charts it can handle, however it can be flexible if you can put in some time and effort into it. Adding values into a chart is relatively simple: ``` .chartAdd({ "label" : "Leads", "type" : "Line", "color" : "#008800", "values" : ["100","124","222","44","123","23","99"] }); ``` --- # [jQchart](http://jsgt.org/lib/jquery/plugin/jqchart/sample/v003/test-use-gradient.html) ## Limitations: Bar, Line jQchart is an odd one, they’ve built in animation transistions and drag/drop functionality into the chart, however it’s a little clunky – and seemingly pointless. It does generate nice looking charts if you get the `CSS` setup right, but there are better out there. --- # [TufteGraph](http://xaviershay.github.com/tufte-graph/) ## Limitations: Bar and Stacked Bar Tuftegraph sells itself as “pretty bar graphs that you would show your mother”. It comes close, Flot is prettier, but Tufte does lend itself to be very lightweight. Although with that comes restrictions – there are few options to choose from, so you get what you’re given. Check it out for a quick win bar chart.
Pie chart with jQuery
[ "", "javascript", "jquery", "jquery-plugins", "google-visualization", "" ]
``` public void wahey(List<Object> list) {} wahey(new LinkedList<Number>()); ``` The call to the method will not type-check. I can't even cast the parameter as follows: ``` wahey((List<Object>) new LinkedList<Number>()); ``` From my research, I have gathered that the reason for not allowing this is type-safety. If we were allowed to do the above, then we could have the following: ``` List<Double> ld; wahey(ld); ``` Inside the method wahey, we could add some Strings to the input list (as the parameter maintains a `List<Object>` reference). Now, after the method call, ld refers to a list with a type `List<Double>`, but the actual list contains some String objects! This seems different to the normal way Java works without generics. For instance: ``` Object o; Double d; String s; o = s; d = (Double) o; ``` What we are doing here is essentially the same thing, except this will pass compile-time checks and only fail at run-time. The version with Lists won't compile. This leads me to believe this is purely a design decision with regards to the type restrictions on generics. I was hoping to get some comments on this decision?
What you are doing in the "without generics" example is a cast, which makes it clear that you are doing something type-unsafe. The equivalent with generics would be: ``` Object o; List<Double> d; String s; o = s; d.add((Double) o); ``` Which behaves the same way (compiles, but fails at runtime). The reason for not allowing the behavior you're asking about is because it would allow *implicit* type-unsafe actions, which are much harder to notice in code. For example: ``` public void Foo(List<Object> list, Object obj) { list.add(obj); } ``` This looks perfectly fine and type-safe until you call it like this: ``` List<Double> list_d; String s; Foo(list_d, s); ``` Which also looks type-safe, because you as the caller don't necessarily know what Foo is going to do with its parameters. So in that case you have two seemingly type-safe bits of code, which together end up being type-unsafe. That's bad, because it's hidden and therefore hard to avoid and harder to debug.
Consider if it was... ``` List<Integer> nums = new ArrayList<Integer>(); List<Object> objs = nums objs.add("Oh no!"); int x = nums.get(0); //throws ClassCastException ``` You would be able to add anything of the parent type to the list, which may not be what it was formerly declared as, which as the above example demonstrates, causes all sorts of problems. Thus, it is not allowed.
Why is List<Number> not a sub-type of List<Object>?
[ "", "java", "generics", "casting", "covariance", "" ]
Given the following in PHP: ``` <?php class foo { public $bar; function __construct() { "Foo Exists!"; } function magic_bullet($id) { switch($id) { case 1: echo "There is no spoon! "; case 2: echo "Or is there... "; break; } } } class bar { function __construct() { echo "Bar exists"; } function target($id) { echo "I want a magic bullet for this ID!"; } } $test = new foo(); $test->bar = new bar(); $test->bar->target(42); ``` I'm wondering if it's possible for the 'bar' class to call the 'magic bullet' method of the 'foo' class. The 'bar' instance is contained by the 'foo' instance, but is not in a parent/child relationship with it. In actuality, I've got many various "bar" classes that "foo" has in an array, each doing something different to $id before wanting to pass it off to the "magic\_bullet" function for an end result, so barring a structure change of the class relations, is it possible to access a method of a 'container' instance?
You have to modify your code to provide a relationship. in OOP-speak, we call this [aggregation](http://en.wikipedia.org/wiki/Object_composition#Aggregation). Assuming PHP 4, and the idea of "an array of bars" ``` <?php class foo { var $bars = array(); function __construct() { "Foo Exists!"; } function magic_bullet($id) { switch($id) { case 1: echo "There is no spoon! "; case 2: echo "Or is there... "; break; } } function addBar( &$bar ) { $bar->setFoo( $this ); $this->bars[] = &$bar; } } class bar { var $foo; function __construct() { echo "Bar exists"; } function target($id){ if ( isset( $this->foo ) ) { echo $this->foo->magic_bullet( $id ); } else { trigger_error( 'There is no foo!', E_USER_ERROR ); } } function setFoo( &$foo ) { $this->foo = &$foo; } } $test = new foo(); $bar1 = new bar(); $bar2 = new bar(); $test->addBar( $bar1 ); $test->addBar( $bar2 ); $bar1->target( 1 ); $bar1->target( 2 ); ```
No, it's not possible, as there is no relationship defined. I'd suggest that instead of setting the `$test->bar` property directly, you use a setter, and you can establish a relationship that way. You'll also need to add a `container` property to the `bar` class. Inside class `foo`: ``` function setBar(bar $bar) { $bar->container = $this; $this->bar = $bar; } ``` That sets up a relationship between the objects. Now change the `bar::target($id)` function to: ``` function target($id) { $this->container->magic_bullet($id); } ``` You should be able to do this now: ``` $test = new foo(); $bar = new bar(); $test->setBar($bar); $test->bar->target(42); ```
Reference a method of container object in PHP?
[ "", "php", "" ]
Is there any difference between the Java `PrintWriter` methods `printf` and `format`? The doc says `printf` is a convenience method but if it behaves exactly as `format`, so I don't understand what's convenient about it.
A convenience method is as the name implies -- it exists just for the sake of convenience, not necessarily for function. One common case where convenience methods exist is for methods which have multiple arguments, but some arguments are used in a particular manner. Many times, the same method will be overloaded with different arguments. Take the following code: ``` public void myMethod(int value, boolean hasImportance) { // do something. } public void myMethod(int value) { myMethod(value, true); } ``` In the above example, the `myMethod(int)` method can be thought of as a convenience method for `myMethod(int, boolean)`, as it provides a default argument for one of its parameters. In the case of [`PrintWriter.printf`](http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html#printf(java.util.Locale,%20java.lang.String,%20java.lang.Object...)), it is basically invoking [`PrintWriter.format`](http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html#format(java.util.Locale,%20java.lang.String,%20java.lang.Object...)), but just provides an alternate way of invoking the `format` method. Probably the justification behind the creation of the `printf` method as a convenience method is because the `printf` method's naming conveys the meaning that one is trying to output with formatting rather than just `format`, which doesn't convey the intent that one is trying to perform a output with formatting.
According to [this](http://kickjava.com/src/java/io/PrintWriter.java.htm), they are the same ``` /** ... * <p> An invocation of this method of the form <tt>out.printf(format, * args)</tt> behaves in exactly the same way as the invocation * * <pre> * out.format(format, args) </pre> ... */ public PrintWriter printf(String format, Object ... args) { return format(format, args); } ```
Difference between PrintWriter.printf and PrintWriter.format methods
[ "", "java", "" ]
`$data` contains tabs, leading spaces and multiple spaces. I wish to replace all tabs with a space. Multiple spaces with one single space, and remove leading spaces. In fact somthing that would turn this input data: ``` [ asdf asdf asdf asdf ] ``` Into output data: ``` [asdf asdf asdf asdf] ``` How do I do this?
``` $data = trim(preg_replace('/\s+/g', '', $data)); ```
Trim, replace tabs and extra spaces with single spaces: ``` $data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data)); ```
How do I replace tabs with spaces within variables in PHP?
[ "", "php", "replace", "tabs", "spaces", "" ]
I am using Enterprise Library 4 on one of my projects for logging (and other purposes). I've noticed that there is some cost to the logging that I am doing that I can mitigate by doing the logging on a separate thread. The way I am doing this now is that I create a LogEntry object and then I call BeginInvoke on a delegate that calls Logger.Write. ``` new Action<LogEntry>(Logger.Write).BeginInvoke(le, null, null); ``` What I'd really like to do is add the log message to a queue and then have a single thread pulling LogEntry instances off the queue and performing the log operation. The benefit of this would be that logging is not interfering with the executing operation and not every logging operation results in a job getting thrown on the thread pool. How can I create a shared queue that supports many writers and one reader in a thread safe way? Some examples of a queue implementation that is designed to support many writers (without causing synchronization/blocking) and a single reader would be really appreciated. Recommendation regarding alternative approaches would also be appreciated, I am not interested in changing logging frameworks though.
I wrote this code a while back, feel free to use it. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MediaBrowser.Library.Logging { public abstract class ThreadedLogger : LoggerBase { Queue<Action> queue = new Queue<Action>(); AutoResetEvent hasNewItems = new AutoResetEvent(false); volatile bool waiting = false; public ThreadedLogger() : base() { Thread loggingThread = new Thread(new ThreadStart(ProcessQueue)); loggingThread.IsBackground = true; loggingThread.Start(); } void ProcessQueue() { while (true) { waiting = true; hasNewItems.WaitOne(10000,true); waiting = false; Queue<Action> queueCopy; lock (queue) { queueCopy = new Queue<Action>(queue); queue.Clear(); } foreach (var log in queueCopy) { log(); } } } public override void LogMessage(LogRow row) { lock (queue) { queue.Enqueue(() => AsyncLogMessage(row)); } hasNewItems.Set(); } protected abstract void AsyncLogMessage(LogRow row); public override void Flush() { while (!waiting) { Thread.Sleep(1); } } } } ``` Some advantages: * It keeps the background logger alive, so it does not need to spin up and spin down threads. * It uses a single thread to service the queue, which means there will never be a situation where 100 threads are servicing the queue. * It copies the queues to ensure the queue is not blocked while the log operation is performed * It uses an AutoResetEvent to ensure the bg thread is in a wait state * It is, IMHO, very easy to follow Here is a slightly improved version, keep in mind I performed very little testing on it, but it does address a few minor issues. ``` public abstract class ThreadedLogger : IDisposable { Queue<Action> queue = new Queue<Action>(); ManualResetEvent hasNewItems = new ManualResetEvent(false); ManualResetEvent terminate = new ManualResetEvent(false); ManualResetEvent waiting = new ManualResetEvent(false); Thread loggingThread; public ThreadedLogger() { loggingThread = new Thread(new ThreadStart(ProcessQueue)); loggingThread.IsBackground = true; // this is performed from a bg thread, to ensure the queue is serviced from a single thread loggingThread.Start(); } void ProcessQueue() { while (true) { waiting.Set(); int i = ManualResetEvent.WaitAny(new WaitHandle[] { hasNewItems, terminate }); // terminate was signaled if (i == 1) return; hasNewItems.Reset(); waiting.Reset(); Queue<Action> queueCopy; lock (queue) { queueCopy = new Queue<Action>(queue); queue.Clear(); } foreach (var log in queueCopy) { log(); } } } public void LogMessage(LogRow row) { lock (queue) { queue.Enqueue(() => AsyncLogMessage(row)); } hasNewItems.Set(); } protected abstract void AsyncLogMessage(LogRow row); public void Flush() { waiting.WaitOne(); } public void Dispose() { terminate.Set(); loggingThread.Join(); } } ``` Advantages over the original: * It's disposable, so you can get rid of the async logger * The flush semantics are improved * It will respond slightly better to a burst followed by silence
Yes, you need a producer/consumer queue. I have one example of this in my threading tutorial - if you look my ["deadlocks / monitor methods"](http://pobox.com/~skeet/csharp/threads/deadlocks.shtml) page you'll find the code in the second half. There are plenty of other examples online, of course - and .NET 4.0 will ship with one in the framework too (rather more fully featured than mine!). In .NET 4.0 you'd probably wrap a [`ConcurrentQueue<T>`](http://msdn.microsoft.com/en-us/library/dd267265(VS.100).aspx) in a [`BlockingCollection<T>`](http://msdn.microsoft.com/en-us/library/dd267312(VS.100).aspx). The version on that page is non-generic (it was written a *long* time ago) but you'd probably want to make it generic - it would be trivial to do. You would call `Produce` from each "normal" thread, and `Consume` from one thread, just looping round and logging whatever it consumes. It's probably easiest just to make the consumer thread a background thread, so you don't need to worry about "stopping" the queue when your app exits. That does mean there's a remote possibility of missing the final log entry though (if it's half way through writing it when the app exits) - or even more if you're producing faster than it can consume/log.
How to effectively log asynchronously?
[ "", "c#", "multithreading", "logging", "enterprise-library", "" ]
I've seen a few questions like this around SO but couldn't find anything that's right for me. The chain of events that I would like to occur is as follows: 1. User clicks an ASP.NET button control 2. This fires that button's onclick event, which is a function foo() in the C# codebehind 3. foo() calls some other (unimportant) function which creates a PDF which ends up saved to the server's disk. That function returns the path to the PDF 4. Without any other user interaction, once the PDF is generated, the print dialog box opens in the user's browser to print that PDF What do I need to do to accomplish step 4? Ideally, it would be something I can call in foo(), passing in the path to the PDF, that will trigger the print dialog box in the user's browser (printing the PDF and not the page the from which the onclick fired). I think that I might be able to forward to the URL of the PDF document, and embed some Javascript in the PDF that automatically prints it, but I would rather not - I don't necessarily want to print the PDF every time it's opened (in a browser). Any other good way to do this?
The solution I arrived at was this: Create a new ASP.NET web form (I called mine BinaryData.aspx) to serve as a placeholder for the PDF. In the code behind, the only method should be Page\_Load, which looks like: ``` protected void Page_Load(object sender, System.EventArgs e) { //Set the appropriate ContentType. Response.ContentType = "Application/pdf"; Response.AppendHeader("Pragma", "no-cache"); Response.AppendHeader("Cache-Control", "no-cache"); //Get the physical path to the file. string FilePath = (string)Session["fileLocation"]; if ( FilePath != null ) { string FileName = Path.GetFileName(FilePath); Response.AppendHeader("Content-Disposition", "attachment; filename="+FileName); //Write the file directly to the HTTP content output stream. Response.WriteFile(FilePath); Response.End(); } } ``` The PDF is passed in to the page through the Session variable named "fileLocation". So, all I have to is set that variable, and then call `Response.Redirect("BinaryData.aspx")`. It doesn't automatically print, but it triggers the download of the PDF without leaving the current page (which is good enough for me).
``` Response.Clear() Response.AddHeader("Content-Disposition", "attachment; filename=myfilename.pdf") Response.ContentType = "application/pdf" Response.BinaryWrite(ms.ToArray()) ``` Where ms = a memorystream containing your file (you don't have to write it to disk in-between.) Otherwise if you absolutely have to deal with coming from the hard disk, use: ``` Response.WriteFile("c:\pathtofile.pdf") ```
How do I print an existing PDF from a code-behind page?
[ "", "c#", "asp.net", "pdf", "printing", "" ]
I've got an ASP.Net project with C# and have a Repeater Control on an aspx page that builds up an html table by iterating over a datasource. I want to use the JQuery Flexigrid plug-in to make the table scrollable, but have been unable to figure out how to make it work due to lack of documentation on the plug-in. Does anyone know how to do this, or have sample code to share?
I have never used Flexigrid myself however after looking at the samples on the site I'll offer my suggestions. It looks like what you need to create with your repeater is a properly formatted html table with at least a thead and tbody section. ``` <table id="mytable"> <thead> <tr> <th>header1</th> <th>header2</th> </tr> </thead> <tbody> <tr> <td>table data 1</td> <td>table data 2</td> <tr> </tbody> </table> ``` Once done, making a simple call to the following should create the Flexigrid table with the default settings: ``` $("#mytable").flexigrid(); ``` From there you can pass in what looks to be a ton of options to make it look as pretty as you want. As for the repeater itself, there are a bunch of ways to set it up depending on what you need. Probably the simplest way is as follows: ``` <table> <thead> <tr> <th><asp:label id="header1" runat="server"></asp:label></th> <th><asp:label id="header2" runat="server"></asp:label></th> </tr> </thead> <tbody> <asp:repeater id="myrepeater" runat="server" OnItemDataBound="myrepeater_ItemDataBound"> <ItemTemplate> <tr> <td><asp:label id="data1" runat="server"></asp:label></td> <td><asp:label id="data2" runat="server"></asp:label></td> </tr> </ItemTemplate> </asp:repeater> </tbody> </table> ``` And your data bind event would look something like this: ``` public void myrepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { myDataObject = e.Item.DataItem; Label data1 = e.Item.FindControl("data1"); Label data2 = e.Item.FindControl("data2"); data1.Text = myDataObject.data1; data2.Text = myDataObject.data2; } ```
A simple google search "asp.net+flexigrid" gave me [this](http://webdevdotnet.blogspot.com/2008/07/flexigrid.html) and [this](http://www.codeproject.com/KB/aspnet/FlexiGrid.aspx) I must also mention that support looks to be thin on the ground for flexigrid so you maybe better looking at the better documented [jqGrid](http://trirand.com/jqgrid/jqgrid.html)
JQuery Flexigrid plug-in in ASP.Net
[ "", "c#", "asp.net", "jquery", "" ]
I'm trying [The Next Palindrome](http://www.spoj.com/problems/PALIN/) problem from Sphere Online Judge (SPOJ) where I need to find a palindrome for a integer of up to a million digits. I thought about using Java's functions for reversing Strings, but would they allow for a String to be this long?
You should be able to get a String of length 1. [`Integer.MAX_VALUE`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#MAX_VALUE) always **2,147,483,647** (231 - 1) (Defined by the Java specification, the maximum size of an array, which the String class uses for internal storage) OR 2. `Half your maximum heap size` (since each character is two bytes) **whichever is smaller**.
I believe they can be up to 2^31-1 characters, as they are held by an internal array, and arrays are indexed by integers in Java.
How many characters can a Java String have?
[ "", "java", "string", "" ]
My team looking of java reports engine. We are looking solutions as cheap as possible. What can you recommend?
To complete [gizmo](https://stackoverflow.com/users/9396/gizmo)'s [answer](https://stackoverflow.com/questions/1216490/java-reports-tooling/1216503#1216503), you also have a comprehensive list of [free charting and reporting tools](http://java-source.net/open-source/charting-and-reporting) (including [Eclipse BIRT](http://www.eclipse.org/birt/phoenix/), but also valid alternatives like [OpenReports in its free version](http://oreports.com/))
JasperReports - free, OSS
Java Reports Tooling
[ "", "java", "report", "" ]
How can i use javascript (i assume) to clone a table row like ive beautifully illustrated in the picture below? [![clone row](https://i.stack.imgur.com/7jL5q.png)](https://i.stack.imgur.com/7jL5q.png)
You can hookup a live event to all the buttons. If you give them a class of clone for instance the following will work. ``` $('input.clone').live('click', function(){ //put jquery this context into a var var $btn = $(this); //use .closest() to navigate from the buttno to the closest row and clone it var $clonedRow = $btn.closest('tr').clone(); //append the cloned row to end of the table //clean ids if you need to $clonedRow.find('*').andSelf().filter('[id]').each( function(){ //clear id or change to something else this.id += '_clone'; }); //finally append new row to end of table $btn.closest('tbody').append( $clonedRow ); }); ``` **Please Note:** If you have elements in the table row with id's you will need to do a .each through them and set them to a new value otherwise you will end up with duplicate id's in the dom which is not valid and can play havoc with jQuery selectors You can do this like so
If you want a really simple solution, just use innerHTML: ``` var html = document.getElementById("the row").innerHTML; var row = document.createElement('p'); row.innerHTML= html; document.getElementById("table id").appendChild(row); ```
clone table row
[ "", "javascript", "jquery", "html", "mootools", "" ]
I'm just curious how I go about splitting a variable into a few other variables. For example, say I have the following JavaScript: ``` var coolVar = '123-abc-itchy-knee'; ``` And I wanted to split that into 4 variables, how does one do that? To wind up with an array where ``` array[0] == 123 and array[1] == abc ``` etc would be cool. Or (a variable for each part of the string) ``` var1 == 123 and var2 == abc ``` Could work... either way. How do you split a JavaScript string?
Use the Javascript string split() function. ``` var coolVar = '123-abc-itchy-knee'; var partsArray = coolVar.split('-'); // Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc ```
Use split on string: ``` var array = coolVar.split(/-/); ```
How to parse a string in JavaScript?
[ "", "javascript", "" ]
I've got a single statement running on a ASP.NET page that takes a long time (by long I mean 100ms, which is too long if I want this page to be lightning fast) , and I don't care when it executes as long as executes. What is the best (and hopefully easiest) way to accomplish this?
The easiest way is probably to get it to execute in the threadpool. For example, to make this asynchronous: using System; using System.Threading; ``` class Test { static void ExecuteLongRunningTask() { Console.WriteLine("Sleeping..."); Thread.Sleep(1000); Console.WriteLine("... done"); } static void Main() { ExecuteLongRunningTask(); Console.WriteLine("Finished"); Console.ReadLine(); } } ``` Change the first line of `Main` to: ``` ThreadPool.QueueUserWorkItem(x => ExecuteLongRunningTask()); ``` Be aware that if you pass any arguments in, they'll be captured variables - that could have subtle side-effects in some cases (particularly if you use it in a loop).
If it's 100ms, then don't bother. Your users can't detect a 100ms delay. --- **Edit:** some explanations. If I remember correctly, 100 milliseconds (1/10 second) is near the minimum amount of time that a human can perceive. So, for the purpose of discussion, let me grant that this 100ms can be perceived by the users of the OP's site, and that it is worthwhile to improve performance by 100ms. I assumed from the start that the OP had correctly identified this "long-running" task as a potential source of a 100ms improvement. So, why did I suggest he ignore it? Dealing with multiple threads properly is not easy, and is a source of bugs that are difficult to track down. Adding threads to a problem is usually not a solution, but is rather a source of other problems you simply don't find right away (\*). I had the opportunity once to learn this the hard way, with a bug that could only be reproduced on the fastest eight-cpu system available at the time, and then only by pounding on the thing relentlessly, while simulating a degree of network failure that would have caused the network administrators to be lined up and shot, if it had happened in real life. The bug turned out to be in the Unix OS kernel handling of signals, and was a matter of the arrangement of a handful of instructions. Granted I've never seen anything that bad since then, I've still seen many developers tripped up by multithreading bugs. This question, seemed to be, on the one hand, asking for an "easy way out" via threading, and on the other hand, the benefit was only 100ms. Since it did not appear that the OP already had a well-tested threading infrastructure, it seemed to me that it made better sense to ignore the 100ms, or perhaps to pick up performance some other way. --- (\*) Of course, there are many circumstances where an algorithm can profitably be made parallel and executed by multiple threads, running on multiple cores. But it does not sound like the OP has such a case.
Easiest way to make a single statement async in C#?
[ "", "c#", ".net", "asp.net", "asynchronous", "" ]
Since C++ lacks the `interface` feature of Java and C#, what is the preferred way to simulate interfaces in C++ classes? My guess would be multiple inheritance of abstract classes. What are the implications in terms of memory overhead/performance? Are there any naming conventions for such simulated interfaces, such as `SerializableInterface`?
Since C++ has multiple inheritance unlike C# and Java, yes you can make a series of abstract classes. As for convention, it is up to you; however, I like to precede the class names with an I. ``` class IStringNotifier { public: virtual void sendMessage(std::string &strMessage) = 0; virtual ~IStringNotifier() { } }; ``` The performance is nothing to worry about in terms of comparison between C# and Java. Basically you will just have the overhead of having a lookup table for your functions or a vtable just like any sort of inheritance with virtual methods would have given.
There's really no need to 'simulate' anything as it is not that C++ is missing anything that Java can do with interfaces. From a C++ pointer of view, Java makes an "artificial" disctinction between an `interface` and a `class`. An `interface` is just a `class` all of whose methods are abstract and which cannot contain any data members. Java makes this restriction as it does not allow unconstrained multiple inheritance, but it does allow a `class` to `implement` multiple interfaces. In C++, a `class` is a `class` and an `interface` is a `class`. `extends` is achieved by public inheritance and `implements` is also achieved by public inheritance. Inheriting from multiple non-interface classes can result in extra complications but can be useful in some situations. If you restrict yourself to only inheriting classes from at most one non-interface class and any number of completely abstract classes then you aren't going to encounter any other difficulties than you would have in Java (other C++ / Java differences excepted). In terms of memory and overhead costs, if you are re-creating a Java style class hierarchy then you have probably already paid the virtual function cost on your classes in any case. Given that you are using different runtime environments anyway, there's not going to be any fundamental difference in overhead between the two in terms of cost of the different inheritance models.
How can I simulate interfaces in C++?
[ "", "c++", "interface", "naming-conventions", "abstract-class", "" ]
I'm loading jQuery from google on my site (<http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js>) which is minned and gzip'd. In firefox, the jquery file shows as a 19k request, but Safari shows it as a 56k request. I'm assuming then that Safari is not accepting it as a gzip'd file. What's the deal? It's coming from google and I'm pretty sure it's supposed to be gzip'd
Just thought I'd add to this in case people stumble upon the same question. After playing around with Dev tools more, and looking at response headers, I noticed that the `Content-Length` actually shows the correct gzip'd size. I can only assume then that it is in fact getting the proper compressed version but in the main resource window it displays the uncompressed size, and the headers show the compressed size.
I found this: you **CAN'T use the '.gz'** extension when serving compressed CSS or JS files to Safari. It knows how to handle gziped files, as long as they don't have the '.gz' extension (it's just that weird :) Here's how I serve compressed JS/CSS files to Safari: * use any other extension, just not '.gz' ('.jgz', '.foo' or any other one) * set the gzip-encoded header for your chosen extensions ('Content-encoding: gzip') * set the appropriate MIME type: text/javascript or text/css all other browsers don't care about what extension you use, as long you set the right content type and encoding, so this works across all browsers. I successfully tested this with **Safari 4.0.4 on Windows XP SP3**. And Chrome 4, FF 3.5.5, IE8 and Opera 10.10 on winxp, for the cross-browser compatibility.
safari and gzip
[ "", "javascript", "safari", "" ]
I have recently moved to .net 3.0 (windows forms, C#). I want to know more about predicates and lambda expressions. Where should we use them? Do they improve performance? and how do they work internally. Thanks.
If you search Stack Overflow you'll find about a thousand answers explaining what they're for. In short - a lambda is a way of writing an anonymous method at the point where you want to pass it to another method. Technically the same as the `delegate` syntax for an anonymous method, although with added powers of type inference so you don't need to state the parameter types. A predicate is a method that accepts some value and returns a `bool` - an example would be the argument to `Where`. A lambda that doesn't refer to any external variables gets turned into a private static method with a made-up name. If it refers to instance members of the enclosing class, it becomes an instance method. If it refers to local variables, those variables get "hoisted" into being fields of a compiler-generated class that is allocated when the enclosing method starts running, and the lambda's body becomes a method in that new class. As for performance, they don't make that much difference. They involve the creation of temporary objects, but [I find that these are collected extremely efficiently by the GC](http://smellegantcode.wordpress.com/2009/03/01/the-amazing-speed-of-the-net-garbage-collector/).
If you want to study the different versions of C# and how they different .My suggestion is read the book C.Sharp.in.Depth by jon skeet . This will give you the better understanding of new versions
Predicates and lambda expression
[ "", "c#", "lambda", "predicate", "" ]
I know this is really easy, and I've done it a million times myself; but it's late in the day and I have a brain meltdown. I'm trying to match and replace whole words rather than every occurance. So, I want to replace each occurance of the word 'me' and replace it with 'xxx' Ie. 'Me meets smeg' becomes 'xxx meets smeg' What I DO NOT want is: 'Me meets smeg' becomes 'xxx xxxets sxxg' I know it's preg\_match but I just can't remember the pattern matching for whole words. Please help Oliver.
Try the following regex: ``` $replaced = preg_replace('/\bme\b/i', 'xxx', $subject); ``` `\b` is the **word boundry** as defined in the [**PCRE Reference**](http://www.php.net/manual/en/regexp.reference.backslash.php).
``` $replaced = preg_replace('/\bme\b/i','xxx',$phrase); ```
preg_replace PHP
[ "", "php", "regex", "" ]
I've two tables with the following fields: table1 : OTNAME table2 : SNCODE, description\_text I'm trying to add the two columns of table2 to table1 and update the columns. My query is: ``` alter table table1 add sncode integer alter table table1 add description_text varchar2(30) update table1 set sncode,description_text = (SELECT sncode, description_text FROM table2, table1 WHERE SUBSTR (otname, INSTR (otname,'.', 1, 3) + 1, INSTR (otname, '.', 1, 4) - INSTR (otname,'.', 1, 3) - 1) = sncode) ``` I get an error: ORA 00927 - Missing Equal to Operator, pointing to the second line of my update statement. Appreciate if someone can point me in the right direction. Regards, novice
``` MERGE INTO table1 t1 USING table2 t2 ON (SUBSTR (otname, INSTR (otname,'.', 1, 3) + 1, INSTR (otname, '.', 1, 4) - INSTR (otname,'.', 1, 3) - 1) = t2.sncode)) WHEN MATCHED THEN UPDATE SET t1.sncode = t2.sncode, t1.description_text = t2.description_text ``` You also can simplify your expression: ``` MERGE INTO table1 t1 USING table2 t2 ON (REGEXP_SUBSTR(otname, '[^.]+', 1, 4) = t2.sncode) WHEN MATCHED THEN UPDATE SET t1.sncode = t2.sncode, t1.description_text = t2.description_text ```
Your problem is you are missing brackets around the fields to be updated. Try ``` update table1 set ( sncode,description_text) = (SELECT sncode, description_text FROM table2, table1 WHERE SUBSTR (otname, INSTR (otname,'.', 1, 3) + 1, INSTR (otname, '.', 1, 4) - INSTR (otname,'.', 1, 3) - 1) = sncode) ```
Updating multiple columns of a table
[ "", "sql", "oracle", "oracle10g", "" ]
I'm fairly new to programming and am working for my dissertation on a web crawler. I've been provided by a web crawler but i found it to be too slow since it is single threaded. It took 30 mins to crawl 1000 webpages. I tried to create multiple threads for execution and with 20 threads simultaneously running the 1000 webpages took only 2 minutes. But now I'm encountering "Heap Out of Memory" errors. I'm sure what i did was wrong which was create a **for** loop for 20 threads. What would be the right way to multi-thread the java crawler without giving out the errors? And speaking of which, is multi-threading the solution to my problem or not?
The simple answer (see above) is to increase the JVM memory size. This will help, but it is likely that the real problem is that your web crawling algorithm is creating an in-memory data structure that grows in proportion to the number of pages you visit. If that is the case, the solution maybe to move the data in that data structure to disc; e.g. a database. The most appropriate solution to your problem depends on how your web crawler works, what it is collecting, and how many pages you need to crawl.
My first suggestion is that you increase the heap size for the JVM: <http://www.informix-zone.com/node/46>
How to handle OUT OF MEMORY error for multiple threads in a Java Web Crawler
[ "", "java", "out-of-memory", "" ]
Okay, so, I have a list table with 2 columns: codes and dates. I want to display the LATEST 25 AND tell the user how long ago they were submitted. So, for example: ``` ABCDEF (1 Second Ago) CCDEE (12 Seconds Ago) 329492 (45 Minutes Ago) ``` I've gotten this far: ``` $result = mysql_query("SELECT `code` FROM `fc` ORDER by datetime LIMIT 25") or die(mysql_error()); ``` but, it doesn't do what I want. It does the reverse. It shows what was inputted FIRST, not LAST. My output looks like this: ``` $output .= "<li><a href=\"http://www.***=" . htmlspecialchars(urlencode($fetch_array["code"])) . "\" target=\"_blank\">" . htmlspecialchars($fetch_array["code"]) . "</a></li>"; ``` I have NO Idea how to add the (time since) part. Help? Thanks :)
Consider `ORDER BY datetime DESC` to sort in the other direction. Consider adding `datetime` to the SELECT list, so you can access the posting date in PHP. You can then use PHP date/time functions to calculte the difference between the current date, and the date posted, to work out how long ago the posting was posted. Added: a bit of code to calculate the time since the posting in a friendly format. ``` $seconds = time() - strtotime($fetch_array["datetime"]); if($seconds < 60) $interval = "$seconds seconds"; else if($seconds < 3600) $interval = floor($seconds / 60) . " minutes"; else if($seconds < 86400) $interval = floor($seconds / 3600) . " hours"; else $interval = floor($seconds / 86400) . " days"; // You can keep on going ``` At the end `$interval` contains a textual representation of the interval
Try using ``` order by datetime desc ``` Then in PHP grab the current time, subtract the time returned from the query, and then take a look at this [SO question about relative time](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time) to display your time in the proper units.
Need help with mysql/php outputting data
[ "", "php", "mysql", "" ]
In CakePHP we can use `$this->Auth->allow('someMethod');` to make a page viewable without having to login. How do I make some the same page is not viewable when a user is logged in? An example of this would be a register page which we want to be accessible without user logged in ... but not accessible once a user logged in. I put `$this->Auth->deny('someMethod')` in `isAuthorized()` but it seems to me that if the method is in the allow list then `isAuthorized` is not called when we try to run that page. Any input? Thank you
There are no complex rules like that built into Cake Auth. You'll have to manually check for conditions like this. It's very simple though: ``` // Controller function register() { if ($this->Auth->user()) { $this->redirect(/* somewhere else */); } } ``` Contrary to mlevits answer, you don't need to store anything in the Session, the info is readily available from the AuthComponent itself. <http://book.cakephp.org/view/387/user> There's also an example how to do it by dynamically using `deny()`, but that's not as clear in a simple case like this IMHO. <http://book.cakephp.org/view/383/deny> Also, `deny()` produces an error message ("You're not authorized to access this location"), which is probably not what you want for the user experience in this case.
EDIT: Wasn't aware that CakePHP used a different syntax. You can then use the following to set the Session variable: ``` $this->Session->write('user_id', '<some_user_name>'); ``` Then use this to redirect the user if they are logged in: ``` if ($this->Session->check('user_id')) { $this->redirect('http://google.com'); } ``` And then to destroy a Session use: ``` $this->Session->destroy() ``` [More information about CakePHP Sessions](http://book.cakephp.org/view/398/Methods) Thanks
How to make some pages not available when a user is logged in
[ "", "php", "cakephp", "authentication", "" ]
I'm primarily an Objective-C/Cocoa developer, but I'm trying to implement the Observer pattern in C#.NET, specifically mimicking the NSKeyValueObserving protocols and methodology. I've gotten as far as mimicking NSKVO with manual support, as described in Apple's KVO Programming Guide (see <http://tinyurl.com/nugolr>). Since I'm writing the setValue:forKey: methods myself, I can implement auto KVO notification through there. However, I'd like to somehow implement auto KVO on all properties by dynamically overriding them at runtime. For example, replacing Button.Title.set with: ``` set { this.willChangeValueForKey("title"); title = value; this.didChangeValueForKey("title"); } ``` So, this is my question: How do I dynamically override a method or property at runtime in C#? I've gotten as far as getting and invoking methods and properties by name using Reflection.MethodInfo. Alternatively, can I observe the runtime and find out when a method is about to be/has been called?
After doing extensive research on this subject, it appears that I can't do exactly what I'd like to do with .NET in its current state. * PostSharp's method is done at compile time, meaning I can't dynamically insert my own implementations to methods. * Reflection.Emit allows me to do this dynamically, but it generates a new instance of the created subclass - I need to do this so it works with the original instance. * INotifyPropertyChanging and INotifyPropertyChanged would be perfect if any of the existing .NET classes actually used them. ... so, at the moment I'm a bit stuck. I've put a more detailed piece on what I'm doing and how I'm trying to achieve in a [post](http://danielkennett.org/?p=398) on my blog. Here's hoping .NET 4.0's dynamic dispatch will help!
Dynamic metaprogramming and aspect oriented programming are not yet strongly supported in C#. What you can do, is look at a free tool called [PostSharp](http://www.postsharp.org/) - it allows supports weaving aspects into your code around properties and method calls quite easily. You can implement the [INotifyPropertyChanged](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx) interface (without postsharp) and it can be used in certain contexts to notify observers that a value of a property has changed. However, it still requires that each property actually broadcast the change notification - which generally requires it to be specifically coded to support that. Injecting change notification to existing code (without actually changing the source) is not an easy thing to do in straight-up C#. PostSharp (other other AOP/dynamic proxy libraries) make this sort of thing dramatically easier.
Dynamically overriding a method -or- observing when a method is called at runtime?
[ "", "c#", ".net", "" ]
Does anyone know if there is a DataSet class in Java like there is in .Net? I am familiar with EJB3 and the "java way" of doing data. However, I really still miss the seamless integration between database queries, xml and objects provided by the DataSet class. Has anyone found a Java implementation of DataSet (including DataTable, DataRow, etc)? Edit: Also if anyone has tutorials for the java flavor of DataSet, please share a link.
Have you looked at [javax.sql.rowset.WebRowSet](http://java.sun.com/javase/6/docs/api/javax/sql/rowset/WebRowSet.html)? From the Javadocs: > The WebRowSetImpl provides the > standard reference implementation, > which may be extended if required. > > The standard WebRowSet XML Schema > definition is available at the > following URI: > > ``` > http://java.sun.com/xml/ns/jdbc/webrowset.xsd > ``` > > It describes the standard XML document > format required when describing a > RowSet object in XML and must be used > be all standard implementations of the > WebRowSet interface to ensure > interoperability. In addition, the > WebRowSet schema uses specific SQL/XML > Schema annotations, thus ensuring > greater cross platform > inter-operability. This is an effort > currently under way at the ISO > organization. The SQL/XML definition > is available at the following URI: > > ``` > http://standards.iso.org/iso/9075/2002/12/sqlxml > ```
you may want to look into this open-source library: <https://www.developerfusion.com/project/20506/casperdatasets/> Its easy to use (a lot like using the sql resultset), and its all in-memory. it also supports complex queries and indexes on your data.
DataSet class in Java?
[ "", "java", "dataset", "" ]
I have a code that looks something like this: ``` struct First { int f1; int f2; }; struct Second { First s1; int s2; }; std::vector < Second > secondVec; Second sec; sec.s1 = First(); secondVec.push_back(sec); secondVec.push_back(sec); std::vector < First > firstVec; firstVec.reserve(secondVec.size()); for (std::vector < Second >::iterator secIter = secondVec.begin(); secIter != = secondVec.end(); ++secIter) { firstVec.push_back(secIter->s1); } ``` I'd like to replace this ugly `for` loop with a simple stl function that could perhaps perform the equivalent process. I was thinking that maybe `std::transform` could help me here, but I'm unsure as to how this could be written. I'd also be interested if *boost* has anything to offer here.
If you have TR1 or Boost available, you could try this: ``` std::transform(secondVec.begin(), secondVec.end(), std::back_inserter(firstVec), std::tr1::bind(&Second::s1, _1)); ```
Define functor that will transform Second to First: ``` struct StoF { First operator()( const Second& s ) const { return s.s1; } }; ``` Then use it in the following way: ``` transform( secondVec.begin(), secondVec.end(), back_inserter(firstVec), StoF() ); ``` If your source vector contains a lot of elements you should consider resizing destination vector to make it work faster, as in @Goz answer: ``` firstVec.resize( secondVec.size() ); transform( secondVec.begin(), secondVec.end(), firstVec.begin(), StoF() ); ```
Building a vector from components contained in another vector type
[ "", "c++", "algorithm", "stl", "boost", "" ]
if a page has `<div class="class1">` and `<p class="class1">`, then `soup.findAll(True, 'class1')` will find them both. If it has `<p class="class1 class2">`, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too?
Just in case anybody comes across this question. BeautifulSoup now supports this: ``` Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. In [1]: import bs4 In [2]: soup = bs4.BeautifulSoup('<div class="foo bar"></div>') In [3]: soup(attrs={'class': 'bar'}) Out[3]: [<div class="foo bar"></div>] ``` Also, you don't have to type findAll anymore.
Unfortunately, BeautifulSoup treats this as a class with a space in it `'class1 class2'` rather than two classes `['class1','class2']`. A workaround is to use a regular expression to search for the class instead of a string. This works: ``` soup.findAll(True, {'class': re.compile(r'\bclass1\b')}) ```
Beautiful Soup cannot find a CSS class if the object has other classes, too
[ "", "python", "screen-scraping", "beautifulsoup", "" ]
I have an element that has two classes at all times: ``` <p class="general_description laptop"> <p class="images laptop"> <p class="specs laptop"> ``` One class describes the item (**laptop**) and the other (**general\_description, images, specs**) describes the state that the page needs to be in to present one of three types of information about the item. **How can I show or hide the `<p>` element only if both classes in my selector are present?** For example, if I only want to show the `<p>` element that corresponds to both the `specs` and `laptop` classes, I have tried doing this but it does not work: ``` $(".specs .laptop").show(); ```
$(".specs.laptop").show(); OR you could use the `is()` function in jquery. it takes a selector and tells you if the element conforms to it: ``` $(".specs").is(".laptop"); //returns true if the element has the laptop class ```
IIRC, it is: ``` $(".specs").filter(".laptop").show() ```
How to select an element that must have more than one css class?
[ "", "javascript", "jquery", "css", "css-selectors", "" ]
I'm currently working on an app that allows the user to play (automatically scroll) through a series of local images. Usually there will be five or six on screen at once. The major bottleneck at the moment seems to be the actual loading of the image data from disk. A timer thread calls for the images to be updated every 1/6 of a second and the app is struggling to keep up with that speed. Each image is around 25Kb. I tried creating a rolling cache to try and preload images but this was also getting caught up with itself so ended up slowing down just as much. Every beat of the timer, I'm looping through the six image placeholders loading the next image using the standard ``` Image img = Image.FromFile("filename"); ``` method but thought someone might know of a faster way to get the images off disk. There are between 500 and 20,000 images in each of the six sets so it's too large to load the whole thing into memory at the start. If anyone has suggestions for a faster way to pull these images through, it would be greatly appreciated. --- Edit to add some more detail of application flow. Okay, this is what's happening: User hits 'play' button. Timer thread starts with 1/6 second timeout. Timer callback: ``` Update image index (_index++) for each viewer in list of visible viewers (the forms to display images) { get the filename from the id stored in the viewer check to see if the file exists if it does exist, create new bitmap from image and return that image otherwise return null if returned image isn't null, display it on screen } ``` That's obviously going across a few layers - the image loading goes on in the services layer and then passes this through to presentation and then to the UI but that's the gist of what's happening.
I came across [this page](http://web.archive.org/web/20120707213018/http://weblogs.asp.net/justin_rogers/pages/131704.aspx) which describes how to use the GDI+ API directly to load images. Very simple to use: ``` ImageFast.FromFile(@"C:\MyPhoto.JPG"); ``` --- ***Added to show speed of ImageFast over Image From File method*** This uses the source code found [here](http://web.archive.org/web/20120707213018/http://weblogs.asp.net/justin_rogers/pages/131704.aspx). The code was copied and pasted and required no changes. ``` Stopwatch watch = Stopwatch.StartNew(); string filePath = @"C:\TestImage25k.png"; Image fromFile = Image.FromFile(filePath); watch.Stop(); Console.WriteLine("Image.FromFile Ticks = {0:n}", watch.ElapsedTicks); long fromFileTicks = watch.ElapsedTicks; watch.Reset(); watch.Start(); Image fastImage = ImageFast.FromFile(filePath); watch.Stop(); long fastFileTicks = watch.ElapsedTicks; Console.WriteLine("ImageFast.FromFile Ticks = {0:n}", watch.ElapsedTicks); Console.WriteLine("fromFileTicks - fastFileTicks = {0:n}", fromFileTicks - fastFileTicks); ``` The console output was ``` Image.FromFile Ticks = 19,281,605.00 ImageFast.FromFile Ticks = 7,557,403.00 fromFileTicks - fastFileTicks = 11,724,202.00 ``` You can see the impact of the ImageFast. Over time those 11 million saved ticks will add up.
Easiest might be to put a 'next' and 'previous' button to limit the number of images and preload.
Speed up loading an image from disk in a windows forms (c#.net) app
[ "", "c#", "winforms", "image", "" ]
I would like to know what is the best pattern when returning objects from custom collection classes. To illustrate my problem, here is an example: I have a Customer class: ``` public class Customer { //properties //methods } ``` Then I have a customer collection class: ``` public class Customercollection: Collection<Customer> { public Collection<Customer> FindCustomers() { //calls DAL and gets a Collection of customers Collection<Customer> customers = DAL.GetCustomers(); return customers; } } ``` Now, an alternative version of this method can be: ``` public class Customercollection: Collection<Customer> { public Collection<Customer> FindCustomers() { //calls DAL and gets a Collection of customers Collection<Customer> customers = DAL.GetCustomers(); foreach(Customer c in customers) this.Add(c); return this; } } ``` I would like to discuss Which one is the better approach? And is there any other approach better than two above two?
I would propose a third approach: **Edit:** *I have updated this code example to reflect the OP's comments below.* ``` public class Customer { public static ICollection<Customer> FindCustomers() { Collection<Customer> customers = new Collection<Customer>(); foreach (CustomerDTO dto in DAL.GetCustomers()) customers.Add(new Customer(dto)); // Do what you need to to create the customer return customers; } } ``` Most of the time a custom collection is not needed - I am assuming that this is one of those cases. Also you can add utility methods onto the type (in this case, the `Customer` type) as this aids developer discovery of these methods. (This point is more a matter of taste - since this is a static method you are free to put it in whatever type you wish `CustomerUtility` or `CustomerHelper` for example). My final suggestion is to return an interface type from `FindCustomers()` to give you greater flexibility in the future for implementation changes. Obviously `DAL.GetCustomers()` would have to return some type that implemented `IList<T>` as well but then any API method (especially in a different tier like a data layer) should be returning interface types as well.
In my opinion both of them are a bit weird and confusing. When you extend the Collection class you kind of imply that your class IS a collection - so that it contains the data. I think when you make this method static in the first case it will make the most sense: ``` public class Customercollection: Collection<Customer> { public static Collection<Customer> FindCustomers() { //calls DAL and gets a Collection of customers Collection<Customer> customers = DAL.GetCustomers(); return customers; } } ```
Question regarding custom collections in C#
[ "", "c#", "design-patterns", "" ]
I'm trying to use cURL to grab an external web page to put into my own website, it's basically a "ladder" of a sports team, I contacted them, but they do not have a RSS feed of the ladder, so I'm trying to obtain the ladder by other means, is it possible to grab everything between < table > and < / table > using cURL? I can grab the page that I want using the following code, but I don't need anything else except for the HTML table. ``` $ch = curl_init ("http://www.sportingpulse.com/rpt_ladder.cgi?results=N&round=15&client=1-3909-47801-81021-6151461&pool=-1"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); echo $page = curl_exec($ch); ``` If someone could help me out, that'd be great. Thanks Leanne
You'll need to use curl to grab the contents of the page and string processing to extract the table from the returned string. A simple regex to start would be: ``` /<table>(.*)<\/table/s ``` So if you take your example above, you'd do something like: ``` $page = curl_exec($ch); if (preg_match("/<table>(.*)<\/table/s", $page, $matches)) { echo $matches[1]; } ``` This code will match the first table on the page. You'd need to tweak it to match exactly the HTML you want to extract.
Ok, so I managed to get it working using this (if anyone else wants to know) ``` $ch = curl_init ("http://www.sportingpulse.com/rpt_ladder.cgi?results=N&round=15&client=1-3909-47801-81021-6151461&pool=-1"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $page = curl_exec($ch); preg_match('#<table[^>]*>(.+?)</table>#is', $page, $matches); foreach ($matches as &$match) { $match = $match; } echo '<table>'; echo $matches[1]; echo '</table>'; ``` :)
Can I use cURL to grab a html table?
[ "", "php", "curl", "" ]
I am fairly new to Java and in another Stack Overflow question about [for loops](https://stackoverflow.com/questions/1241946/how-is-a-for-loop-structured-in-java) an answer said that there was two uses of for in Java: ``` for (int i = 0; i < N; i++) { } for (String a : anyIterable) { } ``` I know the first use of for and have used it a lot, but I have never seen the second one. What is it used to do and when would I use it?
The first of the two you specify is a classic C `for` loop. This gives the programmer control over the iteration criteria and allows for three operations: the initialization; the loop test ; the increment expression. Though it is used often to incrementally repeat for a set number of attempts, as in yor example: ``` for (int i=0; i < N : i++) ``` There are many more instances in code where the `for` was use to iterate over collections: ``` for (Iterator iter = myList.iterator(); iter.hasNext();) ``` To aleviate the boilerplating of the second type (where the third clause was often unused), and to compliment the [Generics](http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf) introduced in Java 1.5, the second of your two examples - the enhanced for loop, or the [`for-each loop`](http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html) - was introduced. The second is used with arrays and Generic collections. [See this documentation](http://java.sun.com/developer/JDCTechTips/2005/tt0505.html#2). It allows you to iterate over a generic collection, where you know the type of the `Collection`, without having to cast the result of the `Iterator.next()` to a known type. Compare: ``` for(Iterator iter = myList.iterator; iter.hasNext() ; ) { String myStr = (String) iter.next(); //...do something with myStr } ``` with ``` for (String myStr : myList) { //...do something with myStr } ``` This 'new style' for loop can be used with arrays as well: ``` String[] strArray= ... for (String myStr : strArray) { //...do something with myStr } ```
The "for in" loop is mostly eye-candy that makes code easier to read. (If you pronounce the : as "in"). I use the second type almost exclusively in my own code whenever I'm iterating over a list or array. I still use the regular for loop when dealing with mostly mathematical code, or when I need an "i" to see how many times I've looped.
Uses of 'for' in Java
[ "", "java", "loops", "for-loop", "" ]
I need to determine if a value exists in an array. I am using the following function: ``` Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] == obj) { return true; } } return false; } ``` The above function always returns false. The array values and the function call is as below: ``` arrValues = ["Sam","Great", "Sample", "High"] alert(arrValues.contains("Sam")); ```
``` var contains = function(needle) { // Per spec, the way to identify NaN is that it is not equal to itself var findNaN = needle !== needle; var indexOf; if(!findNaN && typeof Array.prototype.indexOf === 'function') { indexOf = Array.prototype.indexOf; } else { indexOf = function(needle) { var i = -1, index = -1; for(i = 0; i < this.length; i++) { var item = this[i]; if((findNaN && item !== item) || item === needle) { index = i; break; } } return index; }; } return indexOf.call(this, needle) > -1; }; ``` You can use it like this: ``` var myArray = [0,1,2], needle = 1, index = contains.call(myArray, needle); // true ``` [CodePen validation/usage](http://codepen.io/anon/pen/mVRNaJ)
[jQuery](http://docs.jquery.com/Utilities/jQuery.inArray) has a utility function for this: ``` $.inArray(value, array) ``` Returns index of `value` in `array`. Returns `-1` if `array` does not contain `value`. See also [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/array-containsobj-in-javascript)
Determine whether an array contains a value
[ "", "javascript", "arrays", "contains", "" ]
What is a Class library in Java? Is it a collection of classes with in a package, or it is a package that has collection of classes? I'm bit confused. ^\_^
It's a collection of classes, usually bundled up in a [jar file](http://en.wikipedia.org/wiki/JAR_(file_format)). All the classes *may* be in the same Java package, but they don't have to be. A class library in a jar file may also contain resources and meta-data that it needs (e.g. string translations, driver information for other frameworks etc).
Yes, class libraries are just sets of classes in a package. They could be stored in a folder but mostly they are distributed in JARs (Java ARchives), which are just zipped up class files.
What is a Class Library in Java?
[ "", "java", "" ]
What I need is to encrypt string which will show up in 2D barcode(PDF-417) so when someone get an idea to scan it will get nothing readable. Other requirements: * should not be complicated * it should not consist of RSA, PKI infrastructure, key pairs, etc. It must be simple enough to get rid of the people snooping around, and easy to decrypt for other companies interested in getting that data. They call us, we tell them the standard or give them some simple key which can then be used for decryption. Probably those companies could use different technologies so it would be good to stick to some standard which is not tied to some special platform or technology. What do you suggest? Is there some Java class doing `encrypt()` & `decrypt()` without much complication in achieving high security standards?
> This is the first page that shows up via Google and the security > vulnerabilities in all the implementations make me cringe so I'm > posting this to add information regarding encryption for others as it > has been **7 Years** from the original post. I hold a **Masters Degree** in > Computer Engineering and spent a lot of time studying and learning > Cryptography so I'm throwing my two cents to make the internet a > safer place. > > Also, do note that a lot of implementation might be secure for a given > situation, but why use those and potentially accidentally make a > mistake? Use the strongest tools you have available unless you have a > specific reason not to. Overall I highly advise using a library and > staying away from the nitty gritty details if you can. > > **UPDATE 4/5/18:** I rewrote some parts to make them simpler to understand and changed the recommended library from [Jasypt](http://www.jasypt.org/) to [Google's new library Tink](https://github.com/google/tink/), I would recommend completely removing [Jasypt](http://www.jasypt.org/) from an existing setup. **Foreword** I will outline the basics of secure symmetric cryptography below and point out common mistakes I see online when people implement crypto on their own with the standard Java library. If you want to just skip all the details run over to [Google's new library Tink](https://github.com/google/tink/) import that into your project and use AES-GCM mode for all your encryptions and you shall be secure. Now if you want to learn the nitty gritty details on how to encrypt in java read on :) **Block Ciphers** First thing first you need to pick a symmetric key Block Cipher. A Block Cipher is a computer function/program used to create Pseudo-Randomness. Pseudo-Randomness is fake randomness that no computer other than a Quantum Computer would be able to tell the difference between it and real randomness. The Block Cipher is like the building block to cryptography, and when used with different modes or schemes we can create encryptions. Now regarding Block Cipher Algorithms available today, Make sure to **NEVER**, I repeat **NEVER** use [DES](http://en.wikipedia.org/wiki/Data_Encryption_Standard), I would even say NEVER use [3DES](http://en.wikipedia.org/wiki/3DES). The only Block Cipher that even Snowden's NSA release was able to verify being truly as close to Pseudo-Random as possible is [AES 256](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard). There also exists AES 128; the difference is AES 256 works in 256-bit blocks, while AES 128 works in 128 blocks. All in all, AES 128 is considered secure although some weaknesses have been discovered, but 256 is as solid as it gets. Fun fact [DES](http://en.wikipedia.org/wiki/Data_Encryption_Standard) was broken by the NSA back when it was initially founded and actually kept a secret for a few years. Although some people still claim [3DES](http://en.wikipedia.org/wiki/3DES) is secure, there are quite a few research papers that have found and analyzed weaknesses in [3DES](http://en.wikipedia.org/wiki/3DES). **Encryption Modes** Encryption is created when you take a block cipher and use a specific scheme so that the randomness is combined with a key to creating something that is reversible as long as you know the key. This is referred to as an Encryption Mode. Here is an example of an encryption mode and the simplest mode known as ECB just so you can visually understand what is happening: [![ECB Mode](https://i.stack.imgur.com/DOlZl.png)](https://i.stack.imgur.com/DOlZl.png) The encryption modes you will see most commonly online are the following: *ECB CTR, CBC, GCM* There exist other modes outside of the ones listed and researchers are always working toward new modes to improve existing problems. Now let's move on to implementations and what is secure. **NEVER** use ECB this is bad at hiding repeating data as shown by the famous [Linux penguin](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation).[![Linux Penguin Example](https://i.stack.imgur.com/X67ZV.jpg)](https://i.stack.imgur.com/X67ZV.jpg) When implementing in Java, note that if you use the following code, ECB mode is set by default: ``` Cipher cipher = Cipher.getInstance("AES"); ``` **... DANGER THIS IS A VULNERABILITY!** and unfortunately, this is seen all over StackOverflow and online in tutorials and examples. **Nonces and IVs** In response to the issue found with ECB mode nounces also known as IVs were created. The idea is that we generate a new random variable and attach it to every encryption so that when you encrypt two messages that are the same they come out different. The beauty behind this is that an IV or nonce is public knowledge. That means an attacker can have access to this but as long as they don't have your key, they cant do anything with that knowledge. Common issues I will see is that people will set the IV as a static value as in the same fixed value in their code. and here is the pitfall to IVs the moment you repeat one you actually compromise the entire security of your encryption. **Generating A Random IV** ``` SecureRandom randomSecureRandom = new SecureRandom(); byte[] iv = new byte[cipher.getBlockSize()]; randomSecureRandom.nextBytes(iv); IvParameterSpec ivParams = new IvParameterSpec(iv); ``` **Note:** SHA1 is broken but I couldn't find how to implement SHA256 into this use case properly, so if anyone wants to take a crack at this and update it would be awesome! Also SHA1 attacks still are unconventional as it can take a few years on a huge cluster to crack. [Check out details here.](https://shattered.io/) **CTR Implementation** No padding is required for CTR mode. ``` Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); ``` **CBC Implementation** If you choose to implement CBC Mode do so with PKCS7Padding as follows: ``` Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); ``` **CBC and CTR Vulnerability and Why You Should Use GCM** Although some other modes such as CBC and CTR are secure they run into the issue where an attacker can flip the encrypted data, changing its value when decrypted. So let's say you encrypt an imaginary bank message "Sell 100", your encrypted message looks like this "eu23ng" the attacker changes one bit to "eu53ng" and all of a sudden when decrypted your message, it reads as "Sell 900". To avoid this the majority of the internet uses GCM, and every time you see HTTPS they are probably using GCM. GCM signs the encrypted message with a hash and checks to verify that the message has not been changed using this signature. I would avoid implementing GCM because of its complexity. You are better off using [Googles new library Tink](https://github.com/google/tink/) because here again if you accidentally repeat an IV you are compromising the key in the case with GCM, which is the ultimate security flaw. New researchers are working towards IV repeat resistant encryption modes where even if you repeat the IV the key is not in danger but this has yet to come mainstream. Now if you do want to implement GCM, here is a [link to a nice GCM implementation](https://gist.github.com/praseodym/f2499b3e14d872fe5b4a). However, I can not ensure the security or if its properly implemented but it gets the basis down. Also note with GCM there is no padding. ``` Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); ``` **Keys vs Passwords** Another very important note, is that when it comes to cryptography a Key and a Password are not the same things. A Key in cryptography needs to have a certain amount of entropy and randomness to be considered secure. This is why you need to make sure to use the proper cryptographic libraries to generate the key for you. So you really have two implementations you can do here, the first is to use the code found on [this StackOverflow thread for Random Key Generation](https://stackoverflow.com/questions/18228579/how-to-create-a-secure-random-aes-key-in-java). This solution uses a secure random number generator to create a key from scratch that you can the use. The other less secure option is to use, user input such as a password. The issue as we discussed is that the password doesn't have enough entropy, so we would have to use [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2), an algorithm that takes the password and strengthens it. Here is a [StackOverflow implementation I liked](https://stackoverflow.com/a/27928435/2607972). However Google Tink library has all this built in and you should take advantage of it. **Android Developers** One important point to point out here is know that your android code is reverse engineerable and most cases most java code is too. That means if you store the password in plain text in your code. A hacker can easily retrieve it. Usually, for these type of encryption, you want to use Asymmetric Cryptography and so on. This is outside the scope of this post so I will avoid diving into it. An [interesting reading from 2013](https://cs.ucsb.edu/%7Echris/research/doc/ccs13_cryptolint.pdf): Points out that 88% of Crypto implementations in Android were done improperly. **Final Thoughts** Once again I would suggest avoid implementing the java library for crypto directly and use [Google Tink](https://github.com/google/tink/), it will save you the headache as they have really done a good job of implementing all the algorithms properly. And even then make sure you check up on issues brought up on the Tink github, vulnerabilities popup here and there. If you have any questions or feedback feel free to comment! Security is always changing and you need to do your best to keep up with it :)
I'd recommend to use some standard symmetric cypher that is widely available like [DES](http://en.wikipedia.org/wiki/Data_Encryption_Standard), [3DES](http://en.wikipedia.org/wiki/3DES) or [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard). While that is not the most secure algorithm, there are loads of implementations and you'd just need to give the key to anyone that is supposed to decrypt the information in the barcode. [javax.crypto.Cipher](http://java.sun.com/javase/6/docs/api/javax/crypto/Cipher.html) is what you want to work with here. **Let's assume the bytes to encrypt are in** ``` byte[] input; ``` **Next, you'll need the key and [initialization vector](http://en.wikipedia.org/wiki/Initialization_vector) bytes** ``` byte[] keyBytes; byte[] ivBytes; ``` **Now you can initialize the Cipher for the algorithm that you select:** ``` // wrap key data in Key/IV specs to pass to cipher SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); // create the cipher with the algorithm you choose // see javadoc for Cipher class for more info, e.g. Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); ``` **Encryption would go like this:** ``` cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] encrypted= new byte[cipher.getOutputSize(input.length)]; int enc_len = cipher.update(input, 0, input.length, encrypted, 0); enc_len += cipher.doFinal(encrypted, enc_len); ``` **And decryption like this:** ``` cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); byte[] decrypted = new byte[cipher.getOutputSize(enc_len)]; int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0); dec_len += cipher.doFinal(decrypted, dec_len); ```
How to encrypt String in Java
[ "", "java", "encryption", "" ]
I test the code in IE7, FF, Chrome, Safari and this problem occurs in Firefox only. **I have checked that the problem only occurs in FF 3.5.x, but not FF 3.0.x.** I want to make an image animation which has 10 images in total. Currently, I use the following code to do it: ``` for (var i=1;i<=10;i++){ img[i] = new Image(); img[i].src = "images/survey/share_f"+i+".jpg" } var cornerno = 0; function imganimate(){ $("#surveyicon").attr("src",img[cornerno].src); //some logic to change the cornerno setTimeout("imganimate()",1000); } ``` And then change an element's src to loop through the array "img". however, firefox keeps requesting the images continuous (I expect it only requests each unique image just once). What should I do?
This seems a bug in FF3.5.x. Not sure whether the bug has already been fixed.
Try composing the images into a single image file like a sprite map and then use CSS positioning to shift the image around as a background image. It will be much faster and avoid any reloads.
Image animation keeps requesting the images
[ "", "javascript", "jquery", "" ]
I am writing SQL Server deployment scripts which create SQL Server job automatically on a specific SQL Server server/instance. I have found that I can extract the sql statement which can be used to create SQL Server job automatically by using script job as => Create To. My confusion is that, I find the database name and Owner account name are hardcoded in the sql scripts generated. When I am using sqlcmd to execute the sql scripts on another computer to perform deployment, the database name and Owner account name may be different, so I need a way to pass the database name and Owner account name to the SQL Server job creation script and let the script use the provided database name and Owner account name (other than hard coded ones). Any ideas how to do that?
You would need to dynamically create the job script and then execute it. You could try something like the following or change this to a stored proc with input parameters for the job owner and database name. ``` DECLARE @JobName VARCHAR(20) --Job Name DECLARE @Owner VARCHAR(200) --Job Owner DECLARE @DBName VARCHAR(200) --Database Name DECLARE @JobCode VARCHAR(4000) --Create Statement for Job SET @JobName = 'Test2' SET @Owner = 'BrianD' SET @DBName = 'master' SET @JobCode = 'USE msdb GO BEGIN TRANSACTION DECLARE @ReturnCode INT SELECT @ReturnCode = 0 IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N''[Uncategorized (Local)]'' AND category_class=1) BEGIN EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N''JOB'', @type=N''LOCAL'', @name=N''[Uncategorized (Local)]'' IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback END DECLARE @jobId BINARY(16) EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N''' + @JobName + ''', @enabled=1, @notify_level_eventlog=0, @notify_level_email=0, @notify_level_netsend=0, @notify_level_page=0, @delete_level=0, @description=N''No description available.'', @category_name=N''[Uncategorized (Local)]'', @owner_login_name=N''' + @Owner + ''', @job_id = @jobId OUTPUT IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N''Version and Prod Level'', @step_id=1, @cmdexec_success_code=0, @on_success_action=1, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N''TSQL'', @command=N''select SERVERPROPERTY(''''productversion''''), SERVERPROPERTY(''''productlevel'''')'', @database_name=N''' + @DBName + ''', @flags=0 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N''(local)'' IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback COMMIT TRANSACTION GOTO EndSave QuitWithRollback: IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION EndSave: GO' Exec (@JobCode) ``` Hopefully this will get you going in the right direction. If you need more help let me know.
Using the example from BrainD I'd like to point out that his idea of using variables is just fine, however, passing them to the stored procedures using dymanic SQL most certainly isn't the right approach. Rather, use the parameters of the stored procedures to directly pass the variables directly to where they are needed. ``` DECLARE @JobName VARCHAR(20) --Job Name DECLARE @Owner VARCHAR(200) --Job Owner DECLARE @DBName VARCHAR(200) --Database Name DECLARE @JobCode VARCHAR(4000) --Create Statement for Job SET @JobName = 'Test2' SET @Owner = 'BrianD' SET @DBName = 'master' BEGIN TRANSACTION DECLARE @ReturnCode INT SELECT @ReturnCode = 0 IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1) BEGIN EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]' IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback END DECLARE @jobId BINARY(16) EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name= @JobName, @enabled=1, @notify_level_eventlog=0, @notify_level_email=0, @notify_level_netsend=0, @notify_level_page=0, @delete_level=0, @description=N'No description available.', @category_name=N'[Uncategorized (Local)]', @owner_login_name= @Owner, @job_id = @jobId OUTPUT IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Version and Prod Level', @step_id=1, @cmdexec_success_code=0, @on_success_action=1, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N'TSQL', @command=N'select SERVERPROPERTY(''productversion''), SERVERPROPERTY(''productlevel'')', @database_name=@DBName, @flags=0 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)' IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback COMMIT TRANSACTION GOTO EndSave QuitWithRollback: IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION EndSave: GO ```
Create SQL Server job automatically
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-agent", "" ]
I have a ``` <input type='text' id='text' value='' /> ``` How do I programmatically set the value attrribute using JQuery/Javascript
The simple easy way is: ``` $("#text").val ("foo"); ```
It's as easy as this: ``` $("#text").attr("value", "some value"); ```
Jquery/Javascript Setting the attribute value of a textfield
[ "", "javascript", "jquery", "" ]
Canon/Nikon/other cameras save raw output of their sensor in some of their proprietary formats (.CR2, whatever). Is there any Java library designed to read them and convert into manageable BufferedImages? I don't reqlly care here about fully customizable conversion similar to ufraw or imagemagick, rather something simple that "just works" for rendering simple previews of such images.
I've been where you are, and I feel for you. Your best bet is to use an Adobe or dcraw-based program to create thumbnails automatically. Temporary DNG files using Adobe's converter may be easier to use. **IF you insist on doing it in Java, you're about to run into a mountain of pain.** RAW formats change often, have all sorts of crazy nuances and are intentionally hard to work with. Camera makers want you to use THEIR RAW conversion software, to show the camera's abilities at its best and screw Adobe. The guy behind dcraw found that some are camera manufacturers even use encryption now! The existing Java libraries are poor -- JRawIO has improved since I last looked at it, but it supports only a fraction of the formats that dcraw does. In addition to the listed libraries, the [imagero](http://reader.imagero.com/) library *may* provide the ability to display a thumbnail for your image. **From personal experience, don't even think about writing your own RAW file reader.** I tried to do this with a very simple RAW format once (just a solid array of sensor data, 12 bits per pixel). The dcraw source translates badly to Java. You haven't seen such a nightmare of bit-fiddling ever. Took me days to debug problems with byte alignment and endian-ness.
[jrawio](https://jrawio.dev.java.net/) is a plugin for Java Image I/O. With it you can read the raster data, the thumbnails and the metadata from the raw image file.
Reading RAW images from Java
[ "", "java", "image-processing", "" ]
I've got a problem with JDBC. I'have the following code: ``` //blargeparam is a blob column. PreparedStatement pst =connection.prepareStatement("update gcp_processparams_log set blargeparam= ? where idprocessparamslog=1"); pst.setBinaryStream(1,inputStream); ``` I get the following error: ``` Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.T2CPreparedStatement.setBinaryStream(ILjava/io/InputStream;)V ``` My connection string is `jdbc:oracle:oci:@.....` The Oracle version is 11g. From the error message it seems that something is missing but: * when I read from the same blob column (with blob.getBytes) everything works. * The DLL's of the instant client are (correctly) in the library path. * This is the manifest of the Oracle JDBC JAR in my class path: ``` Manifest-Version: 1.0 Specification-Title: Oracle JDBC driver classes for use with JDK14 Sealed: true Created-By: 1.4.2_14 (Sun Microsystems Inc.) Implementation-Title: ojdbc14.jar Specification-Vendor: Oracle Corporation Specification-Version: Oracle JDBC Driver version - "10.2.0.4.0" Implementation-Version: Oracle JDBC Driver version - "10.2.0.4.0" Implementation-Vendor: Oracle Corporation Implementation-Time: Sat Feb 2 11:40:29 2008 ```
It looks that even if the driver 10.2 is compatible with the JDBC3 it may not work with JRE6 as I've found here: [<http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.html#02_03>](http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.html#02_03) Which JDBC drivers support which versions of Javasoft's JDK? pre-8i OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x 8.1.5 OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x 8.1.6SDK THIN Driver - JDK 1.1.x and JDK 1.2.x (aka Java2) 8.1.6SDK OCI Driver - Only JDK 1.1.x 8.1.6 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x 8.1.7 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x 9.0.1 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x and JDK 1.3.x 9.2.0 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x 10.1.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x 10.2.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, JDK 1.4.x, and JDK 5.0.x 11.1.0 OCI and THIN Driver - JDK 1.5.x and JDK 1.6.x Oracle 10.2.0 supports: Full support for JDBC 3.0 Note that there is no real change in the support for the following in the database. Allthat has changed is that some methods that previously threw SQLException now do something more reasonable instead. result-set holdability returning multiple result-sets.
With JDBC, that error usually occurs because your JDBC driver implements an older version of the JDBC API than the one included in your JRE. These older versions are fine so long as you don't try and use a method that appeared in the newer API. I'm not sure what version of JDBC `setBinaryStream` appeared in. It's been around for a while, I think. Regardless, your JDBC driver version (10.2.0.4.0) is quite old, I recommend upgrading it to the version that was released with 11g (download [here](http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html)), and try again.
Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?
[ "", "java", "oracle", "jdbc", "" ]
I don't claim to be a RegEx guru at all, and I am a bit confused on what this statement is doing. I am trying to refactor and this is being called on a key press and eating a lot of CPU. ``` Regex.Replace(_textBox.Text, "(?<!\r)\n", Environment.NewLine); ``` Thanks.
The regular expression `(?<!\r)\n` will match any `\n` character that is not preceeded by a `\r` character. The syntax `(?<!`*`expr`*`)` is a [negative look-behind assertion](http://www.regular-expressions.info/lookaround.html#lookbehind) and means that *`expr`* must *not* match the part that’s before the current position.
It's replacing every instance where there is a \n not preceeded by a \r with a Environment.NewLine string. This string is the platform specific newline (on Windows it will be the string "\r\n")
What is this RegEx statement doing?
[ "", "c#", ".net", "regex", "refactoring", "" ]
In my application there's the main thread and a worker thread (`QThread`). From the main thread I'd like to invoke a method of my worker thread and have it run in the thread's context. I've tried using `QMetaObject::invokeMethod` and give it the `QueuedConnection` option but it's not working. I've also tried emitting signals from the main thread (which is connected to the worker thread's slot) but that also failed. Here's a snippet of roughly what I tried: ``` class Worker : public QThread { Q_OBJECT public: Worker() { } void run() { qDebug() << "new thread id " << QThread::currentThreadId(); exec(); } public slots: void doWork() { qDebug() << "executing thread id - " << QThread::currentThreadId(); } }; ``` Using the QMetaObject way: ``` int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "main thread id - " << QThread::currentThreadId(); Worker worker; worker.start(); QMetaObject::invokeMethod(&worker, "doWork", Qt::QueuedConnection); return a.exec(); } ``` Using the signal way: ``` class Dummy : public QObject { Q_OBJECT public: Dummy() { } public slots: void askWork() { emit work(); } signals: void work(); }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "main thread id - " << QThread::currentThreadId(); Worker worker; worker.start(); Dummy dummy; QObject::connect(&dummy, SIGNAL(work()), &worker, SLOT(doWork()), Qt::QueuedConnection); QTimer::singleShot(1000, &dummy, SLOT(askWork())); return a.exec(); } ``` Both ways result in the main thread id being printed in the `QThread` `doWork`. Also, I thought of implementing a simple producer-consumer but if this works, is there any reason why not to do it this way?
The problem was that the receiver (the QThread) 'lives' in the main thread and thus the main thread's event loop is the one that executes the slot. from Qt's docs: > With queued connections, the slot is invoked when control returns to the event loop of the thread to which the object belongs. The slot is executed in the thread where the receiver object lives. So the solution I found so far was to create an object inside the thread's run() and use its slots instead. That way the receiver's owner is the thread and then the slot is called in the threads context.
For the simple producer-consumer example, have a look at the blog entry from Bradley T. Hughes [Treading without the headache](http://blog.qt.digia.com/blog/2006/12/04/threading-without-the-headache/).
Invoking methods in QThread's context
[ "", "c++", "multithreading", "qt", "qthread", "" ]
I'm a programmer with some experience working on various languages and platforms, but I lack any web development experience (apart of some very basic HTML produced by PHP). I'm looking for a **tutorial about the basics of web programming under Linux**. I am less interested with apache configuration and server maintenance which I know quite well, but with the actual building of a website using modern techniques. I am familiar with python, but I'll handle any scripting language quite well. Do you have any recommendations? Can you tell anything about the [W3Schhools tutorials](http://www.w3schools.com/)? Bunch of thanks, Udi
This is a fairly broad question you are asking. You have to be aware that there are a *lot* of potential answers, the ones already given here being decent ones. And you have to be aware that it is very much a platform decision that you make, whatever tutorial you choose. And that's because web (application) development is a complex thing that can be addressed on various levels (particularly outside the MS world). * I have no close knowledge about the **W3Schools** you mention, but on first glance it looks they will be teaching you a lot of basic *frontend* technology: HTML, XHTML, Javascript, CSS and the like. This is not bad and will give you a solid foundation in these things. But web development is usually not done on this level, as it is too tedious and inflexible for larger applications. And you would be missing out on backend/database technology altogether. * Then there are platforms (and I would guess this is the majority) which have a **templating** approach. You implement page and business logic in a mix of HTML and programming code in some language (Python, Perl, PHP, ...) within an HTML file that is then processed by an engine to generate the final HTML for the user interface and transaction code for the database. Django and TurboGears are the prominent Python representatives of this, Ruby on Rails probably the biggest name currently. But there are a lot others (how about [Scala/Lift](http://liftweb.net/)?), so it's worth taking the time to see which one you like best. They usually do a good job for the database handling. On the UI side you still have page changes. * In that vein there are platforms that try to move away from HTML with embedded code to a pure **programmatical** approach. You just write code and use specific APIs of the given platform. "Compiling" your project in one way or the other will then generate all the necessary stuff which you have to deploy in a runtime environment. I think [Google's GWT](http://code.google.com/webtoolkit/) and [Eclipse RAP](http://eclipse.org/rap/) are such approaches, and if you think, dream and breath in Java, this is probably for you. * Yet another approach is interesting when page changes in the browser (the most disruptive part of the web experience) is not good enough anymore, when you want desktop-like user interfaces. The way to attack this is to create "**fat web clients**", with lots of interaction logic built in, usually in Javascript, and have them interact with a server backend only for essential data transfer using Ajax, REST or RPC protocols. Candidates for the client technology are e.g. [qooxdoo](http://qooxdoo.org) or [Dojo](http://www.dojotoolkit.org/). On the server side you can still use whatever technology you are comfortable with (from RoR to Servlets and beyond). If I had my pick, I would choose qooxdoo for the frontend, and [Erlang/CouchDb](http://couchdb.apache.org/) on the backend. You have specifically asked about tutorials, and I haven't mentioned a lot. The point I was trying to make was whatever you choose, it is most likely that you will invest quite a bit of time and effort in that technology since they are all quite deep, and will stick with it for some time. During your evaluation you will also check the instructional material for the given platform (don't forget online videos - they're big these days), but this will inevitably be specific. AFAICS, there is no such thing as a "general introduction" to web programming.
With your Python knowledge, you'll might find tutorials like [Django](http://docs.djangoproject.com/en/dev/intro/) useful. It is modern enough to be used in [Google App Engine](http://code.google.com/appengine/docs/whatisgoogleappengine.html). Also try the [TurboGears tutorial](http://www.turbogears.org/2.0/docs/main/Wiki20/index.html), another Python web framework. This will give you a different angle on (modern) web programming. Find an introduction and many pointers to other frameworks on [Wikipedia](http://en.wikipedia.org/wiki/Web_application_framework).
Web programming tutorial
[ "", "python", "" ]
My first attempt using RE has me stuck. I'm using Regex on a Wordpress website via the [Search-Regex Plugin](http://urbangiraffe.com/plugins/search-regex/) and need to match on a specific " buried within a bunch of html code. HTML example: ``` provide brand-strengthening efforts for the 10-school conference.&#0160; </p> <p> <a href="http://www.learfield.com/oldblog/.a/6a00d8345233fa69e201157155a6fc970c-pi"> <img alt="MOvalleyConf500" border="0" class="at-xid-6a00d8345233fa69e201157155a6fc970c" src="http://www.learfield.com/oldblog/.a/6a00d8345233fa69e201157155a6fc970c-800wi" style="border: 1px solid black; margin: 0px; width: 502px; height: 384px;" title="MOvalleyConf500" /> </a> </p> <p>The photo above ``` In the above example, there are three targets ``` 6a00d8345233fa69e201157155a6fc970c-pi" 6a00d8345233fa69e201157155a6fc970c" 6a00d8345233fa69e201157155a6fc970c-800wi" ``` The Regex I'm using is `/6a00d834.*?"/` it locates them, however I only want to match on the ending `"` and not the entire string. These are images that are missing their file extension, so I need to replace the ending " with .jpg" I understand the replacement part of the expression, it's the initial matching I'm having trouble with. I have a bunch of these (221), all the targets all begin with `6a00d834` then some random alphanumeric ending with a `"` Appreciate any insight. Thanks. **Edit added from OP's comment**: Actually it's on a Wordpress site using a plugin (REGEX) to query and replace data within SQL. I can use any Perl compatible regex. (Note from editor - depending on the plugin, this is most likely not actually using Perl but PHP's implementation of PCRE.)
String replacement can be done along with the matching. Since you're using PHP, use [preg\_replace](http://www.php.net/preg_replace) ``` $newstring = preg_replace("/(6a00d834.*?)(\")/", "\\1.jpg\\2", $oldstring) ``` This breaks the match into two groups, and then inserts '.jpg' between them. For the [wordpress regex plugin](http://wordpress.org/extend/plugins/search-regex/screenshots/), use /(6a00d834.\*?)(")/ for the match string, and then use \1.jpg\2 for the replacement string.
Wouldn't this work? ``` /(6a00d834.*?)"/ ``` **Edit:** You said in one of your comments you wanted to replace the `"` with `.jpg"`; in that case this regexp would probably work: ``` /6a00d834.*?(")/ ``` However, the best thing to do is probably to use the first regexp I provided, and use a replacement string that looks like this: ``` '\\1.jpg"' ``` Of course, `\\1` has to be replaced with whatever you particular regexp engine uses for backreferences.
Help with Regex - Wordpress (search-regex)
[ "", "php", "regex", "wordpress", "pcre", "" ]
NOTE: I am pretty much a beginner myself. This question concentrates on C++ usage, since that is the only language I have experience with. There seems to be a consensus on Stack Overflow to use `using namespace std;` in the code examples provided for C++. I originally learned it this way, and was never taught WHY this is a problem later on. I was just wondering why people have a problem with using the prefix std:: in their example code. It seems capricious to declare a global namespace, especially since many of the questioners copy+paste the code from the example to their IDE. Namespaces are an advanced programming concept, but I think it would be best to prefix std:: and then explain later if beginners ask about it. Why is it acceptable to teach beginners this usage?
I think the answer is "it doesn't really matter". It's a subtlety that's fairly easy to pick up and correct later. Every beginners' programming text I know of makes a lot of simplifications and uses a lot of handwaving to hide a lot of what's going on ("this line is magic. Just type it in, and we'll discuss what it does later"). Beginners have enough to worry about without having to fully understand everything in their code, and how/why it is bad, so often these simplifications are good things. Although in this case I kind of agree with you. Adding the `std::` prefix wouldn't be a big deal, and it would demystify namespaces quite a bit. `using namespace std` is actually much harder to explain and understand properly. On the other hand, it takes up space and adds noise to the code which should be as concise and clear as possible.
For a beginner, IMO, it's much more important for them to understand concepts like functions, classes, conditionals and the like. Explicit namespace declarations just get in the way. Once they understand those basic concepts, explaining the benefits of namespaces to them isn't that hard.
Should we be teaching beginners to use a global namespace?
[ "", "c++", "namespaces", "global-namespace", "" ]
Hey all, I'm looking at building an ajax-heavy site, and I'm trying to spend some time upfront thinking through the architecture. I'm using Code Igniter and jquery. My initial thought process was to figure out how to replicate MVC on the javascript side, but it seems the M and the C don't really have much of a place. A lot of the JS would be ajax calls BUT I can see it growing beyond that, with plenty of DOM manipulation, as well as exploring the HTML5 clientside database. How should I think about architecting these files? Does it make sense to pursue MVC? Should I go the jquery plugin route somehow? I'm lost as to how to proceed and I'd love some tips. Thanks all!
I've made an MVC style Javascript program. Complete with M and C. Maybe I made a wrong move, but I ended up authoring my own event dispatcher library. I made sure that the different tiers only communicate using a message protocol that can be translated into pure JSON objects (even though I don't actually do that translation step). So jquery lives primarily in the V part of the MVC architecture. In the M, and C side, I have primarily code which could run in the stand alone CLI version of spidermonkey, or in the serverside rhino implementation of javascript, if necessary. In this way, if requirements change later, I can have my M and C layers run on the serverside, communicating via those json messages to the V side in the browser. It would only require some modifications to my message dispatcher to change this though. In the future, if browsers get some peer to peer style technologies, I could get the different teirs running in different browsers for instance. However, at the moment, all three tiers run in a single browser. The event dispatcher I authored allows multicast messages, so implementing an undo feature now will be as simple as creating a new object that simply listens to the messages that need to be undone. Autosaving state to the server is a similar maneuver. I'm able to do full detailed debugging and profiling inside the event dispatcher. I'm able to define exactly how the code runs, and how quickly, when, and where, all from that central bit of code. Of course the main drawback I've encountered is I haven't done a very good job of managing the complexity of the thing. For that, if I had it all to do over, I would study very very carefully the "Functional Reactive" paradigm. There is one existing implementation of that paradigm in javascript called flapjax. I would ensure that the view layer followed that model of execution, if not used specifically the flapjax library. (i'm not sure flapjax itself is such a great execution of the idea, but the idea itself is important). The other big implementation of functional reactive, is quartz composer, which comes free with apple's developer tools, (which are free with the purchase of any mac). If that is available to you, have a close look at that, and how it works. (it even has a javascript patch so you can prototype your application with a prebuilt view layer) The main takaway from the functional reactive paradigm, is to make sure that the view doesn't appear to maintain any kind of state except the one you've just given it to display. To put it in more concrete terms, I started out with "Add an object to the screen" "remove an object from the screen" type messages, and I'm now tending more towards "display this list of objects, and I'll let you figure out the most efficient way to get from the current display, to what I now want you to display". This has eliminated a whole host of bugs having to do with sloppily managed state. This also gets around another problem I've been having with bugs caused by messages arriving in the wrong order. That's a big one to solve, but you can sidestep it by just sending in one big package the final desired state, rather than a sequence of steps to get there. Anyways, that's my little rant. Let me know if you have any additional questions about my wartime experience.
At the risk of being flamed I would suggest another framework besides JQuery or else you'll risk hitting its performance ceiling. Its ala-mode plugins will also present a bit of a problem in trying to separate you M, V and C. Dojo is well known for its Data Stores for binding to server-side data with different transport protocols, and its object oriented, lighting fast widget system that can be easily extended and customized. It has a style that helps guide you into clean, well-divisioned code – though it's not strictly MVC. That would require a little extra planning. Dojo has a steeper learning curve than JQuery though. More to your question, The AJAX calls and object (or Data Store) that holds and queries this data would be your Model. The widgets and CSS would be your View. And the Controller would basically be your application code that wires it all together. In order to keep them separate, I'd recommend a loosely-coupled event-driven system. Try to directly access objects as little as possible, keeping them "black boxed" and get data via custom events or pub/sub topics.
Ajax Architecture - MVC? Other?
[ "", "javascript", "jquery", "model-view-controller", "architecture", "" ]
I have noticed that many blogs use URLs that look like this: <http://www.hanselman.com/blog/VirtualCamaraderieAPersistentVideoPortalForTheRemoteWorker.aspx> I assume this is done for search engine optimization. How is this read from the underlying data model? Do you really search for ``` VirtualCamaraderieAPersistentVideoPortalForTheRemoteWorker ``` in the database? If so, how is the description managed? If it is a key, is the rule that it can never be changed once it is created, without breaking web links?
You are correct that it is done for search engine optimization. It works best if you separate the individual words with dashes or underscores however. These SE-friendly url portions are often called **slugs** or **url slugs**. A slug must be unique in your application, and generally the function that creates or checks them must take this into account. Just like anything else, there are multiple ways to implement something like this. Generally you store a string of text about a database item, eg. an article title. You can convert this into the url slug at load time dynamically if you don't want to store it, or you can save the real title and the url slug at insert/update time, and use the slug as your database selection criteria when loading the relevant page. If you want to be super-robust with your app, you could automatically save a slug history, and generate "301 Moved Permanently" headers whenever a slug changed.
Typically when the article is created, that string is stored in the database as a key, yes. Some blog engines like Wordpress allow you (the author) to manually change what that string is, and after you do that, links to the old string will no longer function. In Wordpress, they call this the "permalink," although different engines have their own names for it. I don't think there is a universal term for it.
Managing Descriptive URLs
[ "", "c#", "html", "asp.net-mvc", "seo", "" ]
What's the best Ajax library for PHP and why do you prefer it?
If you are searching for a library to facilitate Ajax Requests, it is not dependant of the server-side : launching Ajax requests is done on the client-side, in Javascript. There are plenty of JS Frameworks to do lots of nice things, and, in the middle of those, Ajax Requests. I've used those ones : * [prototype](http://www.prototypejs.org/) : the one I know the best ; and really like it * [jQuery](http://jquery.com/) : probably the most used nowadays * [MooTools](http://mootools.net/) On the server-side, the JS Framework used doesn't make much different. You might still want to take a look at the JSON format, which is great to exchange data between client and server when doing Ajax requests. There are several implementations in PHP that allows you to work with that one. For instance : * With PHP >= 5.2 : [`json_encode`](http://www.php.net/json_encode) and [`json_decode`](http://www.php.net/json_decode) ; nice, as provided by PHP * Zend Framework has [`Zend_Json`](http://framework.zend.com/manual/en/zend.json.html) ; I've already used it on a PHP 5.1 server, outside of Zend Framework ; nice because I like ZF, and this component works on 5.1 *If you want other informations, you might edit your question, to be more clear about what you want :-)*
It's depends on needs, but JSON is also worth a dig; <http://json.org>
Ajax library for PHP
[ "", "php", "ajax", "" ]
Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly: ``` import os.path filename = "A 180 mb large file.data" size = os.path.getsize(filename) f = open(filename, "r") contents = f.read() f.close() print "The real filesize is", size print "The read filesize is", len(contents) f = open(filename, "r") size = 0 while True: contents = f.read(4) if not contents: break size += len(contents) f.close() print "this time it's", size ``` Outputs: ``` The real filesize is 183574528 The read filesize is 10322 this time it's 13440 ``` Somebody knows whats going on here? :)
If your file confuses the C libraries, then your results are expected. The OS thinks it's 180Mb. However, there are null bytes scattered around, which can confuse the C stdio libraries. Try opening the file with "rb" and see if you get different results.
The first is the filesize in bytes, the other times you read the file *as text* and count *characters*. Change all `open(filename, "r")` to `open(filename, "rb")` and it works.
Reading files in python
[ "", "python", "file", "" ]
This may not be possible (or might be dead easy! :) ) so here it is... I want to be able to create objects of a type that is dependant on a variable set, without the need for a big switch statement. I think it is possible in PHP to do something like... ``` $objectType = "myNewClass"; $newObject = new $objectType(); ``` where the $newObject variable will hold an instance of the Class "myNewClass". Is this (or any similar technique) possible with Javascript? Thanks Stuart
If your constructor functions are defined in the global scope, you can access it trough the bracket notation (window[fnName]): ``` function ObjectType1(){ // example constructor function this.type = 1; } var objectType = 'ObjectType1'; // string containing the constructor function name var obj = new window[objectType](); // creating a new instance using the string // variable to call the constructor ``` See: [Member Operators](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Member_Operators)
CMS's answer is good, but in EXT you're probably dealing with namespaces. I create an object map that holds any dynamic classes: ``` // within a namespace: var ns = { Thinger: function(){} }; // globals: var Zinger = function(){} // map: var classes = { zinger:Zinger, thinger:ns.Thinger }; var type = "thinger"; var myClass = new classes[type](props, type, etc); ```
Object type determined at runtime - Javascript (ExtJS)
[ "", "javascript", "dynamic", "extjs", "object", "" ]
Say I have a static C++ lib, static.lib and I want to call some functions from a C++ shared lib, say shared.lib. Is it possible? Now assume that I have another shared lib, say shared2.lib which links to static.lib but does not link to shared.lib. Does the linker automatically link shared2.lib to shared.lib in this case? I am using Microsoft Visual Studio 2003.
Static libraries are not linked. They are just a collection of object files (\*.obj or \*.o) that are archived together into a library file (kind of like a tar/zip file) to make it easier for the linker to find the symbols it needs. A static lib can call functions that are not defined (but are only declared in a header file), as it is only compiled. Then when you link an exe or dll that uses the static lib you will have to link with another library that provides the called from the static lib but not defined in it. If you want to the linker to automatically link other libraries Stephen's suggestion will work and is used by very reputable libraries like boost and stlport. To do this put the pragma in the main header file for the static library. You should include the static library and its dependants. However IMO this feature is really meant for library writers, where the library is in the system library path so the linker will easily find it. Also in the case of boost and stlport they use this feature to support multiple version of the same libraries with options defined with `#define`s where different options require different versions of the library to be linked. This means that users are less likely to configure boost one way and link with a library configured another. My preference for application code is to explicitly link the required parts.
The linker will not automatically bring in the other libraries, but you can use [#pragma comment (lib, "static.lib")](http://msdn.microsoft.com/en-us/library/7f0aews7%28VS.80%29.aspx) to simplify the process of linking the additional files by adding the pragma to your header files.
Can a C++ Static Library link to shared library?
[ "", "c++", "shared-libraries", "visual-c++", "static-libraries", "" ]
I'm taking a look now to XtraReports reporting tool and there's something that I don't get it yet. How do I set the data source for a certain field (showed in the report as a Label I guess), without having to build a connection, adapter and dataset at design time but doing it programatically. For example, I can have a table called "User" with 3 fields: UserId, Username and Password. In the report designer I place 3 labels (and here's my question) set the datasource for showing the 3 database fields. Then, in the code behind, I create a connection, execute a command, fill a dataset, create a report instance, pass the datatable to it and show the report preview. Is this possible? Let me know if it isn't clear enough. Thanks!
You could set your Report's DataSourceSchema property to an XML schema that represents your DataSource. That will let you use the Report Designer to set your data bindings at design time without establishing a connection to the database each time. Here's how I do it: Once I have my report query mostly finalized, I run the code once with a call to ``` myDataSet.WriteXml("C:\myDataSourceSchema.xml", System.Data.XmlWriteMode.WriteSchema) ``` Then in the report designer I set the Report's DataSourceSchema property to the newly created file. This will populate the Report Designer's Field List tab so you can bind at design time. That way you only have to have a valid data source once (or any time you change your columns). You can definitely still do Przemaas's approach and do all of your data bindings in code, but I prefer to let the designer handle most of the work.
Building a report without a dataset, you would use an IList object ... so follow this nice tutorial **How to: Bind a Web Report to an Array List** <https://documentation.devexpress.com/#XtraReports/CustomDocument3851>
How to set datasource for fields in XtraReports without having a dataset at design time?
[ "", "c#", "devexpress", "xtrareport", "" ]
I'm refactoring my code and just hit a snag. The first query in the code below gets the tab\_id of the latest submitted tabs. The second Query gets the detail of each tab. In my old way of doing it, i embedded php and html and it was truly an utter mess. Right now I'd like to merge the 2 queries into 1 and/or load it into an array. feel free to ask and/or butcher ``` function get_newest_tabs() { $db_open; $sql = "SELECT tab_id, song_id, user_id FROM tabs ORDER BY time_added DESC ". "LIMIT 15"; $result = mysql_query($sql) or die("ERROR - newest tabs function: ".mysql_error()); if (mysql_num_rows($result) > 0) { for($i = 0; $i < mysql_num_rows($result); $i++) { $tab_id = mysql_result($result, $i, "tab_id"); $db_open; $sql = "SELECT tabs.tab_id, tabs.tab_version, tabs.number_of_hits, artist.artist_name, users.user_alias, songs.song_name, tabs.time_added FROM tabs, users, artist, songs WHERE tabs.tab_id ='".$tab_id."' AND tabs.user_id = users.user_id AND tabs.song_id = songs.song_id AND songs.artist_id = artist.artist_id"; $result2 = mysql_query($sql) or die("ERROR - i3p mysql - 4: ".mysql_error()); if(mysql_num_rows($result2) == 1) { $song_name = mysql_result($result2, 0, "songs.song_name"); $artist_name = mysql_result($result2, 0, "artist.artist_name"); $user_alias = mysql_result($result2, 0, "users.user_alias"); $tab_version = mysql_result($result2, 0, "tabs.tab_version"); $number_of_hits = mysql_result($result2, 0, "tabs.number_of_hits"); $time_added = mysql_result($result2, 0, "tabs.time_added"); } } } } ```
I'd suggest using JOIN instead of selecting from multiple tables. You can also join the tabs table. ``` SELECT tabs.tab_id, tabs.song_id, tabs.user_id, tabs.tab_version, tabs.number_of_hits, artist.artist_name, users.user_alias, songs.song_name, tabs.time_added FROM tabs LEFT JOIN users ON users.user_id = tabs.user_id LEFT JOIN songs ON songs.song_id = tabs.song_id LEFT JOIN artist ON artist.artist_id = songs.artist_id ORDER BY tabs.time_added DESC LIMIT 15 ``` Then you could do a loop like: ``` while($row = mysql_fetch_array($result)) { $tabs[$row['tab_id']] = $row; } ``` As long as you have one user/song/artist per tab that will get you an array of your data.
Why not use sql: ``` WHERE tabs.tab_id IN (1,2,3,4) ``` or event ``` WHERE tabs.tab_id in (select tab_id from tabs ... ) ``` I think it's rather SQL related question.
multiple mysql queries into one php two-dimensional array
[ "", "php", "mysql", "arrays", "" ]
I know this question isn't exactly a programming question, but it will affect how we program one of our products, so i guess it might be close enough. Do you guys still see the Microsoft JVM (Java 1.1) on client computers anymore? I havent found much info on this particular JVM online... Anyone know of a good resource to find this type of info? Sun's site is pretty much useless for this... Thanks!
Wow, I remember this being installed on work PCs around 2002. It is not supported by Microsoft any more. See- <http://www.microsoft.com/mscorp/java/default.mspx> I'd be surprised if you found many PCs that still had this on.
Haven't seen it in this millennium I think.
How many Microsoft JVMs still in the wild?
[ "", "java", "jvm", "version", "" ]
I have a constructor that takes some arguments. I had assumed that they were initialized in the order listed, but in one case, it appears they were being initialized in reverse, resulting in an abort. When I reversed the arguments, the program stopped aborting. Below is an example of the syntax I'm using. `a_` needs to be initialized before `b_` in this case. Can you ensure this order of initialization? ``` class A { public: OtherClass a_; AnotherClass b_; A(OtherClass o, string x, int y) : a_(o) , b_(a_, x, y) {} }; ```
It depends on the order of data member declarations in the class. So `a_` will be the first one, then `b_` will be the second one in your example.
To quote the standard, for clarification: > 12.6.2.5 > > Initialization shall proceed in the following order: > > **...** > > * Then, nonstatic data members shall be initialized in the order they were declared in the class definition > (again regardless of the order of the mem-initializers). > > **...**
What is the order of evaluation in a member initializer list?
[ "", "c++", "gcc", "constructor", "initialization", "c++-faq", "" ]
I have a windows forms application on which I need to use a for loop having a large number of Remote Calls around 2000 - 3000 calls, and while executing the for loop, I loose my control on form and form controls, as it becomes a large process and some time it shows "Not Responding" but if I wait for a long it comes back again, I think I need to use some threading model for that, is there any idea, how can I proceed to solve the issue?
You need to perform the long running operation on a background thread. There are several ways of doing this. 1. You can queue the method call for execution on a thread pool thread (See [here](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx)): ``` ThreadPool.QueueUserWorkItem(new WaitCallback(YourMethod)); ``` In .NET 4.0 you can use the [TaskFactory](http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.aspx): ``` Task.Factory.StartNew(() => YourMethod()); ``` And in .NET 4.5 and later, you can (and should, rather than `TaskFactory.StartNew()`) use `Task.Run()`: ``` Task.Run(() => YourMethod()); ``` 2. You could use a [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) for more control over the method if you need things like progress updates or notification when it is finished. Drag the a BackgroundWorker control onto your form and attach your method to the dowork event. Then just start the worker when you want to run your method. You can of course create the BackgroundWorker manually from code, just remember that it needs disposing of when you are finished. 3. Create a totally new thread for your work to happen on. This is the most complex and isn't necessary unless you need really fine grained control over the thread. See the MSDN page on the [Thread](http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx) class if you want to learn about this. Remember that with anything threaded, you **cannot** update the GUI, or change any GUI controls from a background thread. If you want to do anything on the GUI you have to use Invoke (and InvokeRequired) to trigger the method back on the GUI thread. See [here](http://weblogs.asp.net/justin_rogers/pages/126345.aspx).
``` private voidForm_Load(object sender, EventArgs e) { MethodInvoker mk = delegate { //your job }; mk.BeginInvoke(callbackfunction, null); } private void callbackfunction(IAsyncResult res) { // it will be called when your job finishes. } ``` use MethodInvoker is the easiest way.
WinForm Application UI Hangs during Long-Running Operation
[ "", "c#", "winforms", "multithreading", "" ]
**Note**: This question has been re-asked with a summary of all debugging attempts [here](https://stackoverflow.com/questions/1367373/python-subprocess-popen-oserror-errno-12-cannot-allocate-memory). --- I have a Python script that is running as a background process executing every 60 seconds. Part of that is a call to [subprocess.Popen](http://docs.python.org/library/subprocess.html) to get the output of [ps](http://linuxcommand.org/man_pages/ps1.html). ``` ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0] ``` After running for a few days, the call is erroring with: ``` File "/home/admin/sd-agent/checks.py", line 436, in getProcesses File "/usr/lib/python2.4/subprocess.py", line 533, in __init__ File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles OSError: [Errno 12] Cannot allocate memory ``` However the output of [free](http://www.linuxcommand.org/man_pages/free1.html) on the server is: ``` $ free -m total used free shared buffers cached Mem: 894 345 549 0 0 0 -/+ buffers/cache: 345 549 Swap: 0 0 0 ``` I have searched around for the problem and found [this article](http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/) which says: Solution is to add more swap space to your server. When the kernel is forking to start the modeler or discovery process, it first ensures there's enough space available on the swap store the new process if needed. I note that there is no available swap from the free output above. Is this likely to be the problem and/or what other solutions might there be? **Update 13th Aug 09** The code above is called every 60 seconds as part of a series of monitoring functions. The process is daemonized and the check is scheduled using [sched](http://docs.python.org/library/sched.html). The specific code for the above function is: ``` def getProcesses(self): self.checksLogger.debug('getProcesses: start') # Memory logging (case 27152) if self.agentConfig['debugMode'] and sys.platform == 'linux2': mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0] self.checksLogger.debug('getProcesses: memory before Popen - ' + str(mem)) # Get output from ps try: self.checksLogger.debug('getProcesses: attempting Popen') ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0] except Exception, e: import traceback self.checksLogger.error('getProcesses: exception = ' + traceback.format_exc()) return False self.checksLogger.debug('getProcesses: Popen success, parsing') # Memory logging (case 27152) if self.agentConfig['debugMode'] and sys.platform == 'linux2': mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0] self.checksLogger.debug('getProcesses: memory after Popen - ' + str(mem)) # Split out each process processLines = ps.split('\n') del processLines[0] # Removes the headers processLines.pop() # Removes a trailing empty line processes = [] self.checksLogger.debug('getProcesses: Popen success, parsing, looping') for line in processLines: line = line.split(None, 10) processes.append(line) self.checksLogger.debug('getProcesses: completed, returning') return processes ``` This is part of a bigger class called checks which is initialised once when the daemon is started. The entire checks class can be found at <http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.
when you use popen you need to hand in close\_fds=True if you want it to close extra file descriptors. creating a new pipe, which occurs in the \_get\_handles function from the back trace, creates 2 file descriptors, but your current code never closes them and your eventually hitting your systems max fd limit. Not sure why the error you're getting indicates an out of memory condition: it should be a file descriptor error as the return value of `pipe()` has an error code for this problem.
You've perhaps got a memory leak bounded by some [resource limit](http://www.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html) (`RLIMIT_DATA`, `RLIMIT_AS`?) inherited by your python script. Check your \*ulimit(1)\*s before you run your script, and profile the script's memory usage, as others have suggested. **What do you do with the variable `ps` after the code snippet you show us?** Do you keep a reference to it, never to be freed? Quoting the [`subprocess` module docs](http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate): > **Note:** The data read is buffered in memory, so do not use this > method if the data size is large or unlimited. ... and *ps aux* can be verbose on a busy system... **Update** You can check rlimits from with your python script using the [resource](http://docs.python.org/library/resource.html#resource.getrlimit) module: ``` import resource print resource.getrlimit(resource.RLIMIT_DATA) # => (soft_lim, hard_lim) print resource.getrlimit(resource.RLIMIT_AS) ``` If these return "unlimited" -- `(-1, -1)` -- then my hypothesis is incorrect and you may move on! See also [`resource.getrusage`](http://docs.python.org/library/resource.html#resource.getrusage), esp. the `ru_??rss` fields, which can help you to instrument for memory consumption from with the python script, without shelling out to an external program.
Python subprocess.Popen erroring with OSError: [Errno 12] Cannot allocate memory after period of time
[ "", "python", "linux", "memory", "" ]
Why do I get the compiler warning > Identifier 'Logic.DomainObjectBase.\_isNew' is not CLS-compliant for the following code? ``` public abstract class DomainObjectBase { protected bool _isNew; } ```
From the [Common Language Specification](http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx): > CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers. This standard is available from the Web site of the Unicode Consortium. If you [look this up](http://www.unicode.org/unicode/reports/tr15/tr15-18.html#Programming%20Language%20Identifiers): > That is, the first character of an identifier can be an uppercase letter, lowercase letter, titlecase letter, modifier letter, other letter, or letter number. The subsequent characters of an identifier can be any of those, plus non-spacing marks, spacing combining marks, decimal numbers, connector punctuations, and formatting codes (such as right-left-mark). Normally the formatting codes should be filtered out before storing or comparing identifiers. Basically, you can't start an identifier with an underscore - this violates CLS compliant on a visible (public/protected) field.
[CLS compliance](http://msdn.microsoft.com/en-us/library/bhc3fa7f%28v=vs.100%29.aspx) has to do with interoperability between the different [.NET](http://en.wikipedia.org/wiki/.NET_Framework) languages. The property is not CLS compliant, because it starts with an underscore and is public (note: protected properties in a public class can be accessed from outside the assembly). Although this will work if the property is accessed from C# it may not if it is accessed from other .NET languages that don't allow underscores at the start of property names, hence it is not CLS-compliant. You are getting this compiler error, because somewhere in your code you have labelled your assembly as CLS compliant with a line something like this: ``` [assembly: CLSCompliant(true)] ``` Visual Studio includes this line in the AssemblyInfo.cs file which can be found under Properties in most projects. To get around this error you can either: 1. Rename your property (recommended): ``` protected bool isNew; ``` 2. Set your whole assembly to be non CLS compliant: ``` [assembly: CLSCompliant(false)] ``` 3. Add an attribute just to your property: ``` [CLSCompliant(false)] protected bool _isNew; ``` 4. Change the scope of the property, so that it can not be seen outside the assembly. ``` private bool _isNew; ```
Why is this name with an underscore not CLS Compliant?
[ "", "c#", ".net", "cls-compliant", "" ]
I'm trying to write a fairly simple threaded application, but am new to boost's thread library. A simple test program I'm working on is: ``` #include <iostream> #include <boost/thread.hpp> int result = 0; boost::mutex result_mutex; boost::thread_group g; void threaded_function(int i) { for(; i < 100000; ++i) {} { boost::mutex::scoped_lock lock(result_mutex); result += i; } } int main(int argc, char* argv[]) { using namespace std; // launch three threads boost::thread t1(threaded_function, 10); boost::thread t2(threaded_function, 10); boost::thread t3(threaded_function, 10); g.add_thread(&t1); g.add_thread(&t2); g.add_thread(&t3); // wait for them g.join_all(); cout << result << endl; return 0; } ``` However, when I compile and run this program I get an output of ``` $ ./test 300000 test: pthread_mutex_lock.c:87: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed. Aborted ``` Obviously, the result is correct but I'm worried about this error message, especially because the real program, which has essentially the same structure, is getting stuck at the join\_all() point. Can someone explain to me what is happening? Is there a better way to do this, i.e. launch a number of threads, store them in a external container, and then wait for them all to complete before continuing the program? Thanks for your help.
I think you problem is caused by the thread\_group destructor which is called when your program exits. Thread group wants to take responsibility of destructing your thread objects. See also in the [boost::thread\_group](http://www.boost.org/doc/libs/1_39_0/doc/html/thread/thread_management.html#thread.thread_management.threadgroup.destructor) documentation. You are creating your thread objects on the stack as local variables in the scope of your main function. Thus, they have already been destructed when the program exits and thread\_group tries to delete them. As a solution, create your thread objects on the heap with *new* and let the thread\_group take care of their destruction: ``` boost::thread *t1 = new boost::thread(threaded_function, 10); ... g.add_thread(t1); ... ```
If you don't need a handle to your threads, try using thread\_group::create\_thread() which alleviates the need to manage the thread at all: ``` // Snip: Same as previous examples int main(int argc, char* argv[]) { using namespace std; // launch three threads for ( int i = 0; i < 3; ++i ) g.create_thread( boost::bind( threaded_function, 10 ) ); // wait for them g.join_all(); cout << result << endl; return 0; } ```
(simple) boost thread_group question
[ "", "c++", "multithreading", "boost", "boost-thread", "" ]
Anyone know of a library that allows data to be serialized in C++ such that it can be deserialized using the default PHP 'unserialize' function?
There are several implementations for other languages here <http://objectmix.com/php/362009-specification-serialize.html#post1335166> The C implementation used by PHP itself is also here: <http://svn.php.net/repository/php/php-src/branches/PHP_5_2/ext/standard/var.c> <http://svn.php.net/repository/php/php-src/branches/PHP_5_2/ext/standard/var_unserializer.c> However, unless you're absolutely certain that your choice serialization format is going to be a major bottleneck, consider using a more readily available serialization format, like JSON, XML, Protocol Buffers, or WDDX.
Since you're probably only serializing data, and not PHP objects, you may find a standardized "common ground" serialization more effective. (JSON is likely the simplest)
PHP compatible serialization from C/C++
[ "", "php", "" ]
I am looking for a nice book, reference material which deals with forward declaration of classes esp. when sources are in multiple directories, eg. class A in dirA is forward declared in class B in dirB ? How is this done ? Also, any material for template issues, advanced uses and instantation problems, highly appreicated ? Thanks.
Forward declarations have nothing to do with the directory structure of your project. You can forward declare something even not existing in your project. They are mostly used to resolve cyclic references between classes and to speed up compilation when the complete class declaration is not necessary, and the corresponding #include can be replaced with a forward declaration. To determine when a forward declaration is sufficient, the sizeof() query can usually answer the question. For example, ``` class Wheel; class Car { Wheel wheels[4]; }; ``` In this declaration, a forward declaration cannot be used since the compiler cannot determine the size of a Car: it doesn't know how much data the wheels contain. In other words, `sizeof(Car)` is unknown. Also regarding templates, forward declared classes cannot be used as template parameters if the template class contains data members of the template parameter (but their pointers can be). For instance, ``` template<class T> class pointer { T *ptr; }; class Test; pointer<Test> testpointer; ``` is legal but `std::vector<Test> testvector` will not compile. Because of the aforementioned limitations, forward declared classes are generally used as pointers or references. I don't know if there's a book on the subject but you can see [this section](http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.12) on c++ faq lite.
if they are in parallel directories you can include it like ``` #include "../dirB/B.h" ``` but in header you just call this line for forward decleration ``` class B; ``` --- instead of this, you can seperate your include directories and source directories. so then you can show include directory as this directory and you can add header by calling ``` #include "dirB/B.h" ``` since you will make a forward decleration on header, it wont be problem.
Forward declaration in multiple source directory; template instantation
[ "", "c++", "templates", "forward-declaration", "" ]