qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
328,391 | <p>I have the following code which is trivial at first sight. I simply set want to set the font type to Georgia with a size of 14 if the cell is from the result of a search or if there is a count of zero in my students array. </p>
<p>However, with this particular code cell that's last in my <code>tableView</code> is taking on the font of Georgia with size 14. All other cells are working proper. Where in my code is the logic wrong?</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
NSInteger section = [indexPath section];
static NSString *CellIdentifier = @"Student";
cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell
if([studentsSearch count] > 0) {
cell.text = (NSString *)[[[studentsSearch objectAtIndex:section] objectAtIndex:row] valueForKey:@"name"];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
} else {
if(isSearching == YES)
cell.text = @"No students available.";
else
cell.text = @"No students have been added for this school.";
cell.font = [UIFont fontWithName:@"Georgia" size:14];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>What appears to be happening is when the view controller gets instantiated and pushed on top of the navigation controller's stack, my <code>studentsSearch</code> array is <code>nil</code>. I populate it within that controller. </p>
<p>So upon initialization, the cell has its font set to Georgia with a size of 14 because the <code>count</code> is < 0. However, once I populate the <code>studentsSearch</code> array and reload the <code>tableView</code>'s data, the font seems to be sticking from when the view first got initialized.</p>
<p>I suppose now I need to find how to set the font back to that cell to what the default is.</p>
| [
{
"answer_id": 328405,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 2,
"selected": false,
"text": "cell.font = [UIFont systemFontOfSize: 14];\n"
},
{
"answer_id": 329696,
"author": "Jonathan Watmough",
"author_id": 33758,
"author_profile": "https://Stackoverflow.com/users/33758",
"pm_score": 1,
"selected": false,
"text": "- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {\n NSInteger row = [indexPath row];\n NSInteger section = [indexPath section];\n\n static NSString *StudentCellIdentifier = @\"Student\";\n static NSString *NoneCellIdentifier = @\"None\";\n\n // did we find students?\n BOOL found = [studentsSearch count] > 0;\n\n // get/create correct cell type\n cell = [tv dequeueReusableCellWithIdentifier:(found ? StudentCellIdentifier : NoneCellIdentifier)];\n if (cell == nil) {\n cell = [[UITableViewCell alloc] initWithFrame:CGRectZero \n reuseIdentifier:(found ? StudentCellIdentifier : NoneCellIdentifier)];\n }\n\n // return a student, or None cell if no studnts found\n if( found ) \n {\n cell.text = (NSString *)[[[studentsSearch objectAtIndex:section] objectAtIndex:row] valueForKey:@\"name\"];\n cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;\n } \n else \n {\n if(isSearching == YES) \n cell.text = @\"No students available.\";\n else \n cell.text = @\"No students have been added for this school.\";\n cell.font = [UIFont fontWithName:@\"Georgia\" size:14];\n cell.accessoryType = UITableViewCellAccessoryNone;\n }\n\n return [cell autorelease];\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
328,430 | <p>I've got jQuery Autocomplete (UI 1.6rc2) up and running fine and when the user picks an item, it updates a hidden form value with the associated ID. How do I set the hidden form value to '0' when the text entered does not match a result from the autocomplete list? In this case, I'll be creating a new entry.</p>
| [
{
"answer_id": 928258,
"author": "turezky",
"author_id": 87997,
"author_profile": "https://Stackoverflow.com/users/87997",
"pm_score": 1,
"selected": false,
"text": "selected: function() {\n if(listItems.filter(”.” + CLASSES.ACTIVE)[0]){\n return data && data[ listItems.filter(\".\" + CLASSES.ACTIVE)[0].index ];\n } else {\n if (options.notFound){\n options.notFound();\n } \n }\n}\n"
},
{
"answer_id": 928345,
"author": "turezky",
"author_id": 87997,
"author_profile": "https://Stackoverflow.com/users/87997",
"pm_score": 1,
"selected": false,
"text": "extraParams"
},
{
"answer_id": 1252154,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "$(\"#txtSearchProvider\").autocomplete(\"../WebServices/PageMethods/AutoComplete.aspx\",\n {\n minChars: 3,\n formatItem: function(data, i, n, value) {\n return value.split(\"-z-\")[0];\n },\n formatResult: function(data, value) \n {\n return value.split(\"-z-\")[0];\n }\n }\n );\n $(\"#txtSearchProvider\").result(function(event, data, formatted) {\n $(\"#txtSearchProviderHidden\").val(data[0].split(\"-z-\")[1]);\n });\n"
},
{
"answer_id": 4857557,
"author": "Rob",
"author_id": 549495,
"author_profile": "https://Stackoverflow.com/users/549495",
"pm_score": 3,
"selected": true,
"text": "change: function(event, ui){\n $(this).next(\"input[id^=person_id]\").val('');\n return false;\n"
},
{
"answer_id": 12884162,
"author": "Harry Binnendyk",
"author_id": 1745174,
"author_profile": "https://Stackoverflow.com/users/1745174",
"pm_score": 2,
"selected": false,
"text": "search: function(event, ui){\n $(this).next(\"input[id^=person_id]\").val('');\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
] |
328,463 | <p>I'm attempting to install phpMyAdmin, but I constantly get errors.</p>
<p>When I type this in the terminal:</p>
<pre><code>sudo dpkg --configure -a
</code></pre>
<p>The following message appears:</p>
<pre>
Setting up mysql-server-5.0 (5.0.45-1ubuntu3) ...
* Stopping MySQL database server mysqld [OK]
* Starting MySQL database server mysqld [FAIL]
invoke-rc.d: initscript mysql, action "start" failed.
dpkg: error processing mysql-server-5.0 (--configure):
subprocess post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
mysql-server depends on mysql-server-5.0; however:
Package mysql-server 5.0 is not configured yet.
dpkg: error processing mysql-server (--configure):
dependency problems - leaving unconfigured
Errors were encounter while processing:
mysql-server-5.0
mysql-server
</pre>
<p>I also attempt to access MySQL through the console by typing: <code>mysql</code></p>
<p>This error appears:</p>
<pre><code>ERROR (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
</code></pre>
<p>This occurred ever I tried to install phpMyAdmin or accessing my <code>libapache</code>. Does anyone know how to resolve these problems?</p>
| [
{
"answer_id": 328559,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 2,
"selected": false,
"text": "mysql-server-5.0"
},
{
"answer_id": 435229,
"author": "dragonmantank",
"author_id": 204,
"author_profile": "https://Stackoverflow.com/users/204",
"pm_score": 1,
"selected": false,
"text": "dpkg --configure mysql-server-5.0\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,468 | <p>I'm using PHP to generate thumbnails. The problem is that I have a set width and height the thumbnails need to be and often times the images are stretched.</p>
<p>What I'd like is the image to remain at the same proportions and just have black filler (or any color) either on the left & right for tall images or top & bottom for wide images.</p>
<p>Here is the code I'm currently using: (dumbed down a bit for readability)</p>
<pre><code>$temp_image_file = imagecreatefromjpeg("http://www.example.com/image.jpg");
list($width,$height) = getimagesize("http://www.example.com/image.jpg");
$image_file = imagecreatetruecolor(166,103);
imagecopyresampled($image_file,$temp_image_file,0,0,0,0,166,103,$width,$height);
imagejpeg($image_file,"thumbnails/thumbnail.jpg",50);
imagedestroy($temp_image_file);
imagedestroy($image_file);
</code></pre>
| [
{
"answer_id": 328543,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 1,
"selected": false,
"text": "$filename = \"http://www.example.com/image.jpg\";\n\nlist($width,$height) = getimagesize($filename);\n\n$width_ratio = 166 / $width;\nif ($height * $width_ratio <= 103)\n{\n $adjusted_width = 166;\n $adjusted_height = $height * $width_ratio;\n}\nelse\n{\n $height_ratio = 103 / $height;\n $adjusted_width = $width * $height_ratio;\n $adjusted_height = 103;\n}\n\n$image_p = imagecreatetruecolor(166,103);\n$image = imagecreatefromjpeg($filename);\nimagecopyresampled($image_p,$image,ceil((166 - $adjusted_width) / 2),ceil((103 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height);\n\nimagejpeg($image_p,\"thumbnails/thumbnail.jpg\",50);\n"
},
{
"answer_id": 386581,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 1,
"selected": false,
"text": "function resized($im, $mx, $my) {\n $x = $nx = imagesx($im);\n $y = $ny = imagesy($im);\n $ar = $x / $y;\n while ($nx > $mx || $ny > $my) {\n if ($nx > $mx) {\n $nx = $mx;\n $ny = $nx / $ar;\n }\n if ($ny > $my) {\n $ny = $my;\n $nx = $ny * $ar;\n }\n }\n if ($nx != $x) {\n $im2 = imagecreatetruecolor($nx, $ny);\n imagecopyresampled($im2, $im, 0, 0, 0, 0, $nx, $ny, $x, $y);\n return $im2;\n } else {\n return $im;\n }\n}\n"
},
{
"answer_id": 2334093,
"author": "CodeChap",
"author_id": 195192,
"author_profile": "https://Stackoverflow.com/users/195192",
"pm_score": 0,
"selected": false,
"text": "// Crete an image forced to width and height\n function createFixedImage($img, $id=0, $preFix=false, $mw='100', $mh='100', $quality=90){\n\n // Fix path\n $filename = '../'.$img;\n\n // Check for file\n if(file_exists($filename))\n { \n // Set a maximum height and width\n $width = $mw;\n $height = $mh;\n\n // Get new dimensions\n list($width_orig, $height_orig) = getimagesize($filename);\n\n $ratio_orig = $width_orig/$height_orig;\n\n if ($width/$height < $ratio_orig) {\n $width = $height*$ratio_orig;\n }else{\n $height = $width/$ratio_orig;\n }\n\n // Resample\n $image_p = imagecreatetruecolor($mw, $mh);\n $image = imagecreatefromjpeg($filename);\n imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);\n\n // Output\n imagejpeg($image_p, \"../images/stories/catalog/{$preFix}{$id}.jpg\", $quality);\n }\n }\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] |
328,475 | <p>So far I've seen many posts dealing with equality of floating point numbers. The standard answer to a question like "how should we decide if x and y are equal?" is</p>
<pre><code>abs(x - y) < epsilon
</code></pre>
<p>where epsilon is a <em>fixed</em>, small constant. This is because the "operands" x and y are often the results of some computation where a rounding error is involved, hence the standard equality operator == is not what we mean, and what we should really ask is whether x and y are <em>close</em>, not equal.</p>
<p>Now, I feel that if x is "almost equal" to y, then also x*10^20 should be "almost equal" to y*10^20, in the sense that the <em>relative</em> error should be the same (but "relative" to what?). But with these big numbers, the above test would fail, i.e. that solution does not "scale".</p>
<p>How would you deal with this issue? Should we rescale the numbers or rescale epsilon? How?
(Or is my intuition wrong?)</p>
<p>Here is a <a href="https://stackoverflow.com/questions/21265/comparing-ieee-floats-and-doubles-for-equality">related question</a>, but I don't like its accepted answer, for the reinterpret_cast thing seems a bit tricky to me, I don't understand what's going on. Please try to provide a simple test.</p>
| [
{
"answer_id": 328509,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "div(max(a, b), min(a, b)) < eps + 1\n"
},
{
"answer_id": 28751714,
"author": "Franz D.",
"author_id": 4610114,
"author_profile": "https://Stackoverflow.com/users/4610114",
"pm_score": 0,
"selected": false,
"text": "boolean approxEqual(float a, float b, float absEps, float relEps) {\n // Absolute error check needed when comparing numbers near zero.\n float diff = abs(a - b);\n if (diff <= absEps) {\n return true;\n }\n\n // Symmetric relative error check without division.\n return (diff <= relEps * max(abs(a), abs(b)));\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
328,485 | <p>WCF is Microsoft's replacement for .Net Remoting and Web services. It's critical to understand if you are a .NET component developer. </p>
<p>The best reference for WCF appears to be (by word of mouth, blogs and Amazon) Juval Lowy's "Programming WCF Services," published by O'Reilly.</p>
<p>This book is advertised in several places around the net as "coming with Juval Lowy's ServiceModelEx library," which is supposed to be this awesome WCF framework that extends and simplifies WCF development. In the book itself Lowy talks about this framework a lot.</p>
<p>However, I can not figure out where to download said library. If you look at his website's download <a href="http://idesign.net/idesign/DesktopDefault.aspx?tabindex=5&tabid=11" rel="noreferrer">page</a> there's tons of stuff but no ServiceModelEx. </p>
<p>Does he intend for his readers to re-code all of it by hand going by code samples in his book?</p>
<p>Anyone with any experience on this?</p>
<p>Yeah, this is a niche question, but I think it's an important topic and it's certainly programming related.</p>
| [
{
"answer_id": 9511632,
"author": "Mili Milutinovic",
"author_id": 1241974,
"author_profile": "https://Stackoverflow.com/users/1241974",
"pm_score": 1,
"selected": false,
"text": "ServiceModelEx"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1572436/"
] |
328,492 | <p>How can I send a monitor into/out-of a different power state (like sleep)?</p>
| [
{
"answer_id": 9511632,
"author": "Mili Milutinovic",
"author_id": 1241974,
"author_profile": "https://Stackoverflow.com/users/1241974",
"pm_score": 1,
"selected": false,
"text": "ServiceModelEx"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
328,496 | <p>What are some <em>common</em>, <em>real world examples</em> of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?</p>
| [
{
"answer_id": 328505,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 3,
"selected": false,
"text": "m.expects(once())\n .method(\"testMethod\")\n .with(eq(1), eq(2))\n .returns(\"someResponse\");\n"
},
{
"answer_id": 328506,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 9,
"selected": true,
"text": "BuildOrderHeaderRow()\nBuildLineItemSubHeaderRow()\nBuildOrderRow()\nBuildLineItemSubRow()\n"
},
{
"answer_id": 329115,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": false,
"text": "Builders"
},
{
"answer_id": 1953567,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 10,
"selected": false,
"text": "Pizza(int size) { ... } \nPizza(int size, boolean cheese) { ... } \nPizza(int size, boolean cheese, boolean pepperoni) { ... } \nPizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }\n"
},
{
"answer_id": 4202116,
"author": "Nitin",
"author_id": 510446,
"author_profile": "https://Stackoverflow.com/users/510446",
"pm_score": 3,
"selected": false,
"text": "class RestaurantObjectBuilder\n{\n IFactory _factory = new DefaultFoodFactory();\n\n //This can be used when you want to plugin the \n public void SetFoodFactory(IFactory customFactory)\n {\n _factory = customFactory;\n }\n\n public IFactory GetFoodFactory()\n {\n return _factory;\n }\n}\n"
},
{
"answer_id": 5353658,
"author": "John Brown",
"author_id": 666214,
"author_profile": "https://Stackoverflow.com/users/666214",
"pm_score": 2,
"selected": false,
"text": "XMLGregorianCalendarBuilder builder = XMLGregorianCalendarBuilder.newInstance(jdkDate);\nXMLGregorianCalendar xmlCalendar = builder.excludeMillis().excludeOffset().build();\n"
},
{
"answer_id": 21162424,
"author": "Raman Zhylich",
"author_id": 1095822,
"author_profile": "https://Stackoverflow.com/users/1095822",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Builder\n/// </summary>\npublic interface IWebRequestBuilder\n{\n IWebRequestBuilder BuildHost(string host);\n\n IWebRequestBuilder BuildPort(int port);\n\n IWebRequestBuilder BuildPath(string path);\n\n IWebRequestBuilder BuildQuery(string query);\n\n IWebRequestBuilder BuildScheme(string scheme);\n\n IWebRequestBuilder BuildTimeout(int timeout);\n\n WebRequest Build();\n}\n\n/// <summary>\n/// ConcreteBuilder #1\n/// </summary>\npublic class HttpWebRequestBuilder : IWebRequestBuilder\n{\n private string _host;\n\n private string _path = string.Empty;\n\n private string _query = string.Empty;\n\n private string _scheme = \"http\";\n\n private int _port = 80;\n\n private int _timeout = -1;\n\n public IWebRequestBuilder BuildHost(string host)\n {\n _host = host;\n return this;\n }\n\n public IWebRequestBuilder BuildPort(int port)\n {\n _port = port;\n return this;\n }\n\n public IWebRequestBuilder BuildPath(string path)\n {\n _path = path;\n return this;\n }\n\n public IWebRequestBuilder BuildQuery(string query)\n {\n _query = query;\n return this;\n }\n\n public IWebRequestBuilder BuildScheme(string scheme)\n {\n _scheme = scheme;\n return this;\n }\n\n public IWebRequestBuilder BuildTimeout(int timeout)\n {\n _timeout = timeout;\n return this;\n }\n\n protected virtual void BeforeBuild(HttpWebRequest httpWebRequest) {\n }\n\n public WebRequest Build()\n {\n var uri = _scheme + \"://\" + _host + \":\" + _port + \"/\" + _path + \"?\" + _query;\n\n var httpWebRequest = WebRequest.CreateHttp(uri);\n\n httpWebRequest.Timeout = _timeout;\n\n BeforeBuild(httpWebRequest);\n\n return httpWebRequest;\n }\n}\n\n/// <summary>\n/// ConcreteBuilder #2\n/// </summary>\npublic class ProxyHttpWebRequestBuilder : HttpWebRequestBuilder\n{\n private string _proxy = null;\n\n public ProxyHttpWebRequestBuilder(string proxy)\n {\n _proxy = proxy;\n }\n\n protected override void BeforeBuild(HttpWebRequest httpWebRequest)\n {\n httpWebRequest.Proxy = new WebProxy(_proxy);\n }\n}\n\n/// <summary>\n/// Director\n/// </summary>\npublic class SearchRequest\n{\n\n private IWebRequestBuilder _requestBuilder;\n\n public SearchRequest(IWebRequestBuilder requestBuilder)\n {\n _requestBuilder = requestBuilder;\n }\n\n public WebRequest Construct(string searchQuery)\n {\n return _requestBuilder\n .BuildHost(\"ajax.googleapis.com\")\n .BuildPort(80)\n .BuildPath(\"ajax/services/search/web\")\n .BuildQuery(\"v=1.0&q=\" + HttpUtility.UrlEncode(searchQuery))\n .BuildScheme(\"http\")\n .BuildTimeout(-1)\n .Build();\n }\n\n public string GetResults(string searchQuery) {\n var request = Construct(searchQuery);\n var resp = request.GetResponse();\n\n using (StreamReader stream = new StreamReader(resp.GetResponseStream()))\n {\n return stream.ReadToEnd();\n }\n }\n}\n\nclass Program\n{\n /// <summary>\n /// Inside both requests the same SearchRequest.Construct(string) method is used.\n /// But finally different HttpWebRequest objects are built.\n /// </summary>\n static void Main(string[] args)\n {\n var request1 = new SearchRequest(new HttpWebRequestBuilder());\n var results1 = request1.GetResults(\"IBM\");\n Console.WriteLine(results1);\n\n var request2 = new SearchRequest(new ProxyHttpWebRequestBuilder(\"localhost:80\"));\n var results2 = request2.GetResults(\"IBM\");\n Console.WriteLine(results2);\n }\n}\n"
},
{
"answer_id": 26236963,
"author": "Pavel Lechev",
"author_id": 1886835,
"author_profile": "https://Stackoverflow.com/users/1886835",
"pm_score": 4,
"selected": false,
"text": "withXyz(...)"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7705/"
] |
328,500 | <p>what is the proper way to scale an SDL Surface? I found one explanation online but it required redrawing the Surface pixel by pixel. It seems like there should be some way of doing this natively through SDL rather than redrawing the image like that. I haven't been able to find anything in the SDL documentation that covers this. I am able to resize surfaces without any problem by modifying the surfaces width and height, but the resulting surface is clipped.</p>
| [
{
"answer_id": 28560314,
"author": "Martin G",
"author_id": 3545094,
"author_profile": "https://Stackoverflow.com/users/3545094",
"pm_score": 1,
"selected": false,
"text": "SDL_RenderCopyEx"
},
{
"answer_id": 30970536,
"author": "Justin Stephens",
"author_id": 5034414,
"author_profile": "https://Stackoverflow.com/users/5034414",
"pm_score": 3,
"selected": false,
"text": "SDL_BlitScaled()"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552/"
] |
328,521 | <p>The execvp() function executes the program that is given as an argument. It checks the $PATH variable to find the program. I'm writing something in which I would like to check to see if several programs exist before calling any exec() functions. What's the best way to do this?</p>
| [
{
"answer_id": 330228,
"author": "joveha",
"author_id": 40668,
"author_profile": "https://Stackoverflow.com/users/40668",
"pm_score": 0,
"selected": false,
"text": "struct stat st;\nif (stat(path, &st)) {\n // path doesn't exist\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,525 | <p>How can I set default value in ActiveRecord?</p>
<p>I see a post from Pratik that describes an ugly, complicated chunk of code: <a href="http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model" rel="noreferrer">http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model</a></p>
<pre><code>class Item < ActiveRecord::Base
def initialize_with_defaults(attrs = nil, &block)
initialize_without_defaults(attrs) do
setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless
!attrs.nil? && attrs.keys.map(&:to_s).include?(key.to_s) }
setter.call('scheduler_type', 'hotseat')
yield self if block_given?
end
end
alias_method_chain :initialize, :defaults
end
</code></pre>
<p>I have seen the following examples googling around:</p>
<pre><code> def initialize
super
self.status = ACTIVE unless self.status
end
</code></pre>
<p>and</p>
<pre><code> def after_initialize
return unless new_record?
self.status = ACTIVE
end
</code></pre>
<p>I've also seen people put it in their migration, but I'd rather see it defined in the model code.</p>
<p>Is there a canonical way to set default value for fields in ActiveRecord model?</p>
| [
{
"answer_id": 328691,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 2,
"selected": false,
"text": "initialize"
},
{
"answer_id": 328870,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 1,
"selected": false,
"text": "class Item < ActiveRecord::Base\n def status\n self[:status] or ACTIVE\n end\n\n before_save{ self.status ||= ACTIVE }\nend\n"
},
{
"answer_id": 328874,
"author": "Laurent Farcy",
"author_id": 40666,
"author_profile": "https://Stackoverflow.com/users/40666",
"pm_score": 6,
"selected": false,
"text": ":default"
},
{
"answer_id": 3299447,
"author": "skalee",
"author_id": 304175,
"author_profile": "https://Stackoverflow.com/users/304175",
"pm_score": 0,
"selected": false,
"text": ":default_scope"
},
{
"answer_id": 3341225,
"author": "Tony",
"author_id": 403029,
"author_profile": "https://Stackoverflow.com/users/403029",
"pm_score": 2,
"selected": false,
"text": "def after_initialize \n self.extras||={}\n self.other_stuff||=\"This stuff\"\nend\n"
},
{
"answer_id": 3951667,
"author": "Greg",
"author_id": 328645,
"author_profile": "https://Stackoverflow.com/users/328645",
"pm_score": 1,
"selected": false,
"text": "after_initialize :defaults\n\ndef defaults\n self.extras||={}\n self.other_stuff||=\"This stuff\"\nend\n"
},
{
"answer_id": 4943650,
"author": "Sean",
"author_id": 609565,
"author_profile": "https://Stackoverflow.com/users/609565",
"pm_score": 2,
"selected": false,
"text": "after_initialize"
},
{
"answer_id": 5127684,
"author": "Jeff Perrin",
"author_id": 95683,
"author_profile": "https://Stackoverflow.com/users/95683",
"pm_score": 10,
"selected": true,
"text": "after_initialize"
},
{
"answer_id": 5492623,
"author": "Kelvin",
"author_id": 498594,
"author_profile": "https://Stackoverflow.com/users/498594",
"pm_score": 0,
"selected": false,
"text": "class MyModel\n validate :init_defaults\n\n private\n def init_defaults\n if new_record?\n self.some_int ||= 1\n elsif some_int.nil?\n errors.add(:some_int, \"can't be blank on update\")\n end\n end\nend\n"
},
{
"answer_id": 10839394,
"author": "jamesc",
"author_id": 847116,
"author_profile": "https://Stackoverflow.com/users/847116",
"pm_score": -1,
"selected": false,
"text": "before_validation"
},
{
"answer_id": 11543883,
"author": "Joseph Lord",
"author_id": 1476206,
"author_profile": "https://Stackoverflow.com/users/1476206",
"pm_score": 5,
"selected": false,
"text": "after_initialize :defaults\n\ndef defaults\n unless persisted?\n self.extras||={}\n self.other_stuff||=\"This stuff\"\n self.assoc = [OtherModel.find_by_name('special')]\n end\nend\n"
},
{
"answer_id": 12327095,
"author": "Jeff Gran",
"author_id": 835766,
"author_profile": "https://Stackoverflow.com/users/835766",
"pm_score": 1,
"selected": false,
"text": "Class Foo < ActiveRecord::Base\n # has a DB column/field atttribute called 'status'\n def status\n (val = read_attribute(:status)).nil? ? 'ACTIVE' : val\n end\nend\n"
},
{
"answer_id": 12418708,
"author": "Brad Murray",
"author_id": 709636,
"author_profile": "https://Stackoverflow.com/users/709636",
"pm_score": 4,
"selected": false,
"text": "after_initialize :some_method_goes_here, :if => :new_record?\n"
},
{
"answer_id": 14271464,
"author": "aidan",
"author_id": 71062,
"author_profile": "https://Stackoverflow.com/users/71062",
"pm_score": 3,
"selected": false,
"text": "attribute-defaults"
},
{
"answer_id": 19917266,
"author": "Bad Request",
"author_id": 243500,
"author_profile": "https://Stackoverflow.com/users/243500",
"pm_score": 0,
"selected": false,
"text": " aasm column: \"status\" do\n state :available, initial: true\n state :used\n # transitions\n end\n"
},
{
"answer_id": 25250416,
"author": "peterhurford",
"author_id": 3317833,
"author_profile": "https://Stackoverflow.com/users/3317833",
"pm_score": 3,
"selected": false,
"text": "def status\n self['status'] || ACTIVE\nend\n"
},
{
"answer_id": 32644208,
"author": "etipton",
"author_id": 1938879,
"author_profile": "https://Stackoverflow.com/users/1938879",
"pm_score": 1,
"selected": false,
"text": "MyModel.new(my_attr: nil)"
},
{
"answer_id": 35398273,
"author": "clem",
"author_id": 507475,
"author_profile": "https://Stackoverflow.com/users/507475",
"pm_score": 2,
"selected": false,
"text": "DefaultValues"
},
{
"answer_id": 36200430,
"author": "Keith Rowell",
"author_id": 6109417,
"author_profile": "https://Stackoverflow.com/users/6109417",
"pm_score": 0,
"selected": false,
"text": "class Task < ActiveRecord::Base\n default :status => 'active'\nend\n"
},
{
"answer_id": 41292328,
"author": "Blair Anderson",
"author_id": 1536309,
"author_profile": "https://Stackoverflow.com/users/1536309",
"pm_score": 3,
"selected": false,
"text": "after_initialize :init"
},
{
"answer_id": 43484863,
"author": "Lucas Caton",
"author_id": 1445184,
"author_profile": "https://Stackoverflow.com/users/1445184",
"pm_score": 7,
"selected": false,
"text": "class Account < ApplicationRecord\n attribute :locale, :string, default: 'en'\nend\n"
},
{
"answer_id": 44115924,
"author": "Magne",
"author_id": 380607,
"author_profile": "https://Stackoverflow.com/users/380607",
"pm_score": 3,
"selected": false,
"text": "db/schema.rb"
},
{
"answer_id": 54595917,
"author": "kdweber89",
"author_id": 4282529,
"author_profile": "https://Stackoverflow.com/users/4282529",
"pm_score": 0,
"selected": false,
"text": "add_column :teams, :new_team_signature, :string, default: 'Welcome to the Team'\n"
},
{
"answer_id": 59347382,
"author": "shilovk",
"author_id": 3563993,
"author_profile": "https://Stackoverflow.com/users/3563993",
"pm_score": 0,
"selected": false,
"text": "# db/schema.rb\ncreate_table :store_listings, force: true do |t|\n t.string :my_string, default: \"original default\"\nend\n\nStoreListing.new.my_string # => \"original default\"\n\n# app/models/store_listing.rb\nclass StoreListing < ActiveRecord::Base\n attribute :my_string, :string, default: \"new default\"\nend\n\nStoreListing.new.my_string # => \"new default\"\n\nclass Product < ActiveRecord::Base\n attribute :my_default_proc, :datetime, default: -> { Time.now }\nend\n\nProduct.new.my_default_proc # => 2015-05-30 11:04:48 -0600\nsleep 1\nProduct.new.my_default_proc # => 2015-05-30 11:04:49 -0600\n"
},
{
"answer_id": 62538071,
"author": "Promise Preston",
"author_id": 10907864,
"author_profile": "https://Stackoverflow.com/users/10907864",
"pm_score": 0,
"selected": false,
"text": "Users"
},
{
"answer_id": 64491375,
"author": "Yana Agun Siswanto",
"author_id": 3034747,
"author_profile": "https://Stackoverflow.com/users/3034747",
"pm_score": 0,
"selected": false,
"text": "# post.rb\nclass Post < ApplicationRecord\n attribute :country, :string, default: 'ID'\nend\n"
},
{
"answer_id": 69163268,
"author": "staxim",
"author_id": 2619196,
"author_profile": "https://Stackoverflow.com/users/2619196",
"pm_score": 2,
"selected": false,
"text": "attribute :status, default: ACTIVE\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2477/"
] |
328,549 | <p>I have an ASPX page where I am uploading an image to server for on a serverside button click event. In my page, it will show the available image if it exists. When I upload an image, it will replace the old one with the new one. Now after uploading also the same image is getting displayed. How can tackle this? I used window.location.reload() javascript function to refresh, but then it is not working. It is posting the page again.</p>
<p>This is my code</p>
<pre><code> Do UploadImage(studentId,mode); // Function to upload image
StringBuilder sbc = new StringBuilder();
sbc.Append("<script language='javascript'>");
sbc.Append("alert('Upload process completed successfully!');");
sbc.Append("window.location.reload()");
sbc.Append("</script>");
HttpContext.Current.Response.Write(sbc);
</code></pre>
| [
{
"answer_id": 328569,
"author": "LeJeune",
"author_id": 37955,
"author_profile": "https://Stackoverflow.com/users/37955",
"pm_score": 0,
"selected": false,
"text": "Response.Redirect(Request.URL)\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40521/"
] |
328,566 | <p>I'm using WatiN, NUnit and ReSharper to run my ASP.NET unit tests inside Visual Studio. I'd like (if it's not already running) to start Cassini to run my tests against.</p>
<p>Is this possible? How would I do it?</p>
| [
{
"answer_id": 328616,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "private static void GetDevelopmentServerVPathAndPortFromProjectFile(\n string csprojFileName,\n out string developmentServerVPath,\n out int developmentServerPort)\n{\n XPathDocument doc = new XPathDocument(csprojFileName);\n XPathNavigator navigator = doc.CreateNavigator();\n\n XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);\n manager.AddNamespace(\"msbuild\",\n \"http://schemas.microsoft.com/developer/msbuild/2003\");\n\n const string xpath = \"/msbuild:Project/msbuild:ProjectExtensions/\"\n + \"msbuild:VisualStudio/msbuild:FlavorProperties/\"\n + \"msbuild:WebProjectProperties\";\n\n XPathNavigator webProjectPropertiesNode =\n navigator.SelectSingleNode(xpath, manager);\n XPathNavigator developmentServerPortNode =\n webProjectPropertiesNode.SelectSingleNode(\"msbuild:DevelopmentServerPort\",\n manager);\n XPathNavigator developmentServerVPathNode =\n webProjectPropertiesNode.SelectSingleNode(\"msbuild:DevelopmentServerVPath\",\n manager);\n\n developmentServerPort = developmentServerPortNode.ValueAsInt;\n developmentServerVPath = developmentServerVPathNode.Value;\n}\n\nprivate static string GetCommonProgramFilesPath()\n{\n string commonProgramFiles =\n Environment.GetEnvironmentVariable(\"CommonProgramFiles(x86)\");\n if (string.IsNullOrEmpty(commonProgramFiles))\n {\n commonProgramFiles =\n Environment.GetEnvironmentVariable(\"CommonProgramFiles\");\n }\n if (string.IsNullOrEmpty(commonProgramFiles))\n {\n commonProgramFiles =\n Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles);\n }\n return commonProgramFiles;\n}\n\nprivate static Process PrepareCassiniProcess(int developmentServerPort,\n string projectPhysicalPath,\n string developmentServerVPath)\n{\n string commonProgramFiles = GetCommonProgramFilesPath();\n string cassiniPath = Path.Combine(commonProgramFiles,\n @\"Microsoft Shared\\DevServer\\9.0\\WebDev.WebServer.exe\");\n string cassiniArgs = string.Format(\n CultureInfo.InvariantCulture,\n \"/port:{0} /nodirlist /path:\\\"{1}\\\" /vpath:\\\"{2}\\\"\",\n developmentServerPort, projectPhysicalPath, developmentServerVPath);\n\n Process cassiniProcess = new Process();\n cassiniProcess.StartInfo.FileName = cassiniPath;\n cassiniProcess.StartInfo.Arguments = cassiniArgs;\n return cassiniProcess;\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
328,568 | <p>I'm thinking how to arrange a deployed python application which will have a </p>
<ol>
<li>Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in</li>
<li>A library installed to wherever the current site-packages directory is.</li>
</ol>
<p>Now, currently, I have the following directory structure in my sources:</p>
<pre><code>foo.py
foo/
__init__.py
...
</code></pre>
<p>which I guess is not the best way to do things. During development, everything works as expected, however when deployed, the "from foo import FooObject" code in foo.py seemingly attempts to import foo.py itself, which is not the behaviour I'm looking for.</p>
<p>So the question is what is the standard practice of orchestrating situations like this? One of the things I could think of is, when installing, rename foo.py to just foo, which stops it from importing itself, but that seems rather awkward...</p>
<p>Another part of the problem, I suppose, is that it's a naming challenge. Perhaps call the executable script foo-bin.py?</p>
| [
{
"answer_id": 328579,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 0,
"selected": false,
"text": "foo"
},
{
"answer_id": 328589,
"author": "Matt Campbell",
"author_id": 41110,
"author_profile": "https://Stackoverflow.com/users/41110",
"pm_score": 2,
"selected": false,
"text": "setup.py"
},
{
"answer_id": 328826,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "foo"
},
{
"answer_id": 333621,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 4,
"selected": true,
"text": "Twisted"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39167/"
] |
328,577 | <p>I'm a long time C++/Java developer trying to get into Python and am looking for the stereotypical "Python for C++ Developers" article, but coming up blank. I've seen these sort of things for C#, Java, etc, and they're incredibly useful for getting up to speed on language features and noteworthy differences. Anyone have any references?</p>
<p>As a secondary bonus question, what open source Python program would you suggest looking at for clean design, commenting, and use of the language as a point of reference for study?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 328599,
"author": "Matt Campbell",
"author_id": 41110,
"author_profile": "https://Stackoverflow.com/users/41110",
"pm_score": 2,
"selected": false,
"text": "urllib2.py"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13257/"
] |
328,600 | <p>I'm using LINQ to Entities (not LINQ to SQL) and I'm having trouble creating an 'IN' style query. Here is my query at the moment:</p>
<pre><code>var items = db.InventoryItem
.Include("Kind")
.Include("PropertyValues")
.Include("PropertyValues.KindProperty")
.Where(itm => valueIds.Contains(itm.ID)).ToList<InventoryItem>();
</code></pre>
<p>When I do this however, the following exception is thrown:</p>
<blockquote>
<p>LINQ to Entities does not recognize the method 'Boolean Contains(Int64)' method, and this method cannot be translated into a store expression.</p>
</blockquote>
<p>Does anyone have a workaround or another solution for this?</p>
| [
{
"answer_id": 328677,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 4,
"selected": true,
"text": ".Where(string.Format(\"it.ID in {0}\", string.Join(\",\", valueIds.ToArray())));\n"
},
{
"answer_id": 2190729,
"author": "Stef Heyenrath",
"author_id": 255966,
"author_profile": "https://Stackoverflow.com/users/255966",
"pm_score": -1,
"selected": false,
"text": "var items = db.InventoryItem\n .Include(\"Kind\")\n .Include(\"PropertyValues\")\n .Include(\"PropertyValues.KindProperty\")\n .ToList()\n .Where(itm => valueIds.Contains(itm.ID));\n"
},
{
"answer_id": 4432065,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 3,
"selected": false,
"text": "Any"
},
{
"answer_id": 4445537,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 1,
"selected": false,
"text": "Contains"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
328,622 | <p>I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?</p>
<ul>
<li>Time between calculations?</li>
<li>Current state of the CPU?</li>
<li>Different hardware?</li>
<li>Language / platform / OS?</li>
<li>Solar flares?</li>
</ul>
<p>I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.</p>
<p>I am currently working in Silverlight though would be interested to know if this question can be answered in general.</p>
<p><strong>Update:</strong> The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.</p>
| [
{
"answer_id": 1008262,
"author": "Grumbel",
"author_id": 28113,
"author_profile": "https://Stackoverflow.com/users/28113",
"pm_score": 2,
"selected": false,
"text": "y == x"
},
{
"answer_id": 5712709,
"author": "Ergwun",
"author_id": 177018,
"author_profile": "https://Stackoverflow.com/users/177018",
"pm_score": 2,
"selected": false,
"text": "(a + b) + c"
},
{
"answer_id": 35785806,
"author": "hypehuman",
"author_id": 1269598,
"author_profile": "https://Stackoverflow.com/users/1269598",
"pm_score": -1,
"selected": false,
"text": "using System;\nusing System.Windows;\n\nnamespace WpfApplication1\n{\n /// <summary>\n /// Interaction logic for MainWindow.xaml\n /// </summary>\n public partial class MainWindow : Window\n {\n public MainWindow()\n {\n InitializeComponent();\n Content = FooConverter.Convert(new Point(950, 500), new Point(850, 500));\n }\n }\n\n public static class FooConverter\n {\n public static string Convert(Point curIPJos, Point oppIJPos)\n {\n var ij = \" Insulated Joint\";\n var deltaX = oppIJPos.X - curIPJos.X;\n var deltaY = oppIJPos.Y - curIPJos.Y;\n var teta = Math.Atan2(deltaY, deltaX);\n string result;\n if (-Math.PI / 4 <= teta && teta <= Math.PI / 4)\n result = \"Left\" + ij;\n else if (Math.PI / 4 < teta && teta <= Math.PI * 3 / 4)\n result = \"Top\" + ij;\n else if (Math.PI * 3 / 4 < teta && teta <= Math.PI || -Math.PI <= teta && teta <= -Math.PI * 3 / 4)\n result = \"Right\" + ij;\n else\n result = \"Bottom\" + ij;\n return result;\n }\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
328,623 | <p>UPDATE:
Thank you all for your input. Some additional information.</p>
<p>It's really just a small chunk of markup (20 lines) I'm working with and had aimed to to leverage a regex to do the work.</p>
<p>I also do have the ability to hack up the script (an ecommerce one) to insert the classes as the navigation is built. I wanted to limit the number of hacks I have in place to keep things easier on myself when I go to update to the latest version of the software.</p>
<p>With that said, I'm pretty aware of my situation and the various options available to me. The first part of my regex works as expected. I posted really more or less to see if someone would say, "hey dummy, this is easy just change this....."</p>
<p>After coming close with a few of my efforts, it's more of the principle at this point. To just know (and learn) a solution exists for this problem. I also hate being beaten by a piece of code.</p>
<p>ORIGINAL:</p>
<p>I'm trying to leverage regular expressions to add a CSS a class to the first and last list items within an ordered list. I've tried a bunch of different ways but can't produce the results I'm looking for.</p>
<p>I've got a regular expression for the first list item but can't seem to figure a correct one out for the last. Here is what I'm working with:</p>
<pre><code> $patterns = array('/<ul+([^<]*)<li/m', '/<([^<]*)(?<=<li)(.*)<\/ul>/s');
$replace = array('<ul$1<li class="first"','<li class="last"$2$3</ul>');
$navigation = preg_replace($patterns, $replace, $navigation);
</code></pre>
<p>Any help would be greatly appreciated.</p>
| [
{
"answer_id": 328626,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 2,
"selected": false,
"text": ".first"
},
{
"answer_id": 328658,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "$patterns = array('/<ul+([^<]*)<li/m','/<([^<]*)(?<=<li)(.*)<\\/ul>/s');\n"
},
{
"answer_id": 328669,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": 2,
"selected": false,
"text": "$(document).ready(\n function() {\n $('#id-of-ul:firstChild').addClass('first'); \n $('#id-of-ul:lastChild').addClass('last');\n }\n\n);\n"
},
{
"answer_id": 355001,
"author": "Pianosaurus",
"author_id": 44680,
"author_profile": "https://Stackoverflow.com/users/44680",
"pm_score": 1,
"selected": false,
"text": "<?php\n$navigation='<ul>\n<li>Coffee</li>\n<li>Tea</li>\n<li>Milk</li>\n<li>Beer</li>\n<li>Water</li>\n</ul>';\n\n$patterns = array('/<ul.*?>\\\\s*<li/',\n '/<li((.(?<!<li))*?<\\\\/ul>)/s');\n$replace = array('$0 class=\"first\"',\n '<li class=\"last\"$1');\n$navigation = preg_replace($patterns, $replace, $navigation);\necho $navigation;\n?>"
},
{
"answer_id": 7248434,
"author": "Brian Link",
"author_id": 841769,
"author_profile": "https://Stackoverflow.com/users/841769",
"pm_score": 0,
"selected": false,
"text": "<?php\n/**\n * Modify list items in pre-rendered html.\n *\n * Usage Example:\n * $replaced_text = ListAlter::addClasses($original_html, array('cool', 'awsome'));\n */\nclass ListAlter {\n private $classes = array();\n private $classes_found = FALSE;\n private $count = 0;\n private $total = 0;\n\n // No public instances.\n private function __construct() {}\n\n /**\n * Adds 'first', 'last', and any extra classes you want.\n */\n static function addClasses($html, $extra_classes = array()) {\n $instance = new self();\n $instance->classes = $extra_classes;\n $total = preg_match_all('~<li([^>]*?)>~', $html, $matches);\n $instance->total = $total ? $total : 0;\n return preg_replace_callback('~<li([^>]*?)>~', array($instance, 'processListItem'), $html);\n }\n\n private function processListItem($matches) {\n $this->count++;\n $this->classes_found = FALSE;\n $processed = preg_replace_callback('~(\\w+)=\"(.*?)\"~', array($this, 'appendClasses'), $matches[0]);\n if (!$this->classes_found) {\n $classes = $this->classes;\n if ($this->count == 1) {\n $classes[] = 'first';\n }\n if ($this->count == $this->total) {\n $classes[] = 'last';\n }\n if (!empty($classes)) {\n $processed = rtrim($matches[0], '>') . ' class=\"' . implode(' ', $classes) . '\">';\n }\n }\n return $processed;\n }\n\n private function appendClasses($matches) {\n array_shift($matches);\n list($name, $value) = $matches;\n if ($name == 'class') {\n $value = array_filter(explode(' ', $value));\n $value = array_merge($value, $this->classes);\n if ($this->count == 1) {\n $value[] = 'first';\n }\n if ($this->count == $this->total) {\n $value[] = 'last';\n }\n $value = implode(' ', $value);\n $this->classes_found = TRUE;\n }\n return sprintf('%s=\"%s\"', $name, $value);\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41903/"
] |
328,655 | <p>How do I add a the <a href="http://github.com/technoweenie/restful-authentication/tree/master" rel="nofollow noreferrer">http://github.com/technoweenie/restful-authentication/tree/master</a> plugin to my Rails project and the commit it to the git repo ? I need it to be committed with the project.</p>
<p>I have tried a few times but it's ignored by git.</p>
<p>Thanks.</p>
| [
{
"answer_id": 328663,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 2,
"selected": false,
"text": "rm -rf restful_authentication/.git"
},
{
"answer_id": 328674,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 0,
"selected": false,
"text": "ruby script/generate authenticated user sessions \n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,661 | <p>I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.</p>
<p>For instance: </p>
<pre><code>System.out.println("obj: "+obj);
</code></pre>
<p>instead of:</p>
<pre><code>System.out.println("obj: "+obj.toString());
</code></pre>
<p>Is there any difference apart from the null case?<br>
Can the latter case work, when the former does not?</p>
<p>Edit:<br>
What exactly is done, in case of the implicit call?</p>
| [
{
"answer_id": 328668,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 7,
"selected": true,
"text": "String s = String.valueOf(obj);\n"
},
{
"answer_id": 328675,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 2,
"selected": false,
"text": "\"\" + obj"
},
{
"answer_id": 17677432,
"author": "ceving",
"author_id": 402322,
"author_profile": "https://Stackoverflow.com/users/402322",
"pm_score": 0,
"selected": false,
"text": "class ref\n{\n static public class Reference<T>\n {\n private T value;\n public Reference(T value) { set(value); }\n public Reference() { set(null); }\n public void set (T value) { this.value = value; }\n public T get () { return this.value; }\n public String toString() { return String.valueOf(this.value); }\n }\n\n static void fillString (Reference<String> str)\n {\n str.set(\"foo\");\n }\n\n public static void main (String[] args)\n {\n Reference<String> str = new Reference<String>(\"\");\n fillString(str);\n System.out.println (str);\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860/"
] |
328,673 | <p>Is there an elegant way in Perl to find the newest file in a directory (newest by modification date)?</p>
<p>What I have so far is searching for the files I need, and for each one get it's modification time, push into an array containing the filename, modification time, then sort it.</p>
<p>There must be a better way.</p>
| [
{
"answer_id": 328686,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 4,
"selected": false,
"text": "ls"
},
{
"answer_id": 328687,
"author": "rjray",
"author_id": 6421,
"author_profile": "https://Stackoverflow.com/users/6421",
"pm_score": 3,
"selected": false,
"text": "$DIR"
},
{
"answer_id": 328879,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "ls"
},
{
"answer_id": 328911,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 6,
"selected": true,
"text": "use File::DirList;\nmy @list = File::DirList::list('.', 'M');\n"
},
{
"answer_id": 329091,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": false,
"text": "{\n opendir my $dh, $dir or die \"Could not open $dir: $!\";\n\n my( $newest_name, $newest_time ) = ( undef, 2**31 -1 );\n\n while( defined( my $file = readdir( $dh ) ) ) {\n my $path = File::Spec->catfile( $dir, $file );\n next if -d $path; # skip directories, or anything else you like\n ( $newest_name, $newest_time ) = ( $file, -M _ ) if( -M $path < $newest_time );\n }\n\n print \"Newest file is $newest_name\\n\";\n}\n"
},
{
"answer_id": 10097814,
"author": "ChristOpher",
"author_id": 1325282,
"author_profile": "https://Stackoverflow.com/users/1325282",
"pm_score": -1,
"selected": false,
"text": "bash -c 'ls -t | head -1'"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
328,682 | <p>I am using RRDtool for storing data for displaying graphs. I update the RRD by RRDs::update and this fails when trying to rewrite the information, means update data for a time in the past (e.g. someone moved the system timer back). The error I get is: </p>
<pre><code>ERROR: Cannot update /opt/dashboard/rrd/Disk/192.168.120.168_disk_1.rrd with
'1228032301:24:24' illegal attempt to update using time 1228032301 when last
update time is 1228050001 (minimum one second step)
</code></pre>
<p>I want to always allow the rewrite, how can I do this?</p>
| [
{
"answer_id": 11645890,
"author": "Vladimir Goshev",
"author_id": 1168700,
"author_profile": "https://Stackoverflow.com/users/1168700",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\nrrdtool dump \"$1\" | perl -ne 'BEGIN {$t=`date +%s`; chomp($t);} $a=$_; if ($a =~ /lastupdate.\\d+..lastupdate/) { $a =~ s/(lastupdate.)\\d+(..lastupdate)/$1$t$2/; } print $a' | rrdtool restore -f - \"$1\"\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,692 | <p>In my application, a user has_many tickets. Unfortunately, the tickets table does not have a user_id: it has a user_login (it is a legacy database). I am going to change that someday, but for now this change would have too many implications.</p>
<p>So how can I build a "user has_many :tickets" association through the <strong>login</strong> column?</p>
<p>I tried the following finder_sql, but it does not work.</p>
<pre><code>class User < ActiveRecord::Base
has_many :tickets,
:finder_sql => 'select t.* from tickets t where t.user_login=#{login}'
...
end
</code></pre>
<p>I get a weird error:</p>
<pre><code>ArgumentError: /var/lib/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:402:in `to_constant_name': Anonymous modules have no name to be referenced by
from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:2355:in `interpolate_sql'
from /var/lib/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:214:in `qualified_name_for'
from /var/lib/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:477:in `const_missing'
from (eval):1:in `interpolate_sql'
from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/association_proxy.rb:95:in `send'
from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/association_proxy.rb:95:in `interpolate_sql'
from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/has_many_association.rb:143:in `construct_sql'
from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/has_many_association.rb:6:in `initialize'
from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations.rb:1032:in `new'
from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations.rb:1032:in `tickets'
from (irb):1
</code></pre>
<p>I also tried this finder_sql (with double quotes around the login):</p>
<pre><code>:finder_sql => 'select t.* from tickets t where t.user_login="#{login}"'
</code></pre>
<p>But it fails the same way (and anyway, if it worked it would be vulnerable to sql injection).</p>
<p>In a test database, I added a user_id column in the tickets table, and tried this finder_sql:</p>
<pre><code>:finder_sql => 'select t.* from tickets t where t.user_login=#{id}'
</code></pre>
<p>Now this works fine. So apparently, my problem has to do with the fact that the users column I am trying to use is a string, not an id.</p>
<p>I searched the net for quite some time... but could not find a clue.</p>
<p>I would love to be able to pass any parameter to the finder_sql, and write things like this:</p>
<pre><code>has_many :tickets_since_subscription,
:finder_sql => ['select t.* from tickets t where t.user_login=?'+
' and t.created_at>=?', '#{login}', '#{subscription_date}']
</code></pre>
<p>Edit: I cannot use the :foreign_key parameter of the has_many association because my users table <em>does</em> have an id primary key column, used elsewhere in the application.</p>
<p>Edit#2: apparently I did not read the documentation thoroughly enough: the has_many association can take a :primary_key parameter, to specify which column is the local primary key (default id). Thank you Daniel for opening my eyes! I guess it answers my original question:</p>
<pre><code>has_many tickets, :primary_key="login", :foreign_key="user_login"
</code></pre>
<p>But I would still love to know how I can make the has_many :tickets_since_subscription association work.</p>
| [
{
"answer_id": 328694,
"author": "dgtized",
"author_id": 34450,
"author_profile": "https://Stackoverflow.com/users/34450",
"pm_score": 1,
"selected": false,
"text": ":foreign_key"
},
{
"answer_id": 329086,
"author": "MiniQuark",
"author_id": 38626,
"author_profile": "https://Stackoverflow.com/users/38626",
"pm_score": 0,
"selected": false,
"text": "def tickets\n return Ticket.find(:all, :conditions=>[\"user_login = ?\", login])\nend\n"
},
{
"answer_id": 329583,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 3,
"selected": true,
"text": ":primary_key"
},
{
"answer_id": 854157,
"author": "klew",
"author_id": 58877,
"author_profile": "https://Stackoverflow.com/users/58877",
"pm_score": 2,
"selected": false,
"text": "named_scope :since_subscription, lambda { |subscription_date| { :conditions => ['created_at > ?', subscription_date] }\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38626/"
] |
328,704 | <p>I use Netbeans IDE (6.5) and I have a SQLite 2.x database. I installed a JDBC SQLite driver from <a href="http://www.zentus.com/sqlitejdbc/" rel="nofollow noreferrer">zentus.com</a> and added a new driver in Nebeans services panel. Then tried to connect to my database file from Services > Databases using this URL for my database: </p>
<p>jdbc:sqlite:/home/farzad/netbeans/myproject/mydb.sqlite</p>
<p>but it fails to connect. I get this exception:</p>
<pre><code>org.netbeans.modules.db.dataview.meta.DBException: Unable to Connect to database : DatabaseConnection[name='jdbc:sqlite://home/farzad/netbeans/myproject/mydb.sqlite [ on session]']
at org.netbeans.modules.db.dataview.output.SQLExecutionHelper.initialDataLoad(SQLExecutionHelper.java:103)
at org.netbeans.modules.db.dataview.output.DataView.create(DataView.java:101)
at org.netbeans.modules.db.dataview.api.DataView.create(DataView.java:71)
at org.netbeans.modules.db.sql.execute.SQLExecuteHelper.execute(SQLExecuteHelper.java:105)
at org.netbeans.modules.db.sql.loader.SQLEditorSupport$SQLExecutor.run(SQLEditorSupport.java:480)
at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:572)
[catch] at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:997)
</code></pre>
<p>What should I do? :(</p>
| [
{
"answer_id": 3011156,
"author": "Toleg",
"author_id": 363038,
"author_profile": "https://Stackoverflow.com/users/363038",
"pm_score": 0,
"selected": false,
"text": "CLASSPATH"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9394/"
] |
328,718 | <p>The <a href="http://code.google.com/p/v8/wiki/BuildingOnWindows" rel="nofollow noreferrer">build instructions of V8 JavaScript Engine</a> mention only Visual Studio 2005 and 2008. Has anybody been successful with <a href="http://mingw.org/" rel="nofollow noreferrer">MinGW</a> on Windows XP/Vista?</p>
| [
{
"answer_id": 1149334,
"author": "the_drow",
"author_id": 85140,
"author_profile": "https://Stackoverflow.com/users/85140",
"pm_score": 2,
"selected": true,
"text": "linkers = ['gnulink', 'mslink', 'ilink', 'linkloc', 'ilink32' ]\nc_compilers = ['mingw', 'msvc', 'gcc', 'intelc', 'icl', 'icc', 'cc', 'bcc32' ]\ncxx_compilers = ['g++', 'msvc', 'intelc', 'icc', 'c++', 'bcc32' ]\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30289/"
] |
328,722 | <p>My current code is this:</p>
<pre><code>int volume = Alert.getVolume(); // reads 100
Alert.setVolume(0);
</code></pre>
<p>It DOESN'T change the volume setting, like it would be supposed to do
Even calling <code>Alert.mute(true);</code> doesn't produce any good effect.
<code>Audio.setVolume(0);</code> also doesn't work!</p>
<p>I am running this on a Curve 8310. I have another software installed though that successfully manages to lower the volume setting a lot. o I suppose I'm doing something wrong. Any idea ?</p>
| [
{
"answer_id": 331036,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "javax.microedition.lcdui.Alert"
},
{
"answer_id": 1421886,
"author": "Maksym Gontar",
"author_id": 67407,
"author_profile": "https://Stackoverflow.com/users/67407",
"pm_score": 2,
"selected": true,
"text": "class Scr extends MainScreen implements FieldChangeListener { \n ButtonField mVolumeUp;\n ButtonField mVolumeDown;\n ButtonField mPlay;\n LabelField mVolumeLabel;\n int mVolumeValue = 50;\n private static final short[] tune = new short[] { 466, 125, 10, 466 };\n\n public Scr() {\n mVolumeLabel = new LabelField(\"Volume: \" + mVolumeValue);\n add(mVolumeLabel);\n mVolumeUp = new ButtonField(\"Vol Up\", ButtonField.CONSUME_CLICK);\n mVolumeUp.setChangeListener(this);\n add(mVolumeUp);\n mVolumeDown = new ButtonField(\"Vol Down\", ButtonField.CONSUME_CLICK);\n mVolumeDown.setChangeListener(this);\n add(mVolumeDown);\n mPlay = new ButtonField(\"Play\", ButtonField.CONSUME_CLICK);\n mPlay.setChangeListener(this);\n add(mPlay);\n }\n\n public void fieldChanged(Field field, int context) {\n if (mVolumeUp == field) {\n if (mVolumeValue <= 90)\n mVolumeValue += 10;\n mVolumeLabel.setText(\"Volume: \" + mVolumeValue);\n } else if (mVolumeDown == field) {\n if (mVolumeValue >= 10)\n mVolumeValue -= 10;\n mVolumeLabel.setText(\"Volume: \" + mVolumeValue);\n } else if (mPlay == field) {\n Alert.startAudio(tune, mVolumeValue);\n }\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39680/"
] |
328,727 | <p>When I am stuck with a problem:</p>
<ul>
<li>I search Google for code snippets.</li>
<li>I look at isolating the problem, so that I can better explain it to others in order to get answers.</li>
</ul>
<p>What search techniques do you use to find the solution to your problem?</p>
<p>I started asking questions in Stack Overflow.</p>
<p>What other techniques or methods do you follow, to fix the problem more quickly?</p>
| [
{
"answer_id": 328733,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 3,
"selected": false,
"text": "$fields = $_SESSION[\"fields\"]; // $fields is an associative array\n$fields[\"blah\"] = \"foo\";\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32670/"
] |
328,730 | <p>I have a dev branch that hasn't been touched for a while. I merged the trunk into it to integrate many fixes/changes in the main line since it was branched out, but now I have many small conflicts (merge-left/merge-right).</p>
<p>I want the latest trunk revision to be used to resolve each conflict. Is there a command I can run that will resolve all conflicts under a working copy in one direction automatically (merge-right should be used for all conflicts)?</p>
<p>EDIT:
As indicated in the comments, I tried reverting and then running svn merge with the --accept option, only apparently there is no such option in SVN 1.0. Still looking for a solution.</p>
| [
{
"answer_id": 328779,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 2,
"selected": false,
"text": "--accept theirs-full"
},
{
"answer_id": 7476036,
"author": "Rondo",
"author_id": 442968,
"author_profile": "https://Stackoverflow.com/users/442968",
"pm_score": 2,
"selected": false,
"text": "svn --version\nsvn, version 1.6.17 (r1128011)\n\nsvn resolve -R --accept='theirs-full' <path>\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585/"
] |
328,743 | <p>I have this code :-</p>
<pre><code>using (System.Security.Cryptography.SHA256 sha2 =
new System.Security.Cryptography.SHA256Managed())
{ .. }
</code></pre>
<p>Do I need to put this line of code, just BEFORE I leave that dispose scope .. or does the dispose 'call' that already.</p>
<pre><code>sha2.Clear();
</code></pre>
| [
{
"answer_id": 328825,
"author": "Brian Rasmussen",
"author_id": 38206,
"author_profile": "https://Stackoverflow.com/users/38206",
"pm_score": 1,
"selected": false,
"text": "Clear"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
328,747 | <p>I have problem with return statment >.< I want to store all magazine names into</p>
<pre><code>ArrayList<String> ListNameMagazine = new ArrayList<String>();
</code></pre>
<p>I have a DB; in the DB there is a table <code>name_magazine</code> and the data in <code>name_magazine</code> is</p>
<blockquote>
<p>Magazine1</p>
<p>Magazine2</p>
<p>Magazine3</p>
<p>Magazine4</p>
</blockquote>
<p>This my main:</p>
<pre><code> ShowData Show = new ShowData();
int HowManyMagazine = Show.HowManyMagazine(1); // to make sure there is how many Magazine name in my database
//System.out.print(HowManyMagazine); //i want to make sure the data is out.
String nmeMagazine = null; // this variable for get data from return statement
// i want to store in ListNameMagazine
ArrayList<String> ListNameMagazine = new ArrayList<String>();
for (int numbeer = 0;numbeer <= HowManyMagazine ; numbeer++)
{
//Store in 1 variable String, because if arrayList it's error
nmeMagazine = Show.getResult("Select Name_Magazine from Magazine");
// Store again in array list
ListNameMagazine.add(nmeMagazine);
}
for (String s : ListNameMagazine)
{
System.out.println(s); // show the data
}
</code></pre>
<p>This is my return statement:</p>
<pre><code>public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
//String just_try = null;
while (rs.next()) {
System.out.println("Result:"+rs.getString(1));
//just_try = rs.getString(1);
//return just_try;
}
return null; //return just_try;
}
</code></pre>
<p>The problem is in return statement.</p>
<p>When the comment ( // ) I erase and the last return null; I delete. It become like here:</p>
<pre><code>public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
String just_try = null;
while (rs.next()) {
//System.out.println("Result:"+rs.getString(1));
just_try = rs.getString(1);
return just_try;
}
return just_try;
}
</code></pre>
<p>When I show the data using this statement.</p>
<pre><code>for (String s : ListNameMagazine)
{
System.out.println(s); // show the data
}
</code></pre>
<p>the result only</p>
<blockquote>
<p>Magazine4</p>
<p>Magazine4</p>
<p>Magazine4</p>
<p>Magazine4</p>
</blockquote>
<p>@.@ I have confuse where the miss @.@</p>
<p>but when I show data in return statement like this</p>
<pre><code>public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
String just_try = null;
while (rs.next()) {
System.out.println("Result:"+rs.getString(1));
//just_try = rs.getString(1);
//return just_try;
}
return null;
}
</code></pre>
<p>The data show what I want. I know I only miss in somewhere but I don't know where that @.@. I hope you guys can found it .THX</p>
| [
{
"answer_id": 328760,
"author": "xan",
"author_id": 15667,
"author_profile": "https://Stackoverflow.com/users/15667",
"pm_score": 4,
"selected": true,
"text": "while (rs.next()) { \n\n //System.out.println(\"Result:\"+rs.getString(1));\n\n just_try = rs.getString(1);\n\n return just_try;\n\n}\n"
},
{
"answer_id": 328785,
"author": "Pål GD",
"author_id": 40058,
"author_profile": "https://Stackoverflow.com/users/40058",
"pm_score": 2,
"selected": false,
"text": "public List<String> getResult(String sql) throws SQLException;\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41780/"
] |
328,763 | <p><strong>Update:</strong> This turned into a blog post, with updated links and code, over at my blog: <a href="https://egilhansen.com/2008/12/01/how-to-take-control-of-style-sheets-in-asp-net-themes-with-the-styleplaceholder-and-style-control/" rel="nofollow noreferrer">https://egilhansen.com/2008/12/01/how-to-take-control-of-style-sheets-in-asp-net-themes-with-the-styleplaceholder-and-style-control/</a></p>
<hr>
<p>The problem is pretty simple. When using ASP.NET Themes you do not have much say in how your style sheets are rendered to the page.</p>
<p>The render engine adds all the style sheets you have in your themes folder in alphabetic order, using the <link href=”...” notation.</p>
<p>We all know the order of the style sheets are important, luckily asp.nets shortcomings can be circumvented by prefixing the style sheets with 01, 02, ... , 99, and thus forcing the order you want (see Rusty Swayne <a href="http://rustyswayne.com/post.aspx?id=cba116ea-b672-4c90-9f4e-18b70ca2f50a" rel="nofollow noreferrer">blog post</a> on the technique for more information).</p>
<p>This is especially important if you use a reset style sheet, which I highly recommend; it makes it much easier to style a site in a consistent form across browsers (take a look at <a href="http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/" rel="nofollow noreferrer">Reset Reloaded from Eric Meyer</a>).</p>
<p>You also miss out of the possibility to specify a media type (e.g. screen, print, projection, braille, speech). And if you prefer to include style sheets using the @import method, you are also left out in the cold.</p>
<p>Another missing option is Conditional Comment, which is especially useful if you use an “ie-fix.css” style sheet.</p>
<p>Before I explain how the StylePlaceholder and Style control resolve the above issues, credit where credit is due, my solution is inspired by <a href="http://www.dentaku.com/2007/01/take-control-over-stylesheet-order-and-media-when-using-asp-net-2-0-themes.aspx" rel="nofollow noreferrer">Per Zimmerman’s blog post</a> on the subject.</p>
<p>The StylePlaceHolder control is placed in the header section of your master page or page. It can host one or more Style controls, and will remove styles added by the render engine by default, and add its own (it will only remove styles added from the current active theme).</p>
<p>The Style control can both host inline styles in-between it’s opening and closing tags and a reference to a external style sheet file through its CssUrl property. With other properties you control how the style sheet it renders to the page.</p>
<p>Let me show an example. Consider a simple web site project with a master page and a theme with three style sheets – 01reset.css, 02style.css, 99iefix.cs. Note: I have named them using prefixing technique described earlier, as it makes for a better design time experience. Also, the tag prefix of the custom controls is “ass:”.</p>
<p>In the master page’s header section, add:</p>
<pre><code><ass:StylePlaceHolder ID="StylePlaceHolder1" runat="server" SkinID="ThemeStyles" />
</code></pre>
<p>In your theme directory, add a skin file (e.g. Styles.skin) and add the following content:</p>
<pre><code><ass:StylePlaceHolder1runat="server" SkinId="ThemeStyles">
<ass:Style CssUrl="~/App_Themes/Default/01reset.css" />
<ass:Style CssUrl="~/App_Themes/Default/02style.css" />
<ass:Style CssUrl="~/App_Themes/Default/99iefix.css" ConditionCommentExpression="[if IE]" />
</ass:StylePlaceHolder1>
</code></pre>
<p>That is basically it. There are a more properties on the Style control that can be used to control the rendering, but this is the basic setup. With that in place, you can easily add another theme and replace all the styles, since you only need to include a different skin file.</p>
<p>Now to the code that makes it all happen. I must admit that the design time experience have some quirks. It is probably due to the fact that I am not very proficient in writing custom controls (in fact, these two are my first attempts), so I would very much like input on the following. In a current WCAB/WCSF based project I am developing, I am seeing errors like this in Visual Studios design view, and I have no idea why. The site compiles and everything works online.</p>
<p><a href="http://www.egil.dk/wp-content/styleplaceholder-error.jpg" rel="nofollow noreferrer">Example of design time error in Visual Studio http://www.egil.dk/wp-content/styleplaceholder-error.jpg</a></p>
<p>The following is the code for the StylePlaceHolder control:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
[assembly: TagPrefix("Assimilated.Extensions.Web.Controls", "ass")]
namespace Assimilated.WebControls.Stylesheet
{
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[DefaultProperty("SkinID")]
[ToolboxData("<{0}:StylePlaceHolder runat=\"server\" SkinID=\"ThemeStyles\"></{0}:StylePlaceHolder>")]
[ParseChildren(true, "Styles")]
[Themeable(true)]
[PersistChildren(false)]
public class StylePlaceHolder : Control
{
private List<Style> _styles;
[Browsable(true)]
[Category("Behavior")]
[DefaultValue("ThemeStyles")]
public override string SkinID { get; set; }
[Browsable(false)]
public List<Style> Styles
{
get
{
if (_styles == null)
_styles = new List<Style>();
return _styles;
}
}
protected override void CreateChildControls()
{
if (_styles == null)
return;
// add child controls
Styles.ForEach(Controls.Add);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// get notified when page has finished its load stage
Page.LoadComplete += Page_LoadComplete;
}
void Page_LoadComplete(object sender, EventArgs e)
{
// only remove if the page is actually using themes
if (!string.IsNullOrEmpty(Page.StyleSheetTheme) || !string.IsNullOrEmpty(Page.Theme))
{
// Make sure only to remove style sheets from the added by
// the runtime form the current theme.
var themePath = string.Format("~/App_Themes/{0}",
!string.IsNullOrEmpty(Page.StyleSheetTheme)
? Page.StyleSheetTheme
: Page.Theme);
// find all existing stylesheets in header
var removeCandidate = Page.Header.Controls.OfType<HtmlLink>()
.Where(link => link.Href.StartsWith(themePath)).ToList();
// remove the automatically added style sheets
removeCandidate.ForEach(Page.Header.Controls.Remove);
}
}
protected override void AddParsedSubObject(object obj)
{
// only add Style controls
if (obj is Style)
base.AddParsedSubObject(obj);
}
}
}
</code></pre>
<p>And the code for the Style control:</p>
<pre><code>using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
[assembly: TagPrefix("Assimilated.Extensions.Web.Controls", "ass")]
namespace Assimilated.WebControls.Stylesheet
{
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[DefaultProperty("CssUrl")]
[ParseChildren(true, "InlineStyle")]
[PersistChildren(false)]
[ToolboxData("<{0}:Style runat=\"server\"></{0}:Style>")]
[Themeable(true)]
public class Style : Control
{
public Style()
{
// set default value... for some reason the DefaultValue attribute do
// not set this as I would have expected.
TargetMedia = "All";
}
#region Properties
[Browsable(true)]
[Category("Style sheet")]
[DefaultValue("")]
[Description("The url to the style sheet.")]
[UrlProperty("*.css")]
public string CssUrl
{
get; set;
}
[Browsable(true)]
[Category("Style sheet")]
[DefaultValue("All")]
[Description("The target media(s) of the style sheet. See http://www.w3.org/TR/REC-CSS2/media.html for more information.")]
public string TargetMedia
{
get; set;
}
[Browsable(true)]
[Category("Style sheet")]
[DefaultValue(EmbedType.Link)]
[Description("Specify how to embed the style sheet on the page.")]
public EmbedType Type
{
get; set;
}
[Browsable(false)]
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public string InlineStyle
{
get; set;
}
[Browsable(true)]
[Category("Conditional comment")]
[DefaultValue("")]
[Description("Specifies a conditional comment expression to wrap the style sheet in. See http://msdn.microsoft.com/en-us/library/ms537512.aspx")]
public string ConditionalCommentExpression
{
get; set;
}
[Browsable(true)]
[Category("Conditional comment")]
[DefaultValue(CommentType.DownlevelHidden)]
[Description("Whether to reveal the conditional comment expression to downlevel browsers. Default is to hide. See http://msdn.microsoft.com/en-us/library/ms537512.aspx")]
public CommentType ConditionalCommentType
{
get; set;
}
[Browsable(true)]
[Category("Behavior")]
public override string SkinID { get; set; }
#endregion
protected override void Render(HtmlTextWriter writer)
{
// add empty line to make output pretty
writer.WriteLine();
// prints out begin condition comment tag
if (!string.IsNullOrEmpty(ConditionalCommentExpression))
writer.WriteLine(ConditionalCommentType == CommentType.DownlevelRevealed ? "<!{0}>" : "<!--{0}>",
ConditionalCommentExpression);
if (!string.IsNullOrEmpty(CssUrl))
{
// add shared attribute
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
// render either import or link tag
if (Type == EmbedType.Link)
{
// <link href=\"{0}\" type=\"text/css\" rel=\"stylesheet\" media=\"{1}\" />
writer.AddAttribute(HtmlTextWriterAttribute.Href, ResolveUrl(CssUrl));
writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
writer.AddAttribute("media", TargetMedia);
writer.RenderBeginTag(HtmlTextWriterTag.Link);
writer.RenderEndTag();
}
else
{
// <style type="text/css">@import "modern.css" screen;</style>
writer.RenderBeginTag(HtmlTextWriterTag.Style);
writer.Write("@import \"{0}\" {1};", ResolveUrl(CssUrl), TargetMedia);
writer.RenderEndTag();
}
}
if(!string.IsNullOrEmpty(InlineStyle))
{
// <style type="text/css">... inline style ... </style>
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
writer.RenderBeginTag(HtmlTextWriterTag.Style);
writer.Write(InlineStyle);
writer.RenderEndTag();
}
// prints out end condition comment tag
if (!string.IsNullOrEmpty(ConditionalCommentExpression))
{
// add empty line to make output pretty
writer.WriteLine();
writer.WriteLine(ConditionalCommentType == CommentType.DownlevelRevealed ? "<![endif]>" : "<![endif]-->");
}
}
}
public enum EmbedType
{
Link = 0,
Import = 1,
}
public enum CommentType
{
DownlevelHidden = 0,
DownlevelRevealed = 1
}
}
</code></pre>
<p>So what do you guys think? Is this a good solution to the asp.net theme problem? And what about the code? I would really like some input on it, especially in regards to the design time experience.</p>
<p>I uploaded a <a href="http://egilhansen.com/sites/default/files/node/9/assimilatedwebcontrols.zip" rel="nofollow noreferrer">zipped version of the Visual Studio solution</a> that contains the project, in case anyone is interested.</p>
<p>Best regards, Egil.</p>
| [
{
"answer_id": 463358,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 0,
"selected": false,
"text": "<%@ Register TagPrefix=\"ass\" Namespace=\"Assimilated.WebControls.Stylesheet\" %>\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32809/"
] |
328,765 | <p>I have a object of type <code>ICollection<string></code>. What is the best way to convert to <code>string[]</code>. </p>
<p>How can this be done in .NET 2?<BR>
How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3?</p>
| [
{
"answer_id": 328767,
"author": "AdrianoKF",
"author_id": 27232,
"author_profile": "https://Stackoverflow.com/users/27232",
"pm_score": 6,
"selected": true,
"text": "string[] array = new string[collection.Count];\ncollection.CopyTo(array, 0);\n"
},
{
"answer_id": 328769,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 3,
"selected": false,
"text": "ICollection<String>"
},
{
"answer_id": 328771,
"author": "CVertex",
"author_id": 209,
"author_profile": "https://Stackoverflow.com/users/209",
"pm_score": 3,
"selected": false,
"text": "ICollection<string> col = new List<string>() { \"a\",\"b\"};\nstring[] colArr = col.ToArray();\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
328,768 | <p>After moving to .NET 2.0+ is there ever a reason to still use the systems.Collections namespace (besides maintaining legacy code)? Should the generics namespace always be used instead?</p>
| [
{
"answer_id": 328811,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 0,
"selected": false,
"text": "List<Person>"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
328,772 | <p>I have a class that inherits a generic dictionary and an inteface</p>
<pre><code>public class MyDictionary: Dictionary<string, IFoo>, IMyDictionary
{
}
</code></pre>
<p>the issue is that consumers of this class are looking for the '.Keys' and ".Values" properties of the interface so i added:</p>
<pre><code> /// <summary>
///
/// </summary>
ICollection<string> Keys { get; }
/// <summary>
///
/// </summary>
IEnumerable<IFoo> Values { get; }
</code></pre>
<p>to the interface. </p>
<p>Now, the implementation needs to have this as well but when i implement these, i get this error:</p>
<p>"The keyword new is required because it hides property Keys . .. "</p>
<p>so what do i need to do. Should i be adding a "new" in front of these get properties?</p>
| [
{
"answer_id": 328782,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 2,
"selected": false,
"text": "class IFoo\n{ }\n\ninterface MyDictionary\n{\n ICollection<string> Keys { get; }\n\n /// <summary>\n /// \n /// </summary>\n IEnumerable<IFoo> Values { get; }\n}\n\nclass IStuff : Dictionary<string, IFoo>, MyDictionary\n{\n #region MyDictionary Members\n\n //Note the new keyword.\n public new ICollection<string> Keys\n {\n get { throw new NotImplementedException(); }\n }\n\n public new IEnumerable<IFoo> Values\n {\n get { throw new NotImplementedException(); }\n }\n\n #endregion\n}\n"
},
{
"answer_id": 328800,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 4,
"selected": true,
"text": "public interface IMyDictionary\n{\n /// <summary>\n /// \n /// </summary>\n Dictionary<string, IFoo>.KeyCollection Keys { get; }\n\n /// <summary>\n /// \n /// </summary>\n Dictionary<string, IFoo>.ValueCollection Values { get; }\n}\n"
},
{
"answer_id": 328817,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "new"
},
{
"answer_id": 328893,
"author": "Mike Two",
"author_id": 23659,
"author_profile": "https://Stackoverflow.com/users/23659",
"pm_score": 2,
"selected": false,
"text": "public class MyDictionary : Dictionary<string, IFoo>, IMyDictionary\n{\n ICollection<string> IMyDictionary.Keys\n {\n get { return Keys; }\n }\n\n IEnumerable<IFoo> IMyDictionary.Values\n {\n get { return Values; }\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
328,793 | <p>The <code>curses.ascii</code> module has some nice functions defined, that allow for example to recognize which characters are printable (<code>curses.ascii.isprint(ch)</code>).</p>
<p>But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are certain polish characters:</p>
<pre><code>>>> ord('a')
97
>>> ord('ą')
177
>>>
</code></pre>
<p>I'm wondering, is there a better way to tell if a number represents printable character then the one used in <code>curses.ascii</code> module:</p>
<pre><code>def isprint(c): return _ctoi(c) >= 32 and _ctoi(c) <= 126
</code></pre>
<p>which is kind of locale-unfriendly.</p>
| [
{
"answer_id": 328807,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 3,
"selected": true,
"text": ">>> unicodedata.category(u'ą')[0] in 'LNPS'\nTrue\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
328,806 | <p>If I've got a variable that contains the fully-qualified name of a file (for example, a project file), should it be called <code>projectFile</code>, <code>projectFileName</code> or <code>projectPath</code>? Or something else?</p>
| [
{
"answer_id": 328810,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "FileName"
},
{
"answer_id": 328812,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "system_configuration_file_URI\nuser_input_file_URI\ndocument_template_file_URI\n"
},
{
"answer_id": 328821,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "projectFile"
},
{
"answer_id": 328854,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "Filename"
},
{
"answer_id": 328860,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "path"
},
{
"answer_id": 328933,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "projectpath"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
328,830 | <p>what is the value of using IDictionary here?</p>
| [
{
"answer_id": 328836,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "Dictionary"
},
{
"answer_id": 328838,
"author": "Arjan Einbu",
"author_id": 19594,
"author_profile": "https://Stackoverflow.com/users/19594",
"pm_score": 4,
"selected": false,
"text": "void DoSomething(IDictionary<string, string> d)\n{\n //...\n}\n"
},
{
"answer_id": 328844,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 1,
"selected": false,
"text": "dictionary<string, IFoo>"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
328,832 | <p>I've been facing this issue where, the hibernate objects on serialization produces unexpect xmls containing all the instrumented code from Hibernate.</p>
<p>We did some cleaning of the object before serializing the object.</p>
<p>But, is there a standard option available to serialize the object directly?</p>
| [
{
"answer_id": 329214,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 2,
"selected": false,
"text": "Set<T>"
},
{
"answer_id": 6719331,
"author": "Tomek Lipski",
"author_id": 848017,
"author_profile": "https://Stackoverflow.com/users/848017",
"pm_score": 2,
"selected": false,
"text": "XStream xs = new XStream();\nxs.registerConverter(new CollectionConverter(xs.getMapper()) {\n @Override\n public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {\n org.hibernate.collection.PersistentSet ps = (PersistentSet) source;\n super.marshal(new HashSet(ps), writer, context);\n }\n\n @Override\n public boolean canConvert(Class type) {\n return type.isAssignableFrom(org.hibernate.collection.PersistentSet.class);\n }\n}, XStream.PRIORITY_VERY_HIGH);\nString s = xs.toXML(processInstance);\n"
},
{
"answer_id": 10697925,
"author": "Ophir Radnitz",
"author_id": 159452,
"author_profile": "https://Stackoverflow.com/users/159452",
"pm_score": 1,
"selected": false,
"text": "Converter"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31590/"
] |
328,834 | <ol>
<li><p>Consider:</p>
<pre><code>char *p=NULL;
free(p) // or
delete p;
</code></pre>
<p>What will happen if I use <code>free</code> and <code>delete</code> on <code>p</code>?</p></li>
<li><p>If a program takes a long time to execute, say 10 minutes, is there any way to reduce its running time to 5 minutes?</p></li>
</ol>
| [
{
"answer_id": 328841,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 4,
"selected": false,
"text": "free(p)"
},
{
"answer_id": 328909,
"author": "cic",
"author_id": 4771,
"author_profile": "https://Stackoverflow.com/users/4771",
"pm_score": 3,
"selected": false,
"text": "<cstdlib>"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41522/"
] |
328,850 | <p>I am developing an Adobe AIR application which stores data locally using a SQLite database.
At any time, I want the end user to synchronize his/her local data to a central MySQL database.</p>
<p>Any tips, advice for getting this right?
Performance and stability is the key (besides security ;))</p>
| [
{
"answer_id": 328841,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 4,
"selected": false,
"text": "free(p)"
},
{
"answer_id": 328909,
"author": "cic",
"author_id": 4771,
"author_profile": "https://Stackoverflow.com/users/4771",
"pm_score": 3,
"selected": false,
"text": "<cstdlib>"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,851 | <p>With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?</p>
| [
{
"answer_id": 328856,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "class MyClassFactory( object ):\n theWholeList= []\n def __call__( self, *args, **kw ):\n x= MyClass( *args, **kw )\n self.theWholeList.append( x )\n return x\n"
},
{
"answer_id": 328882,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 8,
"selected": true,
"text": "import gc\nfor obj in gc.get_objects():\n if isinstance(obj, some_class):\n dome_something(obj)\n"
},
{
"answer_id": 329351,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 2,
"selected": false,
"text": "__metaclass__"
},
{
"answer_id": 9460070,
"author": "MirkoT",
"author_id": 1234804,
"author_profile": "https://Stackoverflow.com/users/1234804",
"pm_score": 5,
"selected": false,
"text": "weakref"
},
{
"answer_id": 50063951,
"author": "Fabio Caccamo",
"author_id": 2096218,
"author_profile": "https://Stackoverflow.com/users/2096218",
"pm_score": 3,
"selected": false,
"text": "print(len(cls.__refs__[cls]))"
},
{
"answer_id": 56849063,
"author": "Илиян Илиев",
"author_id": 9932463,
"author_profile": "https://Stackoverflow.com/users/9932463",
"pm_score": 5,
"selected": false,
"text": "class A:\n instances = []\n def __init__(self):\n self.__class__.instances.append(self)\nprint('\\n'.join(A.instances)) #this line was suggested by @anvelascos\n"
},
{
"answer_id": 63778194,
"author": "alperen atik",
"author_id": 14210471,
"author_profile": "https://Stackoverflow.com/users/14210471",
"pm_score": 1,
"selected": false,
"text": "```\ninstances = [] \n\nclass WorkCalendar:\n def __init__(self, day, patient, worker):\n self.day = day\n self.patient = patient\n self.worker= worker\n def __str__(self):\n return f'{self.day} : {self.patient} : {self.worker}'\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33061/"
] |
328,857 | <p>How to run NAnt scripts in command line and get the timings of each task on the log file?</p>
<pre><code>using nant <record> task or
NAnt -buildfile:testscript.build testnanttarget
</code></pre>
<p>This produces console output but I can't see any timing information.</p>
<p>All I want each log message prefixed with datatime.</p>
| [
{
"answer_id": 329162,
"author": "wimh",
"author_id": 33499,
"author_profile": "https://Stackoverflow.com/users/33499",
"pm_score": 4,
"selected": true,
"text": "<tstamp />\n"
},
{
"answer_id": 11365688,
"author": "aked",
"author_id": 1060656,
"author_profile": "https://Stackoverflow.com/users/1060656",
"pm_score": 3,
"selected": false,
"text": " <echo>\n -----------------------------------------------------------------------------------------------------------------\n -----------------------------------------------------------------------------------------------------------------\n TASK : INITIALIZE\n -----------------------------------------------------------------------------------------------------------------\n -----------------------------------------------------------------------------------------------------------------\n </echo>\n\n <loadtasks assembly=\"nantcontrib-0.85/bin/NAnt.Contrib.Tasks.dll\" /> \n <!-- http://www.basilv.com/psd/blog/2007/how-to-add-logging-to-ant-builds -->\n <tstamp> \n <formatter property=\"timestamp\" pattern=\"yyMMdd_HHmm\"/>\n </tstamp> \n\n <property name=\"build.log.filename\" value=\"build_${timestamp}.log\"/>\n\n <echo message=\"build.log.filename: ${build.log.filename}\" />\n\n <record name=\"${build.log.dir}/${build.log.filename}\" action=\"Start\" level=\"Verbose\"/> \n\n <echo message=\"Build logged to ${build.log.filename}\"/>\n\n <echo message=\"Build Start at: ${datetime::now()}\" />\n\n</target>\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32670/"
] |
328,898 | <p>I'm looking for ideas on how to implement audit trails for my objects in C#, for the current project,basically I need to:</p>
<ol>
<li>Store the old values and new values of a given object.</li>
<li>Record creation of new objects.</li>
<li>Deletion of old object.</li>
</ol>
<p>Is there any generic way of doing this,like using C# Generics,so that I don't have to write code for events of the base object like on creation,on deletion etc.(ORM objects).The thing is that if there was a way to inject audit trail if one is using a .Anybody have any experiences or any methods they follow.Any way to do this in a Aspect-oriented (AOP) mannner.</p>
<p>Please share your ideas etc.</p>
| [
{
"answer_id": 432698,
"author": "Ray Booysen",
"author_id": 42124,
"author_profile": "https://Stackoverflow.com/users/42124",
"pm_score": 2,
"selected": false,
"text": "public interface INotifyProperyChanged<T>\n{\n event PropertyChangedEventHandler<T> PropertyChanged;\n}\n\n public delegate void PropertyChangedEventHandler<T>(object sender, \nPropertyChangedEventArgs<T> e);\n\npublic class PropertyChangedEventArgs<T> : EventArgs\n{\n private readonly string propertyName;\n\n public PropertyChangedEventArgs(string propertyName)\n {\n this.propertyName = propertyName\n }\n\n public virtual string PropertyName { get { return propertyName; } }\n\n public T OldValue { get; set; }\n public T NewValue { get; set; }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39278/"
] |
328,914 | <p>How should I check if my ISP blocks port 25?</p>
| [
{
"answer_id": 329104,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 5,
"selected": true,
"text": "cmd> telnet <some well known email provider IP> 25\n"
},
{
"answer_id": 338830,
"author": "joveha",
"author_id": 40668,
"author_profile": "https://Stackoverflow.com/users/40668",
"pm_score": 2,
"selected": false,
"text": ":~$ hping3 -z -T -p 25 server.com\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16039/"
] |
328,915 | <p>I've been using the following snippet in developements for years. Now all of a sudden I get a DB Error: no such field warning</p>
<pre><code>$process = "process";
$create = $connection->query
(
"INSERT INTO summery (process) VALUES($process)"
);
if (DB::isError($create)) die($create->getMessage($create));
</code></pre>
<p>but it's fine if I use numerics</p>
<pre><code>$process = "12345";
$create = $connection->query
(
"INSERT INTO summery (process) VALUES($process)"
);
if (DB::isError($create)) die($create->getMessage($create));
</code></pre>
<p>or write the value directly into the expression</p>
<pre><code>$create = $connection->query
(
"INSERT INTO summery (process) VALUES('process')"
);
if (DB::isError($create)) die($create->getMessage($create));
</code></pre>
<p>I'm really confused ... any suggestions?</p>
| [
{
"answer_id": 329223,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 3,
"selected": false,
"text": "my $process=1234;\nmy $ins_process = $dbh->prepare(\"INSERT INTO summary (process) values(?)\");\n$ins_process->execute($process);\n"
},
{
"answer_id": 330045,
"author": "dvergin",
"author_id": 9377,
"author_profile": "https://Stackoverflow.com/users/9377",
"pm_score": 0,
"selected": false,
"text": "my $thing = 'abcde';\nmy $sth = $dbh->prepare(\"INSERT INTO table1 (id,field1)\n VALUES (3,'$thing')\");\n$sth->execute;\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,922 | <p>I have a <code>mysql</code> database filled up and running on a <em>Windows</em> computer, is there any tool to transfer the database to another computer (running <em>Ubuntu</em>)?</p>
<p>Else I'll just write a <code>script</code> to take all the data base into <code>SQL</code> and <em>insert</em> it on the other computer. Just trying to save some time :)</p>
<p>Thank you all.</p>
| [
{
"answer_id": 328928,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": 6,
"selected": true,
"text": "mysqldump -u username -p databasename > dumpfile.sql\n"
},
{
"answer_id": 608536,
"author": "AdamK",
"author_id": 14595,
"author_profile": "https://Stackoverflow.com/users/14595",
"pm_score": 0,
"selected": false,
"text": "mysqldump --opt --compress --user=username database | mysql --user=username2 --password=p2 --host=hostB -D database -C database\n"
},
{
"answer_id": 4819610,
"author": "Sanjay Zalke",
"author_id": 286255,
"author_profile": "https://Stackoverflow.com/users/286255",
"pm_score": 4,
"selected": false,
"text": "mysqldump -u username -p --all-databases > c:\\alldbs.sql\n"
},
{
"answer_id": 16072686,
"author": "Petre Lukarov",
"author_id": 391692,
"author_profile": "https://Stackoverflow.com/users/391692",
"pm_score": 1,
"selected": false,
"text": "shell> mysqldump --quick db_name | gzip > db_name.gz\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26004/"
] |
328,925 | <p>When I code like this: </p>
<pre><code>ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress sa = new InetSocketAddress("localhost",8888);
ssc.socket().bind(sa);
ssc.configureBlocking(false);
ssc.socket().accept();
</code></pre>
<p>the <code>ServerSocket.accept()</code> method throws <code>java.nio.channels.IllegalBlockingModeException</code>. Why can't I call <code>accept()</code>, even though I set blocking to <code>false</code>?</p>
| [
{
"answer_id": 431506,
"author": "Brian Clapper",
"author_id": 53495,
"author_profile": "https://Stackoverflow.com/users/53495",
"pm_score": 2,
"selected": false,
"text": "ServerSocketChannel.accept()"
},
{
"answer_id": 546437,
"author": "Nick",
"author_id": 21399,
"author_profile": "https://Stackoverflow.com/users/21399",
"pm_score": 2,
"selected": false,
"text": "ssc.socket().accept()"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41940/"
] |
328,936 | <p>I want to get from any Unix-like system (if this is possible) a unique id that will be persistent every time my application runs in the same machine. If it is possible, I want to get the same id from Linux or FreeBSD or Solaris, etc... I don't want to generate a new id for each machine, but get an already existent id, and I prefer this id to come from the operating system and I don't prefer to use something like the MAC address.</p>
<p>If there is no other option available, I can use MAC in combination with something else, for example the id can be the md5 hash of the combination of the MAC address and something else.</p>
<p>I would like to listen to your suggestions.</p>
<p>If it is useful, my application is written in C/C++.</p>
<p>The aim of all this is to prevent a user to run my application for two or more times. I want to run just once.</p>
| [
{
"answer_id": 328973,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 3,
"selected": false,
"text": "hostid"
},
{
"answer_id": 329023,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "hostid"
},
{
"answer_id": 344570,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "lock = open(filename, O_CREAT | O_EXCL);\ndprintf(lock, \"%u\", getpid());\n"
},
{
"answer_id": 344656,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 5,
"selected": false,
"text": "/etc/fstab"
},
{
"answer_id": 29416511,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "/"
},
{
"answer_id": 36166610,
"author": "Chris Johnson",
"author_id": 763269,
"author_profile": "https://Stackoverflow.com/users/763269",
"pm_score": 0,
"selected": false,
"text": "/sbin/blkid"
},
{
"answer_id": 62681358,
"author": "shrewmouse",
"author_id": 2464381,
"author_profile": "https://Stackoverflow.com/users/2464381",
"pm_score": 2,
"selected": false,
"text": "dmidecode"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41944/"
] |
328,938 | <p>EF has been out for awhile now and I'm considering evaluating it - what have your experiences been?</p>
<p>I am interested in both web and desktop applications, and maybe some comparisons between EF and other ORM tools that you've used. </p>
<p>Learning curve is a factor since there is a team involved. Is this thing a bloated mess, or it is lean and sharp?</p>
<p>I heard that Microsoft is using this internally and in a big way, so that's a good sign. If you have any thoughts about how it might fit into the cloud-based future that MS seems to be spending their money on these days, that might also be interesting. After all, if this is something we might all eventually <em>need</em> to know, that would raise the priority level a notch or two.</p>
<p>Thanks a lot!</p>
| [
{
"answer_id": 329369,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 1,
"selected": false,
"text": "Contains"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16082/"
] |
328,944 | <p>How do i check in C++ if a file is a regular file (and is not a directory, a pipe, etc.)? I need a function isFile(). </p>
<pre><code>DIR *dp;
struct dirent *dirp;
while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
cout << "IS A FILE!" << endl;
i++;
}
</code></pre>
<p>I've tried comparing dirp->d_type with (unsigned char)0x8, but it seems not portable through differents systems. </p>
| [
{
"answer_id": 328948,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 4,
"selected": true,
"text": "#include <sys/stat.h>\n\nstruct stat sb;\n\nif (stat(pathname, &sb) == 0 && S_ISREG(sb.st_mode))\n{\n // file exists and it's a regular file\n}\n"
},
{
"answer_id": 328952,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 2,
"selected": false,
"text": "stat"
},
{
"answer_id": 328958,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "boost::filesystem"
},
{
"answer_id": 329157,
"author": "Emilio",
"author_id": 39796,
"author_profile": "https://Stackoverflow.com/users/39796",
"pm_score": 0,
"selected": false,
"text": "while ((dirp = readdir(dp)) != NULL) { \n if (!S_ISDIR(dirp->d_type)) { \n ... \n i++; \n } \n} \n"
},
{
"answer_id": 20676985,
"author": "edayangac",
"author_id": 2496259,
"author_profile": "https://Stackoverflow.com/users/2496259",
"pm_score": 0,
"selected": false,
"text": "#include <boost/filesystem.hpp>\n\nbool isFile(std::string filepath)\n{\n boost::filesystem::path p(filepath);\n if(boost::filesystem::is_regular_file(p)) {\n return true;\n }\n std::cout<<filepath<<\" file does not exist and is not a regular file\"<<std::endl;\n return false;\n}\n"
},
{
"answer_id": 47854984,
"author": "mehfoos yacoob",
"author_id": 1218748,
"author_profile": "https://Stackoverflow.com/users/1218748",
"pm_score": 2,
"selected": false,
"text": "#include <filesystem> // additional include\n\nif(std::filesystem::is_regular_file(yourFilePathToCheck)) \n ; //Do what you need to do\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39796/"
] |
328,946 | <p>On researching another question I noted that the <code>stat</code> function in Perl can take a dirhandle as its argument (instead of a filehandle or filename).</p>
<p>However I can't find any examples of correct use of this - there are none in the Perl manual.</p>
<p>Can anyone show an example of how to use it?</p>
| [
{
"answer_id": 328971,
"author": "genehack",
"author_id": 39933,
"author_profile": "https://Stackoverflow.com/users/39933",
"pm_score": 2,
"selected": false,
"text": "stat"
},
{
"answer_id": 328979,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "#!/usr/bin/perl\nuse strict;\n\nmy $dir = shift;\nopendir(DIR, $dir) or die \"Failed to open $dir: $!\\n\";\nmy @stats = stat DIR;\nclosedir(DIR);\nmy $atime = scalar localtime $stats[8];\n\nprint \"Last access time on $dir: $atime\\n\";\n"
},
{
"answer_id": 329248,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "$ perl -wl\nopendir $h, \".\" or die;\nopen $h, \"/etc/services\" or die;\nprint \"dir:\".readdir($h);\nprint \"file:\".readline($h);\nprint stat(\"/etc/services\");\nprint stat(\".\");\nprint stat($h);\nclose($h);\nprint stat($h);\n__END__\ndir:.\nfile:# Network services, Internet style\n\n205527886633188100018274122800783211967194861209994037409640\n20551515522168777410001000020480122803711512280371021228037102409640\n205527886633188100018274122800783211967194861209994037409640\nstat() on closed filehandle $h at - line 1.\n (Are you trying to call stat() on dirhandle $h?)\n"
},
{
"answer_id": 1742609,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " my $mtime = (stat( $directory ))[ 9 ];\n print \"D $directory $mtime\\n\";\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6782/"
] |
328,955 | <p>Thanks for a <a href="https://stackoverflow.com/questions/327893/how-to-write-a-compare-function-for-qsort-from-stdlib">solution in C</a>,
now I would like to achieve this in C++ using std::sort and vector:</p>
<pre><code>typedef struct
{
double x;
double y;
double alfa;
} pkt;
</code></pre>
<p><code>vector< pkt > wektor;</code> filled up using push_back(); compare function:</p>
<pre><code>int porownaj(const void *p_a, const void *p_b)
{
pkt *pkt_a = (pkt *) p_a;
pkt *pkt_b = (pkt *) p_b;
if (pkt_a->alfa > pkt_b->alfa) return 1;
if (pkt_a->alfa < pkt_b->alfa) return -1;
if (pkt_a->x > pkt_b->x) return 1;
if (pkt_a->x < pkt_b->x) return -1;
return 0;
}
sort(wektor.begin(), wektor.end(), porownaj); // this makes loads of errors on compile time
</code></pre>
<p>What is to correct? How to use properly std::sort in that case?</p>
| [
{
"answer_id": 328959,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "std::sort"
},
{
"answer_id": 328981,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "boost::bind"
},
{
"answer_id": 5693570,
"author": "Christopher Oezbek",
"author_id": 278842,
"author_profile": "https://Stackoverflow.com/users/278842",
"pm_score": 3,
"selected": false,
"text": "sort(wektor.begin(), wektor.end(), [](pkt const& a, pkt const& b)\n{\n if (a.alfa < b.alfa) return true;\n if (a.alfa > b.alfa) return false;\n\n if (a.x < b.x) return true;\n if (a.x > b.x) return false;\n\n return false;\n});\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41839/"
] |
328,962 | <p>I wrote a Win Forms app to test how a LinkLabel class works. It appears to be fine until I click on the changed LinkLabel. The Form1.cs code is below:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace LinkLabelTest
{
// Editor: code not fully indented - laziness!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLinkColor_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
llblinkLabel1.LinkColor = colorDialog1.Color;
}
private void btnActiveLinkColor_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
llblinkLabel1.ActiveLinkColor = colorDialog1.Color;
}
private void btnVisitedLinkColor_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
llblinkLabel1.VisitedLinkColor = colorDialog1.Color;
}
private void llblinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (!(e.Link.Description == null))
{
if (e.Button == MouseButtons.Right)
{
PopulateLinkDetails(e.Link);
}
if (e.Button == MouseButtons.Left)
{
e.Link.Visited = true;
Debugger.Break();
}
}
}
catch (Exception exc)
{
Debugger.Break();
MessageBox.Show(exc.Message.ToString());
}
}
private void PopulateLinkDetails(LinkLabel.Link link)
{
textDescription.Text = link.Description;
textLinkData.Text = (string)link.LinkData;
textName.Text = link.Name;
checkBoxEnabled.Checked = link.Enabled;
checkBoxVisited.Checked = link.Visited;
nudLinkAreaStart.Value = link.Start;
nudLinkAreaEnd.Value = link.Length;
}
private void Form1_Load(object sender, EventArgs e)
{
cmbLinkBehaviour.DataSource = Enum.GetValues(typeof(LinkBehavior));
}
private void cmbLinkBehaviour_SelectedIndexChanged(object sender, EventArgs e)
{
llblinkLabel1.LinkBehavior = (LinkBehavior)cmbLinkBehaviour.SelectedItem;
}
private void AddLink_Click(object sender, EventArgs e)
{
LinkLabel.Link link = new LinkLabel.Link();
link.Description = textDescription.Text.ToString();
link.LinkData = textLinkData.Text.ToString();
link.Name = textName.Text.ToString();
link.Enabled = checkBoxEnabled.Checked;
link.Visited = checkBoxVisited.Checked;
link.Start = (int)nudLinkAreaStart.Value;
link.Length = (int)nudLinkAreaEnd.Value;
llblinkLabel1.Links.Add(link);
}
}
}
</code></pre>
<p>The stack trace is below :</p>
<blockquote>
<p>at System.Drawing.Region.GetHrgn(Graphics g) at
System.Windows.Forms.Control.Invalidate(Region region, Boolean
invalidateChildren) at
System.Windows.Forms.LinkLabel.InvalidateLink(Link link) at
System.Windows.Forms.LinkLabel.OnGotFocus(EventArgs e) at
System.Windows.Forms.Control.WmSetFocus(Message& m) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.Label.WndProc(Message& m) at
System.Windows.Forms.LinkLabel.WndProc(Message& msg) at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.SetFocus(HandleRef hWnd) at
System.Windows.Forms.Control.FocusInternal() at
System.Windows.Forms.LinkLabel.OnMouseDown(MouseEventArgs e) at
System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons
button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message&
m) at System.Windows.Forms.Label.WndProc(Message& m) at
System.Windows.Forms.LinkLabel.WndProc(Message& msg) at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.Run(Form mainForm) at
LinkLabelTest.Program.Main() in C:\Users\Tony\Documents\Visual Studio
2008\Projects\LinkLabelTest\LinkLabelTest\Program.cs:line 22</p>
</blockquote>
<p>Below is the designer generated code:</p>
<pre><code>using System.Diagnostics;
namespace LinkLabelTest
{
// Editor: code not fully indented - laziness again!
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.llblinkLabel1 = new System.Windows.Forms.LinkLabel();
this.colorDialog1 = new System.Windows.Forms.ColorDialog();
this.btnLinkColor = new System.Windows.Forms.Button();
this.btnActiveLinkColor = new System.Windows.Forms.Button();
this.btnVisitedLinkColor = new System.Windows.Forms.Button();
this.nudLinkAreaStart = new System.Windows.Forms.NumericUpDown();
this.lbllabel1 = new System.Windows.Forms.Label();
this.nudLinkAreaEnd = new System.Windows.Forms.NumericUpDown();
this.lbllabel2 = new System.Windows.Forms.Label();
this.cmbLinkBehaviour = new System.Windows.Forms.ComboBox();
this.lbllabel3 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.textDescription = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.textName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.textLinkData = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.checkBoxEnabled = new System.Windows.Forms.CheckBox();
this.AddLink = new System.Windows.Forms.Button();
this.btnAmendLink = new System.Windows.Forms.Button();
this.checkBoxVisited = new System.Windows.Forms.CheckBox();
this.panel1 = new System.Windows.Forms.Panel();
this.textBox1 = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.nudLinkAreaStart)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudLinkAreaEnd)).BeginInit();
this.groupBox1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// llblinkLabel1
//
this.llblinkLabel1.AutoSize = true;
this.llblinkLabel1.Location = new System.Drawing.Point(13, 27);
this.llblinkLabel1.Name = "llblinkLabel1";
this.llblinkLabel1.Size = new System.Drawing.Size(96, 13);
this.llblinkLabel1.TabIndex = 0;
this.llblinkLabel1.TabStop = true;
this.llblinkLabel1.Text = "This is a link label !";
this.llblinkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.llblinkLabel1_LinkClicked);
//
// btnLinkColor
//
this.btnLinkColor.Location = new System.Drawing.Point(0, 19);
this.btnLinkColor.Name = "btnLinkColor";
this.btnLinkColor.Size = new System.Drawing.Size(93, 23);
this.btnLinkColor.TabIndex = 2;
this.btnLinkColor.Text = "LinkColor";
this.btnLinkColor.UseVisualStyleBackColor = true;
this.btnLinkColor.Click += new System.EventHandler(this.btnLinkColor_Click);
//
// btnActiveLinkColor
//
this.btnActiveLinkColor.Location = new System.Drawing.Point(0, 48);
this.btnActiveLinkColor.Name = "btnActiveLinkColor";
this.btnActiveLinkColor.Size = new System.Drawing.Size(93, 23);
this.btnActiveLinkColor.TabIndex = 3;
this.btnActiveLinkColor.Text = "ActiveLinkColor";
this.btnActiveLinkColor.UseVisualStyleBackColor = true;
this.btnActiveLinkColor.Click += new System.EventHandler(this.btnActiveLinkColor_Click);
//
// btnVisitedLinkColor
//
this.btnVisitedLinkColor.Location = new System.Drawing.Point(0, 77);
this.btnVisitedLinkColor.Name = "btnVisitedLinkColor";
this.btnVisitedLinkColor.Size = new System.Drawing.Size(93, 23);
this.btnVisitedLinkColor.TabIndex = 4;
this.btnVisitedLinkColor.Text = "VisitedLinkColor";
this.btnVisitedLinkColor.UseVisualStyleBackColor = true;
this.btnVisitedLinkColor.Click += new System.EventHandler(this.btnVisitedLinkColor_Click);
//
// nudLinkAreaStart
//
this.nudLinkAreaStart.Location = new System.Drawing.Point(152, 64);
this.nudLinkAreaStart.Maximum = new decimal(new int[] {
21,
0,
0,
0});
this.nudLinkAreaStart.Name = "nudLinkAreaStart";
this.nudLinkAreaStart.Size = new System.Drawing.Size(66, 20);
this.nudLinkAreaStart.TabIndex = 6;
//
// lbllabel1
//
this.lbllabel1.AutoSize = true;
this.lbllabel1.Location = new System.Drawing.Point(224, 71);
this.lbllabel1.Name = "lbllabel1";
this.lbllabel1.Size = new System.Drawing.Size(74, 13);
this.lbllabel1.TabIndex = 7;
this.lbllabel1.Text = "Link area start";
//
// nudLinkAreaEnd
//
this.nudLinkAreaEnd.Location = new System.Drawing.Point(152, 99);
this.nudLinkAreaEnd.Maximum = new decimal(new int[] {
21,
0,
0,
0});
this.nudLinkAreaEnd.Name = "nudLinkAreaEnd";
this.nudLinkAreaEnd.Size = new System.Drawing.Size(67, 20);
this.nudLinkAreaEnd.TabIndex = 8;
//
// lbllabel2
//
this.lbllabel2.AutoSize = true;
this.lbllabel2.Location = new System.Drawing.Point(224, 105);
this.lbllabel2.Name = "lbllabel2";
this.lbllabel2.Size = new System.Drawing.Size(83, 13);
this.lbllabel2.TabIndex = 9;
this.lbllabel2.Text = "Link area length";
//
// cmbLinkBehaviour
//
this.cmbLinkBehaviour.FormattingEnabled = true;
this.cmbLinkBehaviour.Location = new System.Drawing.Point(0, 106);
this.cmbLinkBehaviour.Name = "cmbLinkBehaviour";
this.cmbLinkBehaviour.Size = new System.Drawing.Size(93, 21);
this.cmbLinkBehaviour.TabIndex = 10;
this.cmbLinkBehaviour.SelectedIndexChanged += new System.EventHandler(this.cmbLinkBehaviour_SelectedIndexChanged);
//
// lbllabel3
//
this.lbllabel3.AutoSize = true;
this.lbllabel3.Location = new System.Drawing.Point(-3, 130);
this.lbllabel3.Name = "lbllabel3";
this.lbllabel3.Size = new System.Drawing.Size(78, 13);
this.lbllabel3.TabIndex = 11;
this.lbllabel3.Text = "Link Behaviour";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnLinkColor);
this.groupBox1.Controls.Add(this.btnActiveLinkColor);
this.groupBox1.Controls.Add(this.lbllabel3);
this.groupBox1.Controls.Add(this.btnVisitedLinkColor);
this.groupBox1.Controls.Add(this.cmbLinkBehaviour);
this.groupBox1.Location = new System.Drawing.Point(12, 57);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(124, 155);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "THE link label";
//
// textDescription
//
this.textDescription.Location = new System.Drawing.Point(152, 136);
this.textDescription.Name = "textDescription";
this.textDescription.Size = new System.Drawing.Size(100, 20);
this.textDescription.TabIndex = 14;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(259, 143);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(60, 13);
this.label1.TabIndex = 15;
this.label1.Text = "Description";
//
// textName
//
this.textName.Location = new System.Drawing.Point(152, 163);
this.textName.Name = "textName";
this.textName.Size = new System.Drawing.Size(100, 20);
this.textName.TabIndex = 16;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(262, 170);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 17;
this.label2.Text = "Name";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(16, 11);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(283, 13);
this.label3.TabIndex = 18;
this.label3.Text = "Right Click on a link to retrieve properties. Left Click to visit";
//
// textLinkData
//
this.textLinkData.Location = new System.Drawing.Point(152, 191);
this.textLinkData.Name = "textLinkData";
this.textLinkData.Size = new System.Drawing.Size(100, 20);
this.textLinkData.TabIndex = 19;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(262, 198);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(53, 13);
this.label4.TabIndex = 20;
this.label4.Text = "Link Data";
//
// checkBoxEnabled
//
this.checkBoxEnabled.AutoSize = true;
this.checkBoxEnabled.Location = new System.Drawing.Point(151, 218);
this.checkBoxEnabled.Name = "checkBoxEnabled";
this.checkBoxEnabled.Size = new System.Drawing.Size(65, 17);
this.checkBoxEnabled.TabIndex = 21;
this.checkBoxEnabled.Text = "Enabled";
this.checkBoxEnabled.UseVisualStyleBackColor = true;
//
// AddLink
//
this.AddLink.Location = new System.Drawing.Point(385, 64);
this.AddLink.Name = "AddLink";
this.AddLink.Size = new System.Drawing.Size(75, 23);
this.AddLink.TabIndex = 22;
this.AddLink.Text = "Add Link";
this.AddLink.UseVisualStyleBackColor = true;
this.AddLink.Click += new System.EventHandler(this.AddLink_Click);
//
// btnAmendLink
//
this.btnAmendLink.Enabled = false;
this.btnAmendLink.Location = new System.Drawing.Point(385, 99);
this.btnAmendLink.Name = "btnAmendLink";
this.btnAmendLink.Size = new System.Drawing.Size(75, 23);
this.btnAmendLink.TabIndex = 23;
this.btnAmendLink.Text = "AmendLink";
this.btnAmendLink.UseVisualStyleBackColor = true;
//
// checkBoxVisited
//
this.checkBoxVisited.AutoSize = true;
this.checkBoxVisited.Location = new System.Drawing.Point(151, 241);
this.checkBoxVisited.Name = "checkBoxVisited";
this.checkBoxVisited.Size = new System.Drawing.Size(57, 17);
this.checkBoxVisited.TabIndex = 24;
this.checkBoxVisited.Text = "Visited";
this.checkBoxVisited.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.Controls.Add(this.textBox1);
this.panel1.Location = new System.Drawing.Point(474, 13);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(200, 239);
this.panel1.TabIndex = 25;
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(200, 239);
this.textBox1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(704, 264);
this.Controls.Add(this.panel1);
this.Controls.Add(this.checkBoxVisited);
this.Controls.Add(this.btnAmendLink);
this.Controls.Add(this.AddLink);
this.Controls.Add(this.checkBoxEnabled);
this.Controls.Add(this.label4);
this.Controls.Add(this.textLinkData);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.textName);
this.Controls.Add(this.label1);
this.Controls.Add(this.textDescription);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.lbllabel2);
this.Controls.Add(this.nudLinkAreaEnd);
this.Controls.Add(this.lbllabel1);
this.Controls.Add(this.nudLinkAreaStart);
this.Controls.Add(this.llblinkLabel1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.nudLinkAreaStart)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudLinkAreaEnd)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.LinkLabel llblinkLabel1;
private System.Windows.Forms.ColorDialog colorDialog1;
private System.Windows.Forms.Button btnLinkColor;
private System.Windows.Forms.Button btnActiveLinkColor;
private System.Windows.Forms.Button btnVisitedLinkColor;
private System.Windows.Forms.NumericUpDown nudLinkAreaStart;
private System.Windows.Forms.Label lbllabel1;
private System.Windows.Forms.NumericUpDown nudLinkAreaEnd;
private System.Windows.Forms.Label lbllabel2;
private System.Windows.Forms.ComboBox cmbLinkBehaviour;
private System.Windows.Forms.Label lbllabel3;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox textDescription;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textLinkData;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox checkBoxEnabled;
private System.Windows.Forms.Button AddLink;
private System.Windows.Forms.Button btnAmendLink;
private System.Windows.Forms.CheckBox checkBoxVisited;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TextBox textBox1;
}
}
</code></pre>
<p>Please can someone advise. Is the problem that there is no windows handle for the LinkLabel when its Paint event occurs.</p>
<p>Many thanks in advance</p>
<p>Tony</p>
| [
{
"answer_id": 7297967,
"author": "Chamika Sandamal",
"author_id": 880434,
"author_profile": "https://Stackoverflow.com/users/880434",
"pm_score": 1,
"selected": false,
"text": "ColorDialog"
},
{
"answer_id": 7298042,
"author": "Damith",
"author_id": 2558060,
"author_profile": "https://Stackoverflow.com/users/2558060",
"pm_score": 0,
"selected": false,
"text": " private void AddLink_Click(object sender, EventArgs e)\n {\n // do proper validation and add only proper links\n // this will help you to avoid the exception \n if (!string.IsNullOrEmpty(textLinkData.Text) && \n nudLinkAreaEnd.Value > 0 && \n nudLinkAreaStart.Value >= 0 && \n nudLinkAreaStart.Value < llblinkLabel1.Text.Length)\n {\n LinkLabel.Link link = new LinkLabel.Link();\n link.Description = textDescription.Text.ToString();\n link.LinkData = textLinkData.Text.ToString();\n link.Name = textName.Text.ToString();\n link.Enabled = checkBoxEnabled.Checked;\n link.Visited = checkBoxVisited.Checked;\n link.Start = (int)nudLinkAreaStart.Value;\n link.Length = (int)nudLinkAreaEnd.Value;\n try\n {\n llblinkLabel1.Links.Add(link); \n }\n catch (InvalidOperationException exception) // links can't overlap \n {\n MessageBox.Show(\"Links are overlaping\");\n }\n\n }\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,964 | <p>Is there any lib that convert very long numbers to string just copying the data?</p>
<p>These one-liners are too slow:</p>
<pre><code>def xlong(s):
return sum([ord(c) << e*8 for e,c in enumerate(s)])
def xstr(x):
return chr(x&255) + xstr(x >> 8) if x else ''
print xlong('abcd'*1024) % 666
print xstr(13**666)
</code></pre>
| [
{
"answer_id": 328967,
"author": "ironfroggy",
"author_id": 19687,
"author_profile": "https://Stackoverflow.com/users/19687",
"pm_score": 2,
"selected": false,
"text": "packed = struct.pack('l', 123456)\nassert struct.unpack('l', packed)[0] == 123456\n"
},
{
"answer_id": 329011,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "from binascii import hexlify, unhexlify\n\ndef xstr(x):\n hex = '%x' % x\n return unhexlify('0'*(len(hex)%2) + hex)[::-1]\n\ndef xlong(s):\n return int(hexlify(s[::-1]), 16)\n"
},
{
"answer_id": 329079,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "dumps"
},
{
"answer_id": 329127,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": -1,
"selected": false,
"text": "cPickle"
},
{
"answer_id": 366576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "PyObject * _PyLong_FromByteArray( const unsigned char* bytes, size_t n, int little_endian, int is_signed);\nint _PyLong_AsByteArray(PyLongObject* v, unsigned char* bytes, size_t n, int little_endian, int is_signed);\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,965 | <p>Does anyone know how to auto-mount an <a href="http://aws.amazon.com/ebs/" rel="nofollow noreferrer">Elastic Block Storage</a> (EBS) volume when starting a Windows 2003 instance in Amazon's <a href="http://aws.amazon.com/ec2/" rel="nofollow noreferrer">Elastic Compute Cloud</a> (EC2)?</p>
| [
{
"answer_id": 422575,
"author": "Chris Markle",
"author_id": 1505846,
"author_profile": "https://Stackoverflow.com/users/1505846",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/ruby\n\nrequire 'rubygems'\nrequire 'right_aws'\nrequire 'net/http'\n\nurl = 'http://169.254.169.254/2008-02-01/meta-data/instance-id'\ninstance_id = Net::HTTP.get_response(URI.parse(url)).body\n\nAMAZON_PUBLIC_KEY='your public key'\nAMAZON_PRIVATE_KEY='your private key'\nEC2_LOG_VOL='the volume id'\n\nec2 = RightAws::Ec2.new(AMAZON_PUBLIC_KEY, AMAZON_PRIVATE_KEY)\n\nvol = ec2.attach_volume(EC2_LOG_VOL, instance_id, '/dev/sdh')\nputs vol\n\n# It can take a few seconds for the volume to become ready.\n# This is just to make sure it is ready before mounting it.\nsleep 20\n\nsystem('mount /dev/sdh /mymountpoint')\n"
},
{
"answer_id": 1400623,
"author": "jsw",
"author_id": 168826,
"author_profile": "https://Stackoverflow.com/users/168826",
"pm_score": 3,
"selected": true,
"text": "REM @echo off\nREM setlocal ENABLEDELAYEDEXPANSION\n\nC:\\WINDOWS\\system32\\eventcreate /l SYSTEM /t information /id 100 /so AttachEbsBoot /d \"Starting attach-ebs-boot.cmd\"\n\nREM local variables\nREM Make sure you include the directory with curl.exe and the EC2 command line tools in the path\nset path=C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;c:\\Utils;C:\\ebin\\ec2\\bin\nset JAVA_HOME=c:\\java\nset EC2_HOME=c:\\ebin\\ec2\nset EC2_CERT=<your_cert>\nset EC2_PRIVATE_KEY=<your_private_key>\n\nREM Please note: you should use the Ec2 Config Serive Settings application to ensure\nREM that your EBS volume is mapped to a particular drive letter.\nREM\nREM edit as needed\nset EBS_DRIVE=P:\nset EBS_DEVICE=xvdp\n\nREM Test to see if the drive is already attached. If it is then we're done.\nif exist %EBS_DRIVE%\\nul (goto done)\n\nREM get the EBS volume ID from the user data and the instance ID from the meta-data\nfor /f \"delims=\" %%a in ('curl http://169.254.169.254/latest/user-data') do (set EBS_VOLUME=%%a)\nfor /f \"delims=\" %%b in ('curl http://169.254.169.254/latest/meta-data/instance-id') do (set INSTANCE_ID=%%b)\n\nC:\\WINDOWS\\system32\\eventcreate /l SYSTEM /t information /id 102 /so AttachEbsBoot /d \"Volume == %EBS_VOLUME%\"\nC:\\WINDOWS\\system32\\eventcreate /l SYSTEM /t information /id 103 /so AttachEbsBoot /d \"Instance == %INSTANCE_ID%\"\n\nREM attach the volume\nREM \nREM Use a series of set command to build the command line\nSET COMMAND_LINE=%EBS_VOLUME%\nSET COMMAND_LINE=%COMMAND_LINE% -i\nSET COMMAND_LINE=%COMMAND_LINE% %INSTANCE_ID%\nSET COMMAND_LINE=%COMMAND_LINE% -d\nSET COMMAND_LINE=%COMMAND_LINE% %EBS_DEVICE%\n\nC:\\WINDOWS\\system32\\eventcreate /l SYSTEM /t information /id 104 /so AttachEbsBoot /d \"calling ec2attvole %COMMAND_LINE%\"\n\ncall ec2attvol.cmd %COMMAND_LINE%\n\n:DONE\nC:\\WINDOWS\\system32\\eventcreate /l SYSTEM /t information /id 101 /so AttachEbsBoot /d \"Exiting attach-ebs-boot.cmd\"\n\nREM Events logged in the System event log\nREM source === AttachEbsBoot\nREM \nREM Event 100 - Script start\nREM Event 101 - Script end\nREM Event 102 - Volume ID\nREM Event 103 - Instance ID\nREM Event 104 - Command line for ec2attvol\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16997/"
] |
328,976 | <p>Give me some of your thoughts on which is a better coding practice/makes more efficient code/looks prettier/whatever: Increasing and improving your ability to use if statements to anticipate and catch potential problems? Or simply making good use of try/catch in general?</p>
<p>Let's say this is for Java (if it matters).</p>
<p><strong>Edit:</strong> I'm presently transitioning myself away from some admittedly out-dated and constrained current coding practices, but I'm a little torn on the necessity of doing so on a few points (such as this). I'm simply asking for some perspectives on this. Not a debate.</p>
| [
{
"answer_id": 328998,
"author": "Karl",
"author_id": 36093,
"author_profile": "https://Stackoverflow.com/users/36093",
"pm_score": 3,
"selected": false,
"text": "if"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19825/"
] |
329,020 | <p>I have set up a sort of introspection-enabling C++ library that allows, using minimum macros and a fair amount of template trickery, to declare structures and classes that get enriched with some meta-information.</p>
<p>This meta-information captures all important details about each field of the struct/class that you declare, and at the end of the story you are able, for each struct/class enriched in this way, to produce an xml file that dumps, for each field, its name,type,len,offset etc. etc.</p>
<p>For my problem, I don't need to support fields that are pointers, but only primitive types, arrays and STL containers (vectors, lists etc.)</p>
<p>The code that populates these meta-enriched structs/classes (the "producer"), at a certain point serializes them (for now it's a simple binary dump of all primitive types and of all the "buffers" used by the STL containers, if any).</p>
<p>Now I need to start developing a "reader" counterpart that is able <strong>at runtime</strong>, starting from the xml description that has been built by the "producer", to access the various fields of the stored data.</p>
<p>I think it's a problem of dynamic data-dictionary interpretation, but all that I have found up to know is related to read back xml data, while I have binary data and an xml description of it...</p>
<p>What is the best way to start on this? Is something out there that resembles this problem and that I could get inspiration from?</p>
| [
{
"answer_id": 334544,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " class xmlstream\n {\n ...\n };\n\n class ibase\n {\n void read( xmlstream& rStream ) = 0;\n void write( xmlstream& rStream ) = 0;\n };\n\n class classfactory\n {\n void produce( xmlstream& rStream );\n void consume( xmlstream& rStream ); \n ibase* create( xmlstream& rStream );\n void destroy( ibase* pBase );\n };\n\n class class1 : public ibase\n {\n static class1* create( );\n static void destroy( class1* pObject );\n void read( xmlstream& rStream );\n void write( xmlstream& rStream );\n };\n\n class class2 : public ibase\n {\n static class1* create( );\n static void destroy( class1* pObject );\n void read( xmlstream& rStream );\n void write( xmlstream& rStream );\n };\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41789/"
] |
329,029 | <p>The title basically spells it out. What interfaces have you written that makes you proud and you use a lot. I guess the guys that wrote <code>IEnumerable<T></code> and not least <code>IQueryable<T></code> had a good feeling after creating those.</p>
| [
{
"answer_id": 329045,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "IEnumerable"
},
{
"answer_id": 329106,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "public interface IDataProducer<T>\n{\n event Action<T> DataProduced;\n event Action EndOfData;\n}\n"
},
{
"answer_id": 329271,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 0,
"selected": false,
"text": "public interface ICheckable<T>\n{\n CheckResult Apply(T target);\n}\n"
},
{
"answer_id": 329412,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 0,
"selected": false,
"text": "public interface IDisposable {\n public function dispose():void;\n}\n"
},
{
"answer_id": 329425,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 1,
"selected": false,
"text": "public interface IValidatable {\n bool IsValid { get; set; }\n void ShowValidationFailureMessage(string message);\n}\n\npublic interface ISubmitable {\n event EventHandler Submit;\n void ShowSubmitFailureMessage(string message);\n void ShowSubmitSuccessMessage(string message);\n}\n\npublic interface ICancelable {\n event EventHandler Cancel;\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29519/"
] |
329,033 | <p>In .NET there is the <code>CultureInfo</code> class in the <code>System.Globalization</code> namespace. It has two similar properties both returning values of the <code>CultureInfo</code> type: <code>CurrentCulture</code> and <code>CurrentUICulture</code>.</p>
<p>What is the difference between them? </p>
<p>Which one should I use when and why?</p>
| [
{
"answer_id": 329041,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 10,
"selected": true,
"text": "CurrentCulture"
},
{
"answer_id": 3627020,
"author": "foxontherock",
"author_id": 437946,
"author_profile": "https://Stackoverflow.com/users/437946",
"pm_score": 7,
"selected": false,
"text": "(date, currency, double).tostring = CurrentCulture\n\nresource.fr-CA.resx file = currentUICulture\n"
},
{
"answer_id": 33939766,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 4,
"selected": false,
"text": "CurrentCulture"
},
{
"answer_id": 33940632,
"author": "Ivaylo Slavov",
"author_id": 795158,
"author_profile": "https://Stackoverflow.com/users/795158",
"pm_score": 4,
"selected": false,
"text": "CurrentCulture"
},
{
"answer_id": 37189019,
"author": "Sebris87",
"author_id": 2211125,
"author_profile": "https://Stackoverflow.com/users/2211125",
"pm_score": 4,
"selected": false,
"text": "CurrentUICulture"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
329,039 | <p>I would like to write a program that will identify a machine( for licensing purposes), I tought about getting the following information and to compile an xml file with this data:</p>
<ol>
<li>MAC address.</li>
<li>CPU data (serial, manufacture, etc)</li>
<li>MotherBoard Identification. (serial, manufacture, etc)</li>
</ol>
<p>can someone refer me to a lib that provide such information - I write my program in c++ and have troubles to find such a lib.</p>
<p>Should I dig in the registry for this information? </p>
<p>Many Thanks,
ofer</p>
| [
{
"answer_id": 329096,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 0,
"selected": false,
"text": "/** *************************************\n\n return string containing first MAC address on computer\n\n NOTE: requires adding Iphlpapi.lib to project\n\n */\nstring GetMac()\n{\n char data[4096];\n ZeroMemory( data, 4096 );\n unsigned long len = 4000;\n PIP_ADAPTER_INFO pinfo = ( PIP_ADAPTER_INFO ) data;\n char sbuf[20];\n string sret;\n\n DWORD ret = GetAdaptersInfo( pinfo, &len );\n if( ret != ERROR_SUCCESS )\n return string(\"**ERROR**\");\n\n for(int k = 0; k < 5; k++ ) {\n sprintf(sbuf,\"%02X-\",pinfo->Address[k]);\n sret += sbuf;\n }\n sprintf(sbuf,\"%02X\",pinfo->Address[5]);\n sret += sbuf;\n\n return( sret );\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33030/"
] |
329,043 | <p>I need a conditional compilation switch that knows if I am compiling for the mono or MS .NET runtime. How can I do this? </p>
| [
{
"answer_id": 329072,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 7,
"selected": true,
"text": "__MonoCS__"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024/"
] |
329,044 | <p>I'm using the following as a way of seeing listing the various methods in my developement</p>
<pre><code>print basename(__FILE__) . "::serve_table()"
</code></pre>
<p>is there any function that's able to return the name of a class method so I don't have to trpe it each time?</p>
| [
{
"answer_id": 329047,
"author": "grepsedawk",
"author_id": 14388,
"author_profile": "https://Stackoverflow.com/users/14388",
"pm_score": 3,
"selected": false,
"text": "__FUNCTION__"
},
{
"answer_id": 329050,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "debug_backtrace"
},
{
"answer_id": 329052,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 1,
"selected": false,
"text": "$class = new ReflectionCLass(\"classname\");\n$methods = $class->getMethods();\nforeach($methods as $m)\n print $m->getName();\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
329,058 | <p>Why do you think Microsoft wants us to go through IEnumerable to get to IEnumerator? Isn't the presence or absence of a valid cast to IEnumerator for a given type enough to determine if the type is enumerable or not?</p>
<p>For example whats wrong with the following?</p>
<pre><code>class MyClass : IEnumerator
{
...
}
MyClass myObj = new MyClass();
if(myObj as IEnumerator != null)
{
Console.WriteLine("myObj is enumerable");
}
else
{
Console.WriteLine("myObj doesn't support enumeration");
}
</code></pre>
| [
{
"answer_id": 329551,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 1,
"selected": false,
"text": "int matchCount = 0;\n\nforeach (var x in myList)\n{\n foreach (var y in myList)\n {\n if (x == y)\n matchCount++;\n }\n}\n\nmatchCount /= 2;\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39648/"
] |
329,059 | <p>This is a second-hand question from an OS development site, but it made me curious since I couldn't find a decent explanation anywhere.</p>
<p>When compiling and linking a free-standing C++ program using gcc, sometimes a linker error like this occurs:</p>
<pre><code>out/kernel.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0'
</code></pre>
<p>This is apparently because this symbol is defined in libstdc++, which is missing in a free-standing environment. Fixing the problem simply requires defining this symbol somewhere:</p>
<pre><code>void *__gxx_personality_v0;
</code></pre>
<p>Which is nice, but I don't like things that just magically work... So the question is, what is the purpose of this symbol?</p>
| [
{
"answer_id": 329101,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "libstd++"
},
{
"answer_id": 329161,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "gcc"
},
{
"answer_id": 329195,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 8,
"selected": true,
"text": "-fno-exceptions"
},
{
"answer_id": 24774864,
"author": "jlguenego",
"author_id": 2474330,
"author_profile": "https://Stackoverflow.com/users/2474330",
"pm_score": 3,
"selected": false,
"text": "CLIENT.C"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3121/"
] |
329,061 | <p>What are the tensions between multithreading and exception-safety in C++? Are there good guidelines to follow? Does a thread terminate because of an uncaught exception?</p>
| [
{
"answer_id": 329084,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": true,
"text": "terminate()"
},
{
"answer_id": 329478,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "terminate()"
},
{
"answer_id": 330778,
"author": "coryan",
"author_id": 33325,
"author_profile": "https://Stackoverflow.com/users/33325",
"pm_score": 2,
"selected": false,
"text": "class Foo {\npublic:\n void set_value(std::string const & s);\n\n std::string const & value() const;\n};\n"
},
{
"answer_id": 331018,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "throw;\n"
},
{
"answer_id": 493310,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 3,
"selected": false,
"text": "namespace std {\n\n typedef unspecified exception_ptr;\n\n exception_ptr current_exception();\n void rethrow_exception( exception_ptr p );\n\n template< class E > exception_ptr copy_exception( E e );\n}\n"
},
{
"answer_id": 493421,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "T t;\nt = q.front(); // may throw\nq.pop();\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19630/"
] |
329,063 | <p>For example so that it works like this
toString (Var x)= "x"</p>
| [
{
"answer_id": 329070,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 1,
"selected": false,
"text": "show"
},
{
"answer_id": 1711075,
"author": "Michael Steele",
"author_id": 71116,
"author_profile": "https://Stackoverflow.com/users/71116",
"pm_score": 0,
"selected": false,
"text": "{-# LANGUAGE DeriveDataTypeable #-}\n\nmodule Main where\n\nimport Data.Data\n\ndata Var a = Var a\ndata X = X deriving (Data, Typeable)\n\ntoString :: Data a => Var a -> String\ntoString (Var c) = show (toConstr c)\n\nmain :: IO ()\nmain = putStrLn $ \"toString (Var x)= \" ++ show (toString (Var X))\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41000/"
] |
329,065 | <p>I have a stored procedure that returns values from a temp table. In my DBML, it displays (None) for the return type. What is the trick to get it to recognize the columns from my temp table?</p>
<pre><code>CREATE PROCEDURE [dbo].[GetCategoryPriceRanges]
@CategoryId int
AS
BEGIN
DECLARE @MinPrice money, @MaxPrice money
SELECT @MinPrice = MIN(ourPrice),@MaxPrice = MAX(ourPrice)
DECLARE @loopCatch int
--catch infinite loops
SELECT @loopCatch = 1
WHILE @thisLow <= @maxPrice AND @loopCatch < 100
BEGIN
INSERT INTO #prices(lowRange, hiRange) VALUES (@thisLow, @thisHigh)
SET @thisLow = @thisHigh + 1
SET @thisHigh = 2 * @thisLow - 1
SELECT @loopCatch = @loopCatch + 1
END
SELECT * FROM #prices
DROP TABLE #prices
END
</code></pre>
| [
{
"answer_id": 3896813,
"author": "brooks",
"author_id": 470968,
"author_profile": "https://Stackoverflow.com/users/470968",
"pm_score": 0,
"selected": false,
"text": "SET FMTONLY OFF"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
329,118 | <p>I need to activate a JButton ActionListener within a JDialog so I can do some unit testing using JUnit.</p>
<p>Basically I have this:</p>
<pre><code> public class MyDialog extends JDialog {
public static int APPLY_OPTION= 1;
protected int buttonpressed;
protected JButton okButton;
public MyDialog(Frame f) {
super(f);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonpressed= APPLY_OPTION;
}
} );
public int getButtonPressed() {
return buttonpressed;
}
}
</code></pre>
<p>then I have my JUnit file:</p>
<pre><code>public class testMyDialog {
@Test
public void testGetButtonPressed() {
MyDialog fc= new MyDialog(null);
fc.okButton.???????? //how do I activate the ActionListener?
assertEquals(MyDialog.APPLY_OPTION, fc.getButtonPressed());
}
}
</code></pre>
<p>This may sound redundant to do in a unit test, but the actual class is a lot more complicated than that...</p>
| [
{
"answer_id": 329153,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": true,
"text": "AbstractButton.doClick"
},
{
"answer_id": 330204,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 1,
"selected": false,
"text": "JButton button = (JButton)PrivateAccessor.get(MyDialog , \"okButton\");\nThread t = new Thread(new Runnable() {\n public void run() {\n // What ever you want\n };\n});\n\nt.start();\n\nbutton.doClick();\n\nt.join();\n"
},
{
"answer_id": 62638984,
"author": "Hywel Griffiths",
"author_id": 10707242,
"author_profile": "https://Stackoverflow.com/users/10707242",
"pm_score": 0,
"selected": false,
"text": "@Test\n@DisplayName(\"ActionListener test\")\nvoid testActionListener(){\n HelpWindow helpWindow = new HelpWindow(\"menu\");\n\n assertDoesNotThrow(() -> helpWindow.getReturnButton().doClick());\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485/"
] |
329,142 | <p>Every time I start Visual Studio 2008, the first time I try to run the project I get the error CS0006 The metadata file ... could not be found. If I do a rebuild of the complete solution it works.</p>
<p>Some information about the solution:</p>
<ul>
<li><p>I'm building in debug mode and Visual Studio complains about not finding dll:s in the release folder.</p></li>
<li><p>The projects Visual Studio complains about are used by many other projects in the solution.</p></li>
<li><p>I have changed the default output path of all projects to a ......\build\debug\ProjectName and ......\build\release\ProjectName respectively. (Just to get all build files in one directory)</p></li>
<li><p>I have the same problem with a another solution. </p></li>
<li><p>The solution was created from scratch.</p></li>
<li><p>There are 9 projects in the solution. One WPF and 8 class libraries using dotnet 3.5.</p></li>
</ul>
<p>Any ideas on what is causing this problem?</p>
| [
{
"answer_id": 9921584,
"author": "maksim09",
"author_id": 1133426,
"author_profile": "https://Stackoverflow.com/users/1133426",
"pm_score": 2,
"selected": false,
"text": "C:\\WINDOWS\\microsoft.net\\framework\\v…\\Temporary ASP.NET File\\"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] |
329,144 | <p>This is a question brought up in a local user group mailing list at dot.net.nz ...</p>
<blockquote>
<p>I when I create an XHTML page
old-fashioned way, I used to use the
following syntax for my CSS
declarations:</p>
</blockquote>
<pre><code><link rel=”stylesheet” type=”text/css” media=”screen” href=”css/screen.css” />
<link rel=”stylesheet” type=”text/css” media=”print” href=”css/printer.css” />
</code></pre>
<blockquote>
<p>Now, since I code using ASP.NET 2.0
and beyond; I fell in love with the
Themes. However, I don’t know how to
do the same thing using Themes.</p>
</blockquote>
| [
{
"answer_id": 329179,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": 1,
"selected": false,
"text": "@media print\n{\n /* Print CSS rules here */\n}\n"
},
{
"answer_id": 329182,
"author": "gius",
"author_id": 19712,
"author_profile": "https://Stackoverflow.com/users/19712",
"pm_score": 4,
"selected": true,
"text": "@media print\n{\n p\n {\n ...\n }\n\n ...put styles here.\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377/"
] |
329,145 | <p>Assuming the following directory structure,</p>
<pre><code>htdocs/
images/
css/
.htaccess
system/
index.php
...
</code></pre>
<p>I would like to route all incoming requests through that php script. I have been trying some rewrite rules within the htaccess, but I can't seem to be able to route to files that are outside the document root. I couldn't find a reason for this in the apache manuals, so eventually resorted to "Include" an apache config file, where the rules are different.</p>
<p>Is there a way of rewriting outside of the docroot?</p>
| [
{
"answer_id": 329173,
"author": "Robert K",
"author_id": 24950,
"author_profile": "https://Stackoverflow.com/users/24950",
"pm_score": 2,
"selected": false,
"text": "index.php"
},
{
"answer_id": 329176,
"author": "rojoca",
"author_id": 41967,
"author_profile": "https://Stackoverflow.com/users/41967",
"pm_score": 3,
"selected": true,
"text": "# ignore anything that's an actual file (eg CSS, js, images) \nRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f\n# redirect all other traffic to the index page\nRewriteRule ^.*$ index.php [L]\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1951/"
] |
329,151 | <p>jQuery selectors are wonderful, but I sometimes I find myself typing them over and over, and it gets a little annoying.</p>
<pre><code> $('#mybutton').click(function() {
$('#message-box').doSomething();
$('#message-box').doSomethingElse();
$('#message-box').attr('something', 'something');
});
</code></pre>
<p>So often I like to cache my objects in variables:</p>
<pre><code>$('#mybutton').click(function() {
var msg = $('#message-box');
msg.doSomething();
msg.doSomethingElse();
// you get the idea
});
</code></pre>
<p>Are there any pros or cons between these two patterns? Sometimes it feels like creating the variables is extra work, but sometimes it saves my fingers a lot of typing. Are there any memory concerns to be aware of? Do selectors clean up nicely after being used, whereas my bad coding habits tends to keep the vars in memory longer?</p>
<p>This doesn't keep me up at night, but I am curious. Thanks.</p>
<p>EDIT: Please see <a href="https://stackoverflow.com/questions/291841/does-jquery-do-any-kind-of-caching-of-selectors">this question</a>. It essentially asks the same thing, but I like the answer better.</p>
| [
{
"answer_id": 329155,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 5,
"selected": true,
"text": "$('#mybutton').click(function() {\n $('#message-box').doSomething().doSomethingElse().attr('something', 'something');\n });\n"
},
{
"answer_id": 14057939,
"author": "Joshua Gruber",
"author_id": 361546,
"author_profile": "https://Stackoverflow.com/users/361546",
"pm_score": 0,
"selected": false,
"text": "$('#mybutton').click(function() {\n var msg = $('#message-box');\n msg.doSomething();\n if (msg.hasClass('.something')) {\n msg.dosomethingElse();\n }\n});\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4636/"
] |
329,174 | <p>I've been asked to measure the performance of a fortran program that solves differential equations on a multi-CPU system. My employer insists that I measure FLOP/s (Floating operations per second) and compare the results with benchmarks (<a href="http://www.netlib.org/linpack/" rel="noreferrer">LINPACK</a>) but I am not convinced that it's the way to go, simply because no one can explain to me what a FLOP is.</p>
<p>I did some research on what exactly a FLOP is and I got some pretty contradicting answers. One of the most popular answers I got was '1 FLOP = An addition and a multiplication operation'. Is that true? If so, again, physically, what exactly does that mean?</p>
<p>Whatever method I end up using, it has to be scalable. Some of versions of the code solve systems with multi-million unknowns and takes days to execute.</p>
<p>What would be some other, effective, ways of measuring performance in my case (summary of my case being 'fortran code that does a whole lot of arithmetic calculations over and over again for days on several hundred CPUs)?</p>
| [
{
"answer_id": 988121,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "exp()"
},
{
"answer_id": 64246807,
"author": "m1m1k",
"author_id": 738895,
"author_profile": "https://Stackoverflow.com/users/738895",
"pm_score": 0,
"selected": false,
"text": "\"(# of parallel GPU processing cores multiplied by peak clock speed in MHz multiplied by two) divided by 1,000,000\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39473/"
] |
329,197 | <p>In <code>SQL Server</code>, I can do something like this:</p>
<pre><code>UPDATE tbl1
SET col2 = tbl2.col2
FROM table1 tbl1
INNER JOIN table2 tbl2
ON tbl1.col1 = tbl2.col1
</code></pre>
<p>I haven't bothered to look whether this is part of any SQL standard or not, and I'm sure there are other ways to do it, but it is <em>astoundingly</em> useful.</p>
<p>Here's my problem. I need to do something similar <em>in SQL</em> (i.e, not a host language) with SQLITE3. Can it be done?</p>
| [
{
"answer_id": 329208,
"author": "Gregory Higley",
"author_id": 27779,
"author_profile": "https://Stackoverflow.com/users/27779",
"pm_score": 1,
"selected": false,
"text": "INSERT OR REPLACE INTO"
},
{
"answer_id": 2509921,
"author": "Trey Jackson",
"author_id": 6148,
"author_profile": "https://Stackoverflow.com/users/6148",
"pm_score": 6,
"selected": true,
"text": "UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1)\n"
},
{
"answer_id": 14114198,
"author": "apjs",
"author_id": 1941521,
"author_profile": "https://Stackoverflow.com/users/1941521",
"pm_score": 3,
"selected": false,
"text": "UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1)"
},
{
"answer_id": 71513707,
"author": "P-Gn",
"author_id": 1735003,
"author_profile": "https://Stackoverflow.com/users/1735003",
"pm_score": 1,
"selected": false,
"text": "UPDATE FROM"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27779/"
] |
329,210 | <p>When creating a UIView with a navigation bar in interface builder, the top bar takes some space, but the view still has the same size. This mean that the bottom of the view is not visible.</p>
<p>Is there a way to get the "visible size" of a UIView? I would like to show a subview at the bottom of the screen, but part of the subview is hidden since the parent view goes "below" the screen.</p>
| [
{
"answer_id": 329597,
"author": "Matt Gallagher",
"author_id": 36103,
"author_profile": "https://Stackoverflow.com/users/36103",
"pm_score": 2,
"selected": false,
"text": "view"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9936/"
] |
329,213 | <p>I'm experimenting with the Tiny MCE editor. We also use jQuery, and I noticed that the standard Tiny MCE install includes a file called <code>tiny_mce_jquery.js</code>. Can anyone enlighten me as to what that's for? Oddly, I can't find anything about it online. Should I reference it in addition to the standard Tiny MCE script, or instead of? Does it provide anything additional or just avoid incompatibilities? </p>
| [
{
"answer_id": 329597,
"author": "Matt Gallagher",
"author_id": 36103,
"author_profile": "https://Stackoverflow.com/users/36103",
"pm_score": 2,
"selected": false,
"text": "view"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
329,216 | <p>First off, I apologize if this doesn't make sense. I'm new to XHTML, CSS and JavaScript.</p>
<p>I gather that in XHTML, the correct way to have a nested page is as follows (instead of an iframe):</p>
<pre><code><object name="nestedPage" data="http://abc.com/page.html" type="text/html"
width="500" height="400" />
</code></pre>
<p>If I have a nested page like that - is it possible to change the stylesheet used by the nested page at runtime using JavaScript in the parent page? Ideally this would happen immediately so that the nested page would never be visible with its original stylesheet.</p>
<p>Please assume that you do not have control of the original source code of the nested page, yet it is <strong>on the same domain</strong> (don't ask)</p>
| [
{
"answer_id": 329222,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 0,
"selected": false,
"text": "<iframe>s"
},
{
"answer_id": 329233,
"author": "Javache",
"author_id": 1074,
"author_profile": "https://Stackoverflow.com/users/1074",
"pm_score": 2,
"selected": false,
"text": "$(\"link [rel=stylesheet]\", myFrame).attr('href', <new-url>);\n"
},
{
"answer_id": 329313,
"author": "nsdel",
"author_id": 40807,
"author_profile": "https://Stackoverflow.com/users/40807",
"pm_score": 3,
"selected": true,
"text": "d = document.getElementsByTagName('object').namedItem('nestedPage').getContentDocument();\nd.styleSheets[d.styleSheets.length].href = 'whereever';\n"
},
{
"answer_id": 331838,
"author": "mahemoff",
"author_id": 18706,
"author_profile": "https://Stackoverflow.com/users/18706",
"pm_score": 1,
"selected": false,
"text": "function applyCSS(css) {\n // http://www.quirksmode.org/bugreports/archives/2006/01/IE_wont_allow_documentcreateElementstyle.html\n if (BrowserDetect.browser==\"Safari\" || BrowserDetect.browser==\"Opera\") { /* good for FF too */\n var styleNode = document.createElement(\"style\");\n styleNode.setAttribute(\"type\", \"text/css\");\n styleNode.appendChild(document.createTextNode(css)); \n head.appendChild(styleNode); \n } else {\n var div = document.createElement(\"div\");\n div.innerHTML = \"<p>x</p><style>\"+css+\"</style>\";\n document.body.appendChild(div.childNodes[1]);\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82/"
] |
329,252 | <p>Greetings,</p>
<p>I have problems (when trying to print from c# to certain printers that do not have large print areas. Is there a way to shrink to printable area (like Adobe Acrobat do)? Thanks!</p>
| [
{
"answer_id": 329372,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "System.Drawing.Printing"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34920/"
] |
329,256 | <p>What's the best way to consume REST web services from .NET?</p>
| [
{
"answer_id": 329885,
"author": "Shane K",
"author_id": 4643,
"author_profile": "https://Stackoverflow.com/users/4643",
"pm_score": 5,
"selected": false,
"text": "using System.Net; \n\nstring param = \"hello\";\n\nstring url = String.Format(\"http://somedomain.com/samplerequest?greeting={0}\",param);\n\nWebClient serviceRequest = new WebClient();\nstring response = serviceRequest.DownloadString(new Uri(url));\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
329,259 | <p>I have an MPI program which compiles and runs, but I would like to step through it to make sure nothing bizarre is happening. Ideally, I would like a simple way to attach GDB to any particular process, but I'm not really sure whether that's possible or how to do it. An alternative would be having each process write debug output to a separate log file, but this doesn't really give the same freedom as a debugger.</p>
<p>Are there better approaches? How do you debug MPI programs?</p>
| [
{
"answer_id": 843436,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "static void DebugWait(int rank) {\n char a;\n\n if(rank == 0) {\n scanf(\"%c\", &a);\n printf(\"%d: Starting now\\n\", rank);\n } \n\n MPI_Bcast(&a, 1, MPI_BYTE, 0, MPI_COMM_WORLD);\n printf(\"%d: Starting now\\n\", rank);\n}\n"
},
{
"answer_id": 2364825,
"author": "messenjah",
"author_id": 284571,
"author_profile": "https://Stackoverflow.com/users/284571",
"pm_score": 7,
"selected": false,
"text": "mpirun -np <NP> xterm -e gdb ./program \n"
},
{
"answer_id": 5145188,
"author": "akintayo",
"author_id": 210710,
"author_profile": "https://Stackoverflow.com/users/210710",
"pm_score": 2,
"selected": false,
"text": "mpirun -np <NP> xterm -e gdb ./program \n"
},
{
"answer_id": 10850963,
"author": "RSFalcon7",
"author_id": 1392758,
"author_profile": "https://Stackoverflow.com/users/1392758",
"pm_score": 1,
"selected": false,
"text": "mpirun -gdb"
},
{
"answer_id": 17881783,
"author": "Wesley Bland",
"author_id": 491687,
"author_profile": "https://Stackoverflow.com/users/491687",
"pm_score": 5,
"selected": false,
"text": "mpiexec -n X gdb ./a.out\n"
},
{
"answer_id": 24480711,
"author": "user3788566",
"author_id": 3788566,
"author_profile": "https://Stackoverflow.com/users/3788566",
"pm_score": 3,
"selected": false,
"text": "screen"
},
{
"answer_id": 44717078,
"author": "gagiuntoli",
"author_id": 7539010,
"author_profile": "https://Stackoverflow.com/users/7539010",
"pm_score": 3,
"selected": false,
"text": "tmux"
},
{
"answer_id": 52173222,
"author": "stranger",
"author_id": 10316894,
"author_profile": "https://Stackoverflow.com/users/10316894",
"pm_score": 2,
"selected": false,
"text": "$ mpirun -np <num_of_proc> <prog> <prog_args>\n"
},
{
"answer_id": 65106503,
"author": "Sorush",
"author_id": 2543510,
"author_profile": "https://Stackoverflow.com/users/2543510",
"pm_score": 0,
"selected": false,
"text": "xterm"
},
{
"answer_id": 74151284,
"author": "s417-lama",
"author_id": 11599242,
"author_profile": "https://Stackoverflow.com/users/11599242",
"pm_score": 0,
"selected": false,
"text": "mpitx"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] |
329,264 | <p>I have Swing java application with network communications to several "Players" that are represented as player objects, each with their own communication thread. The app has a "Team" object managing all player objects. Several UI components listen to events passed from the players through the Team object. </p>
<p>In my design, the team object fires all events on the Swing thread using invokeLater, so that the rest of my application does not need to bother with threading issues. However, I don't know how I can test the Team class in a JUnit test.</p>
<p>A little more background. At first I had the Team object fire its events on the player object threads (no thread switching at all). The Team unit test succeeded, but I got into many threading issues in my UI with invokeLaters and synchronized all over the place. I then decided to simplify the threading model by having the Team object fire events on the Swing thread, but now the Team unit test fails because it does not receive the events. What to do?</p>
<p>A solution that comes to mind is to introduce an extra object on top of Team that does the thread switch and keep the original unit test intact, but I do not like the idea of introducing complexity in production code just to make a unit test succeed.</p>
| [
{
"answer_id": 329387,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "EventQueue.invokeLater"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18756/"
] |
329,307 | <p>I'm revisiting som old code of mine and have stumbled upon a method for getting the title of a website based on its url. It's not really what you would call a stable method as it often fails to produce a result and sometimes even produces incorrect results. Also, sometimes it fails to show some of the characters from the title as they are of an alternative encoding.</p>
<p>Does anyone have suggestions for improvements over this old version?</p>
<pre><code>public static string SuggestTitle(string url, int timeout)
{
WebResponse response = null;
string line = string.Empty;
try
{
WebRequest request = WebRequest.Create(url);
request.Timeout = timeout;
response = request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
StreamReader streamRead = new System.IO.StreamReader(streamReceive, encoding);
while(streamRead.EndOfStream != true)
{
line = streamRead.ReadLine();
if (line.Contains("<title>"))
{
line = line.Split(new char[] { '<', '>' })[2];
break;
}
}
}
catch (Exception) { }
finally
{
if (response != null)
{
response.Close();
}
}
return line;
}
</code></pre>
<p>One final note - I would like the code to run faster as well, as it is blocking until the page as been fetched, so if I can get only the site header and not the entire page, it would be great.</p>
| [
{
"answer_id": 329324,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 7,
"selected": true,
"text": "WebClient x = new WebClient();\nstring source = x.DownloadString(\"http://www.singingeels.com/\");\n"
},
{
"answer_id": 49487198,
"author": "Roberto B",
"author_id": 2641447,
"author_profile": "https://Stackoverflow.com/users/2641447",
"pm_score": 3,
"selected": false,
"text": "using HtmlAgilityPack;\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
329,309 | <p>Just wondering if there is any way (in C) to get the contents of the console buffer, preferably as some kind of char array. It is going to be written to a file, so if I am missing out on something stupid that will do exactly that, then point it out. It can be Windows-specific. I am using MinGW (gcc 3.4.5).</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 330787,
"author": "plan9assembler",
"author_id": 1710672,
"author_profile": "https://Stackoverflow.com/users/1710672",
"pm_score": 1,
"selected": false,
"text": "rl_line_buffer\n"
},
{
"answer_id": 40433532,
"author": "nikau6",
"author_id": 2780612,
"author_profile": "https://Stackoverflow.com/users/2780612",
"pm_score": 2,
"selected": false,
"text": "GetNumCharsInConsoleBuffer"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41981/"
] |
329,333 | <p>Has anybody seen such a thing? Small self-sufficient modules are preferred.</p>
| [
{
"answer_id": 329338,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": ">>> from sympy import *\n>>> a = Rational(1,2)\n\n>>> a\n1/2\n\n>>> a*2\n1\n\n>>> Rational(2)**50/Rational(10)**50\n1/88817841970012523233890533447265625\n"
},
{
"answer_id": 330691,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "fractions"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310/"
] |
329,355 | <p>I'm using .NET 3.5, trying to recursively delete a directory using:</p>
<pre><code>Directory.Delete(myPath, true);
</code></pre>
<p>My understanding is that this should throw if files are in use or there is a permissions problem, but otherwise it should delete the directory and all of its contents.</p>
<p>However, I occasionally get this:</p>
<pre><code>System.IO.IOException: The directory is not empty.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
...
</code></pre>
<p>I'm not surprised that the method sometimes throws, but I'm surprised to get this particular message when recursive is true. (I <em>know</em> the directory is not empty.)</p>
<p>Is there a reason I'd see this instead of AccessViolationException?</p>
| [
{
"answer_id": 329502,
"author": "Jeremy Edwards",
"author_id": 42005,
"author_profile": "https://Stackoverflow.com/users/42005",
"pm_score": 8,
"selected": false,
"text": "Directory.Delete"
},
{
"answer_id": 981360,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "File.SetAttributes(target_dir, FileAttributes.Normal);\nDirectory.Delete(target_dir, false);\n"
},
{
"answer_id": 1703799,
"author": "rpisryan",
"author_id": 207291,
"author_profile": "https://Stackoverflow.com/users/207291",
"pm_score": 8,
"selected": false,
"text": "a"
},
{
"answer_id": 7518831,
"author": "Demid",
"author_id": 959668,
"author_profile": "https://Stackoverflow.com/users/959668",
"pm_score": 2,
"selected": false,
"text": " public static void DeleteDirectory(string target_dir)\n {\n DeleteDirectoryFiles(target_dir);\n while (Directory.Exists(target_dir))\n {\n lock (_lock)\n {\n DeleteDirectoryDirs(target_dir);\n }\n }\n }\n\n private static void DeleteDirectoryDirs(string target_dir)\n {\n System.Threading.Thread.Sleep(100);\n\n if (Directory.Exists(target_dir))\n {\n\n string[] dirs = Directory.GetDirectories(target_dir);\n\n if (dirs.Length == 0)\n Directory.Delete(target_dir, false);\n else\n foreach (string dir in dirs)\n DeleteDirectoryDirs(dir);\n }\n }\n\n private static void DeleteDirectoryFiles(string target_dir)\n {\n string[] files = Directory.GetFiles(target_dir);\n string[] dirs = Directory.GetDirectories(target_dir);\n\n foreach (string file in files)\n {\n File.SetAttributes(file, FileAttributes.Normal);\n File.Delete(file);\n }\n\n foreach (string dir in dirs)\n {\n DeleteDirectoryFiles(dir);\n }\n }\n"
},
{
"answer_id": 10860157,
"author": "Piyush Soni",
"author_id": 501004,
"author_profile": "https://Stackoverflow.com/users/501004",
"pm_score": 4,
"selected": false,
"text": "Process.Start(\"cmd.exe\", \"/c \" + @\"rmdir /s/q C:\\Test\\TestDirectoryContainingReadOnlyFiles\"); \n"
},
{
"answer_id": 14933880,
"author": "Andrey Tarantsov",
"author_id": 58146,
"author_profile": "https://Stackoverflow.com/users/58146",
"pm_score": 6,
"selected": false,
"text": "private static void DeleteRecursivelyWithMagicDust(string destinationDir) {\n const int magicDust = 10;\n for (var gnomes = 1; gnomes <= magicDust; gnomes++) {\n try {\n Directory.Delete(destinationDir, true);\n } catch (DirectoryNotFoundException) {\n return; // good!\n } catch (IOException) { // System.IO.IOException: The directory is not empty\n System.Diagnostics.Debug.WriteLine(\"Gnomes prevent deletion of {0}! Applying magic dust, attempt #{1}.\", destinationDir, gnomes);\n\n // see http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true for more magic\n Thread.Sleep(50);\n continue;\n }\n return;\n }\n // depending on your use case, consider throwing an exception here\n}\n"
},
{
"answer_id": 16321356,
"author": "citykid",
"author_id": 857848,
"author_profile": "https://Stackoverflow.com/users/857848",
"pm_score": 2,
"selected": false,
"text": "public class IOUtils\n{\n public static void DeleteDirectory(string directory)\n {\n Directory.GetFiles(directory, \"*\", SearchOption.AllDirectories).ForEach(File.Delete);\n Directory.Delete(directory, true);\n }\n}\n"
},
{
"answer_id": 20214706,
"author": "Roman",
"author_id": 905439,
"author_profile": "https://Stackoverflow.com/users/905439",
"pm_score": 1,
"selected": false,
"text": "<healthMonitoring enabled=\"true\">\n <rules>\n <add name=\"MyAppLogEvents\" eventName=\"Application Lifetime Events\" provider=\"EventLogProvider\" profile=\"Critical\"/>\n </rules>\n</healthMonitoring>\n"
},
{
"answer_id": 20430675,
"author": "Reactgular",
"author_id": 1031569,
"author_profile": "https://Stackoverflow.com/users/1031569",
"pm_score": -1,
"selected": false,
"text": "DirectoryInfo"
},
{
"answer_id": 25681266,
"author": "Olivier de Rivoyre",
"author_id": 740362,
"author_profile": "https://Stackoverflow.com/users/740362",
"pm_score": 4,
"selected": false,
"text": "Directory.CreateDirectory(@\"C:\\Temp\\a\\b\\c\\\");\nProcess.Start(@\"C:\\Temp\\a\\b\\c\\\");\nThread.Sleep(1000);\nDirectory.Delete(@\"C:\\Temp\\a\\b\\c\");\nDirectory.Delete(@\"C:\\Temp\\a\\b\");\nDirectory.Delete(@\"C:\\Temp\\a\");\n"
},
{
"answer_id": 31531223,
"author": "Rob",
"author_id": 4141167,
"author_profile": "https://Stackoverflow.com/users/4141167",
"pm_score": 1,
"selected": false,
"text": "public static void rmdir(string target, bool recursive)\n{\n string tfilename = Path.GetDirectoryName(target) +\n (target.Contains(Path.DirectorySeparatorChar.ToString()) ? Path.DirectorySeparatorChar.ToString() : string.Empty) +\n Path.GetRandomFileName();\n Directory.Move(target, tfilename);\n Directory.Delete(tfilename, recursive);\n}\n"
},
{
"answer_id": 38777415,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 2,
"selected": false,
"text": " public static void DeleteDirectory(string dir, bool secondAttempt = false)\n {\n // If this is a second try, we are going to manually \n // delete the files and sub-directories. \n if (secondAttempt)\n {\n // Interrupt the current thread to allow Explorer time to release a directory handle\n Thread.Sleep(0);\n\n // Delete any files in the directory \n foreach (var f in Directory.GetFiles(dir, \"*.*\", SearchOption.TopDirectoryOnly))\n File.Delete(f);\n\n // Try manually recursing and deleting sub-directories \n foreach (var d in Directory.GetDirectories(dir))\n DeleteDirectory(d);\n\n // Now we try to delete the current directory\n Directory.Delete(dir, false);\n return;\n }\n\n try\n {\n // First attempt: use the standard MSDN approach.\n // This will throw an exception a directory is open in explorer\n Directory.Delete(dir, true);\n }\n catch (IOException)\n {\n // Try again to delete the directory manually recursing. \n DeleteDirectory(dir, true);\n }\n catch (UnauthorizedAccessException)\n {\n // Try again to delete the directory manually recursing. \n DeleteDirectory(dir, true);\n } \n }\n"
},
{
"answer_id": 40311471,
"author": "Pat Pattillo",
"author_id": 3195974,
"author_profile": "https://Stackoverflow.com/users/3195974",
"pm_score": 0,
"selected": false,
"text": "// delete any existing update content folder for this update\nif (await fileHelper.DirectoryExistsAsync(currentUpdateFolderPath))\n await fileHelper.DeleteDirectoryAsync(currentUpdateFolderPath);\n"
},
{
"answer_id": 40550211,
"author": "HostageBrain",
"author_id": 5093432,
"author_profile": "https://Stackoverflow.com/users/5093432",
"pm_score": 1,
"selected": false,
"text": "\\\\\\\\?\\C:\\mydir"
},
{
"answer_id": 40789093,
"author": "jettatore",
"author_id": 3374491,
"author_profile": "https://Stackoverflow.com/users/3374491",
"pm_score": 4,
"selected": false,
"text": "Directory.Delete(myPath, true);\n"
},
{
"answer_id": 44324346,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 4,
"selected": false,
"text": "Thread.Sleep"
},
{
"answer_id": 47766250,
"author": "cahit beyaz",
"author_id": 1639347,
"author_profile": "https://Stackoverflow.com/users/1639347",
"pm_score": 2,
"selected": false,
"text": " /// <summary>\n /// Depth-first recursive delete, with handling for descendant \n /// directories open in Windows Explorer.\n /// </summary>\n public static void DeleteDirectory(string path)\n {\n foreach (string directory in Directory.GetDirectories(path))\n {\n Thread.Sleep(1);\n DeleteDir(directory);\n }\n DeleteDir(path);\n }\n\n private static void DeleteDir(string dir)\n {\n try\n {\n Thread.Sleep(1);\n Directory.Delete(dir, true);\n }\n catch (IOException)\n {\n DeleteDir(dir);\n }\n catch (UnauthorizedAccessException)\n {\n DeleteDir(dir);\n }\n }\n"
},
{
"answer_id": 53052622,
"author": "Mauricio Rdz",
"author_id": 6669688,
"author_profile": "https://Stackoverflow.com/users/6669688",
"pm_score": 0,
"selected": false,
"text": "bool deleted = false;\n do\n {\n try\n {\n Directory.Delete(rutaFinal, true); \n deleted = true;\n }\n catch (Exception e)\n {\n string mensaje = e.Message;\n if( mensaje == \"The directory is not empty.\")\n Thread.Sleep(50);\n }\n } while (deleted == false);\n"
},
{
"answer_id": 58768689,
"author": "nzrytmn",
"author_id": 3193030,
"author_profile": "https://Stackoverflow.com/users/3193030",
"pm_score": 2,
"selected": false,
"text": " var directoryInfo = new DirectoryInfo(\"My directory path\");\n // Delete all files from app data directory.\n\n foreach (var subDirectory in directoryInfo.GetDirectories())\n {\n subDirectory.Delete(true);// true set recursive paramter, when it is true delete sub file and sub folder with files too\n }\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142/"
] |
329,359 | <p>I faced a little trouble - I do not know if I can define my own operators for my classes.
For example:<br></p>
<pre><code>type
TMinMatrix = class(TMatrix)
private
RowAmount: Byte;
ColAmount: Byte;
Data: DataMatrix;
DemVector, SupVector: SupplyDemand;
public
constructor Create(Rows, Cols: Byte);
function GetRowAmount: Byte; override;
function GetColAmount: Byte; override;
destructor Destroy;
end;
</code></pre>
<p>How can I - or can`t I:) - do something like:</p>
<pre><code>TMinMatrix TMinMatrix::operator=(TMinMatrix* matr) (c++ code)
</code></pre>
<p>And, by the way, can I define copy constructor for my class?</p>
| [
{
"answer_id": 329901,
"author": "Gerry Coll",
"author_id": 22545,
"author_profile": "https://Stackoverflow.com/users/22545",
"pm_score": 2,
"selected": false,
"text": "TSubclass(Dest).Field1 := Field1;\nTSubclass(Dest).Field2 := Field2;\n"
},
{
"answer_id": 1384477,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "type\n TMinMatrix = class(TMatrix)\n public\n A : integer;\n class operator Add( ATM, BTM : TMinMatrix ) : TMinMatrix;\n // CTM := ATM + BTM\n class operator Subtract( ATM, BTM : TMinMatrix ) : TMinMatrix;\n // CTM := ATM - BTM;\n end;\n\nclass operator TMinMatrix.Add( ATM, BTM : TMinMatrix ) : TMinMatrix;\n begin\n result := ATM.A + BTM.A;\n end;\n\nclass operator TMinMatrix.Subtract( ATM, BTM : TMinMatrix ) : TMinMatrix;\n begin\n result := ATM.A - BTM.A;\n end;\n\n\nvar\n A, B, C : TMinMatrix;\nbegin\n C := A + B; // calls Add()\n C := B - A; // calls Subtract()\nend.\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
329,399 | <p>In C++, on the stack, a simple variable is assigned a memory address so that we can use a pointer to contain this memory to point to it; then is a pointer also assigned a memory address?</p>
<p>If yes, can we have a pointer of pointers?</p>
| [
{
"answer_id": 329403,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "int a;\nint b;\nint * pa = &a;\nint ** ppa = &pa;\n\n// set a to 10\n**ppa = 10;\n\n// set pa so it points to b. and then set b to 11.\n*ppa = &b;\n**ppa = 11;\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36064/"
] |
329,411 | <p>config file :</p>
<pre><code><system.net>
<mailSettings>
<smtp from="YYYYY@xxxxxx.com">
<network
host="mail.xxxxxx.com"
port="25"
password="password"
userName="user@xxxxxx.com"
defaultCredentials="false"
/>
</smtp>
</mailSettings>
</system.net>
</code></pre>
<p>I've already tried defaultCredentials="true" but i recieved following message:</p>
<p>System.FormatException: Smtp server returned an invalid response.</p>
<p>how to fix the problem?</p>
| [
{
"answer_id": 329432,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<configuration>\n <system.net>\n <mailSettings>\n <smtp from=\"YYYYY@xxxxxx.com\">\n <network host=\"mail.xxxxxx.com\" port=\"25\" password=\"password\" userName=\"user@xxxxxx.com\" defaultCredentials=\"false\"/>\n </smtp>\n </mailSettings>\n </system.net>\n<configuration>\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
329,423 | <p>I understand how Map is easily parallelizable - each computer/CPU can just operate on a small portion of the array.</p>
<p>Is Reduce/foldl parallelizable? It seems like each computation depends on the previous one. Is it just parallelizable for certain types of functions?</p>
| [
{
"answer_id": 329461,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 1,
"selected": false,
"text": "// Original\nresult = null;\nforeach(item in map) {\n result += item;\n}\n\n// Parallel\nresultArray = array();\nmapParts = map.split(numThreads);\nforeach(thread) {\n result = null;\n foreach(item in mapParts[thread]) {\n result += item;\n }\n resultArray += result; // Lock this!\n}\nwaitForThreads();\nreduce(resultArray);\n"
},
{
"answer_id": 329465,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 5,
"selected": true,
"text": "a + b + c + d\n \\ / \\ /\n (a+b) (c+d)\n \\ /\n ((a+b)+(c+d))\n"
},
{
"answer_id": 329507,
"author": "Jules",
"author_id": 40078,
"author_profile": "https://Stackoverflow.com/users/40078",
"pm_score": 3,
"selected": false,
"text": "step 1: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8\nstep 2: 3 + 7 + 11 + 15\nstep 3: 10 + 26\nstep 4: 36\n"
},
{
"answer_id": 2226302,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 1,
"selected": false,
"text": "step 1: 1 + 2 + 3 + 4 \nstep 2: 3 + 7 \nstep 3: 10 \n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
329,429 | <p>You know how Subversion stores a copy of every file it has checked-out in the hidden .svn folders? The website I'm building is pretty big (has over 1Gig of PDF files). These PDF files will very rarely change throughout the existence of the website.</p>
<p>I was wondering if there was a way of telling Subversion that it shouldn't store a local revision copy of a certain set of files (my PDF files) but just sync with the server whenever a change is made to any of these files?</p>
| [
{
"answer_id": 329433,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "svn export"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] |
329,447 | <p>I've got a form inside an <code><asp:Content></code> block that is being submitted to a controller. For one of the controls, I need to get some information from it directly that won't happen automatically by calling <code>UpdateModel()</code>.</p>
<p>However, in the <code>Request.Form</code> dictionary, the control's id is of the mangled form <code>ctl00$ContentPlaceHolder${name}</code>. Given that I'm in the controller, and know nothing about the view at this point, what is the proper way of accessing the control's data?</p>
<p>Here is what the view (.aspx) looks like (removed extraneous code):</p>
<pre><code><%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" AutoEventWireup="true"
CodeBehind="...." Inherits="...." %>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<form id="form1" action="..." method="post">
<FCKeditorV2:FCKeditor ID="AuthorBio" runat="server" Height="250"/>
<input type="submit" value="Save" />
</form>
</asp:Content>
</code></pre>
<p>The control named <code>AuthorBio</code> shows up in the controller in the <code>Form.Request</code> dictionary as <code>ctl00$ContentPlaceHolder$AuthorBio$</code></p>
<p>The reason I'm trying to use the 3rd-party control with "runat-server" is because I need to set the editor's Value as follows: </p>
<pre><code>AuthorBio.Value = HttpUtility.HtmlDecode(ViewData.Model.Bio);
</code></pre>
<p>Trying to do this in the .aspx file in the FCKeditorV2 tag doesn't work. (Or maybe I'm missing something there too)</p>
<p>Ok, so the key is to use the JavaScript version of the editor rather than the wrapped control. There was also a handy comment that I'm going to include here to accompany the accepted answer:</p>
<blockquote>
<p>you should use the javascript version
of the FCKEditor control not the .NET
custom control as the .NET custom
control was built on the WebForms
paradigm. The JS version should have a
hidden field for the value of the Html
which you can access in your
controller using Request["FieldName"]</p>
</blockquote>
| [
{
"answer_id": 329552,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "string editorKey = null;\nforeach (string key in Request.Form.Keys)\n{\n if (key.EndsWith( \"$AuthorBio\" ))\n {\n editorKey = key;\n break;\n }\n}\n\nif (!string.IsNullOrEmpty( editorKey ))\n{\n ... process\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9913/"
] |
329,477 | <p>I have an SQL 2005 table, let's call it Orders, in the format:</p>
<pre><code>OrderID, OrderDate, OrderAmount
1, 25/11/2008, 10
2, 25/11/2008, 2
3, 30/1002008, 5
</code></pre>
<p>Then I need to produce a report table showing the ordered amount on each day in the last 7 days:</p>
<pre><code>Day, OrderCount, OrderAmount
25/11/2008, 2, 12
26/11/2008, 0, 0
27/11/2008, 0, 0
28/11/2008, 0, 0
29/11/2008, 0, 0
30/11/2008, 1, 5
</code></pre>
<p>The SQL query that would normally produce this:</p>
<pre><code>select count(*), sum(OrderAmount)
from Orders
where OrderDate>getdate()-7
group by datepart(day,OrderDate)
</code></pre>
<p>Has a problem in that it will skip the days where there are no orders:</p>
<pre><code>Day, OrderCount, OrderAmount
25/11/2008, 2, 12
30/11/2008, 1, 5
</code></pre>
<p>Normally I would fix this using a tally table and outer join against rows there, but I'm really looking for a simpler or more efficient solution for this. It seems like such a common requirement for a report query that some elegant solution should be available for this already. </p>
<p>So: 1. Can this result be obtain from a simple query without using tally tables?</p>
<p>and 2. If no, can we create this tally table (reliably) on the fly (I can create a tally table using CTE but recursion stack limits me to 100 rows)?</p>
| [
{
"answer_id": 329515,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE #MyDates ( TargetDate DATETIME )\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 0, 101))\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 1, 101))\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 2, 101))\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 3, 101))\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 4, 101))\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 5, 101))\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 6, 101))\nINSERT INTO #MyDates VALUES CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE() - 7, 101))\n\nSELECT CONVERT(VARCHAR, TargetDate, 101) AS Date, COUNT(*) AS OrderCount\nFROM dbo.Orders INNER JOIN #MyDates ON Orders.Date = #MyDates.TargetDate\nGROUP BY blah blah blah (you know the rest)\n"
},
{
"answer_id": 3538780,
"author": "user427265",
"author_id": 427265,
"author_profile": "https://Stackoverflow.com/users/427265",
"pm_score": 1,
"selected": false,
"text": "select count(*), sum(OrderAmount)\nfrom Orders\nwhere OrderDate>getdate()-7\n and sum(OrderAmount) > 0 or sum(OrderAmount) = 0\ngroup by datepart(day,OrderDate)\n"
},
{
"answer_id": 4020987,
"author": "C73",
"author_id": 487216,
"author_profile": "https://Stackoverflow.com/users/487216",
"pm_score": 2,
"selected": false,
"text": "SELECT datename(DW,nDays) TimelineDays, \n Convert(varchar(10), nDays, 101) TimelineDate,\n ISNULL(SUM(Counter),0) Totals \nFROM (Select GETDATE() AS nDays\n union Select GETDATE()-1\n union Select GETDATE()-2\n union Select GETDATE()-3\n union Select GETDATE()-4\n union Select GETDATE()-5\n union Select GETDATE()-6) AS tDays\n\nLeft Join (Select * From tHistory Where Account = 1000) AS History\n on (DATEPART(year,nDays) + DATEPART(MONTH,nDays) + DATEPART(day,nDays)) = \n (DATEPART(year,RecordDate) + DATEPART(MONTH,RecordDate) + DATEPART(day,RecordDate)) \nGROUP BY nDays\nORDER BY nDays DESC\n"
},
{
"answer_id": 4519216,
"author": "Suvabrata Roy",
"author_id": 552415,
"author_profile": "https://Stackoverflow.com/users/552415",
"pm_score": 1,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[sp_Myforeach_Date]\n -- Add the parameters for the stored procedure here\n @SatrtDate as DateTime,\n @EndDate as dateTime,\n @DatePart as varchar(2),\n @OutPutFormat as int \nAS\nBEGIN\n -- SET NOCOUNT ON added to prevent extra result sets from\n -- interfering with SELECT statements.\n Declare @DateList Table\n (Date varchar(50))\n\n WHILE @SatrtDate<= @EndDate\n BEGIN\n INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))\n IF Upper(@DatePart)='DD'\n SET @SatrtDate= DateAdd(dd,1,@SatrtDate)\n IF Upper(@DatePart)='MM'\n SET @SatrtDate= DateAdd(mm,1,@SatrtDate)\n IF Upper(@DatePart)='YY'\n SET @SatrtDate= DateAdd(yy,1,@SatrtDate)\n END \n SELECT * FROM @DateList\nEND\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
] |
329,490 | <p>in Microsoft Access, is there a way which I can programatically set the Confirm Action Queries flag on the options screen to False? Ideally when the database is started up I would like to check if it's true, and if so, mark it as false for the currently logged in user.</p>
<p>The application is locked down reasonably tightly, so ideally, we don't want to have to give users acces to the action menu.</p>
<p>Thanks in advance.</p>
<p>PG</p>
| [
{
"answer_id": 329524,
"author": "Harry Steinhilber",
"author_id": 6118,
"author_profile": "https://Stackoverflow.com/users/6118",
"pm_score": 2,
"selected": true,
"text": "If Application.GetOption(\"Confirm Action Queries\") Then\n Application.SetOption \"Confirm Action Queries\", False\nEnd If\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] |
329,497 | <p>i have code like, sorry i dont have the exact code now. but its valid.</p>
<pre><code><iframe src="..." borderframe="0" scrolling="no" width=728px" height="90px"></iframe>
</code></pre>
<p>the target is a html file that contains code for a banner.
everything displays well. but when i resize browser or go to maximize. the content is shiftet to the left by 1 pixel. so the banner is displayed missing the first vertical 1px line. and only 727px is visible.</p>
<p>anyone has an idea?</p>
<p>thank you.</p>
| [
{
"answer_id": 780820,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "0.5px"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
329,498 | <p>I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.</p>
<p>What's included, and where can I get other good quality libraries from?</p>
| [
{
"answer_id": 329510,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 5,
"selected": true,
"text": "try:\n import foobar\nexcept:\n print 'No foobar module'\n"
},
{
"answer_id": 329518,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 4,
"selected": false,
"text": "pydoc -p 8080\n"
},
{
"answer_id": 329519,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 0,
"selected": false,
"text": ">>> import math\n>>> dir(math)\n['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']\n>>> help( math.log )\nHelp on built-in function log in module math:\n\nlog(...)\n log(x[, base]) -> the logarithm of x to the given base.\n If the base not specified, returns the natural logarithm (base e) of x.\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
] |
329,500 | <p>I would like to use <code>[Authorize]</code> for every action in my admin controller except the <code>Login</code> action. </p>
<pre><code>[Authorize (Roles = "Administrator")]
public class AdminController : Controller
{
// what can I place here to disable authorize?
public ActionResult Login()
{
return View();
}
}
</code></pre>
| [
{
"answer_id": 329562,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": true,
"text": "[AdminAuthorize (Roles = \"Administrator\", Exempt = \"Login, Logout\") ]\npublic class AdminController : Controller\n{\n public ActionResult Login()\n {\n return View();\n }\n\n public ActionResult Login()\n {\n return View();\n }\n\n ... other, restricted actions ...\n}\n"
},
{
"answer_id": 329578,
"author": "MrJavaGuy",
"author_id": 7138,
"author_profile": "https://Stackoverflow.com/users/7138",
"pm_score": 3,
"selected": false,
"text": " protected override void OnAuthorization(AuthorizationContext filterContext)\n {\n if ((string)(filterContext.RouteData.Values[\"action\"]) == \"Login\")\n {\n filterContext.Cancel = true;\n filterContext.Result = Login();\n }\n }\n"
},
{
"answer_id": 11554471,
"author": "Azat",
"author_id": 188862,
"author_profile": "https://Stackoverflow.com/users/188862",
"pm_score": 1,
"selected": false,
"text": "public class SelectableAuthorizeAttribute : AuthorizeAttribute\n{\n public SelectableAuthorizeAttribute(params Type[] typesToExclude)\n {\n _typesToExlude = typesToExclude;\n }\n\n private readonly Type[] _typesToExlude;\n\n public override void OnAuthorization(AuthorizationContext filterContext)\n {\n bool skipAuthorization = _typesToExlude.Any(type => filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == type);\n\n if (!skipAuthorization)\n {\n base.OnAuthorization(filterContext);\n }\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31624/"
] |
329,516 | <p>I'm using the following code to have a non-JS navigation:</p>
<pre><code><ol id="navigation">
<li id="home"><a href="#"><img src="./images/nav/home-hover.png" alt="Home" /></li>
...
</ol>
</code></pre>
<p>And the CSS:</p>
<pre><code>#navigation a {
display: block;
height: 25px;
}
#navigation a img {
display: none;
}
#navigation a:hover img {
display: block;
}
#home a {
background: url('./images/nav/home-normal.png') no-repeat;
width: 100px;
}
</code></pre>
<p>My problem is they won't change images on hover in IE6. I'm using the <code>:hover</code> on an anchor so that should be fine and am using <code>display</code> rather than <code>visibility</code> which is another thing that doesn't work in IE6.</p>
<p>I'd really like not having to add a load of javascript for image replacing/preloading (embedding something like jQuery isn't an option) - can anyone help me here?</p>
<p>Thanks,</p>
| [
{
"answer_id": 329550,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": true,
"text": "<a>"
},
{
"answer_id": 329992,
"author": "Jason",
"author_id": 22786,
"author_profile": "https://Stackoverflow.com/users/22786",
"pm_score": 1,
"selected": false,
"text": "<ol>\n <li><a href=\"#\"></a></li>\n</ol>\n"
},
{
"answer_id": 341238,
"author": "Wayne Austin",
"author_id": 31109,
"author_profile": "https://Stackoverflow.com/users/31109",
"pm_score": 2,
"selected": false,
"text": "#home a { \n background: url('./images/nav/home-normal.png') no-repeat left top; \n width: 100px;\n}\n#home a:hover { \n background-position:left bottom;\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] |
329,517 | <p>There is a simple C++ method to use pattern matching on strings? The code should sound like this:</p>
<pre><code>if (regexpcmp("l?nole*[0-9]", "linoleum1")) {
//we have a match!
} else {
//no match
}
</code></pre>
| [
{
"answer_id": 329522,
"author": "Reunanen",
"author_id": 19254,
"author_profile": "https://Stackoverflow.com/users/19254",
"pm_score": 4,
"selected": false,
"text": "const boost::regex e(\"l?nole*[0-9]\");\nif (regex_match(\"linoleum1\", e)) {\n //we have a match!\n} else {\n //no match \n}\n"
},
{
"answer_id": 329527,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": true,
"text": "pcre"
},
{
"answer_id": 329531,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "pcrecpp"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39796/"
] |
329,535 | <p>What's the best way to get a list of users that are assigned to a SharePoint portal?</p>
| [
{
"answer_id": 333183,
"author": "Ryan Smith",
"author_id": 10420,
"author_profile": "https://Stackoverflow.com/users/10420",
"pm_score": 2,
"selected": false,
"text": "Dim Site As New SPSite(\"SiteURL\")\nDim AllUsers As SPUserCollection = Site.RootWeb.AllUsers\nDim u As SPUser\nFor Each u In AllUsers\n Response.Write(u.LoginName & \" \" & u.Name & \" \" & u.Email & \"<br />\")\nNext\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10420/"
] |
329,547 | <p>I have some code that I am putting in the code-behind of a master page. This master page is my main layout and the purpose of the code is to check whether the user is logged in and take the appropriate action depending on whether they are or not. I would be interested in hearing alternate methods on how to approach this, but I am doing it this way for now as it is a direct port from another MVC framework, and I want to alter as little code or flow as possible during the port.</p>
<p>My real question is, how do I determine the name of the current controller, action, and view that are being executed? Some of the logic in the code-behind depends on knowing the current page name. To be specific, it says (pseudocode):</p>
<pre><code>if (!isLoggedIn && !isLoginPage)
Redirect(loginPage);
</code></pre>
<p>So, I need to know whether I am on the login page already to avoid an infinite redirect loop. I am currently achieving this by examining the Url to see if it contains the string /Login/, but this is hacky and I would rather use a more robust and intelligent method.</p>
| [
{
"answer_id": 330171,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<authentication mode=\"Forms\">\n <forms loginUrl=\"~/Account/Login\"/>\n</authentication>\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.