Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is there a way to query SQL Server XML type so that for an element with `xsi:nil="true"`, return null instead of default datetime value, which is `1900-01-01 00:00:00.000`? here is a code snippet ``` declare @data xml set @data = '<DOD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />' select Value1 = @data.value('/DOD[1]', 'datetime'), Value2 = IsNull(@data.value('/DOD[1]', 'datetime'), 'NOT NULL?'), Value3 = nullif(@data.value('/DOD[1]', 'datetime'), '1900-01-01') ``` Value1 & Value2 both returns `1900-01-01 00:00:00.000`. Is there a way to return a null, instead? without using `nullif`?
The "default" datetime is caused by casting an empty string which is "zero" which gives 01 jan 1900. So: tidy the string, then CAST ``` declare @data xml set @data = '<DOD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />' select Value1 = CAST(NULLIF(@data.value('/DOD[1]', 'varchar(30)'), '') AS datetime) ```
easy: ``` declare @data xml set @data = '<DOD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />' select Value1 = @data.value('(/DOD/text())[1]', 'varchar(30)') ```
How to convert SQL Server XML type value (xsi:nil) of DateTime to null
[ "", "sql", "sql-server", "xml", "sql-server-2005", "t-sql", "" ]
I have a decent, lightweight search engine working for one of my sites using MySQL fulltext indexes and php to parse the results. Work fine but I'd like to offer more 'google-like' results with text snippets from the results and the found words highlighted. Looking for a php based solution. Any recommendations?
Searching the actual database is fine until you want to add snazzy features like the one above. In my experience it is best to create a dedicated search table, with keywords and page IDs/URLs/etc. Then populate this table every *n* hours with content. During this population you can add snippets for each document for each keyword. Alternatively a quick hack might be: ``` <?php $text = 'This is an example text page with content. It could be red, green or blue.'; $keyword = 'red'; $size = 5; // size of snippet either side of keyword $snippet = '...'.substr($text, strpos($text, $keyword) - $size, strpos($text, $keyword) + sizeof($keyword) + $size).'...'; $snippet = str_replace($keyword, '<strong>'.$keyword.'</strong>', $snippet); echo $snippet; ?> ```
For MySQL, your best bet would be to first split up your query words, clean up your values, and then concatenate everything back into a nice regular expression. In order to highlight your results, you can use the `<strong>` tag. Its usage would be semantic as you are putting **strong** emphasis on an item. ``` // Done ONCE per page load: $search = "Hello World"; //Remove the quotes and stop words $search = str_ireplace(array('"', 'and', 'or'), array('', '', ''), $search); // Get the words array $words = explode(' ', $search); // Clean the array, remove duplicates, etc. function remove_empty_values($value) { return trim($value) != ''; } function regex_escape(&$value) { $value = preg_quote($value, '/'); } $words = array_filter($words, 'remove_empty_values'); $words = array_unique($words); array_walk($words, 'regex_escape'); $regex = '/(' . implode('|', $words) . ')/gi'; // Done FOR EACH result $result = "Something something hello there yes world fun nice"; $highlighted = preg_replace($regex, '<strong>$0</strong>', $result); ``` --- If you are using PostgreSQL, you can simply use the built-in `ts_headline` [as described in the documentation](http://www.postgresql.org/docs/8.4/interactive/textsearch-controls.html).
Best practices on displaying search results with associated text snippets from actual result
[ "", "php", "mysql", "search", "" ]
I have been looking into using the Entity Framework in my C# game server to make querying easier. I am a huge fan of type safety, and the Entity Framework does a great job at automating most of the boilerplate code. Though I am not quite sure how to go about utilizing some of the components, namely the `ObjectContext`. The server uses quite a lot of threading, so thread safety is a concern. Right now I just use a custom pool for executing queries. Without going into much detail, each query works in the fashion of: 1. Grab a `DbConnection` 2. Grab a `DbCommand` 3. Allow for the query class to set the parameters 4. Execute the `DbCommand` 5. Allow for the query class to handle the query result, if any 6. Free the `DbCommand` 7. Free the `DbConnection` It is very clean, fast, and safe, but the problem is that creating queries is a bit of a hassle, and I have to manually generate and update "container classes" if I want the type safety. This is why I have turned to the Entity Framework. This all works great with using just the `DbConnection` and `DbCommand` since there is no concerns about which `DbConnection`/Command performs queries for which object or anything. Anyways, I don't really know how to explain it much more without imposing restrictions. Doing something like executing a query every time I would normally with the `DbConnection`/Command, saving it, and disposing the ObjectContext just adds too much overhead when I really don't need the database to be updated so frequently. How would you go about using the Entity Framework for a game server that doesn't have a high demand on the database being immediately and constantly up-to-date?
The place that you will most probably notice the difference in performance with Entity framework is in the update of data (not insert). This is due to the fact that the data must first be read from the database, then changed, then saved back to the database. For the object context we use the using statement, so that it gets disposed straight away. It would not be good for a game to get a pause while the garbage collector ran dispose on all objects that were out of scope. If you have mainly read I would recommend caching the data, using for example Enterprise Library Caching application block. Entity Framework will give you a more productive programming model, while the caching will give you better performance.
First, you need to read this, and internalize it: [Performance Considerations for Entity Framework Applications](http://msdn.microsoft.com/en-us/library/cc853327.aspx) Of particular note: 1. Set the merge option correctly for re-only queries 2. Note that pre-generation of views helps only for things like RelatedEnd.Load and not for ad hoc queries. Use CompiledQuery to optimize ad hoc queries. Query preparation can be a significant overhead for complex queries, so do this wherever possible. 3. Instantiating and disposing of an object context does not have a lot of overhead if you've pre-generated your views and you set your merge options correctly. Use it in a way that makes sense for your application; don't "prematurely optimize" its lifetime.
Entity Framework with a game server
[ "", "c#", ".net", "multithreading", "entity-framework", "" ]
I have a dropdown box that I construct with PHP. Here is the code: ``` $region_result = mysql_query("SELECT * FROM region ORDER BY region"); $dropdown = "<select name='region'>"; while($row = mysql_fetch_assoc($region_result)) { $rid = $row["id"]; $region = $row["region"]; $dropdown .= "\r\n<option value='{$row['rid']}'>{$region}</option>"; } $dropdown .= "\r\n</select>"; ``` I need to set the selected value of the dropdown box AFTER the above code is processed. Is there any easy way to do this? Does anyone have any suggestions? Thanks! EDIT: Thank you all for your answers. Let me explain what I am doing. I was setting up an "Edit Users" page, where you can search for a user by multiple criteria and then the results are listed in an "edit mode" - that is - in text boxes and dropdown boxes. So you can then edit and update a user. For two user fields, I need to list the data in dropdown boxes (to ensure data integrity and constraints). So, I want to show those dropdown boxes with all the possible values you can change to, except I want the selected value of the dropdown to be the one currently associated with the user. So, I was able to get this working with deceze's suggestion - In my while loop that has that is setting my PHP values with the database results, I have inserted a nested while loop which will construct $dropdown, and within that, a nested if-loop. I'm not crazy about all these nested loops. Here is the code segment for that: ``` if (@mysql_num_rows($result)) { while ($r=@mysql_fetch_assoc($result)) { $fname = $r["fname"]; $lname = $r["lname"]; $region = $r["region"]; $role = $r["role"]; $extension = $r["extension"]; $username = $r["username"]; $building = $r["building"]; $room = $r["room"];?> <?php $dropdown = "<select name='region'>"; while($row = mysql_fetch_assoc($region_result)) { $rid = $row["id"]; $region2 = $row["region"]; if($region == $region2){ $dropdown .= "\r\n<option selected='selected' value='{$row['rid']}'>{$region}</option>"; }else{ $dropdown .= "\r\n<option value='{$row['rid']}'>{$region2}</option>"; } } $dropdown .= "\r\n</select>"; ?> ``` However, I am considering changing this to the text replacement (suggested by soulscratch and zombat), as I think it would be better on performance. ...This doesn't seem to work when more than one result set meets the search criteria, though (as the dropdown boxes for the 2nd and 3rd and etc. results are empty). What do you guys think?
With the way your string is built, it's a fairly simple [str\_replace()](http://php.net/str_replace), which is nice as it saves the hassle of needing regular expressions: ``` $dropdown = str_replace("value='".$rid."'","value='".$rid."' selected=\"selected\"",$dropdown); ```
If you want to change your assembled HTML *after the fact* you need to use complicated string replace methods, or Javascript, neither of which is a good choice. The best option you have would be to restructure your program so you can set the `selected` attribute when going through the loop the first time around.
PHP set selected value of dropdown box
[ "", "php", "html", "drop-down-menu", "" ]
``` $value = $simpleXmlDoc->SomeNode->InnerNode; ``` actually assigns a simplexml object to $value instead of the actual value of InnerNode. If I do: ``` $value = $simpleXmlDoc->SomeNode->InnerNode . "\n"; ``` I get the value. Anyway of getting the actual value without the clumsy looking `. "\n"`?
Cast as whatever type you want (and makes sense...). By concatenating, you're implicitly casting to string, so ``` $value = (string) $xml->someNode->innerNode; ```
You don't have to specify `innerNode`. `$value = (string) $simpleXmlDoc->SomeNode;`
Getting actual value from PHP SimpleXML node
[ "", "php", "simplexml", "" ]
I'm doing a little experiment trying to randomly place images inside a div using a javascript loop. I've been having some trouble with it. Here's what I have (simplified): ``` for(var i = 0; i < 10; i++) { var top = random(-20, 20); var left = random(-20, 20); document.write( <div class="one" style="\"left:" + left + ";\""> <img src="hein.png"/> </div> ); } ``` The goal being to generate some top and left values, and every itteration display a new image with these generated values. I know it's a syntax error with the style="". But nothing I've tried has worked How can I get this working.
You forgot the quotes in `document.write` and you are escaping wrong characters inside of it ``` document.write( "<div class=\"one\" style=\"left:" + left + ";\"> <img src=\"hein.png\"/> </div>" ); ```
You meed to wrap the whole of the `document.write` output in quotes, like this: ``` document.write('<div class="one" style="left:"' + left + ';"><img src="hein.png"/></div>'); ```
Styling Divs with Javascript Vars
[ "", "javascript", "html", "variables", "coding-style", "" ]
In asp.net MVC the "homepage" (ie the route that displays when hitting www.foo.com) is set to Home/Index . * Where is this value stored? * How can I change the "homepage"? * Is there anything more elegant than using RedirectToRoute() in the Index action of the home controller? I tried grepping for Home/Index in my project and couldn't find a reference, nor could I see anything in IIS (6). I looked at the default.aspx page in the root, but that didn't seem to do anything relevent. Thanks
Look at the `Default.aspx/Default.aspx.cs` and the Global.asax.cs You can set up a default route: ``` routes.MapRoute( "Default", // Route name "", // URL with parameters new { controller = "Home", action = "Index"} // Parameter defaults ); ``` Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table.
# ASP.NET Core Routing is configured in the `Configure` method of the `Startup` class. To set the "homepage" simply add the following. This will cause users to be routed to the controller and action defined in the MapRoute method when/if they navigate to your site’s base URL, i.e., yoursite.com will route users to yoursite.com/foo/index: ``` app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=FooController}/{action=Index}/{id?}"); }); ``` # Pre-ASP.NET Core Use the RegisterRoutes method located in either App\_Start/RouteConfig.cs (MVC 3 and 4) or Global.asax.cs (MVC 1 and 2) as shown below. This will cause users to be routed to the controller and action defined in the MapRoute method if they navigate to your site’s base URL, i.e., yoursite.com will route the user to yoursite.com/foo/index: ``` public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // Here I have created a custom "Default" route that will route users to the "YourAction" method within the "FooController" controller. routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "FooController", action = "Index", id = UrlParameter.Optional } ); } ```
Set "Homepage" in Asp.Net MVC
[ "", "c#", "asp.net-mvc", "asp.net-mvc-routing", "" ]
I'd like to know how do you test your methods if the libs you are using don't use Interfaces My class is like ``` private ThirdParyClass thirdPartyClass; void myMethod() { AnotherThirdPartyClass param = "abc"; ... thirdPartyClass.execute(param); } ``` I want to test that execute is called with the "abc" param. I was thinking in creating MyInterface with an implementation that wraps the ThirdPartyClass and then change the class attribute to refer MyInterface. Quite boring stuff but I don't see any other way to be able to successfully test my class. If ThirdParyClass was an Interface I could mock it, but in this case how do you procede?
i do not know which mock implementation you use it. But [EasyMock](http://www.easymock.org) has an extension available at the EasyMock home page that generate mock Objects for classes. See your mock implementation whether it does not support mock Objects for classes. regards,
You can use [JMockit](https://jmockit.dev.java.net). It goes far beyond what is possible with EasyMock Class Extension or with jMock and its ClassImposteriser. You actually get all the power of AspectJ, but with a much easier to use, mocking-specific, API.
Java Unit tests on methods that use third parties libs that don't use Interfaces
[ "", "java", "unit-testing", "testing", "mocking", "" ]
Given a string as user input to a Python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result: ``` class Foo: pass str_to_class("Foo") ==> <class __main__.Foo at 0x69ba0> ``` Is this, at all, possible?
> **Warning**: `eval()` can be used to execute arbitrary Python code. You should ***never*** use `eval()` with untrusted strings. (See *[Security of Python's eval() on untrusted strings?](https://stackoverflow.com/q/661084/3357935)*) This seems simplest. ``` >>> class Foo(object): ... pass ... >>> eval("Foo") <class '__main__.Foo'> ```
This could work: ``` import sys def str_to_class(classname): return getattr(sys.modules[__name__], classname) ```
Convert string to Python class object?
[ "", "python", "" ]
Two days ago I started working on a code parser and I'm stuck. How can I split a string by commas that are not inside brackets, let me show you what I mean: I have this string to parse: ``` one, two, three, (four, (five, six), (ten)), seven ``` I would like to get this result: ``` array( "one"; "two"; "three"; "(four, (five, six), (ten))"; "seven" ) ``` but instead I get: ``` array( "one"; "two"; "three"; "(four"; "(five"; "six)"; "(ten))"; "seven" ) ``` How can I do this in PHP RegEx. Thank you in advance !
You can do that easier: ``` preg_match_all('/[^(,\s]+|\([^)]+\)/', $str, $matches) ``` But it would be better if you use a real parser. Maybe something like this: ``` $str = 'one, two, three, (four, (five, six), (ten)), seven'; $buffer = ''; $stack = array(); $depth = 0; $len = strlen($str); for ($i=0; $i<$len; $i++) { $char = $str[$i]; switch ($char) { case '(': $depth++; break; case ',': if (!$depth) { if ($buffer !== '') { $stack[] = $buffer; $buffer = ''; } continue 2; } break; case ' ': if (!$depth) { continue 2; } break; case ')': if ($depth) { $depth--; } else { $stack[] = $buffer.$char; $buffer = ''; continue 2; } break; } $buffer .= $char; } if ($buffer !== '') { $stack[] = $buffer; } var_dump($stack); ```
Hm... OK already marked as answered, but since you asked for an easy solution I will try nevertheless: ``` $test = "one, two, three, , , ,(four, five, six), seven, (eight, nine)"; $split = "/([(].*?[)])|(\w)+/"; preg_match_all($split, $test, $out); print_r($out[0]); ``` Output ``` Array ( [0] => one [1] => two [2] => three [3] => (four, five, six) [4] => seven [5] => (eight, nine) ) ```
PHP and RegEx: Split a string by commas that are not inside brackets (and also nested brackets)
[ "", "php", "regex", "parsing", "split", "" ]
I have a project written in Django. All fields that are supposed to store some strings are supposed to be in UTF-8, however, when I run ``` manage.py syncdb ``` all respective columns are created with cp1252 character set (where did it get that -- I have no idea) and I have to manually update every column... Is there a way to tell Django to create all those columns with UTF-8 encoding in the first place? BTW, I use MySQL.
Django does not specify charset and collation in `CREATE TABLE` statements. Everything is determined by database charset. Doing `ALTER DATABASE ... CHARACTER SET utf8 COLLATE utf8_general_ci` before running `syncdb` should help. For connection, Django issues `SET NAMES utf8` automatically, so you don't need to worry about default connection charset settings.
Django’s database backends automatically handles Unicode strings into the appropriate encoding and talk to the database. You don’t need to tell Django what encoding your database uses. It handles it well, by using you database's encoding. I don't see any way you can tell django to create a column, using some specific encoding. As it appears to me, there is absolutely some previous MySQL configuration affecting you. And despite of doing it manually for all column, use these. ``` CREATE DATABASE db_name [[DEFAULT] CHARACTER SET charset_name] [[DEFAULT] COLLATE collation_name] ALTER DATABASE db_name [[DEFAULT] CHARACTER SET charset_name] [[DEFAULT] COLLATE collation_name] ```
How to set the encoding for the tables' char columns in django?
[ "", "python", "mysql", "django", "" ]
I have generated a XML file automatically from the below code. ``` if (isset($_POST["song"])&& $_POST['song'] != "") { $song = $_POST["song"]; } else { $song = array(); } $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes // create root element $root = $dom->createElement("playlist"); $dom->appendChild($root); $root->setAttribute('version', "1"); $root->setAttribute('xmlns', "http://xspf.org/ns/0/"); $rootnext = $dom->createElement("trackList"); $root->appendChild($rootnext); foreach ($song as $counter) { $tokens = ","; $tokenized = strtok($counter, $tokens); // create child element $song = $dom->createElement("track"); $rootnext->appendChild($song); $song1 = $dom->createElement("creator"); $song->appendChild($song1); $text = $dom->createTextNode("www.musicking.in"); $song1->appendChild($text); $song1 = $dom->createElement("title"); $song->appendChild($song1); // create text node $text = $dom->createTextNode($tokenized); $song1->appendChild($text); $tokenized = strtok($tokens); $song1 = $dom->createElement("location"); $song->appendChild($song1); $text = $dom->createTextNode($tokenized); $song1->appendChild($text); } $dom->save("playlist.xml"); ``` Actually after generating XML file it’s storing in the root directory. Can you please tell me how to store the generated XML file into MySQL database? After generating XML file I have to call that file. I am using below code to call: ``` <object data="musicplayer.swf?autostart=true&playlist=playlist.xml" type="application/x-shockwave-flash" width="400" height="300"> <param name="movie" value="musicplayer.swf?autostart=true&playlist=playlist.xml"/> </object> ``` Please tell me how to store and retrieve this playlist.xml file from mysql database?
Use [`DOMDocument::saveXML()`](https://www.php.net/manual/en/domdocument.savexml.php) to get a string representation of your xml file and insert this string into an approrpiate column in your database. Depending on the size fo your data use a column of type `TINYBLOB` (2^8 bytes), `BLOB` (2^16 bytes), `MEDIUMBLOB` (2^24 bytes) or `LONGBLOB` (2^32 bytes) (if using MySQL or an appropriate data type in the RDBMS of your choice).
``` <?php if(isset($_POST["song"])&& $_POST['song'] != "") { $song = $_POST["song"]; } else {$song=array();} $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes // create root element $root = $dom->createElement("playlist"); $dom->appendChild($root); $root->setAttribute('version', "1"); $root->setAttribute('xmlns', "http://xspf.org/ns/0/"); $rootnext = $dom->createElement("trackList"); $root->appendChild($rootnext); foreach ($song as $counter) { $tokens = ","; $tokenized = strtok($counter, $tokens); // create child element $song = $dom->createElement("track"); $rootnext->appendChild($song); $song1 = $dom->createElement("creator"); $song->appendChild($song1); $text = $dom->createTextNode("www.musicking.in"); $song1->appendChild($text); $song1 = $dom->createElement("title"); $song->appendChild($song1); // create text node $text = $dom->createTextNode($tokenized); $song1->appendChild($text); $tokenized = strtok($tokens); $song1 = $dom->createElement("location"); $song->appendChild($song1); $text = $dom->createTextNode($tokenized); $song1->appendChild($text); } DOMDocument::saveXML(); $con = mysql_connect("localhost","music123_sri","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("music123_telugu", $con); $sql="INSERT INTO xml (File) VALUES (" . mysql_escape_string($xmlString) . ")"; $data = mysql_query("SELECT File FROM xml") $info = mysql_fetch_array( $data ); ?> <object data="musicplayer.swf?autostart=true&playlist=<?php $info ?>" type="application/x-shockwave-flash" width="400" height="300"><param name="movie" value="musicplayer.swf?autostart=true&playlist=<?php $info ?>"/></object> can u check the above code its not working. ```
how to store a xml file into mysqldatabase and retrieve it?
[ "", "php", "html", "xml", "" ]
I need to add a delay of about 100 miliseconds to my Javascript code but I don't want to use the `setTimeout` function of the `window` object and I don't want to use a busy loop. Does anyone have any suggestions?
Unfortunately, `setTimeout()` is the only **reliable** way (not the only way, but the only **reliable** way) to pause the execution of the script without blocking the UI. It's not that hard to use actually, instead of writing this: ``` var x = 1; // Place mysterious code that blocks the thread for 100 ms. x = x * 3 + 2; var y = x / 2; ``` you use `setTimeout()` to rewrite it this way: ``` var x = 1; var y = null; // To keep under proper scope setTimeout(function() { x = x * 3 + 2; y = x / 2; }, 100); ``` I understand that using `setTimeout()` involves more thought than a desirable `sleep()` function, but unfortunately the later doesn't exist. Many workarounds are there to try to implement such functions. Some using busy loops: ``` function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } ``` others [using an `XMLHttpRequest` tied with a server script that sleeps for a amount of time before returning a result](http://narayanraman.blogspot.com/2005/12/javascript-sleep-or-wait.html). Unfortunately, those are workarounds and are likely to cause other problems (such as freezing browsers). It is recommended to simply stick with the recommended way, which is `setTimeout()`).
If you're okay with ES2017, `await` is good: ``` const DEF_DELAY = 1000; function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY)); } await sleep(100); ``` Note that the `await` part needs to be in an async function: ``` //IIAFE (immediately invoked async function expression) (async()=>{ //Do some stuff await sleep(100); //Do some more stuff })() ```
Put a Delay in Javascript
[ "", "javascript", "" ]
A RTP packet consists of a 12-byte RTP header and subsequent RTP payload The 3rd and 4th byte of the header contain the Most-Significant-Byte and Least-Significant-Byte of the sequence number of the RTP packet Seq Num= (MSB<<8)+LSB char pszPacket[12]; ... long lSeq = ???? - How to get the sequence number from a packet?
``` unsigned short seq = (packet[2] << 8) | packet[3]; ``` Note that this assumes `packet` is an array of `unsigned char`.
Surely thats just "long lSeq = (unsigned char)(pszPacket[2] << 8) | (unsigned char)pszPacket[3];"?
RTP sequence extract
[ "", "c++", "rtp", "" ]
**The Objective** I want to dynamically assign event handlers to some divs on pages throughout a site. **My Method** Im using jQuery to bind anonymous functions as handlers for selected div events. **The Problem** The code iterates an array of div names and associated urls. The div name is used to set the binding target i.e. attach this event handler to this div event. While the event handlers are successfully bound to each of the div events, the actions triggered by those event handlers only ever target the last item in the array. So the idea is that if the user mouses over a given div, it should run a slide-out animation for that div. But instead, mousing over div1 (rangeTabAll) triggers a slide-out animation for div4 (rangeTabThm). The same is true for divs 2, 3, etc. The order is unimportant. Change the array elements around and events will always target the last element in the array, div4. **My Code - (Uses jQuery)** ``` var curTab, curDiv; var inlineRangeNavUrls=[['rangeTabAll','range_all.html'],['rangeTabRem','range_remedial.html'], ['rangeTabGym','range_gym.html'],['rangeTabThm','range_thermal.html']]; for (var i=0;i<inlineRangeNavUrls.length;i++) { curTab=(inlineRangeNavUrls[i][0]).toString(); curDiv='#' + curTab; if ($(curDiv).length) { $(curDiv).bind("mouseover", function(){showHideRangeSlidingTabs(curTab, true);} ); $(curDiv).bind("mouseout", function(){showHideRangeSlidingTabs(curTab, false);} ); } } ``` **My Theory** I'm either not seeing a blindingly obvious syntax error or its a pass by reference problem. Initially i had the following statement to set the value of curTab: ``` curTab=inlineRangeNavUrls[i][0]; ``` So when the problem occured i figured that as i changed (via for loop iteration) the reference to curTab, i was in fact *changing* the reference for all previous anonymous function event handlers to the new curTab value as well.... which is why event handlers always targeted the last div. So what i really needed to do was pass the curTab *value* to the anonymous function event handlers not the curTab *object* reference. So i thought: ``` curTab=(inlineRangeNavUrls[i][0]).toString(); ``` would fix the problem, but it doesn't. Same deal. So clearly im missing some key, and probably very basic, knowledge regarding the problem. Thanks.
You need to create a new variable on each pass through the loop, so that it'll get captured in the closures you're creating for the event handlers. However, merely moving the variable declaration into the loop won't accomplish this, because [JavaScript doesn't introduce a new scope for arbitrary blocks](https://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement/185283#185283). One easy way to force the introduction of a new scope is to use another anonymous function: ``` for (var i=0;i<inlineRangeNavUrls.length;i++) { curDiv='#' + inlineRangeNavUrls[i][1]; if ($(curDiv).length) { (function(curTab) { $(curDiv).bind("mouseover", function(){showHideRangeSlidingTabs(curTab, true);} ); $(curDiv).bind("mouseout", function(){showHideRangeSlidingTabs(curTab, false);} ); })(inlineRangeNavUrls[i][0]); // pass as argument to anonymous function - this will introduce a new scope } } ``` [As Jason suggests](https://stackoverflow.com/questions/1203876/how-to-pass-a-variable-by-value-to-an-anonymous-javascript-function/1203917#1203917), you can actually clean this up quite a bit using jQuery's built-in [`hover()`](http://docs.jquery.com/Events/hover) function: ``` for (var i=0;i<inlineRangeNavUrls.length;i++) { (function(curTab) // introduce a new scope { $('#' + inlineRangeNavUrls[i][1]) .hover( function(){showHideRangeSlidingTabs(curTab, true);}, function(){showHideRangeSlidingTabs(curTab, false);} ); // establish per-loop variable by passsing as argument to anonymous function })(inlineRangeNavUrls[i][0]); } ```
what's going on here is that your anonmymous functions are forming a closure, and taking their outer scope with them. That means that when you reference curTab inside your anomymous function, when the event handler runs that function, it's going to look up the *current* value of curTab in your outer scope. That will be whatever you last assigned to curTab. (not what was assigned at the time you binded the function) what you need to do is change this: ``` $(curDiv).bind("mouseover", function(){showHideRangeSlidingTabs(curTab, true);} ); ``` to this: ``` $(curDiv).bind("mouseover", (function (mylocalvariable) { return function(){ showHideRangeSlidingTabs(mylocalvariable, true); } })(curTab) ); ``` this will copy the value of curTab into the scope of the outer function, which the inner function will take with it. This copying happens at the same time that you're binding the inner function to the event handler, so "mylocalvariable" reflects the value of curTab at that time. Then next time around the loop, a new outer function, with a new scope will be created, and the next value of curTab copied into it. shog9's answer accomplishes basically the same thing, but his code is a little more austere. it's kinda complicated, but it makes sense if you think about it. Closures are weird. edit: oops, forgot to return the inner function. Fixed.
How to pass a variable by value to an anonymous javascript function?
[ "", "javascript", "closures", "pass-by-reference", "anonymous-function", "pass-by-value", "" ]
I have to read line-by-line a log file. It's about 6MB in size and 40000 line total. But after testing my program, I discover that that log file is only delimited by LF character only. So I can't use the `Readline` method of `StreamReader` class How can I fix this problem? edit: I tried to use Text Reader, but my program still didn't work: ``` using (TextReader sr = new StreamReader(strPath, Encoding.Unicode)) { sr.ReadLine(); //ignore three first lines of log file sr.ReadLine(); sr.ReadLine(); int count = 0; //number of read line string strLine; while (sr.Peek()!=0) { strLine = sr.ReadLine(); if (strLine.Trim() != "") { InsertData(strLine); count++; } } return count; } ```
Does File.ReadAllLines(fileName) not correctly load files with LF line ends? Use this if you need the whole file - I saw a site indicating it's slower than another method, but it's not if you pass the correct Encoding to it (default is UTF-8), plus it's as clean as you can get. Edit: It does. And if you need streaming, TextReader.ReadLine() correctly handles Unix line ends as well. Edit again: So does StreamReader. Did you just check the documentation and assume it won't handle LF line ends? I'm looking in Reflector and it sure seems like a proper handling routine.
`TextReader.ReadLine` already handles lines terminated just by `\n`. From [the docs](http://msdn.microsoft.com/en-us/library/system.io.textreader.readline.aspx): > A line is defined as a sequence of > characters followed by a carriage > return (0x000d), a line feed (0x000a), > a carriage return followed by a line > feed, Environment.NewLine, or the end > of stream marker. The string that is > returned does not contain the > terminating carriage return and/or > line feed. The returned value is a > null reference (Nothing in Visual > Basic) if the end of the input stream > has been reached. So basically, you should be fine. (I've talked about `TextReader` rather than `StreamReader` because that's where the method is declared - obviously it will still work with a `StreamReader`.) If you want to iterate through lines easily (and potentially use LINQ against the log file) you may find my `LineReader` class in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) useful. It basically wraps calls to `ReadLine()` in an iterator. So for instance, you can do: ``` var query = from file in Directory.GetFiles("logs") from line in new LineReader(file) where !line.StartsWith("DEBUG") select line; foreach (string line in query) { // ... } ``` All streaming :)
How to read each line in a file which is delimited by LF only?
[ "", "c#", "file", "streamreader", "" ]
Is there a way for a python script to automatically detect whether it is being run interactively or not? Alternatively, can one detect whether ipython is being used versus the regular c python executable? Background: My python scripts generally have a call to exit() in them. From time to time, I run the scripts interactively for debugging and profiling, usually in ipython. When I'm running interactively, I want to suppress the calls to exit. **Clarification**: Suppose I have a script, myscript.py, that looks like: ``` #!/usr/bin/python ...do useful stuff... exit(exit_status) ``` Sometimes, I want to run the script within an IPython session that I have already started, saying something like: ``` In [nnn]: %run -p -D myscript.pstats myscript.py ``` At the end of the script, the exit() call will cause ipython to hang while it asks me if I really want to exit. This is a minor annoyance while debugging (too minor for me to care), but it can mess up profiling results: the exit prompt gets included in the profile results (making the analysis harder if I start a profiling session before going off to lunch). What I'd like is something that allows me modify my script so it looks like: ``` #!/usr/bin/python ...do useful stuff... if is_python_running_interactively(): print "The exit_status was %d" % (exit_status,) else: exit(exit_status) ```
I stumbled on the following and it seems to do the trick for me: ``` def in_ipython(): try: return __IPYTHON__ except NameError: return False ```
I compared all the methods I found and made a table of results. The best one seems to be this: ``` hasattr(sys, 'ps1') ``` [![enter image description here](https://i.stack.imgur.com/46JOY.png)](https://i.stack.imgur.com/46JOY.png) If anyone has other scenarios that might differ, comment and I'll add it
Detecting when a python script is being run interactively in ipython
[ "", "python", "interactive", "ipython", "" ]
I apologize if this is a dumb question, but hear me out: ``` Dictionary<string, string> genericDict = new Dictionary<string, string>; genericDict.Add("blah", "bloop"); // Use the copy constructor to create a copy of this dictionary return new Dictionary<string, string>(genericDict); ``` In the above code sample, I can create a copy of a generic dictionary. Now suppose I'm using a System.Collections.Specialized.StringDictionary, because I don't feel like typing the "string" types everywhere. StringDictionary has no copy constructor! In fact, it only has the default constructor. Sure, I can iterate through the StringDictionary and add each key/value pair manually, but I don't want to :-P Why no copy constructor? Am I missing something here?
The `StringDictionary` type is rather obsolete. I think that `Dictionary<String,String>` is what you want to use here. The `Dictionary<TKey,TValue>` type implements some strongly-typed interfaces (`ICollection<KeyValuePair<TKey, TValue>>` and `IEnumerable<KeyValuePair<TKey, TValue>>`) which makes it more useful than the `StringDictionary` type. While the `StringDictionary` type *is* strongly typed I wouldn't advise its use for the sake of laziness alone.
If you really want to use a StringDictionary (perhaps to support a *legacy application*), you can create an extension method: ``` public static StringDictionary NewCopy(this StringDictionary olddict) { var newdict = new StringDictionary(); foreach (string key in olddict.Keys) { newdict.Add(key, olddict[key]); } return newdict; } ``` Then you can do this: ``` StringDictionary newdict = olddict.NewCopy(); ```
In C# .NET, is there a reason for no copy constructor for StringDictionary?
[ "", "c#", ".net", "collections", "dictionary", "stringdictionary", "" ]
What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below ``` indexes = [5, 12, 17] list = range(20) ``` return something like this ``` part1 = list[:5] part2 = list[5:12] part3 = list[12:17] part4 = list[17:] ``` If there are no indexes it should return the entire list.
This is the simplest and most pythonic solution I can think of: ``` def partition(alist, indices): return [alist[i:j] for i, j in zip([0]+indices, indices+[None])] ``` if the inputs are very large, then the iterators solution should be more convenient: ``` from itertools import izip, chain def partition(alist, indices): pairs = izip(chain([0], indices), chain(indices, [None])) return (alist[i:j] for i, j in pairs) ``` and of course, the very, very lazy guy solution (if you don't mind to get arrays instead of lists, but anyway you can always revert them to lists): ``` import numpy partition = numpy.split ```
I would be interested in seeing a more Pythonic way of doing this also. But this is a crappy solution. You need to add a checking for an empty index list. Something along the lines of: ``` indexes = [5, 12, 17] list = range(20) output = [] prev = 0 for index in indexes: output.append(list[prev:index]) prev = index output.append(list[indexes[-1]:]) print output ``` produces ``` [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16], [17, 18, 19]] ```
Split a list into parts based on a set of indexes in Python
[ "", "python", "list", "" ]
Right now I'm writing a program that will determine the value of a hand of cards. five in total. i have a cardHand object. I'm planning to write an object that compares two objects together in order to determine which hand has a higher value. the two objects that will be compared are objects that contain the possible hand values (one pair, three of a kind... etc). would stackoverflow see this as a fit method of OOP? PS: i do know that the algorithm is floating around on the internet but im trying to do this by my self first for the XP.
What you'll want to do is something like this: * Create a card class. Add an `operator<` to this class so you can determine the sorting of individual cards. * Create a card collection (hand) class that stores a collection of these cards. Define an operator< for this class as well, to determine the sorting of hands. If you store your cards in an [`std::multiset`](http://www.cplusplus.com/reference/stl/multiset/) in the hand, your cards will group themselves together automatically. That is, if you insert `2, 7, 3, 4, 3` they will be in this order: `2, 3, 3, 4, 7`. This will help you determine things like pairs and tuplets.
Shouldn't each hand object have an innate value? You could then have another object (the dealer?) compare the values of each hand. The dealer could also be used to instantiate each hand object. Then again, maybe I'm taking the whole 'modelling the problem domain' approach a bit too far. ;-)
OOP style question
[ "", "c++", "coding-style", "object", "" ]
I am building a game and the main character's arm will be following the mouse cursor, so it will be rotating quite frequently. What would be the best way to rotate it?
With SDL you have a few choices. --- 1. Rotate all your sprites in advance (pre-render all possible rotations) and render them like you would any other sprite. This approach is fast but uses more memory and more sprites. As [@Nick Wiggle](https://stackoverflow.com/users/279738) pointed out, [RotSprite](http://en.wikipedia.org/wiki/Pixel_art_scaling_algorithms#RotSprite) is a great tool for generating sprite transformations. 2. Use something like [SDL\_gfx](http://freshmeat.net/projects/sdl_gfx/) to do real-time rotation/zooming. (Not recommended, very slow) 3. Use SDL in OpenGL mode and render your sprites to primitives, applying a rotation to the primitives. --- Option `3` is probably your best bet because you gain all of the advantages of using OpenGL. It's really up to you how to want to do it. It's also a possibility that you can load your sprites, perform all rotation calculations with SDL\_gfx and then save the rotated versions to an SDL\_Surface in memory. EDIT: In response to your comment I would recommend checking out Lazyfoo's SDL tutorials. [Specifically, this one about rotation](http://lazyfoo.net/tutorials/SDL/15_rotation_and_flipping/index.php). There is also an [OpenGl function, `glRotatef`](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glRotate.xml), which can be useful in your case. A quick search brought back [this little tidbit](http://lists.libsdl.org/pipermail/sdl-libsdl.org/2003-September/037830.html) which could also be helpful.
``` SDL_RenderCopyEx() ``` has extra arguments for rotation, flipping, and the rotation center.
Best way to rotate an image using SDL?
[ "", "c++", "user-interface", "image", "sdl", "" ]
I have a site running in Django. Frontend is lighttpd and is using fcgi to host django. I start my fcgi processes as follows: ``` python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid ``` For logging, I have a RotatingFileHandler defined as follows: ``` file_handler = RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5,encoding='utf-8') ``` The logging is working. However, it looks like the files are rotating when they do not even get up to 10Kb, let alone 10Mb. My guess is that each fcgi instance is only handling 10 requests, and then re-spawning. Each respawn of fcgi creates a new file. I confirm that fcgi is starting up under new process id every so often (hard to tell time exactly, but under a minute). Is there any way to get around this issues? I would like all fcgi instances logging to one file until it reaches the size limit, at which point a log file rotation would take place.
As Alex stated, logging is thread-safe, but the standard handlers cannot be safely used to log from multiple processes into a single file. [ConcurrentLogHandler](http://pypi.python.org/pypi/ConcurrentLogHandler/0.8.2) uses file locking to allow for logging from within multiple processes.
In your shoes I'd switch to a [TimedRotatingFileHandler](http://docs.python.org/library/logging.handlers.html#timedrotatingfilehandler) -- I'm surprised that the size-based rotating file handles is giving this problem (as it should be impervious to what processes are producing the log entries), but the timed version (though not controlled on exactly the parameter you prefer) should solve it. Or, write your own, more solid, rotating file handler (you can take a lot from the standard library sources) that *ensures* varying processes are not a problem (as they should never be).
Django and fcgi - logging question
[ "", "python", "django", "fastcgi", "lighttpd", "python-logging", "" ]
Essentially need to read the dependencies programmatically without loading the assembly itself, as then you can't unload them
2 solutions come to my mind, although I think there's easier way (which I forgot or don't know :) ): 1. Load your assemblies using some additional `AppDomain` that you can create. Unloading whole `AddDomain` will also unload loaded assemblies (but only those, which were loaded using this `AppDomain`). 2. Use some api, for example [CCI](http://ccimetadata.codeplex.com/) that allows you to look inside managed dll's without loading it using reflection mechanism.
found this System.Reflection.Assembly.ReflectionOnlyLoadFrom(path) does the trick
how to read the assembly manifest without loading the .dll
[ "", "c#", ".net", "reflection", "clr", "" ]
Is there a way to invoke a method on a background thread ? I am aware of BackgroundWorker/Creating a thread or use ThreadPool.QueueUserWorkItem etc but that's not the answer i am looking for for e.g. the SCSF has attributes to ensure the method is invoked on a background or a UI thread I'd like to do something similar for a small app and am looking for a working example
I think the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) will fit your needs. It allows you to [run an operation in the background](http://msdn.microsoft.com/en-us/library/hybbz6ke.aspx) in a Winform app. Those articles have working examples. :)
There are many ways to invoke a method on a background thread. Do you want to block while the method is running? Do you want a result returned from the method? Do you want this result displayed in the UI? Is the method called only once? Many times, as needed? Many times in a loop? Asynchronously? Should the background thread continue if your app quits? The answer to these questions will tell you which method you should use. You can get an overview of the various thread message passing methods from a great [article](http://www.codeproject.com/csharp/AsyncMethodInvocation.asp) at The Code Project.
How to Invoke on background thread
[ "", "c#", "winforms", "multithreading", "thread-safety", "switching", "" ]
If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?
Regular expressions: ``` var numberPattern = /\d+/g; 'something102asdfkj1948948'.match( numberPattern ) ``` This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null. To concatenate them: ``` 'something102asdfkj1948948'.match( numberPattern ).join('') ``` Assuming you're not dealing with complex decimals, this should suffice I suppose.
You could also strip all the non-digit characters (`\D` or `[^0-9]`): ``` let word_With_Numbers = 'abc123c def4567hij89' let numbers = word_With_Numbers.replace(/\D/g, ''); console.log(numbers) ```
Regex using javascript to return just numbers
[ "", "javascript", "regex", "" ]
I have a website authored in PHP where any time a user receives an error I will redirect them to a another page (using `header(Location:...)`) and put the error ID in the URL so that I know which error to display. E.g. If the user tries to access a product page but that item is no longer available I will redirect back to the category of items they were previously looking at and display an error based on the error ID I have specified in the URL. www.example.com/view\_category.php?product\_category\_id=4&error\_id=5 There are two things I don't like about this approach: 1. It displays the error\_id in the URL. 2. if the page is refreshed, the error will still display. Is there a way to cleanly remove a specific $\_GET variable from a URL while leaving the rest of the variables intact AFTER the page is loaded? I'm thinking maybe it's using modRewrite or a redirect back to the page itself but removing the error\_id from the URL or using a $\_SESSION variable and avoiding putting the error\_id in the URL. Your thoughts? I really am learning a lot from this community and thought if I posed the question I might be able to learn something new or to get some varied ideas as I'm fairly new to scripting.
No, there's no way to do that explicitly - at least not without a page refresh but then you'd lose the data anyway. You're better off using a temporary session variable. ``` if ( /* error condition */ ) { $_SESSION['last_error_id'] = 5; header( 'Location: http://www.example.com/view_category.php?product_category_id=4' ); } ``` Then, in view\_category.php ``` if ( isset( $_SESSION['last_error_id'] ) ) { $errorId = $_SESSION['last_error_id']; unset( $_SESSION['last_error_id'] ); // show error #5 } ```
Yes, there is a way to remove especific `$_GET` from PHP... ``` varToRemove = "anyVariable"; foreach($_GET as $variable => $value){ if($variable != varToRemove){ $newurl .= $variable.'='.$value.'&'; } } $newurl = rtrim($newurl,'&'); ``` Then, put the $newurl in the link.. like this: `pageurl?something=something&<? echo $newurl; ?>` I know it´s an old post, but, other programers may be search for it!
How to remove a specific $_GET variable from a URL
[ "", "php", "error-handling", "get", "" ]
The first line is true, the second is false. htmlOut and s2 are StringWriter objects. ``` bool b = s2.ToString() == htmlOut.ToString(); ret = htmlOut.Equals(s2); ``` I expected true which b is but why is ret false?
StringWriter doesn't override object.Equals. ``` htmlOut.Equals(s2); ``` is equivalent to : ``` object.ReferenceEquals(htmlOut, s2); ```
`StringWriter` uses an internal `StringBuilder` to write to. `StringWriter.ToString()` returns the string built by `StringBuilder`. `StringWriter` does not override `object.Equals()` so `StringWriter.Equals()` compares if the two objects are the same reference, not if their string representations are equal.
Why is .Equal False when i expect it to be true?
[ "", "c#", ".net", "" ]
Is there a better way to do this simple task below? Like with an array or even another method? ``` <?PHP // current way if ($city != NULL) { $city = FilterALLHTML($city); } if ($state != NULL) { $state = FilterALLHTML($state); } if ($title != NULL) { $title = FilterALLHTML($title); } if ($division != NULL) { $division = FilterALLHTML($division); } ?> ``` Here is my current function ``` function FilterALLHTML($document) { //old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html $text = strip_tags($document); $search = array ("/f.?u.?c.?k/i", "/(s|$).?h.?i.?t/i", '/(potspace|mycrib|palbolt)/i'); $text = preg_replace ($search, '', $text); return $text; } ``` --- **UPDATE - Ok my new function after the suggestions from this post thanks guys** ``` function FilterALLHTML($var) { //old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html if ($var != null){ $text = strip_tags($var); $search = array ("/f.?u.?c.?k/i", "/(s|$).?h.?i.?t/i", '/(potspace|mycrib|palbolt|pot space)/i'); $text = preg_replace ($search, '', $text); return $text; } return null; } ```
Change your `FilterALLHTML` function to do the `null` check and have it return `null`? Then you can throw away all the `if`s. Example: ``` function FilterALLHTML($input) { if ($input === null) return null; // Original code, I'll just use strip_tags() for a functional example return strip_tags($input); } ``` **Edit:** I felt like sharing an alternative to variable variables, as I don't really like the idea of using string literals instead of variable names. References all the way :) ``` function FilterALLHTML(&$text) { if ($text !== null) { // Omitted regex bit for simplicity $text = strip_tags($text); } } $city = "<b>New York</b>"; $state = null; $title = "<i>Mr.</i>"; $fields = array(&$city, &$state, &$title); foreach ($fields as &$var) FilterALLHTML($var); ``` (*note: `FilterALLHTML` implementation differs from first example*)
Yes, use PHP's [variable variables](http://www.php.net/manual/en/language.variables.variable.php). ``` $vars = array('city','state','title','division'); foreach($vars as $v) { if ($$v != null) $$v = FilterAllHTML($$v); } ``` If you know for a fact that all the variables have been previously defined, then you don't need the null check. Otherwise, the null check will prevent E\_NOTICE errors from triggering.
Can this PHP code be improved?
[ "", "php", "" ]
I have a java app + SQL server database. DB operation use JDBC with dynamic SQL string. Example: Select Column from tab where column=StringParm StringParam is user input. if the stringParm include apostrophe, Java app will throw exception and said Can't execute the SQL. How to resolve this problem with no java code changing?
Never put user input directly in a SQL query. You need to use a PreparedStatement with parameters. Without changing the Java code, I don't see any way to make this safe.
I'm guessing you construct the SQL in some manner like ``` String sql = "Select Column from tab where column='" + StringParm + "'"; ``` Or something like it ? If you do that, you're open to all kinds of exploits and you'll also see behavior like you describe, where the resulting string is no longer valid SQL. You'd have to escape the user supplied parameter first. The best solution is to use PreparedStatements, so you do ``` Statement stmt = conn.prepareStatement("Select Column from tab where column=?"); stmt.setString(1,StringParam); ``` I can't see any quick way of solving your problem without altering any Java code though, bar perhaps escaping/sanitizing the input before it hits your code (e.g. javascript if you're a webapp)
How to capture/encode special character for SQL Server in java app?
[ "", "java", "sql-server-2008", "" ]
I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible. That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must. Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.
The real answer is that there isn't a library, and you can't make one. You can use rarfile, or you can use 7zip unRAR (which is less free than 7zip, but still free as in beer), but both approaches require an external executable. The license for RAR basically requires this, as while you can get source code for unRAR, you cannot modify it in any way, and turning it into a library would constitute illegal modification. Also, solid RAR archives (the best compressed) can't be randomly accessed, so you have to unarchive the entire thing anyhow. WinRAR presents a UI that seems to avoid this, but really it's just unpacking and repacking the archive in the background.
See the rarfile module: * <http://grue.l-t.ee/~marko/src/rarfile/README.html> * <http://pypi.python.org/pypi/rarfile/> * <https://github.com/markokr/rarfile>
Read content of RAR file into memory in Python
[ "", "python", "linux", "stream", "rar", "" ]
I have a script where i need to pull two seperate and different RSS feeds, break them up, assign variables, and execute code thats different for each file. What im wondering, and i dont know if this can even be done, but once i use a function and give it settings, can i then re-use that function with different settings even though some of its internal variables will have different values? say the first time i run it, it looks like this ``` $xml = simplexml_load_string($raw_xml); foreach($xml->channel as $channel) ``` then i run ``` $xml = simplexml_load_string($raw_xml2); foreach($xml->item as $item) ``` Will I get errors or redundant data because i re-used the XML variable?
Not at all. Assigning a new value to a variable completely overwrites the first value. The code you posted should work fine.
Just assign it to a different variable. Very easy.
reading two rss/xml files in a single php page
[ "", "php", "xml", "simplexml", "" ]
We store documents in an SQL Server 2005 database table with a column format of "Image". Every time I try to store a PDF file which is greater than 1 Meg, it somehow gets corrupted. Is there any particularly efficient method in .NET to serialize and store large files (~10megs) into a database? [Edit] Microsoft actually says the max file size is about 2G Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes. <http://msdn.microsoft.com/en-us/library/ms187993.aspx>
A quick solution if you don't want to refactor your documents out of the db at this point is to use compression on your data: <http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx> i doubt that Sql Server is corrupting your files but working in the gzip algorithm might help you find a bug.
Wouldn't it make more sense to store the file in the file system, and store a reference to the file in the database? storing 20MB files in the database sounds like it could cause some performace issues.
Most efficient way to store a 20 Meg file in a SQL Server 2005 IMAGE Column
[ "", "c#", "sql-server", "sql-server-2005", "image", "database-design", "" ]
I'm writing my first bit of jQuery, and I'm having a problem with `jQuery.get()`. I'm calling this; ``` $.get(url, updateList); ``` where updateList is defined like so; ``` function updateList(data) { if (data) { $('#contentlist').html(data); } else { $('#contentlist').html('<li><a href="#" id="synclink">Nothing found. Try again</a></li>'); } } ``` The function runs, and `updateList` is called. It works fine in Internet Explorer. However, in Firefox, the `data` parameter is always empty. I would expect it to be filled with the content of the webpage I passed in as the URL. Am I using it wrong? Notes; * in Firebug, I've enabled the *Net* panel, and I get the request showing up. I get a `200 OK`. The `Headers` tab looks fine, while the `Response` and `HTML` panels are both empty. * The page I'm trying to download is a straight HTML page -- there's no problem with server code. * The page with JavaScript is local to my machine; the page I'm downloading is hosted on the Internet. * I've tried checking the URL by copy-pasting it from my page into the browser -- it happily returns content. * The error occurs even in Firefox Safe Mode -- hopefully that rules out rogue addins.
You probably won't be able to do this due to cross-domain security. Internet Explorer will allow you to Ajax remote domain when running from `file://`, but Firefox and Chrome won't. Try to put both files on the same server and see if it works (it should).
You'll most likely need to fix your page that you're quering with XHR because it should be returning content. Copy paste the link in the Firebug net tab and make a new tab, and edit that page with your text editor so it spits content back.
jQuery $.get() function succeeds with 200 but returns no content in Firefox
[ "", "javascript", "jquery", "ajax", "firefox", "" ]
I'm searching for a way to extract a file in c++ by using the boost::iostreams classes. There is an example in the [boost documentation](http://www.boost.org/doc/libs/1_39_0/libs/iostreams/doc/classes/gzip.html#examples). But it outputs the content of the compressed file to std::cout. I'm looking for a way to extract it to a file structure. Does anybody know how to do that? Thanks!
Boost.IOStreams does not support compressed archives, just single compressed files. If you want to extract a .zip or .tar file to a directory tree, you'll need to use a different library.
The example in the documentation shows how to decompress the file and push the result to another stream. If you want the output to be directed to an in-memory array instead, you can use a stream of type `boost::iostreams::stream<boost::iostreams::array_source>`instead. That is basically a stream-wrapper around an array. I'm not sure what you mean when you say you want the output in "a file structure" though.
extracting compressed file with boost::iostreams
[ "", "c++", "compression", "boost-iostreams", "" ]
I have an typical CUSTOMER/ORDERS set of tables and I want to display the total **percentage** of sales a particular customer is responsible for. I can get the total number of orders in the system like so: ``` SELECT COUNT(order_id) FROM orders ``` And I can get the the total number of orders made by the customer like so: ``` SELECT COUNT(order_id) FROM orders WHERE cust_id = 541 ``` How can I combine these into a single query that returns the percentage of sales for a particular customer? Thanks!
MySQL: ``` SELECT ROUND( 100.0 * ( SUM(IF(cust_id = 541, 1, 0)) / COUNT(order_id) ), 1) AS percent_total FROM orders; ``` **Edit** I guess it helps if I would have noticed the **postgres** tag. I thought it was a MySQL question. PostgreSQL: ``` SELECT ROUND( 100.0 * ( SUM(CASE WHEN cust_id = 541 THEN 1 ELSE 0 END)::numeric / COUNT(order_id) ), 1) AS percent_total FROM orders; ``` P.S. My PostgreSQL is rusty, so if the MySQL query works on PostgreSQL I'd like to know :) **Edit 2** I can't stress enough to be wary of the count(\*) suggestion below. You generally want to avoid this with PostgreSQL.
One solution is to use a nested query- ``` SELECT count(*) / (SELECT count(*) FROM orders) FROM orders WHERE cust_id = 541 ```
How To Do Percent/Total in SQL?
[ "", "sql", "postgresql", "" ]
When I call the EntryPoint with a parameter of type TemplateA, I always receive an exception, since the first overload is always called. What I expected to happen is that the most specific method (second overload) will be called due to dynamic binding. Any ideas why? ``` private object _obj; public void EntryPoint(object p) { myFunc(p); } //first overload private void myFunc(object container) { throw new NotImplementedException(); } //second overload private void myFunc(TemplateA template) { _obj = new ObjTypeA(template); } //third overload private void myFunc(TemplateB template) { _obj = new ObjTypeB(template); } ```
You will be able to do this in C# 4.0 if you use `dynamic` instead of `object`. Download the Visual Studio 2010 Beta if you want to give it a try. Until then, the compiler chooses exactly which method to call based on the parameter's compile-time types. It's not clear from your question whether you know about ordinary single-dispatch polymorphism, as it would solve your example problem. ``` class TemplateBase { public virtual object MyFunc() { throw new NotImplementedException(); } } class TemplateA : TemplateBase { public override object MyFunc() { return new ObjTypeA(this); } } class TemplateB : TemplateBase { public override object MyFunc() { return new ObjTypeB(this); } } ``` And elsewhere: ``` private object _obj; public void EntryPoint(TemplateBase p) { _obj = p.MyFunc(); } ``` There are alternatives for when you can't modify the `TemplateN` classes. The simplest would be for the `EntryPoint` method to have access to a `Dictionary` mapping from `Type` to some delegate. ``` Dictionary<Type, Func<object, object>> _myFuncs; _myFuncs.Add(typeof(TemplateA), o => new ObjTypeA((TemplateA)o)); _myFuncs.Add(typeof(TemplateB), o => new ObjTypeB((TemplateA)o)); ``` It could then look up the delegate to execute for the type of object passed to it. ``` Func<object, object> f = _myFuncs[p.GetType()]; _obj = f(p); ``` But you need to take care over inheritance hierarchies if you want to mimic the exact way virtual functions work.
> What I expected to happen is that the most specific method (second overload) will be called due to dynamic binding. Where do you see dynamic binding here? The static type of the variable is `object`. Unless you call a virtual method *on it* directly, no dynamic dispatch is going to happen. The overload is completely statically resolved at compile time. Eric Lippert has a related blog entry on this: [Double Your Dispatch, Double Your Fun](http://blogs.msdn.com/ericlippert/archive/2009/04/09/double-your-dispatch-double-your-fun.aspx).
Methods overloading
[ "", "c#", "overloading", "" ]
SmtpClient() allows you to add attachments to your mails, but what if you wanna make an image appear when the mail opens, instead of attaching it? As I remember, it can be done with about 4 lines of code, but I don't remember how and I can't find it on the MSDN site. EDIT: I'm not using a website or anything, not even an IP address. The image(s) are located on a harddrive. When sent, they should be part of the mail. So, I guess I might wanna use an tag... but I'm not too sure, since my computer isn't broadcasting.
One solution that is often mentioned is to add the image as an `Attachment` to the mail, and then reference it in the HTML mailbody using a `cid:` reference. However if you use the `LinkedResources` collection instead, the inline images will still appear just fine, but don't show as additional attachments to the mail. **That's what we want to happen**, so that's what I do here: ``` using (var client = new SmtpClient()) { MailMessage newMail = new MailMessage(); newMail.To.Add(new MailAddress("you@your.address")); newMail.Subject = "Test Subject"; newMail.IsBodyHtml = true; var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"), "image/png"); inlineLogo.ContentId = Guid.NewGuid().ToString(); string body = string.Format(@" <p>Lorum Ipsum Blah Blah</p> <img src=""cid:{0}"" /> <p>Lorum Ipsum Blah Blah</p> ", inlineLogo.ContentId); var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); view.LinkedResources.Add(inlineLogo); newMail.AlternateViews.Add(view); client.Send(newMail); } ``` **NOTE:** This solution adds an `AlternateView` to your `MailMessage` of type `text/html`. For completeness, you should also add an `AlternateView` of type `text/plain`, containing a plain text version of the email for non-HTML mail clients.
The HTML Email and the images are attachments so it's just a case of referring to the image(s) by their content ids, i.e. ``` Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text) Dim RGen As Random = New Random() A.ContentId = RGen.Next(100000, 9999999).ToString() EM.Body = "<img src='cid:" + A.ContentId +"'>" ``` There seems to be comprehensive examples here: [Send Email with inline images](http://www.dotnetspider.com/resources/28412-Send-Email-with-inline-images.aspx)
C# sending mails with images inline using SmtpClient
[ "", "c#", "inline", "smtpclient", "" ]
Here's a problem that I seem to be running into working with an accounting system. I have a set of transactions, but their sum does not equal the amount that the accounting department thinks that it should. They are not questioning the math, just the transactions being included :p Is there an algorithm that would help me determine which transactions in the set should not be included in order for the sum to match a given amount. ``` Given Set: 2 4 5 7 Given Sum Amount: 13 Result Set: 2 4 7 ``` **Edit:** There's less than 100 transactions in the set. Does anyone have a C# example as there is not one on the [Solving the NP-complete problem in XKCD](https://stackoverflow.com/questions/141779/solving-the-np-complete-problem-in-xkcd) question? *Man, I should have gotten a CS degree.*
This is the [Subset Sum](http://en.wikipedia.org/wiki/Subset_sum_problem) problem, which is [NP-Complete](http://en.wikipedia.org/wiki/NP-complete). But that doesn't mean there isn't an algorithm for finding a subset sum.
This is the [Knapsack Problem](http://en.wikipedia.org/wiki/Knapsack_problem) and it's NP-Complete. You won't easily solve it exactly with anything except small input sets. For any decent-sized problem set, it's one of those lifetime-of-the-universe-to-solve problems. That said, there are genetic-algorithm knapsack solvers out there.
How to find what numbers in a set add up to another given number?
[ "", "c#", "algorithm", "np-complete", "np-hard", "" ]
In the PHP world it's common to create a directory called 'uploads' or something similar in the application folder. All uploaded files are then stored there, the database containing the relative paths to those files. In the Java/servlet world however, I'm not sure what the common way to handle uploaded files is. Getting the path to a directory inside the application directory can be difficult, and the entire directory could be destroyed if the WAR file is redeployed. At the moment I'm storing uploaded files in the database as a blob, but this is not my preferred solution. So my question is, where should I store uploaded files?
In any folder on the disk that doesn't belong to your app's file structure nor the application server/container server. You may keep the absolute path to this folder/folders as a configuration in a file or database.
Why not store in a directory outside the .war hierarchy ? Specify a directory in a servlet parameter (to make it configurable), and check/create on servlet initialisation (so things don't first blow up when someone uploads a file for the first time).
Servlets: where to store uploaded files?
[ "", "java", "servlets", "file-upload", "" ]
Short version: Is there a simple way to get the value of a primary key after doing a merge() in Hibernate JPA? Details: I'm making a generic library that uses Hibernate. The library uses JPA's merge() to serialize a POJO to the database. What's the best way to discover the primary key's new value? I'm assuming that the primary key will never be a composite key. However, there are cases where the POJO is a subclass of class containing the primary key. So, using reflection on the POJO isn't an easy answer (ie it's necessary to reflect the class and all super classes). Any suggestions?
The Hibernate SessionFactory has methods to do this: SessionFactory.getClassMetaData().getIdentifierPropertyName(). From there I was able to get it working. Thanks everyone!
You can look at all of the methods (or fields) in the class (and parent classes) until you find one with the @Id tag, then use that field to get the value off of the returned result from the merge call. Outside of that, I do not know of a way without knowing *what* the element is directly. ***Edit*** Much like someone else mentioned, you could require a standard method - and this could be on an interface. Thus, you could cast the classes to that interface, and then get the id off of them.
Find primary key created by Hibernate JPA
[ "", "java", "hibernate", "jpa", "" ]
I'm trying to write a program that takes input of - hexadecimals, octals, and decimals -, stores them in integer variables, and outputs them along with their conversion to decimal form. For example: User inputs: 0x43, 0123, 65 Program outputs: ``` 0x43 hexadecimal converts to 67 decimal 0123 octal converts to 83 decimal 65 decimal converts to 65 decimal ``` So obviously I need a way to interpret the numbers, but I'm not sure how to go about doing it. I've tried various methods such as reading them into a function and converting them into a string, and vice versa (see [here](https://stackoverflow.com/questions/1195656/integer-storage-hexadecimal-octal) for code examples), but interpreting the numbers always requires conversion to some format that trashes the original input. The only thing I can think of is overloading a >> operator that reads a character at a time and if it sees 0x or 0 at the beginning of the input then it stores the whole input into a string before it is read into an int. Then the program would somehow have to determine the right manipulator during output. Not sure if there is a simpler way to do this, any help is appreciated. Edit: This has been solved, but I decided to post the code in if anyone is interested. ``` #include "std_lib_facilities.h" void number_sys(string num, string& s) { if(num[0] == '0' && (num[1] != 'x' && num[1] != 'X')) s = "octal"; else if(num[0] == '0' && (num[1] == 'x' || num[1] == 'X')) s = "hexadecimal"; else s = "decimal"; } int main() { cout << "Input numbers in hex, dec, or oct. Use 0xx to cancel.\n"; string a; while(cin >> a){ if(a == "0xx")break; string atype; number_sys(a, atype); int anum = strtol(a.c_str(), NULL, 0); cout << a << setw(20-a.length()) << atype << setw(20) << "converts to" << setw(10) << anum << setw(10) << "decimal\n"; } keep_window_open(); } ```
Take a look at the strtol function. ``` char * args[3] = {"0x43", "0123", "65"}; for (int i = 0; i < 3; ++i) { long int value = strtol(args[i], NULL, 0); printf("%s converts to %d decimal\n", args[i], value); } ``` Outputs: ``` 0x43 converts to 67 decimal 0123 converts to 83 decimal 65 converts to 65 decimal ```
You could always store it as a string to start, and look at the first two characters to see if they are 0x: ``` std::string num; std::cin >> num; if (num[0] == '0' && num[1] == 'x') { //handle } ```
How to interpret numbers correctly (hex, oct, dec)
[ "", "c++", "numbers", "string-parsing", "" ]
Let's say I have the following: ``` def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) return decorated @with_connection def spam(connection): # Do something ``` I want to test the `spam` function without going through the hassle of setting up a connection (or whatever the decorator is doing). Given `spam`, how do I strip the decorator from it and get the underlying "undecorated" function?
In the general case, you can't, because ``` @with_connection def spam(connection): # Do something ``` is equivalent to ``` def spam(connection): # Do something spam = with_connection(spam) ``` which means that the "original" spam might not even exist anymore. A (not too pretty) hack would be this: ``` def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) decorated._original = f return decorated @with_connection def spam(connection): # Do something spam._original(testcon) # calls the undecorated function ```
There's been a bit of an update for this question. If you're using Python 3, and `@functools.wraps` you can use `__wrapped__` property for decorators from stdlib. Here's an example from [Python Cookbook, 3rd edition, section 9.3 Unwrapping decorators](https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch09.html#_unwrapping_a_decorator) ``` >>> @somedecorator >>> def add(x, y): ... return x + y ... >>> orig_add = add.__wrapped__ >>> orig_add(3, 4) 7 >>> ``` If you are trying to unwrap a function from custom decorator, the decorator function needs to use `wraps` function from `functools` See discussion in [Python Cookbook, 3rd edition, section 9.2 Preserving function metadata when writing decorators](https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch09.html#decoratormeta) ``` >>> from functools import wraps >>> def somedecorator(func): ... @wraps(func) ... def wrapper(*args, **kwargs): ... # decorator implementation here ... # ...... ... return func(*args, **kwargs) ... ... return wrapper ```
How to strip decorators from a function in Python
[ "", "python", "decorator", "" ]
In linux, is there a built-in C library function for getting the CPU load of the machine? Presumably I could write my own function for opening and parsing a file in /proc, but it seems like there ought to be a better way. * Doesn't need to be portable * Must not require any libraries beyond a base RHEL4 installation.
If you really want a c interface use `getloadavg()`, which also works in unixes without `/proc`. It has a [man page](http://www.manpagez.com/man/3/getloadavg/) with all the details.
The preferred method of getting information about CPU load on linux is to read from **/proc/stat**, **/proc/loadavg** and **/proc/uptime**. All the normal linux utilities like **top** use this method.
C API for getting CPU load in linux
[ "", "c++", "c", "linux", "" ]
Pretty straightforward, I've got a JS script that's included on many different sites and needs to have parameters passed to it. It would be useful if those could be passed via the URL, eg: ``` <script type="text/javascript" src="http://path.to/script.js?var1=something&var2=somethingelse"></script> ``` Yes, you can still pre-populate variables, in a separate script tag, but it's a smidge messy and less easy to pass around: ``` <script type="text/javascript">var1=something; var2=somethingelse</script> <script type="text/javascript" src="http://path.to/script.js"></script> ```
`error.fileName` will tell you the file that a script is from (not sure if it works in every browser; I've tested it in Firefox & Opera) ``` var filename = (new Error).fileName; ```
Yep. Added bonus: I convert the query string parameters into a more usable javascript hash. HTML: ``` <script src="script.js?var1=something&var2=somethingelse" type="text/javascript"></script> ``` `script.js`: ``` var scriptSource = (function() { var scripts = document.getElementsByTagName('script'); return scripts[scripts.length - 1].src }()); var params = parseQueryString(scriptSource.split('?')[1]); params.var1; // 'something' params.var2; // 'somethingelse' // Utility function to convert "a=b&c=d" into { a:'b', c:'d' } function parseQueryString(queryString) { var params = {}; if (queryString) { var keyValues = queryString.split('&'); for (var i=0; i < keyValues.length; i++) { var pair = keyValues[i].split('='); params[pair[0]] = pair[1]; } } return params; } ```
Is there any analogue in Javascript to the __FILE__ variable in PHP?
[ "", "javascript", "variables", "" ]
I always thought you should never set/get a member variable directly. E.g. ``` $x = new TestClass(); $x->varA = "test": echo $->varB; ``` I thought you should *always* use object methods to access member variables. But I've just been looking at \_\_set and \_\_get, which imply it's ok to access members directly.
There's no right answer here. In the beginning, direct access to member variables was considered a bad idea because you lose the ability to make that access conditional upon some set of arbitrary programming logic. That's why we have the terror of getter and setter methods. Having magic methods like `__set` and `__get` removes this concern. You can have users of your object access member variables all you want and then if you discover you need some programatic logic around that access, you can use the magic methods. **However**, particularly in PHP, `__set` and `__get` aren't free from a performance perspective. Also, remember that `__set` and `__get` are only invoked when an inaccessible (private, protected, etc.) member variable is accessed. This means there's no way to invoke `__set` and `__get` from within a class, outside of removing the member variable from the class definition, which makes your class less clear. Like most things PHP, there's no clear "best" way to handle this.
Not only in PHP but in object oriented programming in general, if a class has member variables for which it's not necessary to execute code when they are accessed, there's no need to make setters and getters, and the variables can be accessed directly.
OO PHP direct member access
[ "", "php", "oop", "" ]
How can I pass input from a text-type input element into a hidden input element in the same form on a site that has jquery installed?
Triggered when the text changes: ``` $("#text_id").change(function(){ $("#hidden_id").val($("#text_id").val()) }); ``` Triggered when the form submits: ``` $("#form_id").submit(function(){ $("#hidden_id").val($("#text_id").val()) }); ``` Check out other [jQuery Events](http://docs.jquery.com/Events).
If `input_1` is the id of the input you want to populate, and `input_2` the id you want to populate **from**, use: ``` $("#input_1").val($("#input_2").val()) ```
Javascript question: How do I duplicate user input into a hidden field?
[ "", "javascript", "jquery", "input", "hidden-field", "" ]
this is what i have right now Drawing an RSS feed into the php, the raw xml from the rss feed reads: ``` Paul&#8217;s Confidence ``` The php that i have so far is this. ``` $newtitle = $item->title; $newtitle = utf8_decode($newtitle); ``` The above returns; ``` Paul?s Confidence ``` If i remove the utf\_decode, i get this ``` Paul’s Confidence ``` When i try a str\_replace; ``` $newtitle = str_replace("&#8221;", "", $newtitle); ``` It doesnt work, i get; ``` Paul’s Confidence ``` Any thoughts?
Try this: ``` $newtitle = html_entity_decode($newtitle, ENT_QUOTES, "UTF-8") ``` If this is not the solution browse this page <https://www.php.net/manual/en/function.html-entity-decode.php>
This is my function that always works, regardless of encoding: ``` function RemoveBS($Str) { $StrArr = str_split($Str); $NewStr = ''; foreach ($StrArr as $Char) { $CharNo = ord($Char); if ($CharNo == 163) { $NewStr .= $Char; continue; } // keep £ if ($CharNo > 31 && $CharNo < 127) { $NewStr .= $Char; } } return $NewStr; } ``` How it works: ``` echo RemoveBS('Hello õhowå åare youÆ?'); // Hello how are you? ```
removing strange characters from php string
[ "", "php", "" ]
Has anyone used the **Intel Math Kernel library** <http://software.intel.com/en-us/intel-mkl/> I am thinking of using this for **Random Number generation from a C# application** as we need extreme performance (1.6 trillion random numbers per day). Also any advice on minimising the overhead of **consuming functions from this c++ code in my c#** Monte Carlo simulation. * Am about to download the Eval from the site and above and try and benchmark this from my c# app, any help much appreciated. Thanks
I've developed a monte carlo/stochastic software using that utilizes the MKL and the Intel Compiler. In general, you will have to wrap the random number generation in a c++ dll. This is the easiest, as you can control name mangling and calling convention. As for minimizing overhead, the best way of going about this is to keep the simulation code completely in c++, where it probably belongs anyway, and only having the C# layer call in to get an update. The only way to minimize the interop penalty is to make fewer calls, I've found the other advice (/unsafe, etc) to be useless from a performance perspective. You can see an example of the interaction and structure of this type of program at my project's repository - [Stochfit](http://stochfit.svn.sourceforge.net/viewvc/stochfit/trunk/StochFitMain/).
I don't know much / anything about this library. But if it is truly C++ code then you won't be able to call it directly from C#. C# is only capable of interacting with C++ in one of three ways 1. PInvoke into a C wrapper on top of the C++ lib 2. COM Interop 3. Reverse PInvoke (still need 1 or 2 above to insert the wrapper func) If it is a large C++ code base, it may be best to create a thin C++/CLI wrapper to interact with the library. Then call that from C#.
Intel Math Kernel on windows, calling from c# for random number generation
[ "", "c#", "math", "random", "intel", "" ]
I've done some searching on this but can't find any sort of best practice or recommendation -- and perhaps that's because there isn't any. I'm using all sorts of jQuery plugins on my site, in addition to TinyMCE and some other plugins, and my site's specific JS file. On top of that, I have three stylesheets ..... and there's more coming as the site grows! Is there any sort of 'limit' or anything you should keep an eye out for including scripts in the tag? I know that each one is another HTTP request that needs to be completed, but if they are all minified and as small as can be, will there be issues? ``` <link rel="stylesheet" type="text/css" href="http://mysite.com/assets/css/redmond.css" /> <link rel="stylesheet" type="text/css" href="http://mysite.com/assets/css/style.css" /> <link rel="stylesheet" type="text/css" href="http://mysite.com/assets/css/jqueryFileTree.css" /> <!--[if gte IE 7]> <link rel="stylesheet" type="text/css" href="http://mysite.com/scripts/style.ie.css" /> <![endif]--> <script type="text/javascript" src="http://mysite.com/assets/js/jquery.js"></script> <script type="text/javascript" src="http://mysite.com/assets/js/jquery-ui.js"></script> <script type="text/javascript" src="http://mysite.com/assets/js/jqueryFileTree.js"></script> <script type="text/javascript" src="http://mysite.com/assets/js/jqminmax.js"></script> <script type="text/javascript" src="http://mysite.com/assets/js/jquery.corner.js"></script> <script type="text/javascript" src="http://mysite.com/assets/js/jquery.jeditable.js"></script> <script type="text/javascript" src="http://mysite.com/assets/js/jquery.qtip.js"></script> <script type="text/javascript" src="http://mysite.com/assets/plugins/tinymce/tiny_mce.js"></script> <script type="text/javascript" src="http://mysite.com/assets/js/latitude.js"></script> ```
Not good! I would reccomend combining these files into one js and one css using a script before deploying to live. There are many reasons why this is not good, see the link below for more info: <http://developer.yahoo.com/performance/rules.html> **Edit:** To answer further No, there are no limits on the number of files, but most browsers can only have 2 connections (for a site) to a web server at any one time and thus will load your js 2 files at a time. The [YSlow plugin](http://developer.yahoo.com/yslow/) for firefox will show you a graph of how your files are being downloaded. If you are using ASP.NET this [codeproject](http://www.codeproject.com/KB/aspnet/combineMinify.aspx?fid=1537173&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=3013634) article might help, if you are on linux then [this](http://littlegreenfootballs.com/article/30834_Tech_Note-_Minifying_Javascript_Quickly_and_Easily) might help. **Edit:** A simple batch file on windows (to plug into your build tools) would be ``` @echo off copy file1.js + file2.js + file3.js merged.js /b ```
Browsers have a limit to the number of concurrent requests to a domain, so they can slow down the loading of other items in your page. For example, [IE8 has a limit of 6 concurrent connections, and IE7 has a limit of 2](http://weblogs.asp.net/mschwarz/archive/2008/07/21/internet-explorer-8-and-maximum-concurrent-connections.aspx). I'd recommend combining the files you host locally, referencing others externally (e.g. on Google), and potentially moving others to the bottom of the page so they don't delay load. You can combine scripts with a lot of online tools, like [jsCompress](http://jscompress.com/). It's got an "Upload Files" tab, so you can just upload all your js files and it'll compress and minify. There are also server-side utilities that will do that for you. You don't say what server-side technology you're using, but for instance in the PHP world you can use [Minify](http://code.google.com/p/minify/).
How many is too many includes in <HEAD>?
[ "", "javascript", "css", "xhtml", "" ]
**Scenario**: A `Customer` entity has properties for `State` and `Color`. i.e. Washington and green. The SQL Server foreign key relationships are setup fine, and all have correct data with proper referential integrity. Consider this LINQ to SQL query: ``` var cust = (from c in db.Customers join s in db.States on c.StateID equals s.ID join cl in db.Color on c.ColorID equals cl.ID where c.ID == someCustomerID select c).SingleOrDefault(); ``` **Given**: The SQL statement that is produced, when viewed through SQL Server Profiler generates a proper query. Capturing and running the same query in SQL Management Studio returns the data as expected. The `cust.StateID` and `cust.State` properties are populated fine. I am able to inspect those properties fine just after executing the above L2S query. **Problem**: The `cust.Color` object, evaluates to `null`. The good news is that the `cust.ColorID` s populated with the correct FK number from the DB. There IS a row in the Color table with that ID. **Question**: how can this query be changed or improved to include the Color entity? ## Edit: Closing This Question The root of the problem was on the LINQ To SQL designer and a previous screw-up on the FK relationship. The association between Customer and Color had the association to another field on the Customer. This was total PEBKAC, and I hadn't checked the L2S designer for any problems. I deleted the Color table from the L2S designer, refreshed the table list in Server Explorer, and dragged the Color table over to L2S again. The association was corrected.
The root of the problem was on the LINQ To SQL designer and a previous screw-up on the FK relationship. The association between Customer and Color had the association to another field on the Customer. This was total PEBKAC, and I hadn't checked the L2S designer for any problems. I deleted the Color table from the L2S designer, refreshed the table list in Server Explorer, and dragged the Color table over to L2S again. The association was corrected.
Do you have a LoadOptions object associated with your data context? Try adding that with this: ``` var lo = new LoadOptions(x => x.Color); lo.LoadWith<Color>(); using (var db = new SomeDataContext()) { db.LoadOptions = lo; . . . } ```
LINQ to SQL: Child property is null even though it was returned
[ "", "c#", "linq-to-sql", "" ]
What is the best way to create your own GetHashCode method for a class in C#? Suppose I have a simple class (which overrides the Equals method), as follows: ``` class Test { public string[] names; public double[] values; public override bool Equals(object obj) { return (obj is Test) && this.Equals((Test)obj); } public bool Equals(Test t) { return names.Equals(t.names) && values.Equals(t.values); } } ``` Should I use the default code for the GetHashCode method? ``` public override int GetHashCode() { return base.GetHashCode(); } ``` Should I base the method on the contents of my class? ``` public override int GetHashCode() { return names.GetHashCode() + values.GetHashCode() ; } ``` Or should I do something else?
`System.Array` does not override `GetHashCode` or `Equals`, so they use reference equality. Therefore, you shouldn't call them. To implement `GetHashCode`, see [this question](https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode). To implement `Equals`, use the [`SequenceEqual`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.sequenceequal.aspx) extension method. **EDIT**: On .Net 2.0, you'll have to write your own version of `SequenceEqual`, like this: ``` public static bool SequenceEquals<T>(IList<T> first, IList<T> second) { if (first == second) return true; if (first == null || second == null) return false; if (first.Count != second.Count) return false; for (int i = 0; i < first.Count; i++) if (!first[i].Equals(second[i])) return false; return true; } ``` You could write it to take `IEnumerable<T>` instead of `IList<T>`, but it'd be somewhat slower because it wouldn't be able to exit early if the parameters have different sizes.
It is really important to make sure you keep the override of .GetHashCode() *in step* with .Equals(). Basically, you must make sure they consider the same fields so as not to violate the first of the three rules of GetHashCode (from [MSDN object.GetHashCode()](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx)) > If two objects compare as equal, the > GetHashCode method for each object > must return the same value. However, > if two objects do not compare as > equal, the GetHashCode methods for the > two object do not have to return > different values. In other words, you must make sure that every time .Equals considers two instances equal, they will also have the same .GetHashCode(). As mentioned by someone else here, [this question](https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode) details a good implementation. In case you are interested, I wrote up a few blog articles on investigating hash codes early last year. You can find my ramblings [here](http://blog.roblevine.co.uk/?p=15) (the first blog entry I wrote on the subject)
Creating the GetHashCode method in C#
[ "", "c#", ".net", "hashcode", "gethashcode", "" ]
I want to split a string into an array. The string is as follows: > :hello:mr.zoghal: I would like to split it as follows: > hello mr.zoghal I tried ... ``` string[] split = string.Split(new Char[] {':'}); ``` and now I want to have: ``` string something = hello ; string something1 = mr.zoghal; ``` How can I accomplish this?
For your original request: ``` string myString = ":hello:mr.zoghal:"; string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); var somethings = split.Select(s => String.Format("something = {0};", s)); Console.WriteLine(String.Join("\n", somethings.ToArray())); ``` This will produce ``` something = hello; something = mr.zoghal; ``` in accordance to your request. Also, the line ``` string[] split = string.Split(new Char[] {':'}); ``` is not legal C#. `String.Split` is an instance-level method whereas your current code is either trying to invoke `Split` on an instance named `string` (not legal as "`string`" is a reserved keyword) or is trying to invoke a static method named `Split` on the class `String` (there is no such method). Edit: It isn't exactly clear what you are asking. But I think that this will give you what you want: ``` string myString = ":hello:mr.zoghal:"; string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); string something = split[0]; string something1 = split[1]; ``` Now you will have ``` something == "hello" ``` and ``` something1 == "mr.zoghal" ``` both evaluate as true. Is this what you are looking for?
String myString = ":hello:mr.zoghal:"; ``` string[] split = myString.Split(':'); string newString = string.Empty; foreach(String s in split) { newString += "something = " + s + "; "; } ``` Your output would be: something = hello; something = mr.zoghal;
How do I split a string into an array?
[ "", "c#", "split", "" ]
I am using .post to post my data to my controller. I would like to pass all the data that I have in a form. Is there an easy way to take all the form data and add it to the .post command to send it?
use the .[serialize](http://docs.jquery.com/Ajax/serialize) method. ``` var postData = $('#formId').serialize(); $.post(url, postData); ```
``` $("form").submit(function(e) { e.preventDefault(); $.post("/url", $(this).serialize(), callbackFunction); }); ```
Jquery .post and form data
[ "", "javascript", "jquery", "" ]
I am trying to generate an archive on-the-fly in PHP and send it to the user immediately (without saving it). I figured that there would be no need to create a file on disk as the data I'm sending isn't persistent anyway, however, upon searching the web, I couldn't find out how. I also don't care about the file format. So, the question is: Is it possible to create and manipulate a file archive in memory within a php script without creating a tempfile along the way?
I had the same problem but finally found a somewhat obscure solution and decided to share it here. I came accross the great `zip.lib.php`/`unzip.lib.php` scripts which come with `phpmyadmin` and are located in the "libraries" directory. Using `zip.lib.php` worked as a charm for me: ``` require_once(LIBS_DIR . 'zip.lib.php'); ... //create the zip $zip = new zipfile(); //add files to the zip, passing file contents, not actual files $zip->addFile($file_content, $file_name); ... //prepare the proper content type header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=my_archive.zip"); header("Content-Description: Files of an applicant"); //get the zip content and send it back to the browser echo $zip->file(); ``` This script allows downloading of a zip, without the need of having the files as real files or saving the zip itself as a file. It is a shame that this functionality is not part of a more generic PHP library. Here is a link to the `zip.lib.php` file from the phpmyadmin source: [<https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php>](https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php) **UPDATE:** Make sure you remove the following check from the beginning of zip.lib.php as otherwise the script just terminates: ``` if (! defined('PHPMYADMIN')) { exit; } ``` **UPDATE:** This code is available on the CodeIgniter project as well: [<https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a448ae6c2cbae0890c9f672efcae32d/system/helpers/zip_helper.php>](https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a448ae6c2cbae0890c9f672efcae32d/system/helpers/zip_helper.php)
what are you using to generate the archive? You might be able to use the stream php://temp or php://memory to read and write to/from the archive. See <http://php.net/manual/en/wrappers.php.php>
Manipulate an Archive in memory with PHP (without creating a temporary file on disk)
[ "", "php", "memory", "archive", "disk", "" ]
``` int n; std::cin >> n; std::string s = ""; std::getline(cin, s); ``` I noticed that if I use `cin`, my program would hang the next time I reach the line `getline(cin, rangeInput)`. Since `getline()` is using `cin`, is that why it is causing the program to hang if I have previously used `cin`? What should I do if I want to get a line after using `cin`?
You need to clear the input stream - try adding the following after your cin: ``` cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); ``` The accepted answer to [this](https://stackoverflow.com/questions/478258/why-is-this-cin-reading-jammed) question gives a good explanation of why/when this is required.
`std::cin` leaves an extraneous `\n` in the input stream. When you use `std::getline()`, you are retrieving that `\n`. Although @WilliamLannen's answer works if you *really* need `std::cin`, you are better off using this method: ``` int n; std::string sn; std::stringstream ssn; std::getline(std::cin, sn); ssn << sn; ssn >> n; ``` --- > ## References > > <http://www.daniweb.com/software-development/cpp/tutorials/71858>
Using `getline(cin, s);` after using `cin >> n;`
[ "", "c++", "stream", "" ]
I would like to determine whether or not the user is logged in or if they're just anonymous from javascript... I found [this question](https://stackoverflow.com/questions/982104/check-if-user-is-logged-in), but it's php code and I wasn't sure if there is a session variable called logged\_in that gets stored on login or if that was just something that person had implemented himself. Anyone know how I can check to see if the user is logged in from javascript, possibly using ajax? **Edit:** I'm running Asp.Net MVC, sorry should have specified This is so that I can implement a client-side ajax login. When the page loads, I need to know if the user is logged in or not so I can implement something similar to an `<asp:LoggedInView>` control using jquery. Thanks, Matt
You can't read session saved data from JavaScript. An easy way to do it is to create a JS var from PHP (easier than cookies solution), like this: ``` if ($_SESSION['logged_in'] == 1) { echo '<script type="text/javascript">var logged_in=true;</script>'; } else { echo '<script type="text/javascript">var logged_in=false;</script>'; } ``` Then the JS will simply check the native `logged_in` var to see if the user is logged in. ``` <script type="text/javascript"> if (logged_in) { alert("My user is logged in!"); } </script> ```
[DISCLAIMER] Since I've been getting so many comments from people about this being 'bad practice', I'm just going to say this: It IS bad practice to do it this way, but we don't know what the original poster is intending to do. For all we know, he's done everything else 100% correct and secure, and was just asking if there was a way to get at it from javascript. What I have done below is provided my best idea for how to accomplish what he has asked. [/DISCLAIMER] You can have your php, or whatever backend language you're using, set a cookie that you can then read with javascript. ``` document.cookie ``` simple as that. You'll have to search the cookie string for the name of your logged in cookie. You can also use that to set a cookie and do your logging in through javascript (though probably not the best idea.) See [here](http://www.w3schools.com/JS/js_cookies.asp) for a quick overview of javascript cookie access. [edit] To address the issue of a client script having access to session information, and the possible use of ajax suggested in the original question: Yes, an ajax call would be a very easy way to check this. I'm more of a jQuery guy, so my ajax experience lies there, but basically, you'd do an ajax call to your backend function, and that backend function just checks the 'loggedin' session variable, returning a true or false. Also, since you now mentioned that you're using jQuery, see [this page](http://plugins.jquery.com/project/Cookie) for easy jQuery cookie access. [/edit]
How can I check to see if the user is anonymous or logged in from javascript?
[ "", "javascript", "authentication", "session-variables", "" ]
1. ``` static final String memFriendly = "Efficiently stored String"; System.out.println(memFriendly); ``` 2. ``` System.out.println("Efficiently stored String"); ``` Will Java compiler treat both (1 and 2) of these in the same manner? FYI: By efficiently I am referring to runtime memory utilization as well as code execution time. e.g. can the 1st case take more time on stack loading the variable memFriendly?
``` public static void main(String[] args) { System.out.println("Hello world!"); String hola = "Hola, mundo!"; System.out.println(hola); } ``` Here is what javap shows as the disassembly for this code: ``` 0: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #22; //String Hello world! 5: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: ldc #30; //String Hola, mundo! 10: astore_1 11: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream; 14: aload_1 15: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 18: return ``` Looks like the second string is being stored, whereas the first one is simply passed to the method directly. This was built with Eclipse's compiler, which may explain differences in my answer and McDowell's. **Update**: Here are the results if `hola` is declared as `final` (results in no `aload_1`, if I'm reading this right then it means this String is both stored and inlined, as you might expect): ``` 0: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #22; //String Hello world! 5: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: ldc #30; //String Hola, mundo! 10: astore_1 11: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream; 14: ldc #30; //String Hola, mundo! 16: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 19: return ```
This is covered in the [Java Language Spec](http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5): > Each string literal is a reference > (§4.3) to an instance (§4.3.1, §12.5) > of class String (§4.3.3). String > objects have a constant value. String > literals-or, more generally, strings > that are the values of constant > expressions (§15.28)-are "interned" so > as to share unique instances, using > the method String.intern. You can also see for yourself using the [javap](http://java.sun.com/javase/6/docs/technotes/tools/index.html#basic) tool. For this code: ``` System.out.println("Efficiently stored String"); final String memFriendly = "Efficiently stored String"; System.out.println(memFriendly); ``` javap gives the following: ``` 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3; //String Efficiently stored String 5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 11: ldc #3; //String Efficiently stored String 13: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V ```
Does Java compiler handle inline Strings efficiently?
[ "", "java", "string", "optimization", "compiler-construction", "" ]
I'm using an STL std::multiset<> as a sorted list of pointers. The sort order is determined by a property of the items being pointed to, something along the lines of this simplified example: ``` struct A { int x; }; bool CompareAPointers(const A* lhs, const A* rhs) { return lhs->x < rhs->x; } std::multiset<A*, CompareAPointers> sorted_set; ``` The complication is that the values of the property used to sort the set can change (you can change A.x in the example above), which can make the sort order incorrect: ``` A a1, a2; a1.x = 1; a2.x = 2; sorted_set.insert(&a1); sorted_set.insert(&a2); a1.x = 3; ``` I'm able to keep the list sorted by erasing and reinserting elements when the relevant attribute changes, but the book keeping is getting to be a bit of a pain. I feel like I'm going about this all wrong. Can anyone suggest a better way to keep a list sorted when the sort order can dynamically change? The changes occur in predictable ways at predictable times, but my current approach just *feels* wrong.
[Boost Multi-Index](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/index.html) supports sorting anything you want and supports changing the fields the list gets oderdered by, although you can't just type `a1.x=1` anymore, instead, you have to use [MultiIndex::replace()](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/tutorial/basics.html#ord_updating). I can't think of a faster/more natural way of doing this, as deleting and reinserting the element would've to be done anyway.
I would consider using a sorted `std::vector` instead. At one of those points where you predictably modify `x` for one of the set's members, then just re-sort the vector. It's a little cleaner than having to remove and reinsert items. This might be too much overhead though if you're frequently modifying a single set member's property and re-sorting. It would be much more useful if you're likely to be changing many of these properties at once.
How to keep items sorted based on dynamic attribute?
[ "", "c++", "sorting", "stl", "" ]
Title covers it all. I'd like classes which implement IDisposable to show up in a specific color so I can know if I should wrap them in a using block. Is there a setting or a process by which you can extend the IDE?
It is certainly possible to do this though it isn't as simple as just changing a setting. You would need to write a Visual Studio addin to accomplish this. Visit <http://msdn.microsoft.com/en-us/vsx/bb980955.aspx> to get started. As others will point out. This is not for the faint of heart. Here's a link that may point you toward what you are looking for:<http://msdn.microsoft.com/en-us/library/bb166778.aspx>
I assume this will become easier/extension-free once Roslyn comes out, but this is presently not easy because you can't access the code as C# from an extension easily. **In Resharper** it's easy, though! My example was tested in ReSharper 9.0. Sadly, there's no easy way to give this to you. * Extensions -> Resharper -> Options -> Code Inspection -> Custom Patterns -> Add, dialog popup * Select C# (upper left) * Select "Find" (upper right) * Add the pattern of `new $disp$($args$)` * Pattern severity: Show as suggestion * Description: Disposable construction * "Add Placeholder" of type: `Type`, name: `disp`, type: `System.IDisposable` * "Add Placeholder" of type: `Arguments`, name: `args` Save and you'll now get a "suggestion" whenever a new disposable is being constructed. Adding the pattern `$disp$ $var$ = $exp$;` could also be helpful. * "Add Placeholder" of type: `Type`, name: `disp`, type: `System.IDisposable` * "Add Placeholder" of type: `Expression`, name: `exp` * "Add Placeholder" of type: `Identifier`, name: `var` ![enter image description here](https://i.stack.imgur.com/I7RoN.png)
How can I make all of the IDisposable classes colored differently in the Visual Studio IDE?
[ "", "c#", "visual-studio", "ide", "" ]
Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is `bayesm`, which is really a companion to a book (*Bayesian Statistics and Marketing*, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language?
Here are four books on hierarchical modeling and bayesian analysis written with R code throughout the books. Hierarchical Modeling and Analysis for Spatial Data (Monographs on Statistics and Applied Probability) (Hardcover) [http://www.amazon.com/gp/product/158488410X](https://rads.stackoverflow.com/amzn/click/com/158488410X) Data Analysis Using Regression and Multilevel/Hierarchical Models (Paperback) [http://www.amazon.com/Analysis-Regression-Multilevel-Hierarchical-Models/dp/052168689X/ref=pd\_sim\_b\_1](https://rads.stackoverflow.com/amzn/click/com/052168689X) Bayesian Computation with R (Use R) (Paperback) [http://www.amazon.com/Bayesian-Computation-R-Use/dp/0387922970/ref=pd\_bxgy\_b\_img\_c](https://rads.stackoverflow.com/amzn/click/com/0387922970) Hierarchical Modelling for the Environmental Sciences: Statistical Methods and Applications (Oxford Biology) (Paperback) (I'm assuming this one has R code as both authors use R extensively) I know some python books dabble in multivariate analysis (Collective Intelligence, for example) but I haven't seen any that really delve into bayesian or hierarchical modeling.
There's OpenBUGS and R helper packages. Check out Gelman's site for his book, which has most of the relevant links: * <http://www.stat.columbia.edu/~gelman/software/> * [Example of computation in R and Bugs](http://www.stat.columbia.edu/~gelman/bugsR/software.pdf) On the Python side, I only know of PyMC: * <http://code.google.com/p/pymc/> * [An example statistical model](http://pymc.googlecode.com/svn/doc/tutorial.html) EDIT: Added a link to the appropriate appendix from Gelman's book, available online, for an example using R and BUGS.
Hierarchical Bayes for R or Python
[ "", "python", "r", "statistics", "" ]
What is the Java equivalent of Cocoa delegates? (I understand that I can have an interface passed to a class, and have that class call the appropriate methods, but I'm wondering if there is any other way to achieve something closer to Cocoa/Objective-C's informal protocols)
The short answer is there's nothing in Java as close as you'd like, but there are alternatives. The delegate pattern isn't hard to implement, it's just not quite as convenient as doing it with Objective-C. The reason "informal protocols" work in Objective-C is because the language supports **categories**, which allow you to add methods to existing classes without subclassing them, or even having access to the source code. Thus, most informal protocols are a category on NSObject. This is clearly impossible in Java. Objective-C 2.0 opts for @optional protocol methods, which is a much cleaner abstraction and preferred for new code, but even further from having an equivalent in Java. Honestly, the most flexible approach is to define a delegate protocol, then have classes implement all the methods. (With modern IDEs like Eclipse, this is trivial.) Many Java interfaces have an accompanying adapter class, and this is a common approach for not requiring the user to implement a lot of empty methods, but it restricts inheritance, which makes code design inflexible. (Josh Bloch addresses this in his book "Effective Java".) My suggestion would be to only provide an interface first, then add an adapter if it's truly necessary. Whatever you do, avoid throwing an `UnsupportedOperationException` for "unimplemented" methods. This forces the delegating class to handle exceptions for methods that should be optional. The correct approach is to implement a method that does nothing, returns a default value, etc. These values should be well documented for methods that don't have a void return type.
Best analog to an informal protocol I can think of is an interface that also has an adapter class to allow implementers to avoid implementing every method. ``` public class MyClass { private MyClassDelegate delegate; public MyClass () { } // do interesting stuff void setDelegate(MyClassDelegate delegate) { this.delegate = delegate; } interface MyClassDelegate { void aboutToDoSomethingAwesome(); void didSomethingAwesome(); } class MyClassDelegateAdapter implements MyClassDelegate { @Override public void aboutToDoSomethingAwesome() { /* do nothing */ } @Override public void didSomethingAwesome() { /* do nothing */ } } } ``` Then someone can come along and just implement the stuff they care about: ``` class AwesomeDelegate extends MyClassDelegateAdapter { @Override public void didSomethingAwesome() { System.out.println("Yeah!"); } } ``` Either that, or pure reflection calling "known" methods. But that's insane.
Java equivalent of Cocoa delegates / Objective-C informal protocols?
[ "", "java", "objective-c", "cocoa", "delegates", "protocols", "" ]
What's the equivalent to SQL Server's `TOP` or DB2's `FETCH FIRST` or mySQL's `LIMIT` in PostgreSQL?
You can use [LIMIT](http://www.postgresql.org/docs/current/static/sql-select.html#SQL-LIMIT) just like in MySQL, for example: ``` SELECT * FROM users LIMIT 5; ```
You could always add the `OFFSET` clause along with `LIMIT` clause. You may need to pick up a set of records from a particular offset. Here is an example which picks up 3 records starting from 3rd position: ``` testdb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2; ``` This would produce the following result: ``` id | name | age | address | salary ----+-------+-----+-----------+-------- 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 ``` Full explanation and more examples check [HERE](http://www.tutorialspoint.com/postgresql/postgresql_limit_clause.htm)
How to limit rows in PostgreSQL SELECT
[ "", "sql", "postgresql", "sql-limit", "" ]
I'm learning events in C# and understand that the `EventArgs` class carries data about the event. But I am having difficulties understanding why `EventArgs` is necessary. For instance, in [this MSDN example](https://msdn.microsoft.com/en-us/library/9aackb16(VS.71).aspx), couldn't the `WakeMeUp` class read all of the necessary data (`snoozePressed`, `nrings`) from the fields of `AlarmClock`? If it can set them, why couldn't it also get them?
The upsides with the EventArgs class are (as I see it) mainly these two: * You can add members to the EventArgs class withouth altering the signature of the event * You disconnect the information passed to the event handler from the object instance It may even be that the information contained in the EventArgs is not exposed by the object raising the event. Sure, in some cases it may seem like overkill, but I think that the power of sameness is a good thing here; if you know how one event works, you know how other events work as well.
The `EventArgs` class is necessary because if you wanted to extend your event to provide more information in the future, you would have portability problems for all clients using the original method signature of the original event. For example, ``` public void IHandleEventVersion1(string p1, int p2) { .... } ``` Now you want to provide more information in event `EventVersion1` above (you want to include a `char`). You would then have to force the client rewrite their event handling to to match your new requirements like so: ``` public void IHandleEventVersion1(string p1, int p2, char p2) { ... } ``` See how awkward it could become when trying to provide more information? So, the `EventArgs` class provides a common design pattern to programme against, allowing you and me to quickly extend the data we want to provide for an event. The general coding pattern of the eventing framework is such: **Basic event handling strategy** 1. Define an `event` that consumers of your class can subscribe to 2. Define a `delegate` signature that the event declares (yes, you can also use the .NET 2.0 generic version of `EventHandler`, namely, `EventHandler<TEventArgs>`) 3. Provide a `protected` `virtual` method for inheritors to override in response to the event being raised in your base class 4. In the base class that declares your event, provide a base implementation of the `protected` method where you actually raise the event. > ``` > public class MyClass > { > public event EventHandler /* (point 2) */ MyEvent; /* (point 1) */ > > // (point 3 + 4) > protected virtual void OnMyEvent() > { > EventHandler temp = MyEvent; > if (temp != null) > temp(this, EventArgs.Empty); > } > > public void SomeMethodThatWillRaiseTheEvent() > { > .... > OnMyEvent(); > } > } > ```
Rationale behind EventArgs class
[ "", "c#", ".net", "events", "" ]
Could somebody please explain to me why does this code only print "42" instead of "created\n42"? ``` #include <iostream> #include <string> #include <memory> using namespace std; class MyClass { public: MyClass() {cout<<"created"<<endl;}; int solution() {return 42;} virtual ~MyClass() {}; }; int main(int argc, char *argv[]) { auto_ptr<MyClass> ptr; cout<<ptr->solution()<<endl; return 0; } ``` BTW I tried this code with different values in solution and I always get the "right" value, so it doesn't seem to be a random lucky value.
Because it exhibits undefined behaviour - you dereference a null pointer. When you say: ``` auto_ptr<MyClass> ptr; ``` you create an autopointer which doesn't point to anything. This is equivalent to saying: ``` MyClass * ptr = NULL; ``` Then when you say: ``` cout<<ptr->solution()<<endl; ``` you dereference this null pointer. Doing that is undefined in C++ - for your implementation, it appears to work.
[std::auto\_ptr](http://en.cppreference.com/w/cpp/memory/auto_ptr) will not automatically create an object for you. That is, `ptr` in main as it stands is initialized to null. Dereferencing this is undefined behavior, and you just happen to be getting lucky and getting 42 as a result. If you actually create the the object: ``` int main(int argc, char *argv[]) { auto_ptr<MyClass> ptr(new MyClass); cout << ptr->solution() << endl; return 0; } ``` You will get the output you expect.
Why does this code only print 42?
[ "", "c++", "gcc", "auto-ptr", "" ]
Checking function takes two arguments, I want to have a testcase for each element of the cartesian product of the respective domains, but without manually writing all the test cases like in ``` void check(Integer a, Integer b) { ... } @Test public void test_1_2() { check(1, 2); } ... ``` In python I would go with ``` class Tests(unittest.TestCase): def check(self, i, j): self.assertNotEquals(0, i-j) for i in xrange(1, 4): for j in xrange(2, 6): def ch(i, j): return lambda self: self.check(i, j) setattr(Tests, "test_%r_%r" % (i, j), ch(i, j)) ``` How could I do this with Java and JUnit?
I think your looking for **Parameterized Tests** in JUnit 4. [JUnit test with dynamic number of tests](https://stackoverflow.com/questions/358802/junit-test-with-dynamic-number-of-tests)
with theories you can write something like: ``` @RunWith(Theories.class) public class MyTheoryOnUniverseTest { @DataPoint public static int a1 = 1; @DataPoint public static int a2 = 2; @DataPoint public static int a3 = 3; @DataPoint public static int a4 = 4; @DataPoint public static int b2 = 2; @DataPoint public static int b3 = 3; @DataPoint public static int b4 = 4; @DataPoint public static int b5 = 5; @DataPoint public static int b6 = 6; @Theory public void checkWith(int a, int b) { System.out.format("%d, %d\n", a, b); } } ``` (tested with JUnit 4.5) **EDIT** Theories also produces nice error messages: ``` Testcase: checkWith(MyTheoryOnUniverseTest): Caused an ERROR checkWith(a1, b2) // <--- test failed, like your test_1_2 ``` so you don't need to name your test in order to easly identify failures. **EDIT2** alternatively you can use DataPoint**s** annotation: ``` @DataPoints public static int as[] = { 1, 2, 3, 4} ; @DataPoints public static int bs[] = { 2, 3, 4, 5, 6}; @Theory public void checkWith(int a, int b) { System.out.format("%d, %d\n", a, b); } ```
JUnit two variables iterating respective value sets, create test functions
[ "", "java", "junit", "" ]
Per my other post about [WCF service return values](https://stackoverflow.com/questions/1195438/should-wcf-services-return-plain-old-objects-or-the-actual-class-that-youre-wor), I'm consuming a web service from another company, and when I add the service reference inside Visual Studio, the return value of the method is an object of type `object`. The author of the web service showed me the code, and it actually returns a typed object. Am I missing something, or is the proxy class supposed to return a typed value? Is there a setting for generating the proxy class, or the actual service? ***UPDATE:*** I looked at the actual classes behind the WCF service and realized that the return value of the service method is actually returning an **interface**, that the concrete type implements. The concrete type is marked with the [DataContract] attribute ( and appropriate [DataMember] attributes), but the interface has no such attributes. Could this be causing the service to set the return type as object?
Hypothetically, if you were the service developer, you could use a `KnownTypeAttribute`: ``` [DataContract] [KnownType(typeof(MyConcreteClass))] public interface IMyInterface { } [DataContract] public class MyConcreteClass : IMyInterface { } ``` I haven't personally tried this with an interface, but I have tried it with an abstract base class and it works fine. When the client receives the return value, it can successfully downcast to the derived class. It might be that the service code actually does this, and the problem lies with `svcutil.exe` not generating the proxy classes accurately enough. Although you don't control the service code, you do control the client proxy code. You could try manually editing the proxy classes that `svcutil.exe` gave you to add the `KnownTypeAttribute` yourself. By doing this, you are taking control of the behaviour of the DataContractSerializer at your end, and as long as you take care not to change the wire format of the data by mistake, it should all still work.
The proxy class is a generated file and as such it can contain mistakes. If you have a copy of the data contract you are free to change the proxy class to use the correct type rather than `System.Object` and things ought to work properly. The Visual Studio "Add Service Reference" tool and `svcutil.exe` are very good at generating proxy classes but they are not perfect. The files that they generate are yours to modify and I would encourage you to simply modify the operation to return the proper data contract.
What would cause a WCF service to return an object of type "object"
[ "", "c#", "asp.net", "wcf", "return-value", "proxy-classes", "" ]
I want to refactor some code. Basically the code I want to refactor is a Form (using System.Windows.Forms;) The way it is setup now, depending on which radio button you selected it shows a different layout for the window: different labels, buttons, etc. Not always a big difference, but different. This is a lot of conditional statement junk all over the place. I wanted instead to refactor it with the State pattern. There are three main states. I'm not sure the best way to do this. Right now the IState interface has a DoAction() method which does some action particular to the unique State, and a DrawForm() method which re-draws the form based on the current State... However, to do the DrawForm(), the State classes need to be able to access the Form's member variables. That's what threw me for a loop. I didn't really want to expose them. Is there a better way to do this?
You could make your state classes nested in your form. They will then be able to acces fields of form without having to expose them.
If your primary concern is keeping form stuff encapsulated, and you want to keep the state machine outside, I had a similar question a while back, you could check out the answer [here](https://stackoverflow.com/questions/653512/internal-interfaces-exposing-my-ignorance) - basically it entails creating a private inner 'action' class which DOES have access to form methods, then passing this to the state machine so that it can use the action class to invoke form methods indirectly.
Refactoring Form to State Pattern?
[ "", "c#", "design-patterns", "refactoring", "" ]
In one of my projects I have used `input[type="button"]` to apply a style to all the buttons. It works fine in all browsers except Internet Explorer 6. It doesn't style the buttons. Is there a solution for this, like creating some class for the button and applying it to all buttons? I want to apply that class to all buttons but not manually. I think it's possible to use jQuery for this, could you please help me with this?
I usually like not to use JavaScript for this, so I add `class="text"` for `<input>` elements that are of text type, `class="button"` for `<input>` elements that are of button type, and so on. Then I can match them with `input.text` etc. While you don't want to do it manually, I consider it better practice. If you still want to do it with jQuery, you do it like this: ``` $('input:button').addClass('button'); // Or to include <button> elements: $('button, input:button').addClass('button'); // Text inputs: $('input:text').addClass('text'); // And so on... ```
``` $(":button").addClass("yourclassname"); ``` This matches all button elements and input elements of type button and adds class to them.
How to apply a class to all button?
[ "", "javascript", "jquery", "css", "forms", "internet-explorer-6", "" ]
I'm trying to have overloaded methods in a web service but I am getting a System.InvalidOperationException when attempting "Add Web Reference" in Visual Studio 2005 (here's the relevant snippets of code): ``` public class FileService : System.Web.Services.WebService { private static readonly MetaData[] EmptyMetaData = new MetaData[0]; public FileService() { // a few innocent lines of constructor code here... } [WebMethod(MessageName = "UploadFileBasic", Description = "Upload a file with no metadata properties")] public string UploadFile(string trimURL , byte[] incomingArray , string fileName , string TrimRecordTypeName) { return UploadFile(trimURL , incomingArray , fileName , TrimRecordTypeName , EmptyMetaData); } [WebMethod(MessageName = "UploadFile", Description = "Upload a file with an array of metadata properties (Name/Value pairs)")] public string UploadFile( string trimURL , byte[] incomingArray , string FileName , string TrimRecordTypeName , MetaData[] metaDataArray) { // body of UploadFile function here ``` I thought supplying a different MessageName property on the WebMethod attribute would fix this problem but here is the entire error message I get: Both System.String UploadFileBasic(System.String, Byte[], System.String, System.String) and System.String UploadFile(System.String, Byte[], System.String, System.String) use the message name 'UploadFileBasic'. Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods. The web service compiles OK; I cannot see what is wrong here.
My suggestion is to not use overloaded method names. There is no such concept in WSDL, so why bother?
You need to change this part: ``` [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] ``` to this one: ``` [WebServiceBinding(ConformsTo = WsiProfiles.None)] ```
How to access a web service with overloaded methods
[ "", "c#", "web-services", "asmx", "" ]
I am developing an application which monitors the presence of the power supply of the laptop. If there is a power cut or restoration it will intimate me over email. It will also application monitoring and controlling over email (Basically to control my laptop from my office over email). I am done with email interfacing but I have no idea on how to monitor the power supply / battery supply from java. If any can give some pointer on this it will be of great help. Thanks in advance ....
You have probably already solved this problem but for the others - you can do it the way Adam Crume suggests, using an already written script [battstat.bat](http://www.robvanderwoude.com/files/battstat_xp.txt) for Windows XP and higher. Here is an example of the resulting function: ``` private Boolean runsOnBattery() { try { Process proc = Runtime.getRuntime().exec("cmd.exe /c battstat.bat"); BufferedReader stdInput = new BufferedReader( new InputStreamReader(proc.getInputStream())); String s; while ((s = stdInput.readLine()) != null) { if (s.contains("mains power")) { return false; } else if (s.contains("Discharging")) { return true; } } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return false; } ``` Or you can simplify the script to return directly True/False or whatever fits.
On linux, you can use /proc/acpi/battery/
Monitoring battery or power supply of laptop from java
[ "", "java", "hardware-interface", "" ]
I have inherited a large c++ code base and I have a task to avoid any null pointer exceptions that can happen in the code base. Are there are static analysis tools available, I am thinking lint, that you have used successfully. What other things do you look out for?
You can start by eliminating sources of NULL: Change ``` if (error) { return NULL; } ``` Into ``` if (error) { return DefaultObject; // Ex: an empty vector } ``` If returning default objects does not apply and your code base already uses exceptions, do ``` if (error) { throw BadThingHappenedException; } ``` Then, add handling at appropriate places. If you are working with legacy code, you could make some wrapper functions/classes: ``` ResultType *new_function() { ResultType *result = legacy_function(); if (result) { return result; } else { throw BadThingHappenedException; } } ``` New functionalities should start using new functions and have proper exception handling. I know some programmers just don't get exceptions, including smart people like [Joel](http://www.joelonsoftware.com/items/2003/10/13.html). But, what ends up happening by returning NULL is that this NULL gets pass around like crazy since everybody would just think it's not their business to handle it and return silently. Some functions may return error code, which is fine, but the caller often ends up returning yet-another-NULL in response to errors. Then, you see a lot of NULL-checking in every single functions, no matter how trivial the function is. And, all it takes is just ONE place that doesn't check for NULL to crash the program. Exceptions force you to carefully think about the error and decide exactly where and how it should be handled. It seems like you're just looking for easy solutions like static analysis tools (which you should always use). Changing pointers to references is also a great solution too. However, C++ has the beauty of RAII, which eliminates the need for having "try {} finally {}" everywhere, so I think it worths your serious consideration.
First, as a technical point, C++ does not have NULL pointer exceptions. Dereferencing a NULL pointer has undefined behavior, and on most systems causes the program to abruptly terminate ("crash"). As for tools, I too recommend the question: [Are C++ static code analyis tools worth it?](https://stackoverflow.com/questions/639694/are-c-static-code-analyis-tools-worth-it) Regarding NULL pointer dereferences in particular, consider that a NULL pointer dereference has three main elements: 1. The introduction of a NULL pointer. 2. The flow of that pointer elsewhere in the program. 3. The dereference of that pointer. The hard part for a static analysis tool is of course step 2, and tools are differentiated by how complicated a path they can accurately (i.e., without too many false positives) track. It might be useful to see some specific examples of bugs you want to catch in order to better advise about what sort of tool will be most effective. Disclaimer: I work for Coverity.
Avoiding null pointer exceptions in a large c++ code base
[ "", "c++", "null", "nullpointerexception", "" ]
Consider a method in a .NET assembly: ``` public static string GetSecurityContextUserName() { //extract the username from request string sUser = HttpContext.Current.User.Identity.Name; //everything after the domain sUser = sUser.Substring(sUser.IndexOf("\\") + 1).ToLower(); return sUser; } ``` I'd like to call this method from a unit test using the Moq framework. This assembly is part of a webforms solution. The unit test looks like this, but I am missing the Moq code. ``` //arrange string ADAccount = "BUGSBUNNY"; string fullADName = "LOONEYTUNES\BUGSBUNNY"; //act //need to mock up the HttpContext here somehow -- using Moq. string foundUserName = MyIdentityBL.GetSecurityContextUserName(); //assert Assert.AreEqual(foundUserName, ADAccount, true, "Should have been the same User Identity."); ``` **Question**: * How can I use Moq to arrange a fake HttpContext object with some value like 'MyDomain\MyUser'? * How do I associate that fake with my call into my static method at `MyIdentityBL.GetSecurityContextUserName()`? * Do you have any suggestions on how to improve this code/architecture?
Webforms is notoriously untestable for this exact reason - a lot of code can rely on static classes in the asp.net pipeline. In order to test this with Moq, you need to refactor your `GetSecurityContextUserName()` method to use dependency injection with an `HttpContextBase` object. `HttpContextWrapper` resides in `System.Web.Abstractions`, which ships with .Net 3.5. It is a wrapper for the `HttpContext` class, and extends `HttpContextBase`, and you can construct an `HttpContextWrapper` just like this: ``` var wrapper = new HttpContextWrapper(HttpContext.Current); ``` Even better, you can mock an HttpContextBase and set up your expectations on it using Moq. Including the logged in user, etc. ``` var mockContext = new Mock<HttpContextBase>(); ``` With this in place, you can call `GetSecurityContextUserName(mockContext.Object)`, and your application is much less coupled to the static WebForms HttpContext. If you're going to be doing a lot of tests that rely on a mocked context, I highly suggest [taking a look at Scott Hanselman's MvcMockHelpers class](http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx), which has a version for use with Moq. It conveniently handles a lot of the setup necessary. And despite the name, you don't need to be doing it with MVC - I use it successfully with webforms apps when I can refactor them to use `HttpContextBase`.
``` [TestInitialize] public void TestInit() { HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null)); } ``` Also you can moq like below ``` var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["User"]).Returns(TestGetUser); controllerContext.SetupGet(p => p.HttpContext.Request.Url).Returns(new Uri("http://web1.ml.loc")); ```
Moq: unit testing a method relying on HttpContext
[ "", "c#", "unit-testing", "mocking", "moq", "" ]
CakePHP makes heavy use of associative arrays for passing large numbers of parameters to functions. I have not really seen this technique outside of PHP and never seen it used to the extent that Cake uses it. I really like this approach because as it seems it would be easier to handle new parameters in future releases of your own code and it's alot more readable than simply a long list of params. As an example... ``` function myFunc($params = array('name' => 'rob', 'count' => 5, 'anArray' => array('A string', 5, myObject))) { // ... } ``` I guess this is similar to using argc/argv, but is a bit easier to read. Does anyone have a list of pros and cons on this method or know of anyone that's written on best practices with this? I've tried just Googling it but "associative array of parameters" brings up pretty much every programming article ever written. Also, is there even a term for passing parameters this way?
It is a emulation of using keyword arguments. In python, for example, you can say: ``` myFunc(name="bob", age=10, gender="male") ``` Since PHP does not support this syntax, associative arrays are the next-best-thing.
A downside to using named parameters is documenting the parameters with PHPDoc. Many editors/IDEs provide "automatic" documentation that can parse your code and generate generic docblocks. e.g. ``` function foo(array $bar, SomeClass $stuff) { returns $magic; } ``` would produce: ``` /** * foo * * @param array $bar * @param SomeClass $stuff * @return mixed */ function foo(array $bar, SomeClass $stuff) { returns $magic; } ``` If you put all your parameters in a $params array, it would only look like ``` /** * foo * * @param array $params * @return mixed */ ``` It also adds a lot of additional burden to your developers to have to type the extra code for each parameter. I'd suggest using a mix of the two approaches. e.g. If you had a function to return an HTML text input element you could have the following method signature: ``` /** * formText * * @param string $name name of text element * @param string $value value of text element * @param array $options additional options for text element * @return string */ function formText($name, $value, $options = array()); ``` Thus, you can easily pass the most common values to the function. ``` $this->formText('foo', 'Default...'); ``` and if you need additional, less common params you'd use the convenient named parameter syntax: ``` $this->formText('foo', 'Default...', array( 'class' => 'bold highlighted' )); ``` otherwise, using only a generic $params array you'd have to type: ``` $this->formText(array( 'name' => 'foo', 'value' => 'Default...' )); ```
Array of parameters
[ "", "php", "cakephp", "" ]
I'm wondering what the best practice is for having redundant columns in a MySQL database. I'm wondering this because I have a User table in my database but I also want to be able to display many statistics about each individual user. These stats might include how many times a user has interacted with another model or how many messages they have. Does it hurt performance to search for all records of a certain object (such as messages) in order to count them? Or is it better to make a redundant column in the user table called total\_messages that gets updated every time a message is added/removed? Thanks, this has been confusing me for awhile.
The short answer: **do both** As a rule of thumb, I don't like creating and updating data that can be calculated on the fly (i.e. counting). Therefore, I would hold off on adding those redundant statistics until you find performance bottlenecks and adjust accordingly. You can always add retroactive statistics based on user activity, so you could "grow" your application by only adding the redundancy you absolutely need. Adding redundant data can improve your performance, but it is never a one size fits all solution and you could end up hurting overall performance if you are constantly trying to calculate and update usage values that can be calculated on the fly with a simple request.
What I'd do is to create a [view](http://dev.mysql.com/doc/refman/5.0/en/views.html) in your database that gives you the relevant information; instead of adding a redundant column, you're adding an optimizable bit of SQL code that LOOKS like a column to the outside world, but which is guaranteed to remain in sync with your data. And the fact that SQL optimizes views makes retrieving the data quite fast.
Using multiple tables in MySQL and/or multiple columns for a Rails application
[ "", "sql", "mysql", "ruby-on-rails", "database", "" ]
I'm writing Content Management software in PHP (which should not be bigger then 3kb when minified), but what engine should I use for languages (english, dutch, german, chinese, etc...)? I was thinking of creating a function called ``` function _(){} ``` that reads strings from a file (a .ini file or similar). But does somebody has an (preferably one with as less code as possible) engine that might be smaller or faster? I'm not sure if these engines exist already, if not, please say and I will use the \_() function.
You can't use `_()` because this is a build-in function for internationalization. You are free to roll your own function (call it `__()`) or use the build-in one which uses the widespread gettext system.
If I were you I would make my translation function like such (which I believe is very similar to gettext): make it into an sprintf()-like function and translate based on the format string, like so: ``` function __() { $a = func_get_args(); $a[0] = lookup_translation($a[0]); return call_user_func_array("sprintf", $a); } ``` Now, you can use the function simply like this: ``` echo __("Thanks for logging in, %s!", $username); ``` And in a data file somewhere you have: ``` "Thanks for logging in, %s!"="Merci pour enlogger, %s!" (*) ``` The advantages of this are: * You don't have to think up identifiers for every single message: `__("login_message", $username)`, `__("logout_message", $username)`, etc... * You don't immediately have to write a translation for the string, which you would have to if you just used an identifier. You can defer the translation until later, once you're done coding and everything works in English. * (Similarly) You don't have to translate all strings for all languages at once, but you can do it in chunks For maximum convenience, I would make the `__` function log untranslated messages somewhere, so you don't have to go hunting for untranslated strings. Let the system tell you what needs to be translated! (\*) Disclaimer: I don't speak French ;)
PHP language engine
[ "", "php", "function", "" ]
I heard that there is a keyboard short cut to bring up the code of a SQL Server 2005 (Management Studio) stored procedure. This key combination would do the same function as sp\_helptext. This may only be an Urban Legend. Thanks
The first thing I do after installing management studio on a new machine is to set sp\_helptext to be CTL+F1 in management studio. Tools / Options / Environment / Keyboard / Ctrl-F1 == sp\_helptext Then, i can highlight any view, stored proc, function, whatever - and press CTL-F1 and get the text of the object in my results window. Not sure if this is exactly what you're looking for, but it definitely helps me to be more productive in the query windows.
Just using the Ctrl + F1 for the first time it works well & displays the SP in the results grid. Shortcut hotkey combination to view the code of an SP can also be done by the following: 1. **F8** - Open Object Explorer 2. **Arrow keys** down to SP 3 **Right Click** (usually located between right windows key & right ctrl key) 4 **Y** - press Y which will select Modify 5 New Query Window opens with alter SP code Hope this helps
What is the keyboard shortcut to view a SQL Server 2005 (Management Studio) stored procedure
[ "", "sql", "sql-server-2005", "" ]
I have a column, say PROD\_NUM that contains a 'number' that is left padded with zeros. For example 001004569. They are all nine characters long. I do not use a numeric type because the normal operation on numbers do not make sense on these "numbers" (For example PROD\_NUM \* 2 does not make any sense.) And since they are all the same length, the column is defined as a CHAR(9) ``` CREATE TABLE PRODUCT ( PROD_NUM CHAR(9) NOT NULL -- ETC. ) ``` I would like to constrain PROD\_NUM so it can only contain nine digits. No spaces, no other characters besides '0' through '9'
``` REGEXP_LIKE(PROD_NUM, '^[[:digit:]]{9}$') ```
You already received some nice answers on how to continue on your current path. Please allow me to suggest a different path: use a number(9,0) datatype instead. Reasons: * You don't need an additional check constraint to confirm it contains a real number. * You are not fooling the optimizer. For example, how many prod\_num's are "BETWEEN '000000009' and '000000010'"? Lots of character strings fit in there. Whereas "prod\_num between 9 and 10" obviously selects only two numbers. Cardinalities will be better, leading to better execution plans. * You are not fooling future colleagues who have to maintain your code. Naming it "prod\_num" will have them automatically assume it contains a number. Your application can use lpad(to\_char(prod\_num),9,'0'), preferably exposed in a view. Regards, Rob. *(update by MH) The comment thread has a discussion which nicely illustrates the various things to consider about this approach. If this topic is interesting you should read them.*
CHECK CONSTRAINT of string to contain only digits. (Oracle SQL)
[ "", "sql", "oracle", "" ]
``` var total = 0; $(".amount").each(function () { var value = $(this).val(); value = (value.length < 1) ? 0 : value; var tmp = parseFloat(value).toFixed(2); total += tmp; }); $(".total").text(total); ``` I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?
.toFixed converts the object from a Number to a String. Leave the full values in place and only convert using .toFixed at the very end ``` $(".total").text(total.toFixed(2)); ``` Alternatively, convert the string back to a number. ``` total = total + + tmp; ```
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: [jQuery Calculation](http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm) Using that plugin may also indirectly solve your issue. It's usage would reduce your script to: ``` $('.total').text($('.amount').sum()); ```
Javascript: why does this produce and ugly string??? I would like currency
[ "", "javascript", "jquery", "string-formatting", "" ]
I wanted to know if I can write something on the HTML page containing my Java applet from within the applet. More generally, what interactions are possible between these two? Thanks.
From within your java applet ``` // object to allow applet to invoke Javascript methods protected static JSObject appletWindowJSObject = null; appletWindowJSObject = JSObject.getWindow(this); //Call your javascript method on the page and pass it something appletWindowJSObject.call("myJavascriptMethod", "This is what I am passing"); ``` You can then use javascript to manipulate the html page as usual. May also need to include the mayscript parameter when declaring the applet, not sure if this is needed anymore or not.
You could use the JSObject. [Sun: java to javascript communication](http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/java_js.html)
Can a java applet manipulate the HTML page containing it?
[ "", "java", "applet", "liveconnect", "" ]
I'm trying to get this Generic DuplicateValidationRule working, which basically checks a Collection for duplicates (based on a generic business object type passed in). Lets take the IBankAccount Business Object for example: ``` public interface IBankAccount : IMyBusinessObjectBase { IBank Bank { get; set; } IBankAccountType BankAccountType { get; set; } string AccountName { get; set; } string AccountNumber { get; set; } DateTime EffectiveDate { get; set; } } ``` Lets say I have the following collection of IBankAccount ``` IBankAccount acc1 = new BankAccount(); acc1.AccountName = "Account1"; acc1.AccountNumber = "123456"; acc1.Bank = FetchBusinessObjectByID(1); //Fetch Bank 1 IBankAccount acc2 = new BankAccount(); acc2.AccountName = "Account2"; acc2.AccountNumber = "654321"; acc2.Bank = FetchBusinessObjectByID(1); //Fetch Bank 1 IBankAccount acc3 = new BankAccount(); acc3.AccountName = "Account3"; acc3.AccountNumber = "123456"; acc3.Bank = FetchBusinessObjectByID(2); //Fetch Bank 2 IBankAccount acc4 = new BankAccount(); acc4.AccountName = "Account3"; acc4.AccountNumber = "123456"; acc4.Bank = FetchBusinessObjectByID(1); //Fetch Bank 2 ICollection<IBankAccount> bankAccounts = new List<IBankAccount>(); bankAccount.Add(acc1); bankAccount.Add(acc2); bankAccount.Add(acc2); bankAccount.Add(acc4); ``` Parameters: T = BusinessObject Type Class (Person,Address,BankAccount,Bank,BankBranch etc) string[] entityPropertyName = Array of properties to include when checking for duplicates. Now lets use the following senario: Lets say I want to check for duplicate BankAccounts, by checking the on the account number, and the bank. The Account Number is unique within a bank, but can exist in another bank. So if you look at the list above, Acc1,Acc2 and Acc3 is valid. Acc4 is invalid because that account number for that Bank already exist. So, the call to validate would look like this. DuplicateValidationRule.Validate(newBankAccountEntry,new string[] {"AccountNumber","Bank.Name"}); The code above passes in the the business entity to check duplicates for, and the property array which includes the properties to check against. ``` public ValidationError Validate<T>(T entityProperty, string[] entityPropertyName) { ICollection<T> businessObjectList = FetchObjectsByType<T>(); bool res = true; for (int i = 0; i < entityPropertyName.Length; i++) { object value = getPropertyValue(entityProperty, entityPropertyName[i]); //By Using reflection and the getPropertyValue method I can substitute the properties to //compare. if (businessObjectList.Any(x => getPropertyValue(x, entityPropertyName[i]).Equals(value) && x.GetType().GetProperty("ID").GetValue(x,null).ToString() != ((IBusinessObjectBase)entityProperty).ID.ToString())) res &= true; else res &= false; } if (res) return new ValidationError(_DuplicateMessage); else return ValidationError.Empty; } ``` This method is used to get the actual object to check the duplicates on: ``` private static object getPropertyValue(object obj, string propertyName) { string[] PropertyNames = propertyName.Split('.'); object propertyValue = obj; for (int i = 0; i < PropertyNames.Length; i++) { propertyValue = propertyValue.GetType().GetProperty(PropertyNames[i], BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy). GetValue(propertyValue, null); } if (propertyValue.GetType() == typeof(string)) return propertyValue.ToString().ToLower(CultureInfo.CurrentCulture); else return propertyValue; } ``` The above code works, but it has a flaw: The code above will only work if you check a single property for a duplicate match: ``` DuplicateValidationRule.Validate<IBankAccount>(newBankAccountEntry,new string[] {"AccountNumber"}); ``` When you add another property to check against, for example: ``` DuplicateValidationRule.Validate<IBankAccount>(newBankAccountEntry,new string[] {"AccountNumber","Bank.Name"}); ``` then the code will check the second property, on the next occurange in the list. It should test all the properties in the .Any for the currently object being compared. Hope this makes sence, maybe someone can give me some advice on how to fix this! Thanks :)
Here's me under the assumption that you have a BusinessObject entity and you want to match ALL properties against another in a list of BusinessObjects: ``` public ValidationError Validate<T>(T entityProperty, string[] entityPropertyName) { ICollection<T> businessObjectList = FetchObjectsByType<T>(); Hashtable properties = EnumeratePropertyInfo<T>(entityProperty, entityPropertyName); return businessObjectList.Any(obj => IsDuplicate<T>(obj, properties)) == true ? new ValidationError(_DuplicateMessage) : ValidationError.Empty; } private Hashtable EnumeratePropertyInfo<T>(T entityProperty, string[] entityPropertyName) { Hashtable properties = new Hashtable(); for (int i = 0; i < entityPropertyName.Length; i++) { object value = getPropertyValue(entityProperty, entityPropertyName[i]); properties.Add(entityPropertyName[i], value); } return properties; } // all properties must be matched for a duplicate to be found private bool IsDuplicate<T>(T entityProperty, Hashtable properties) { foreach(DictionaryEntry prop in properties) { var curValue = getPropertyValue(entityProperty, prop.Key.ToString()); if (!prop.Value.Equals(curValue)) { return false; } } return true; } ``` If you are perhaps a little concerned about using a Hastable for the property mappings then I would advise you create your own custom type for this instead. Hope that helps.
If I'm not wrong right now you are checking the unique existence of every single property not the combination of them. Instead of using reflection can't you use the Equals method or an interface (eg. IMyComparable) like this: ``` public interface IMyComparable<T> { bool MyComparableMethod(T account); } public interface IBankAccount : IMyBusinessObjectBase, IMyComparable<T> { ... public bool MyComparableMethod(IBankAccount account) { return this.AccountNumber == account.AccountNumber && this.Bank.Name == account.Bank.Name && this.Id != account.Id; } } public ValidationError Validate<T>(T entityProperty) where T : IMyComparable<T> { ... if (!businessObjectList.Any(x => entityProperty.MyComparableMethod(x)) return new ValidationError(_DuplicateMessage); ... ``` than in the Any method you can use the MyComparableMethod method defined in the interface. Hope this helps :)
Generic DuplicateValidationRule (Checking Business Objects for duplicates)
[ "", "c#", "validation", "generics", "reflection", "" ]
I'm using `XmlTextWriter` and its `WriteElementString` method, for example: ``` XmlTextWriter writer = new XmlTextWriter("filename.xml", null); writer.WriteStartElement("User"); writer.WriteElementString("Username", inputUserName); writer.WriteElementString("Email", inputEmail); writer.WriteEndElement(); writer.Close(); ``` The expected XML output is: ``` <User> <Username>value</Username> <Email>value</Email> </User> ``` However, if for example inputEmail is empty, the result XML I get as as follows: ``` <User> <Username>value</Username> <Email/> </User> ``` Whereas I would expect it to be: ``` <User> <Username>value</Username> <Email></Email> </User> ``` What am I doing wrong? Is there a way to achieve my expected result in a simple way using `XmlTextWriter`?
Your output is correct. An element with no content should be written as `<tag/>`. You can force the use of the full tag by calling WriteFullEndElement() ``` writer.WriteStartElement("Email"); writer.WriteString(inputEmail); writer.WriteFullEndElement(); ``` That will output `<Email></Email>` when inputEmail is empty. If you want to do that more than once, you could create an extension method: ``` public static void WriteFullElementString(this XmlTextWriter writer, string localName, string value) { writer.WriteStartElement(localName); writer.WriteString(value); writer.WriteFullEndElement(); } ``` Then your code would become: ``` writer.WriteStartElement("User"); writer.WriteFullElementString("Username", inputUserName); writer.WriteFullElementString("Email", inputEmail); writer.WriteEndElement(); ```
It doesn't fail `<Tag/>` is just a shortcut for `<Tag></Tag>`
C#: XmlTextWriter.WriteElementString fails on empty strings?
[ "", "c#", "xml", "xmltextwriter", "writeelementstring", "" ]
I'm trying to speed up my code and the bottleneck seems to be the individual insert statements to a Jet MDB from outside Access via ODBC. I need to insert 100 rows at a time and have to repeat that many times. It is possible to insert multiple rows in a table with SQL code? Here is some stuff that I tried but neither of them worked. Any suggestions? ``` INSERT INTO tblSimulation (p, cfYear, cfLocation, Delta, Design, SigmaLoc, Sigma, SampleSize, Intercept) VALUES (0, 2, 8.3, 0, 1, 0.5, 0.2, 220, 3.4), (0, 2.4, 7.8, 0, 1, 0.5, 0.2, 220, 3.4), (0, 2.3, 5.9, 0, 1, 0.5, 0.2, 220, 3.4) INSERT INTO tblSimulation (p, cfYear, cfLocation, Delta, Design, SigmaLoc, Sigma, SampleSize, Intercept) VALUES (0, 2, 8.3, 0, 1, 0.5, 0.2, 220, 3.4) UNION (0, 2.4, 7.8, 0, 1, 0.5, 0.2, 220, 3.4) UNION (0, 2.3, 5.9, 0, 1, 0.5, 0.2, 220, 3.4) ```
I found an elegant solution within [R](http://www.r-project.org), (the software I'm working with). The RODBC package has a function sqlSave which allow to append and entire data.frame at once to a table. This works almost twice as fast as individual inserts within a transaction. ``` library(RODBC) MDB <- odbcConnectAccess("database.mdb") sqlSave(channel = MDB, dat = sims, tablename = "tblSimulation", append = TRUE, rownames = FALSE) odbcClose(MDB) ```
Your query should look like this ``` insert into aaa (col1, col2) select * from (select 'yourdatarow1col1' as col1 , 'yourdatarow1col2' as col2 from ddd union all select 'yourdatarow2col1' as col1, 'yourdatarow1col2' as col2 from ddd) as tmp ``` aaa: Is your target table in access ddd: create a table in access db with one colum and must have 1 row, doesn't not mater what data. aliases: All aliases should have same name and order has target table Hope works for you, my process drop from 15 minutes to 1.30 minutes Bye Gus
SQL code to insert multiple rows in ms-access table
[ "", "sql", "ms-access", "" ]
I'm working on an example from Bruce Eckel's book and i was wondering why the initialized values don't stick when I output them? ``` class InitialValues2 { boolean t = true; char c = 'x'; byte b = 47; short s = 0xff; int i =999; long l =1; float f = 3.14f; double d =3.14159; InitialValues reference; void printInitialValues() { System.out.println("data type Initial values"); System.out.println("boolean " + t); System.out.println("char [" + c + "]"); System.out.println("byte " + b); System.out.println("short " + s); System.out.println("int " + i); System.out.println("long " + l); System.out.println("float " + f); System.out.println("double " + d); System.out.println("reference " + reference); } //end printinitialvalues public static void main(String args[]) { InitialValues iv = new InitialValues(); iv.printInitialValues(); //new InitialValues().printInitialValues(); } //end main } ``` All the variables output 0 and null values.
I see one problem. The variables are declared in a class called InitialValues2, yet you are calling the printInitialValues() method on an object that is of the type InitialValues. It appears that you are never calling your printInitialValues() method.
``` class InitialValues { boolean t = true; char c = 'x'; byte b = 47; short s = 0xff; int i =999; long l =1; float f = 3.14f; double d =3.14159; InitialValues reference; void printInitialValues() { System.out.println("data type Initial values"); System.out.println("boolean " + t); System.out.println("char [" + c + "]"); System.out.println("byte " + b); System.out.println("short " + s); System.out.println("int " + i); System.out.println("long " + l); System.out.println("float " + f); System.out.println("double " + d); System.out.println("reference " + reference); } //end printinitialvalues public static void main(String args[]) { InitialValues iv = new InitialValues(); iv.printInitialValues(); //new InitialValues().printInitialValues(); } //end main } ``` You're class is called InitialValues2 You should rename it to InitialValues.
Java: why don't these variables initialize?
[ "", "java", "" ]
Which is more correct and why? ``` Control.BeginInvoke(new Action(DoSomething), null); private void DoSomething() { MessageBox.Show("What a great post"); } ``` or ``` Control.BeginInvoke((MethodInvoker) delegate { MessageBox.Show("What a great post"); }); ``` I kinda feel like I am doing the same thing, so when is the right time to use `MethodInvoker` vs `Action`, or even writing a lambda expression? *EDIT:* I know that there isn't really much of a difference between writing a lambda vs `Action`, but `MethodInvoker` seems to be made for a specific purpose. Is it doing anything different?
Both are equally correct, but the documentation for [`Control.Invoke`](http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx) states that: > The delegate can be an instance of > EventHandler, in which case the sender > parameter will contain this control, > and the event parameter will contain > EventArgs.Empty. The delegate can also > be an instance of MethodInvoker, or > any other delegate that takes a void > parameter list. A call to an > EventHandler or MethodInvoker delegate > will be faster than a call to another > type of delegate. So `MethodInvoker` would be a more efficient choice.
For each solution bellow I run a 131072 (128\*1024) iterations (in one separated thread). The VS2010 performance assistant give this results: * read-only MethodInvoker: 5664.53 (+0%) * New MethodInvoker: 5828.31 (+2.89%) * function cast in MethodInvoker: 5857.07 (+3.40%) * read-only Action: 6467.33 (+14.17%) * New Action: 6829.07 (+20.56%) Call to a new **Action** at each iteration ``` private void SetVisibleByNewAction() { if (InvokeRequired) { Invoke(new Action(SetVisibleByNewAction)); } else { Visible = true; } } ``` Call to a read-only, build in constructor, **Action** at each iteration ``` // private readonly Action _actionSetVisibleByAction // _actionSetVisibleByAction= SetVisibleByAction; private void SetVisibleByAction() { if (InvokeRequired) { Invoke(_actionSetVisibleByAction); } else { Visible = true; } } ``` Call to a new **MethodInvoker** at each iteration. ``` private void SetVisibleByNewMethodInvoker() { if (InvokeRequired) { Invoke(new MethodInvoker(SetVisibleByNewMethodInvoker)); } else { Visible = true; } } ``` Call to a read-only, build in constructor, **MethodInvoker** at each iteration ``` // private readonly MethodInvoker _methodInvokerSetVisibleByMethodInvoker // _methodInvokerSetVisibleByMethodInvoker = SetVisibleByMethodInvoker; private void SetVisibleByMethodInvoker() { if (InvokeRequired) { Invoke(_methodInvokerSetVisibleByMethodInvoker); } else { Visible = true; } } ``` Call to the function cast in **MethodInvoker** at each iteration ``` private void SetVisibleByDelegate() { if (InvokeRequired) { Invoke((MethodInvoker) SetVisibleByDelegate); } else { Visible = true; } } ``` Example of call for the "New Action" solution : ``` private void ButtonNewActionOnClick(object sender, EventArgs e) { new Thread(TestNewAction).Start(); } private void TestNewAction() { var watch = Stopwatch.StartNew(); for (var i = 0; i < COUNT; i++) { SetVisibleByNewAction(); } watch.Stop(); Append("New Action: " + watch.ElapsedMilliseconds + "ms"); } ```
MethodInvoker vs Action for Control.BeginInvoke
[ "", "c#", ".net", "delegates", "invoke", "" ]
I currently have a menu with subitems that is being stored in this dictionary variable: ``` private Dictionary<string, UserControl> _leftSubMenuItems = new Dictionary<string, UserControl>(); ``` So I add views to the e.g. the "Customer" section like this: ``` _leftSubMenuItems.Add("customers", container.Resolve<EditCustomer>()); _leftSubMenuItems.Add("customers", container.Resolve<CustomerReports>()); ``` But since I am using a Dictionary, **I can only have one key named "customers"**. My natural tendency would be to now create a **custom struct** with properties "Section" and "View", but **is there a .NET collection is better suited for this task, something like a "MultiKeyDictionary"?** # ANSWER: Thanks maciejkow, I expanded your suggestion to get exactly what I needed: ``` using System; using System.Collections.Generic; namespace TestMultiValueDictionary { class Program { static void Main(string[] args) { MultiValueDictionary<string, object> leftSubMenuItems = new MultiValueDictionary<string, object>(); leftSubMenuItems.Add("customers", "customers-view1"); leftSubMenuItems.Add("customers", "customers-view2"); leftSubMenuItems.Add("customers", "customers-view3"); leftSubMenuItems.Add("employees", "employees-view1"); leftSubMenuItems.Add("employees", "employees-view2"); foreach (var leftSubMenuItem in leftSubMenuItems.GetValues("customers")) { Console.WriteLine(leftSubMenuItem); } Console.WriteLine("---"); foreach (var leftSubMenuItem in leftSubMenuItems.GetAllValues()) { Console.WriteLine(leftSubMenuItem); } Console.ReadLine(); } } public class MultiValueDictionary<TKey, TValue> : Dictionary<TKey, List<TValue>> { public void Add(TKey key, TValue value) { if (!ContainsKey(key)) Add(key, new List<TValue>()); this[key].Add(value); } public List<TValue> GetValues(TKey key) { return this[key]; } public List<TValue> GetAllValues() { List<TValue> list = new List<TValue>(); foreach (TKey key in this.Keys) { List<TValue> values = this.GetValues(key); list.AddRange(values); } return list; } } } ``` # Answer 2: Thanks Blixt for the tip about yield, here is GetAllValues with that change: ``` public IEnumerable<TValue> GetAllValues() { foreach (TKey key in this.Keys) { List<TValue> values = this.GetValuesForKey(key); foreach (var value in values) { yield return value; } } } ``` # Answer 2 refactored further: Here is a much more succinct way to do the same thing, thanks Keith: ``` public IEnumerable<TValue> GetAllValues() { foreach (var keyValPair in this) foreach (var val in keyValPair.Value) yield return val; } ```
If you need variable number of values for one key, why not create `Dictionary<string, List<UserControl>>` ? Furthermore, you could inherit this class and create your own Add, get same syntax you're using now. This way you can avoid manual adding of empty lists before adding new control. sth like this: ``` class MultiValueDictionary<TKey, TValue> : Dictionary<TKey, List<TValue>> { public void Add(TKey key, TValue value) { if(!ContainsKey(key)) Add(key, new List<TValue>()); this[key].Add(value); } } ```
Check out [NGenerics](http://www.codeplex.com/NGenerics)' [HashList](http://ngenerics.codeplex.com/Wiki/View.aspx?title=HashList). It's a Dictionary which maintains a list of values for each key. [Wintellect's PowerCollections](http://www.codeplex.com/PowerCollections) library also has a handy MultiDictionary class which does things like automatically clean up when you remove the last value associated with a given key.
Is there a Dictionary<string, object> collection which allows multiple keys?
[ "", "c#", "collections", "" ]
I have one method that receives a Stream to write on it using a BinaryWriter. But when I dispose this BinaryWriter it also closes the stream. Can I leave it undisposed so I can leave my stream open?
Just do not call Dispose, use Flush instead, its safe.
As of .NET 4.5, the BinaryWriter class has a new constructor that takes a boolean parameter to indicate whether to leave the stream open or not. Ref: <http://msdn.microsoft.com/en-us/library/gg712841.aspx> ``` public BinaryWriter( Stream output, Encoding encoding, bool leaveOpen ) ```
Why a BinaryWriter closes the outer Stream on disposal, and how to prevent that? (.NET C#)
[ "", "c#", ".net", "stream", "binarywriter", "" ]
I am working on my first PHP based website, and I was wondering what solutions were out there for a username/password system? I have tried using a .htaccess file for basic security, and while it works, I want something a little easier for a layman to administer. Are there any other solutions out there that I could try? I don't have a database server available, so it would have to support flat file databases...thanks! **Edit** I have determined that I do have SQLite support, so I do have a database option available. Also, I feel I should mention a little further some requirements that I have. I originally looked to using .htaccess to protect my website, since I need security over the entire directory. Most of the files I am trying to protect are .pdf and .doc...any solution would have to allow me to secure those files as well as any web pages in the directory. If I could find a good solution to more or less "skin" the .htaccess method of locking a directory, so that I could do things like have an actual login/register page, etc. then I would just stick to the .htaccess method. I would however like something that is more manageable, I just need the directory security.
I wrote up this code quickly, it is syntacticly correct but I have not tested it. There are 2 things that I did not do here, first, I did not provide a function to remove a user and second I did not provide a function to change a users password, these you'll have to write yourself. However this should provide for a good place to start. These functions will store your usernames/passwords in a file called passwords in the following format ``` username0:password0 username1:password1 username2:password2 ... ``` . ``` function authenticate($username, $password) { //ALWAYS use a salt to secure the encryption of your passwords, this can be any value of any //length, the longer and the more characters the better //I like to use a "perfect password" from Steve Gibbson's https://www.grc.com/passwords.htm //This must the exactly the same as the salt in theaddUser() function $salt = 'voDeaFWckErOPPGwiapYBwEoc4O2d1M60m2QsYc7A15PUshrLamoVioG1wUmEgF'; //First we need to get the contents of the file that has the usernames/passwords in it. //we don't want to use fopen() or we may end up with a locked file error if another access is //attempted before we've closed it. //this line will get the contents of the file named passwords and store it in the $fh variable $fh = file_get_contents('passwords'); //Now lets take the file and split it into an array where each line is a new element in the array. $fh = split("\n", $fh); //Now lets loop over the entire array spliting each row into it's username/password pair foreach($fh as $r) { //Every time this loop runs $r will be populated with a new row //Lets split the line into it's username/password pairs. $p = split(':', $p); //Since we don't need all the usernames/password to be in memory lets stop when we find the one we need if($p[0] == $username && $p[1] == sha1($salt . $password)) { //We've found the correct use so lets stop looping and return true return true; } } //If we've reached this point in the code then we did not find the user with the correct password in the 'database' //so we'll just return false return false; } function addUser($username, $password) { //ALWAYS use a salt to secure the encryption of your passwords, this can be any value of any //length, the longer and the more characters the better //I like to use a "perfect password" from Steve Gibbson's https://www.grc.com/passwords.htm //This must the exactly the same as the salt in the authenticate() function $salt = 'voDeaFWckErOPPGwiapYBwEoc4O2d1M60m2QsYc7A15PUshrLamoVioG1wUmEgF'; //We need to parse out some preticularly bad characters from the user name such as : which is used to seperate the username and password //and \r and \n which is the new line character which seperates our lines $username = preg_replace('/\r|\n|\:/', '', $username); //Now lets encrypt our password with the salt added $password = sha1($salt . $password); //Lets build the new line that is going to be added $line = $username . ':' . $password . "\n"; //Lets open the file in append mode so that the pointer will be placed at the end of the file $fh = fopen('passwords', 'a'); //Write the new entry to the file fwrite($fh, $line); //Close the file fclose($fh); //Typicaly one would write a bunch of error handling code on the above statments and if something //goes wrong then return false but if you make it this far in the code then return true return true; } ```
Have a look at [Zend\_Auth](http://framework.zend.com/manual/en/zend.auth.html). It's open source, so you can sniff around to get a feel for how an authentication module should (or could) be implemented. From the doc: > Zend\_Auth is concerned only with > authentication and not with > authorization. Authentication is > loosely defined as determining whether > an entity actually is what it purports > to be (i.e., identification), based on > some set of credentials.
PHP Username Password Solution
[ "", "php", "security", "" ]
We have an application with multiple subsystems running in different threads (ie one thread monitors the GPS, another monitors a RFID reader etc). The threads are started and monitored by a service registry which is seperate from the win forms part. The initial release of the App just had a single form which would run on an update timer and just check the values of static variables on each of the subsystems every second or so. I'm trying to clean this up, as we're adding in extra forms and there's virtually no thread safety with the current approach. I want each subsystem to throw a new event when its underlying state has changed so each form can subscribe only to the events it cares about and we can move to a more responsive UI...I don't like the update timer approach. I'm running into problems here as events are triggered in the subsystems thread so I get System.InvalidOperationException exceptions complaining about cross thread calls when I try and update the UI with any state that is passed through with the event. So at the moment, after reading through the msdn documentation, my options are to use control.invoke for each field I wish to update which is pretty annoying on complex forms with lots of fields, use background workers to run the subsystems in the forms themselves or have the forms still run on a timer and query the subsystems themselves, which I'm trying to avoid. I want the forms to be as separate from the underlying system as possible...they should only know which events they care about and update the relevant fields. My question is, what am I missing here?? is there a better way I can architect this system so that the subsystems can run in their own threads but still send notifications off in a non coupled way? any help would be greatly appreciated cheers nimai
Rather than invoke across for each field you want to update, use a [MethodInvoker](http://msdn.microsoft.com/en-us/library/system.windows.forms.methodinvoker.aspx) delegate with [BeginInvoke](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx) and call a method that does all your updates at once. For example ... ``` BeginInvoke( new MethodInvoker( MyUIUpdaterMethodHere ) ); ```
You can take a look at [Event Aggregator](http://martinfowler.com/eaaDev/EventAggregator.html) pattern which basically allows a loosely coupled pub/sub type event-based architecture. Prism, a framework from Microsoft Patterns and Practices team for building composite applications with WPF and Silverlight has event aggregation that allows different UI components to communicate with each other in a loosely coupled way similar to your design goal. You can take a look at it and try to use just the event aggregation part of it. If not, you have access to the source code so that you can craft something that fits your requirements.
best way to handle multiple threads in a Win Forms Application
[ "", "c#", "winforms", "multithreading", "" ]
I have some javascript which parses an ISO-8601 date. For some reason, it is failing for dates in June. But dates in July and May work fine, which doesn't make sense to me. I'm hoping a fresh set of eyes will help, because I can't see what I'm doing wrong here. ## Function definition (with bug) ``` function parseISO8601(timestamp) { var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$"); var matches = regex.exec(timestamp); if(matches != null) { var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10); if(matches[7] == "-") offset = -offset; var date = new Date(); date.setUTCFullYear(parseInt(matches[1], 10)); date.setUTCMonth(parseInt(matches[2], 10) - 1); //UPDATE - this is wrong date.setUTCDate(parseInt(matches[3], 10)); date.setUTCHours(parseInt(matches[4], 10)); date.setUTCMinutes(parseInt(matches[5], 10) - offset); date.setUTCSeconds(parseInt(matches[6], 10)); date.setUTCMilliseconds(0); return date; } return null; } ``` ## Test code ``` alert(parseISO8601('2009-05-09T12:30:00-00:00').toUTCString()); alert(parseISO8601('2009-06-09T12:30:00-00:00').toUTCString()); alert(parseISO8601('2009-07-09T12:30:00-00:00').toUTCString()); ``` ## Output * Sat, 09 May 2009 12:30:00 GMT * Thu, 09 **Jul** 2009 12:30:00 GMT * Thu, 09 Jul 2009 12:30:00 GMT --- ## Update Thanks for the quick answers, the problem was that the Date object was initially today, which happened to be July 31. When the month was set to June, before I changed the day, it was temporarily **June 31**, which got rolled forward to July 1. I've since found the following to be a cleaner implementation, as it sets all the date attributes at once: ``` function parseISO8601(timestamp) { var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$"); var matches = regex.exec(timestamp); if(matches != null) { var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10); if(matches[7] == "-") offset = -offset; return new Date( Date.UTC( parseInt(matches[1], 10), parseInt(matches[2], 10) - 1, parseInt(matches[3], 10), parseInt(matches[4], 10), parseInt(matches[5], 10), parseInt(matches[6], 10) ) - offset*60*1000 ); } return null; } ```
The problem is that today is July 31. When you set: ``` var date = new Date(); ``` Then `date.getUTCDate()` is 31. When you set `date.setUTCMonth(5)` (for June), you are setting `date` to **June 31**. Because there is no June 31, the JavaScript `Date` object turns it into *July 1*. So immediately after setting calling `date.setUTCMonth(5)` if you `alert(date.getUTCMonth());` it will be `6`. This isn't unique to June. Using your function on the 31st of any month for any other month that does not have 31 days will exhibit the same problem. Using your function on the 29th (non-leap years), 30th or 31st of any month for February would also return the wrong result. Calling `setUTC*()` in such a way that any rollovers are overwritten by the correct value should fix this: ``` var date = new Date(); date.setUTCMilliseconds(0); date.setUTCSeconds(parseInt(matches[6], 10)); date.setUTCMinutes(parseInt(matches[5], 10) - offset); date.setUTCHours(parseInt(matches[4], 10)); date.setUTCDate(parseInt(matches[3], 10)); date.setUTCMonth(parseInt(matches[2], 10) - 1); date.setUTCFullYear(parseInt(matches[1], 10)); ```
The date object starts off with the current date. It's the 31st today so setting 2009-06-09 gives: ``` var date = new Date(); // Date is 2009-07-31 date.setUTCFullYear(2009); // Date is 2009-07-31 date.setUTCMonth(6 - 1); // Date is 2009-06-31 = 2009-07-01 date.setUTCDate(9); // Date is 2009-07-09 ``` If you set the date to the 1st before you begin, then you should be safe.
Javascript date parsing bug - fails for dates in June (??)
[ "", "javascript", "parsing", "date", "" ]
I've got a winform with 2 treeviews. my left treeview is being loaded with data from an adserver which is being loaded by clicking on a button. This triggers my backgroundworker which fetches my data and builds up my tree. Now while doing this I'm disabling the treeview control and showing a picturebox with an animated gif on it. So when my backgroundworker is finished I enable back my treeview and hide my picturebox. So what I want to do is that the picturebox stays in center of the treeview. both treeviews are on a splitted container. so maybe I need to get the borders of those panels? So when the size of the form changes, my picturebox stays nicely in the center of the treeview.
Create a panel to the same size and location of your treeview. Add this treeview in the panel and set it to **DockStyle.Fill**. Add your picture to the panel and set the anchor to **AnchorStyles.None**. ``` this.panel1.Controls.Add(treeView2); this.panel1.Controls.Add(pictureBox1); this.treeView2.Dock = DockStyle.Fill; this.pictureBox1.Anchor = AnchorStyles.None; ``` The anchor style **AnchorStyles.None** will keep your picture box in the center of the panel. Set your picture box in front of your tree view. Once, your processing is over just hide the picture box.
Not clear on how you set up your form, but you either want to put the logic in the form Resize event or the TreeView Resize event. When either is resized, place the image at the location = half way across the TreeView, minus half the widht of your image, repeat for height.
Keeping Windows Forms Picturebox in middle of TreeView
[ "", "c#", "winforms", "treeview", "picturebox", "" ]
So, maybe I misunderstood the usage of Func but ``` Func<ComboBox, string> getCurrentValue = s => s.SelectedValue.ToString(); ``` Creates a Thread Error when calling `getCurrentValue(cb_message_type)` from my Workerthread. Whats the best solution to get the Selected Value of the Combobox? Many thanks, rAyt **Edit** MSDN *"The underlying type of a lambda expression is one of the generic Func delegates. This makes it possible to pass a lambda expression as a parameter without explicitly assigning it to a delegate."*
Since windows controls have thread affinity, you have 2 options: 1. query this data before doing your threading code, for example passing it in as the state to the worker 2. query it in the worker via Control.Invoke Since the first is trivial, I'll give an example of the second using captured variables: ``` object value = null; yourCombo.Invoke((MethodInvoker) delegate {value=yourCombo.SelectedValue;}); string s = value.ToString(); ``` Here the bits inside `delegate {...}` happen on the UI thread, even if the code around it is on the worker thread. You can mix the above either *inside* your func, or call the entire func once you've switched threads.
You need to call `Control.Invoke` with that delegate - or make the delegate itself call it. Using a lambda expression doesn't change the threading requirements of Windows Forms - it just makes it easier to create a delegate. You might want to make a convenience method to do this: ``` // (Untested) public static Func<TControl, TResult> WrapInvocation(Func<TControl,TResult> func) where TControl : Control { return control => { return (TResult) control.Invoke(func); }; } ``` Use as: ``` Func<ComboBox, string> getCurrentValue = s => s.SelectedValue.ToString(); getCurrentValue = WrapInvocation(getCurrentValue); ``` Then you can call `getCurrentValue(comboBox)` from any thread.
C# Func Delegate throws Thread Exception
[ "", "c#", "" ]
I picked this up in one of my brief forays to reddit: <http://www.smallshire.org.uk/sufficientlysmall/2009/07/31/in-c-throw-is-an-expression/> Basically, the author points out that in C++: ``` throw "error" ``` is an expression. This is actually fairly clearly spelt out in the C++ Standard, both in the main text and the grammar. However, what is not clear (to me at least) is what is the type of the expression? I guessed "`void`", but a bit of experimenting with g++ 4.4.0 and Comeau yielded this code: ``` void f() { } struct S {}; int main() { int x = 1; const char * p1 = x == 1 ? "foo" : throw S(); // 1 const char * p2 = x == 1 ? "foo" : f(); // 2 } ``` The compilers had no problem with //1 but barfed on //2 because the the types in the conditional operator are different. So the type of a `throw` expression does not seem to be void. So what is it? If you answer, please back up your statements with quotes from the Standard. --- **This turned out not to be so much about the type of a throw expression as how the conditional operator deals with throw expressions - something I certainly didn't know about before today. Thanks to all who replied, but particularly to David Thornley.**
According to the standard, 5.16 paragraph 2 first point, "The second or the third operand (but not both) is a throw-expression (15.1); the result is of the type of the other and is an rvalue." Therefore, the conditional operator doesn't care what type a throw-expression is, but will just use the other type. In fact, 15.1, paragraph 1 says explicitly "A throw-expression is of type void."
> "A throw-expression is of type void" ISO14882 Section 15
In C++, if throw is an expression, what is its type?
[ "", "c++", "throw", "" ]
Just for the disclaimer, I'm not trying to win the prize in Android Developer Challenge, but just want to participate. I heard about the Android buzz lately and got interested in it. And today I stumbled upon a site talking about Android Developer Challenge 2. Luckily, the submission hasn't ended but unfortunately it starts tomorrow, August 1. Since this is a new opportunity I want to give it a try but I think I'm a little bit late. I have configured the development platform and got some tutorials. I wanted to know if I could successfully develop a project within 30 days and submit it. Or is it really a big task which needs months of preparation. I just want to know if it is worth a try. And for the record I know nothing about Androids except that it is an open source platform for application development on mobiles. I know Java but not competent, so may be need to touch up on that too. It would be nice, if I get some real pointers on what I'm about to embark on. If it isn't possible I may need to pace down and enjoy other things in life too. So is is possible to complete a small and decent app within 30 days or is it already late and if so are there any suggestions?
The real answer: It Depends. The size and your capacity of learning are very important. The smallest and simplest your app is, the more chances you have. The faster you learn, the more chances you have. If you make it too complex, then you have no chance. Note that being capable of making a decent app is different of being capable of making a great app. It's still possible, but it'll be a real challenge.
My answer: Why not just try? No matter what happens you'll get a lot of valuable experience. Working with a new technology, time management, project gauging, working under pressure. I really don't see a drawback to just giving it a shot.
Is it realistic for an android newbie to successfully complete a project in 30 days and submit it to ADC2?
[ "", "java", "android", "" ]
I've been programming for so long its hard to keep up with language changes sometimes... Is it really ok to set properties like this after .net v2 ``` public string LocaleName { get; set; } ``` Not requiring an inner field? Seems like the compiler takes care of this lately?
Yes, this is a new feature in C# 3.0
Just so you know, you can also do something like this: ``` public string MyString { get; private set; } ``` which gives you a public accessor but a private setter.
Is this the correct syntax for auto properties?
[ "", "c#", "automatic-properties", "" ]
Imagine I have a db table of Customers containing {id,username,firstname,lastname} If I want to find how many instances there are of different firstnames I can do: ``` select firstname,count(*) from Customers group by 2 order by 1; username | count(*) =================== bob | 1 jeff | 2 adam | 5 ``` How do I write the same query to only return firstnames that occur more than once? i.e. in the above example only return the rows for jeff and adam.
You want the `having` clause, like so: ``` select firstname, count(*) from Customers group by firstname having count(*) > 1 order by 1 ```
`group by 2 order by 1` is terrible, I should say. Use proper column names if that's supported: this will drastically improve readability. With that in mind, ``` select firstname, count(*) c from Customers group by firstname having count(*) > 1 -- Kudos to Shannon order by c; ```
SQL - WHERE AGGREGATE>1
[ "", "sql", "aggregate", "informix", "" ]
So I have a client that needs to be running tomcat for various things (Solr and a webservice as well) and after having a meeting with him and another programmer on the project, I got a little confused. The other programmer was throwing around buzzwords and saying things like "We need to have middleware for tomcat." In response to this, my client asks me to look for middleware for tomcat which confused me because I thought that writing a webservice would be specific to the project at hand and so the "middleware" would be developed by us. If this is the case, why not just say "Web service"? My question is this: Is there an open source servlet or plug-in for tomcat that makes it middleware (maybe something from apache's site?) or does it make sense that I should be writing my own middleware for tomcat? Or... is tomcat considered middleware? I am a total n00b when it comes to Java and tomcat, but I have a lot of experience with C#, so I'm trying to figure out how this relates to C#. I have never used the term "middleware" before and I'm pretty sure "webservice" is pretty much the same thing. Any ideas?
All of these answers are too verbose. Yes, Tomcat is middleware. it sits between the HTML/Javascript layer on the client's browser and the database layer on your server. It's not as full featured as a J2EE server but it's still "middleware" as far as the generally accepted buzzword-term goes.
The term middleware is usually used to describe software who's purpose is to connect together two different systems. If you are writing web services on top of another application and the third application will talk to the web services. Then yes, you are writing middleware. If you are generally working in a .NET environment and some systems are on Tomcat. Then it's likely that the other programmer was claiming that to connect the .NET apps to the Java apps on Tomcat, some middleware would have to be written. (He's probably right.)
Is Tomcat middleware?
[ "", "java", "web-services", "tomcat", "solr", "middleware", "" ]
Following-on from [this question](https://stackoverflow.com/questions/336817/how-can-i-detect-whether-a-user-control-is-running-in-the-ide-in-debug-mode-or), is it possible to detect whether one is in design or runtime mode from within an object's constructor? I realise that this may not be possible, and that I'll have to change what I want, but for now I'm interested in this specific question.
You can use the [LicenceUsageMode](http://msdn.microsoft.com/en-us/library/system.componentmodel.licenseusagemode.aspx) enumeration in the `System.ComponentModel` namespace: ``` bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime); ```
Are you looking for something like this: ``` public static bool IsInDesignMode() { if (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) { return true; } return false; } ``` You can also do it by checking process name: ``` if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv") return true; ```
Detecting design mode from a Control's constructor
[ "", "c#", "winforms", "" ]
Is there any way to bind a DataTable object to an actual table in my database? Right now I perform a query and fill the DataTable with the result. It would be really cool if I could just DataTable.(Save/Update) with out having to write additional code! Is such a thing or a similar solution possible?
See [DataAdapter.Update()](http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update(VS.71).aspx). You should write some code..
Take a look at [MyGeneration](http://www.mygenerationsoftware.com/portal/default.aspx) (template based code generator) and [EasyObjects](http://www.easyobjects.net/) (ORM Mapping library) which, when combined, get you pretty close to this. MyGeneration will even write the CRUD stored procedures for you (but you need to apply them to the db).
Is there a way to bind a DataTable to an actual Table in a data base?
[ "", "c#", "ado.net", "datatable", "" ]
I am looking for an elegant way to call a function based on the type of parameter that is passed as parameter. In other words, I want the `EntryPoint` method (below) to dynamically call the appropriate myFunc method, based on the type of the `template` parameter. ``` public void EntryPoint(object template) { missingMethod(template);//This is the code in question that should call myFunc } private void myFunc(TemplateA template) { doSomething(template); } private void myFunc(TemplateB template) { doSomethingElse(template); } private void myFunc(object template) { throw new NotImplementedException(template.GetType()); } ```
Three options: * A series of if/else statements (ugly but simple and easy to understand) * [Double dispatch](http://en.wikipedia.org/wiki/Double_dispatch) with the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern) (can be awkward) * Wait until C# 4 and use dynamic typing (might not be feasible in your case) Personally I'd try to think of an alternative design which didn't require this in the first place, but obviously that's not always realistic.
Here is a quick and dirty solution... should get you going right away. ``` public void EntryPoint(object template) { TemplateA a = template as TemplateA; if (a != null) { myFunc(a); //calls myFunc(TemplateA template) return; } TemplateB b = template as TemplateB; if (b != null) { myFunc(b); //calls myFunc(TemplateB template) return; } myFunc(template); //calls myFunc(object template) } ``` Also, see Jon Skeet's answer for some additional education.
How to call a function dynamically based on an object type
[ "", "c#", "" ]
Does anyone have experience using the Facebook Developer Toolkit? I am trying to post something to a Facebook user's Wall, but can't figure out how to use the API? Could someone could give me an example or point me to some documentation on the API's usage?
I actually found documentation and samples to do what I was looking for here: <http://facebooktoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28001> EDIT: After initializing the Facebook session I called the Stream.Publish() method on the API. ``` FacebookService.API.stream.publish(...); ```
I created a video tutorial showing how to do exactly this. Here is the link: <http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet> And here is the code: ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Facebook; namespace FBO { public partial class facebooksync : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { CheckAuthorization(); } private void CheckAuthorization() { string app_id = "374961455917802"; string app_secret = "9153b340ee604f7917fd57c7ab08b3fa"; string scope = "publish_stream,manage_pages"; if (Request["code"] == null) { Response.Redirect(string.Format( "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", app_id, Request.Url.AbsoluteUri, scope)); } else { Dictionary<string, string> tokens = new Dictionary<string, string>(); string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}", app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); string vals = reader.ReadToEnd(); foreach (string token in vals.Split('&')) { //meh.aspx?token1=steve&token2=jake&... tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1)); } } string access_token = tokens["access_token"]; var client = new FacebookClient(access_token); client.Post("/me/feed", new { message = "markhagan.me video tutorial" }); } } } } ```
How can I post something to a Wall using Facebook Developer Toolkit?
[ "", "c#", ".net", "facebook", "" ]