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
|
---|---|---|---|---|---|---|
224,009 |
<p>Session variables are normally keept in the web server RAM memory.</p>
<p>In a cluster, each request made by a client can be handled by a different cluster node. right?!</p>
<p>So, in this case... </p>
<ul>
<li>What happens with session variables? Aren't they stored in the nodes RAM memory? </li>
<li>How the other nodes will handled my request correctly if it doesn't have my session variables, or at least all of it?</li>
<li>This issue is treated by the web server (Apache, IIS) or by the language runtime (PHP, ASP.NET, Ruby, JSP)?</li>
</ul>
<p>EDIT: Is there some solution for <strong>Classic ASP</strong>?</p>
|
[
{
"answer_id": 224012,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 0,
"selected": false,
"text": "<p>In ASP.NET you can persist session data to an SQL Server database which is common to all web servers in the cluster.</p>\n\n<p>Once configured (in the web.config for your site), the framework handles all of the persistance for you and you can access the session data as normal.</p>\n"
},
{
"answer_id": 224015,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 3,
"selected": false,
"text": "<p>There are 3 ways to store session state in ASP.NET. The first is in process, where the variables are stored in memory. The second is to use a session state service by putting the following in your web.config file:</p>\n\n<pre><code><sessionState\n mode=\"StateServer\"\n stateConnectionString=\"tcpip=127.0.0.1:42424\"\n sqlConnectionString=\"data source=127.0.0.1;user id=sa;password=\"\n cookieless=\"false\"\n timeout=\"20\" />\n</code></pre>\n\n<p>As you can see in the stateConnectionString attribute, the session state service can be located on a different computer.</p>\n\n<p>The third option is to use a centralized SQL database. To do that, you put the following in your web.config: </p>\n\n<pre><code><sessionState\n mode=\"SQLServer\"\n stateConnectionString=\"tcpip=127.0.0.1:42424\"\n sqlConnectionString=\n \"data source=SERVERHAME;user id=sa;password=\"\n cookieless=\"false\"\n timeout=\"20\"\n/>\n</code></pre>\n\n<p>More details on all of these options are written up here: <a href=\"http://www.ondotnet.com/pub/a/dotnet/2003/03/24/sessionstate.html\" rel=\"noreferrer\">http://www.ondotnet.com/pub/a/dotnet/2003/03/24/sessionstate.html</a></p>\n"
},
{
"answer_id": 224019,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 2,
"selected": false,
"text": "<p>Get a Linux machine and set up <a href=\"http://www.danga.com/memcached\" rel=\"nofollow noreferrer\">http://www.danga.com/memcached</a> . Its speed is unbeatable compared to other approaches. (for example, cookies, form hidden variables, databases)</p>\n"
},
{
"answer_id": 224053,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 2,
"selected": false,
"text": "<p>As with all sorts of thing, \"it depends\".</p>\n\n<p>There are different solutions and approaches.</p>\n\n<p>As mentioned, there's the concept of a centralized store for session state (database, memcached, shared file system, etc.).</p>\n\n<p>There are also cluster wide caching systems available that make local data available to all of the machines in the cluster. Conceptually it's similar to the centralized session state store, but this data isn't persistent. Rather it lives within the individual nodes and is replicated using some mechanism provided by your provider.</p>\n\n<p>Another method is server pinning. When a client hits the cluster the first time, some mechanism (typically a load balancer fronting the cluster) pins the client to a specific server. In a typical client lifespan, that client will spend their entire time on a single machine.</p>\n\n<p>For the failover mechanism, each machine of the cluster is paired with another machine, and so any session changes are shared with the paired machine. Should the clients pinned machine encounter an issue, the client will hit another machine. At this point, perhaps due to cookies, the new machine sees that it's not the original machine for the client, so it pings both the original machine, and the paired machine for the clients session data.</p>\n\n<p>At that point the client may well be pinned to the new machine.</p>\n\n<p>Different platforms do it in different ways, including having no session state at all.</p>\n"
},
{
"answer_id": 224133,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 3,
"selected": false,
"text": "<p>To extend @yogman's answer.</p>\n\n<p><a href=\"http://www.danga.com/memcached\" rel=\"noreferrer\">Memcached</a> is pure awesomeness! It's a high performance and distributed object cache.</p>\n\n<p>And even though I mentioned distributed it's basically as simple as starting one instance on one of your spare/idle servers, you configure it as in ip, port and how much ram to use and you're done.</p>\n\n<pre><code>memcached -d -u www -m 2048 -l 10.0.0.8 -p 11211\n</code></pre>\n\n<p>(Runs memcached in daemon mode, as user www, 2048 MB (2 GB) of RAM on IP 10.0.0.8 with port 11211.)</p>\n\n<p>From then on, you ask memcached for data and if the data is not yet cached you pull it from the original source and store it in memcached. I'm sure you are familiar with cache basics.</p>\n\n<p>In a cluster environment you can link up your memcached's into a cluster and replicate the cache across your nodes. Memcached runs on Linux, Unix and Windows, start it anywhere you have spare RAM and start using your resources.</p>\n\n<p>APIs for memcached should be <a href=\"http://www.socialtext.net/memcached/index.cgi?clients\" rel=\"noreferrer\">generally available</a>. I'm saying <em>should</em> because I only know of Perl, Java and PHP. But I am sure that e.g. in Python people have means to leverage it as well. There is a <a href=\"http://www.socialtext.net/memcached/index.cgi\" rel=\"noreferrer\">memcached wiki</a>, in case you need pointers, or let me know in the comments if I was raving too much. ;)</p>\n"
},
{
"answer_id": 247742,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>With <a href=\"http://www.hazelcast.com\" rel=\"nofollow noreferrer\">Hazelcast</a>, you can either use Hazelcast distributed map to store and share sessions across the cluster or let Hazelcast Webapp Manager do everything for you. Please check out the docs for details. Hazelcast is a distributed/partitioned, super lite and easy, free data distribution solution for Java.</p>\n\n<p>Regards,</p>\n\n<p>-talip</p>\n\n<p><a href=\"http://www.hazelcast.com\" rel=\"nofollow noreferrer\">http://www.hazelcast.com</a></p>\n"
},
{
"answer_id": 280815,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 0,
"selected": false,
"text": "<p>As Will said, most load-balancing approaches will use some sort of stickiness in the way the distribute forthcoming requests from the same client, meaning, a unique client will hit the same server unless that actual server goes down.</p>\n\n<p>That minimizes the need of distribution of session-data, meaning that only in the eventual failure of a server, a client would loose his session. Depending on your app, this is more or less critical. In most cases, this is not a big issue.</p>\n\n<p>Even the simplest way of loadbalacing (round-rubin the DNS-lookups) will do some sort of stickiness since most browsers will cache the actual lookup and therefor keep going to the first record it received, AFAIK.</p>\n\n<p>It's usually the runtime that is responsible for the sessiondata, in for exampla PHP it's possible to define your own session-handler, which can persist the data into a database for instance. By default PHP stores sessiondata on files, and it might be possible to share these files on a SAN or equivalent in order to share session-data. This was just a theory I had but never got around to test since we decided that loosing sessions wasn't critical and didn't want that single point of failure. </p>\n"
},
{
"answer_id": 281070,
"author": "Nahom Tijnam",
"author_id": 11172,
"author_profile": "https://Stackoverflow.com/users/11172",
"pm_score": 1,
"selected": false,
"text": "<p>To achieve <strong>load balancing for classic ASP</strong>, you may <strong>store the user specific values in the database</strong> and pass a <strong>reference unique id in the URL</strong> as follows.</p>\n\n<p>Maintain a <strong>session table</strong> in the database which generates a <strong>unique id</strong> for each record. The first time you want to store session specific data, generate a record in your session table and store the session values in it. Obtain the unique id of the new session record and <strong>re-write all links</strong> in your web application to send the unique id as part of querystring.</p>\n\n<p>In every subsequent page where you need the session data, query the session table with the unique id passed in the querystring.</p>\n\n<p><strong>Example:</strong></p>\n\n<p>Consider your website to have 4 pages: Login.asp, welcome.asp, taskList.asp, newtask.asp</p>\n\n<p>When the user logs in using login.asp page, after validating the user, create a record in <strong>session table</strong> and store the required session specific values (lets say user's <strong><em>login date/time</em></strong> for this example). Obtain the <strong>new session record's unique id</strong> (lets say the unique id is <strong><em>abcd</em></strong>).</p>\n\n<p>Append all links in your website with the unique id as below:</p>\n\n<ul>\n<li>welcome.asp?sessionId=abcd</li>\n<li>tasklist.asp?sessionId=abcd</li>\n<li>newtask.asp?sessionId=abcd</li>\n</ul>\n\n<p>Now, if in any of the above web pages you want to show the user's login date/time, you just have to query your session table with the sessionID parameter (<strong><em>abcd</em></strong> in this case) and display to the user.</p>\n\n<p>Since the <strong>unique value identifying the session is a part of the URL</strong>, any of your web servers serving the user will be able to display the correct login date/time value.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
Session variables are normally keept in the web server RAM memory.
In a cluster, each request made by a client can be handled by a different cluster node. right?!
So, in this case...
* What happens with session variables? Aren't they stored in the nodes RAM memory?
* How the other nodes will handled my request correctly if it doesn't have my session variables, or at least all of it?
* This issue is treated by the web server (Apache, IIS) or by the language runtime (PHP, ASP.NET, Ruby, JSP)?
EDIT: Is there some solution for **Classic ASP**?
|
There are 3 ways to store session state in ASP.NET. The first is in process, where the variables are stored in memory. The second is to use a session state service by putting the following in your web.config file:
```
<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false"
timeout="20" />
```
As you can see in the stateConnectionString attribute, the session state service can be located on a different computer.
The third option is to use a centralized SQL database. To do that, you put the following in your web.config:
```
<sessionState
mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString=
"data source=SERVERHAME;user id=sa;password="
cookieless="false"
timeout="20"
/>
```
More details on all of these options are written up here: <http://www.ondotnet.com/pub/a/dotnet/2003/03/24/sessionstate.html>
|
224,026 |
<p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
|
[
{
"answer_id": 224051,
"author": "Smashery",
"author_id": 14902,
"author_profile": "https://Stackoverflow.com/users/14902",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know, Python classes use dictionaries to store their attributes anyway (that's hidden from the programmer), so it looks to me that what you've done there is effectively emulate a Python class... using a python class. </p>\n"
},
{
"answer_id": 224071,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 1,
"selected": false,
"text": "<p>I like dot notation a lot better than dictionary fields personally. The reason being that it makes autocompletion work a lot better.</p>\n"
},
{
"answer_id": 224080,
"author": "hlzr",
"author_id": 19139,
"author_profile": "https://Stackoverflow.com/users/19139",
"pm_score": 4,
"selected": false,
"text": "<p>With regards to the <code>DictObj</code>, would the following work for you? A blank class will allow you to arbitrarily add to or replace stuff in a container object.</p>\n\n<pre><code>class Container(object):\n pass\n\n>>> myContainer = Container()\n>>> myContainer.spam = \"in a can\"\n>>> myContainer.eggs = \"in a shell\"\n</code></pre>\n\n<p>If you want to not throw an AttributeError when there is no attribute, what do you think about the following? Personally, I'd prefer to use a dict for clarity, or to use a try/except clause.</p>\n\n<pre><code>class QuietContainer(object):\n def __getattr__(self, attribute):\n try:\n return object.__getattr__(self,attribute)\n except AttributeError:\n return None\n\n>>> cont = QuietContainer()\n>>> print cont.me\nNone\n</code></pre>\n\n<p>Right?</p>\n"
},
{
"answer_id": 224722,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 4,
"selected": true,
"text": "<p>This is a simpler version of your DictObj class:</p>\n\n<pre><code>class DictObj(object):\n def __getattr__(self, attr):\n return self.__dict__.get(attr)\n\n>>> d = DictObj()\n>>> d.something = 'one'\n>>> print d.something\none\n>>> print d.somethingelse\nNone\n>>> \n</code></pre>\n"
},
{
"answer_id": 224787,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 1,
"selected": false,
"text": "<p>It's not bad if it serves your purpose. \"Practicality beats purity\".</p>\n\n<p>I saw such approach elserwhere (eg. in <a href=\"http://www.blueskyonmars.com/projects/paver/\" rel=\"nofollow noreferrer\">Paver</a>), so this can be considered <em>common need</em> (or desire).</p>\n"
},
{
"answer_id": 224876,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 5,
"selected": false,
"text": "<p>Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with ‘things that resemble objects’, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this kind of object, making code a little more readable without the excess of ['item access'].</p>\n\n<p>The implementation is a bit limited - you don't get the nice constructor syntax of dict, len(), comparisons, 'in', iteration or nice reprs. You can of course implement those things yourself, but in the new-style-classes world you can get them for free by simply subclassing dict:</p>\n\n<pre><code>class AttrDict(dict):\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n</code></pre>\n\n<p>To get the default-to-None behaviour, simply subclass Python 2.5's collections.defaultdict class instead of dict.</p>\n"
},
{
"answer_id": 235675,
"author": "Ryan",
"author_id": 8819,
"author_profile": "https://Stackoverflow.com/users/8819",
"pm_score": 2,
"selected": false,
"text": "<p>The one major disadvantage of using something like your DictObj is you either have to limit allowable keys or you can't have methods on your DictObj such as <code>.keys()</code>, <code>.values()</code>, <code>.items()</code>, etc.</p>\n"
},
{
"answer_id": 235686,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 2,
"selected": false,
"text": "<p>It's not \"wrong\" to do this, and it can be nicer if your dictionaries have a strong possibility of turning into objects at some point, but be wary of the reasons for having bracket access in the first place:</p>\n\n<ol>\n<li>Dot access can't use keywords as keys.</li>\n<li>Dot access has to use Python-identifier-valid characters in the keys.</li>\n<li>Dictionaries can hold any hashable element -- not just strings.</li>\n</ol>\n\n<p>Also keep in mind you can always make your objects access like dictionaries if you decide to switch to objects later on.</p>\n\n<p>For a case like this I would default to the \"readability counts\" mantra: presumably other Python programmers will be reading your code and they probably won't be expecting dictionary/object hybrids everywhere. If it's a good design decision for a particular situation, use it, but I wouldn't use it without necessity to do so.</p>\n"
},
{
"answer_id": 11350835,
"author": "Andre Blum",
"author_id": 1326888,
"author_profile": "https://Stackoverflow.com/users/1326888",
"pm_score": 0,
"selected": false,
"text": "<p>Because you ask for undesirable side-effects:</p>\n\n<p>A disadvantage is that in visual editors like eclipse+pyDev, you will see many undefined variable errors on lines using the dot notation. Pydef will not be able to find such runtime \"object\" definitions. Whereas in the case of a normal dictionary, it knows that you are just getting a dictionary entry.</p>\n\n<p>You would need to 1) ignore those errors and live with red crosses; 2) suppress those warnings on a line by line basis using #@UndefinedVariable or 3) disable undefined variable error entirely, causing you to miss real undefined variable definitions.</p>\n"
},
{
"answer_id": 11620531,
"author": "Sebastian",
"author_id": 1413374,
"author_profile": "https://Stackoverflow.com/users/1413374",
"pm_score": 2,
"selected": false,
"text": "<p>There's a symmetry between <a href=\"https://stackoverflow.com/a/224876/1413374\">this</a> and <a href=\"https://stackoverflow.com/a/224080/1413374\">this</a> answer:</p>\n\n<pre><code>class dotdict(dict):\n __getattr__= dict.__getitem__\n __setattr__= dict.__setitem__\n __delattr__= dict.__delitem__\n</code></pre>\n\n<p>The same interface, just implemented the other way round...</p>\n\n<pre><code>class container(object):\n __getitem__ = object.__getattribute__\n __setitem__ = object.__setattr__\n __delitem__ = object.__delattr__\n</code></pre>\n"
},
{
"answer_id": 26553870,
"author": "Dannid",
"author_id": 1231241,
"author_profile": "https://Stackoverflow.com/users/1231241",
"pm_score": 2,
"selected": false,
"text": "<p>Don't overlook <a href=\"https://pypi.python.org/pypi/bunch/1.0.1\" rel=\"nofollow\" title=\"Bunch\">Bunch</a>. </p>\n\n<p>It is a child of dictionary and can import YAML or JSON, or convert any existing dictionary to a Bunch and vice-versa. Once \"bunchify\"'d, a dictionary gains dot notations without losing any other dictionary methods.</p>\n"
},
{
"answer_id": 58514526,
"author": "fkotsian",
"author_id": 1580498,
"author_profile": "https://Stackoverflow.com/users/1580498",
"pm_score": 0,
"selected": false,
"text": "<p>If you're looking for an alternative that handles nested dicts: </p>\n\n<p>Recursively transform a dict to instances of the desired class</p>\n\n<pre><code>import json\nfrom collections import namedtuple\n\n\nclass DictTransformer():\n @classmethod\n def constantize(self, d):\n return self.transform(d, klass=namedtuple, klassname='namedtuple')\n\n @classmethod\n def transform(self, d, klass, klassname):\n return self._from_json(self._to_json(d), klass=klass, klassname=klassname)\n\n @classmethod\n def _to_json(self, d, access_method='__dict__'):\n return json.dumps(d, default=lambda o: getattr(o, access_method, str(o)))\n\n @classmethod\n def _from_json(self, jsonstr, klass, klassname):\n return json.loads(jsonstr, object_hook=lambda d: klass(klassname, d.keys())(*d.values()))\n</code></pre>\n\n<p>Ex: </p>\n\n<pre><code>constants = {\n 'A': {\n 'B': {\n 'C': 'D'\n }\n }\n}\nCONSTANTS = DictTransformer.transform(d, klass=namedtuple, klassname='namedtuple')\nCONSTANTS.A.B.C == 'D'\n</code></pre>\n\n<p>Pros:</p>\n\n<ul>\n<li>handles nested dicts</li>\n<li>can potentially generate other classes</li>\n<li>namedtuples provide immutability for constants</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>may not respond to <code>.keys</code> and <code>.values</code> if those are not provided on your klass (though you can sometimes mimic with <code>._fields</code> and <code>list(A.B.C)</code>)</li>\n</ul>\n\n<p>Thoughts?</p>\n\n<p>h/t to @hlzr for the original class idea</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
I've started to use constructs like these:
```
class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
```
Update: based on this thread, I've revised the DictObj implementation to:
```
class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
```
where DictObj is a dictionary that can be accessed via dot notation:
```
d = DictObj()
d.something = 'one'
```
I find it more aesthetically pleasing than `d['something']`. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.
Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using **dict** instead of defining a new dictionary; if not, I like mhawke's solution a lot.
AutoEnum is an auto-incrementing Enum, used like this:
```
CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
```
Both are working well for me, but I'm feeling unpythonic about them.
Are these in fact bad constructs?
|
This is a simpler version of your DictObj class:
```
class DictObj(object):
def __getattr__(self, attr):
return self.__dict__.get(attr)
>>> d = DictObj()
>>> d.something = 'one'
>>> print d.something
one
>>> print d.somethingelse
None
>>>
```
|
224,038 |
<p>My $SHELL is tcsh. I want to run a C shell script that will call a program many times with some arguments changed each time. The program I need to call is in Fortran. I do not want to edit it. The program only takes arguments once it is executed, but not on the command line. Upon calling the program in the script, the program takes control (this is where I am stuck currently, I can never get out because the script will not execute anything until after the program process stops). At this point I need to pass it some variables, then after several iterations I will need to <kbd>Ctrl</kbd>+<kbd>C</kbd> out of the program and continue with the script.</p>
<p>How can this be done?</p>
|
[
{
"answer_id": 224045,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 0,
"selected": false,
"text": "<p>Not a <code>tcsh</code> user, but if the program runs then reads in commands via <code>stdin</code> then you can use shell redirection <code><</code> to feed it the required commands. If you run it in the background with <code>&</code> you will not block when it is executed. Then you can <code>sleep</code> for a bit, then use whatever tools you have (<code>ps</code>, <code>grep</code>, <code>awk</code>, etc) to discover the program's PID, then use <code>kill</code> to send it <code>SIGTERM</code> which is the same as doing a <kbd>Ctrl</kbd>-<kbd>C</kbd>.</p>\n"
},
{
"answer_id": 224046,
"author": "Toybuilder",
"author_id": 22329,
"author_profile": "https://Stackoverflow.com/users/22329",
"pm_score": 1,
"selected": false,
"text": "<p>Uhm, can you feed your Fortran code with a redirection? You can create a temporary file with your inputs, and then pipe it in with the stdin redirect (<).</p>\n"
},
{
"answer_id": 224050,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>What you want to use is <a href=\"http://expect.nist.gov/\" rel=\"nofollow noreferrer\">Expect</a>.</p>\n"
},
{
"answer_id": 224068,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 4,
"selected": true,
"text": "<p>To add to what @Toybuilder said, you can use a \"here document\". I.e. your script could have</p>\n\n<pre><code>./myfortranprogram << EOF\nfirst line of input\nsecond line of input\nEOF\n</code></pre>\n\n<p>Everything between the \"<code><<EOF</code>\" and the \"<code>EOF</code>\" will be fed to the program's standard input (does Fortran still use \"read (5,*)\" to read from standard input?)</p>\n\n<p>And because I think @ephemient's comment deserves to be in the answer:</p>\n\n<blockquote>\n <p>Some more tips: <<'EOF' prevents\n interpolation in the here-doc body;\n <<-EOF removes all leading tabs (so\n you can indent the here-doc to match\n its surroundings), and EOF can be\n replaced by any token. An empty token\n (<<\"\") indicates a here-doc that stops\n at the first empty line.</p>\n</blockquote>\n\n<p>I'm not sure how portable those ones are, or if they're just tcsh extensions - I've only used the <code><<EOF</code> type \"here document\" myself.</p>\n"
},
{
"answer_id": 224147,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 0,
"selected": false,
"text": "<p>This is a job for the unix program expect, which can nicely and easily interactively command programs and respond to their prompts.</p>\n"
},
{
"answer_id": 36287163,
"author": "Steve",
"author_id": 787832,
"author_profile": "https://Stackoverflow.com/users/787832",
"pm_score": 0,
"selected": false,
"text": "<p>I was sent here after being told my question was close to being a duplicate of this one.</p>\n\n<p>FWIW, I had a similar problem with a csh C shell script.</p>\n\n<p>This bit of code was allowing the custom_command to execute without getting ANY input arguments:</p>\n\n<pre><code>foreach f ($forecastTimes)\n custom_command << EOF\n arg1=x$f;2\n arg2=ya\n arg3=z,z$f\n run\n exit\n EOF\nend\n</code></pre>\n\n<p>It didn't work the first time I tried it, but after I backspaced out all of the white space in that section of the code I removed the space between the \"<<\" and the \"EOF\". I also backspaced the closing \"EOF\" all the way to the left margin. After that it worked:</p>\n\n<pre><code>foreach f ($forecastTimes)\n custom_command <<EOF\n arg1=x$f;2\n arg2=ya\n arg3=z,z$f\n run\n exit\nEOF\nend\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30181/"
] |
My $SHELL is tcsh. I want to run a C shell script that will call a program many times with some arguments changed each time. The program I need to call is in Fortran. I do not want to edit it. The program only takes arguments once it is executed, but not on the command line. Upon calling the program in the script, the program takes control (this is where I am stuck currently, I can never get out because the script will not execute anything until after the program process stops). At this point I need to pass it some variables, then after several iterations I will need to `Ctrl`+`C` out of the program and continue with the script.
How can this be done?
|
To add to what @Toybuilder said, you can use a "here document". I.e. your script could have
```
./myfortranprogram << EOF
first line of input
second line of input
EOF
```
Everything between the "`<<EOF`" and the "`EOF`" will be fed to the program's standard input (does Fortran still use "read (5,\*)" to read from standard input?)
And because I think @ephemient's comment deserves to be in the answer:
>
> Some more tips: <<'EOF' prevents
> interpolation in the here-doc body;
> <<-EOF removes all leading tabs (so
> you can indent the here-doc to match
> its surroundings), and EOF can be
> replaced by any token. An empty token
> (<<"") indicates a here-doc that stops
> at the first empty line.
>
>
>
I'm not sure how portable those ones are, or if they're just tcsh extensions - I've only used the `<<EOF` type "here document" myself.
|
224,040 |
<p>What is the most elegant way to calculate the previous business day in shell ksh script ?</p>
<p>What I got until now is :</p>
<pre><code>#!/bin/ksh
set -x
DAY_DIFF=1
case `date '+%a'` in
"Sun")
DAY_DIFF=2
;;
"Mon")
DAY_DIFF=3
;;
esac
PREV_DT=`perl -e '($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time()-${DAY_DIFF}*24*60*60);printf "%4d%02d%02d",$year+1900,$mon+1,$mday;'`
echo $PREV_DT
</code></pre>
<p>How do I make the ${DAY_DIFF} variable to be transmitted as value and not as string ?</p>
|
[
{
"answer_id": 224428,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>Well, if running Perl counts as part of the script, then develop the answer in Perl. The next question is - what defines a business day? Are you a shop/store that is open on Sunday? Saturday? Or a 9-5 Monday to Friday business? What about holidays?</p>\n\n<p>Assuming you're thinking Monday to Friday and holidays are temporarily immaterial, then you can use an algorithm in Perl that notes that wday will be 0 on Sunday through 6 on Saturday, and therefore if wday is 1, you need to subtract 3 * 86400 from time(); if wday is 0, you need to subtract 2 * 86400; and if wday is 6, you need to subtract 1 * 86400. That's what you've got in the Korn shell stuff - just do it in the Perl instead:</p>\n\n<pre><code>#!/bin/perl -w\nuse strict;\nuse POSIX;\nuse constant SECS_PER_DAY => 24 * 60 * 60;\nmy(@days) = (2, 3, 1, 1, 1, 1, 1);\nmy($now) = time;\nmy($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($now);\nprint strftime(\"%Y-%m-%d\\n\", localtime($now - $days[$wday] * SECS_PER_DAY));\n</code></pre>\n\n<p>This does assume you have the POSIX module; if not, then you'll need to do roughly the same printf() as you used. I also use ISO 8601 format for dates by preference (also used by XSD and SQL) - hence the illustrated format.</p>\n"
},
{
"answer_id": 229222,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a solution that doesn't use Perl. It works both with <code>ksh</code> and <code>sh</code>.</p>\n\n<pre><code>#!/bin/ksh\n\ndiff=-1\n[ `date +%u` == 1 ] && diff=-3\n\nseconds=$((`date +%s` + $diff * 24 * 3600))\nformat=+%Y-%m-%d\n\nif date --help 2>/dev/null | grep -q -- -d ; then\n # GNU date (e.g., Linux)\n date -d \"1970-01-01 00:00 UTC + $seconds seconds\" $format\nelse\n # For BSD date (e.g., Mac OS X)\n date -r $seconds $format\nfi\n</code></pre>\n"
},
{
"answer_id": 1455968,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#!/bin/ksh\n# GNU date is a veritable Swiss Army Knife...\n((D=$(date +%w)+2))\nif [ $D -gt 3 ]; then D=1; fi\nPREV_DT=$(date -d \"-$D days\" +%F)\n</code></pre>\n"
},
{
"answer_id": 1852385,
"author": "user224243",
"author_id": 224243,
"author_profile": "https://Stackoverflow.com/users/224243",
"pm_score": 0,
"selected": false,
"text": "<p>This should work for Solaris and Linux. It's realy complicating on Unix that you can not use the same commandline arguments on all Unix derivates.</p>\n\n<p>On Linux you can use <code>date -d '-d24 hour ago'</code> to get the last day\non Solaris its <code>TZ=CET+24 date</code>. I guess other UNIX'es works the same way as Solaris does.</p>\n\n<pre><code>#!/usr/bin/ksh\n\nlbd=5 # last business day (1=Mon, 2=Thu ... 6=Sat, 7=Sun)\nlbd_date=\"\" # last business day date\n\nfunction lbdSunOS\n{\n typeset back=$1\n typeset tz=`date '+%Z'` # timezone\n\n lbd_date=`TZ=${tz}+$back date '+%Y%m%d'`\n}\n\nfunction lbdLinux\n{\n typeset back=$1\n\n lbd_date=`date -d \"-d$back hour ago\"`\n}\n\nfunction calcHoursBack\n{\n typeset lbd=$1\n typeset dow=`date '+%u'` # day of the week\n\n if [ $dow -ge $lbd ]\n then\n return $(((dow-lbd)*24))\n else\n return $(((dow-lbd+7)*24))\n fi\n}\n\n# Main\n\ncalcHoursBack $lbd\nlbd`uname -s` $?\n\necho $lbd_date\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What is the most elegant way to calculate the previous business day in shell ksh script ?
What I got until now is :
```
#!/bin/ksh
set -x
DAY_DIFF=1
case `date '+%a'` in
"Sun")
DAY_DIFF=2
;;
"Mon")
DAY_DIFF=3
;;
esac
PREV_DT=`perl -e '($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time()-${DAY_DIFF}*24*60*60);printf "%4d%02d%02d",$year+1900,$mon+1,$mday;'`
echo $PREV_DT
```
How do I make the ${DAY\_DIFF} variable to be transmitted as value and not as string ?
|
Here is a solution that doesn't use Perl. It works both with `ksh` and `sh`.
```
#!/bin/ksh
diff=-1
[ `date +%u` == 1 ] && diff=-3
seconds=$((`date +%s` + $diff * 24 * 3600))
format=+%Y-%m-%d
if date --help 2>/dev/null | grep -q -- -d ; then
# GNU date (e.g., Linux)
date -d "1970-01-01 00:00 UTC + $seconds seconds" $format
else
# For BSD date (e.g., Mac OS X)
date -r $seconds $format
fi
```
|
224,059 |
<p>When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.</p>
<p>As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:</p>
<pre><code>if (condition)
{
do
{
...
} while (same condition);
}
</code></pre>
<p>or the inverse (<code>if</code> inside the <code>while</code>), it makes me wonder if they actually wrote it that way or if they added the <code>if</code> statement when they realized the loop didn't handle the null case.</p>
<p>I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?</p>
|
[
{
"answer_id": 224074,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 1,
"selected": false,
"text": "<p>I write mine pretty much exclusively testing at the top. It's less code, so for me at least, it's less potential to screw something up (e.g., copy-pasting the condition makes two places you always have to update it)</p>\n"
},
{
"answer_id": 224075,
"author": "Brett McCann",
"author_id": 9293,
"author_profile": "https://Stackoverflow.com/users/9293",
"pm_score": 6,
"selected": false,
"text": "<p>I always follow the rule that if it should run zero or more times, test at the beginning, if it must run <em>once</em> or more, test at the end. I do not see any logical reason to use the code you listed in your example. It only adds complexity.</p>\n"
},
{
"answer_id": 224101,
"author": "mxcl",
"author_id": 6444,
"author_profile": "https://Stackoverflow.com/users/6444",
"pm_score": 3,
"selected": false,
"text": "<p>For the sake of readability it seems sensible to test at the top. The fact it is a loop is important; the person reading the code should be aware of the loop conditions before trying to comprehend the body of the loop.</p>\n"
},
{
"answer_id": 224104,
"author": "Salamander2007",
"author_id": 10629,
"author_profile": "https://Stackoverflow.com/users/10629",
"pm_score": 2,
"selected": false,
"text": "<p>It's actually meant for a different things. In C, you can use <strong>do - while</strong> construct to achieve both scenario (runs at least once and runs while true). But PASCAL has <strong>repeat - until</strong> and <strong>while</strong> for each scenario, and if I remember correctly, ADA has another construct that lets you quit in the middle, but of course that's not what you're asking.\nMy answer to your question : I like my loop with testing on top.</p>\n"
},
{
"answer_id": 224111,
"author": "None",
"author_id": 25012,
"author_profile": "https://Stackoverflow.com/users/25012",
"pm_score": 2,
"selected": false,
"text": "<p>The use cases are different for the two. This isn't a \"best practices\" question.</p>\n\n<p>If you want a loop to execute based on the condition exclusively than use \n<strong>for</strong> or <strong>while</strong></p>\n\n<p>If you want to do something once regardless of the the condition and then continue doing it based the condition evaluation.\n<strong>do..while</strong></p>\n"
},
{
"answer_id": 224120,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": 1,
"selected": false,
"text": "<p>It really depends there are situations when you want to test at the top, others when you want to test at the bottom, and still others when you want to test in the middle.</p>\n\n<p>However the example given seems absurd. If you are going to test at the top, don't use an if statement and test at the bottom, just use a while statement, that's what it is made for.</p>\n"
},
{
"answer_id": 224191,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 1,
"selected": false,
"text": "<p>You should first think of the test as part of the loop code. If the test logically belongs at the start of the loop processing, then it's a top-of-the-loop test. If the test logically belongs at the end of the loop (i.e. it decides if the loop should continue to run), then it's probably a bottom-of-the-loop test.</p>\n\n<p>You will have to do something fancy if the test logically belongs in them middle. :-)</p>\n"
},
{
"answer_id": 225472,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone who can't think of a reason to have a one-or-more times loop:</p>\n\n<pre><code>try {\n someOperation();\n} catch (Exception e) {\n do {\n if (e instanceof ExceptionIHandleInAWierdWay) {\n HandleWierdException((ExceptionIHandleInAWierdWay)e);\n }\n } while ((e = e.getInnerException())!= null);\n}\n</code></pre>\n\n<p>The same could be used for any sort of hierarchical structure.</p>\n\n<p>in class Node:</p>\n\n<pre><code>public Node findSelfOrParentWithText(string text) {\n Node node = this;\n do {\n if(node.containsText(text)) {\n break;\n }\n } while((node = node.getParent()) != null);\n return node;\n}\n</code></pre>\n"
},
{
"answer_id": 390608,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 4,
"selected": false,
"text": "<p>Difference is that the do loop executes \"do something\" once and then checks the condition to see if it should repeat the \"do something\" while the while loop checks the condition before doing anything</p>\n"
},
{
"answer_id": 390609,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 4,
"selected": false,
"text": "<p>First one may not execute at all if condition is false. Other one will execute at least once, then check the conidition.</p>\n"
},
{
"answer_id": 390610,
"author": "Eric Sabine",
"author_id": 1493157,
"author_profile": "https://Stackoverflow.com/users/1493157",
"pm_score": 2,
"selected": false,
"text": "<p>The first tests the condition before performing so it's possible your code won't ever enter the code underneath. The second will perform the code within before testing the condition. </p>\n"
},
{
"answer_id": 390612,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 2,
"selected": false,
"text": "<p>The while loop will check \"condition\" first; if it's false, it will never \"do something.\" But the do...while loop will \"do something\" first, then check \"condition\".</p>\n"
},
{
"answer_id": 390634,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 2,
"selected": false,
"text": "<p>A <strong>while()</strong> checks the condition before each execution of the loop body and a <strong>do...while()</strong> checks the condition after each execution of the loop body.</p>\n\n<p>Thus, **do...while()**s will always execute the loop body at least once.</p>\n\n<p>Functionally, a while() is equivalent to</p>\n\n<pre><code>startOfLoop:\n if (!condition)\n goto endOfLoop;\n\n //loop body goes here\n\n goto startOfLoop;\nendOfLoop:\n</code></pre>\n\n<p>and a do...while() is equivalent to</p>\n\n<pre><code>startOfLoop:\n\n //loop body\n\n //goes here\n if (condition)\n goto startOfLoop;\n</code></pre>\n\n<p>Note that the implementation is probably more efficient than this. However, a do...while() does involve one less comparison than a while() so it is slightly faster. Use a do...while() if:</p>\n\n<ul>\n<li>you <em>know</em> that the condition will always be true the first time around, or</li>\n<li>you <em>want</em> the loop to execute once even if the condition is false to begin with.</li>\n</ul>\n"
},
{
"answer_id": 390642,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "<p>In a typical Discrete Structures class in computer science, it's an easy proof that there is an equivalence mapping between the two.</p>\n\n<p>Stylistically, I prefer while (easy-expr) { } when easy-expr is known up front and ready to go, and the loop doesn't have a lot of repeated overhead/initialization. I prefer do { } while (somewhat-less-easy-expr); when there is more repeated overhead and the condition may not be quite so simple to set up ahead of time. If I write an infinite loop, I always use while (true) { }. I can't explain why, but I just don't like writing for (;;) { }.</p>\n"
},
{
"answer_id": 390646,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the translation:</p>\n\n<pre><code>do { y; } while(x); \n</code></pre>\n\n<p>Same as</p>\n\n<pre><code>{ y; } while(x) { y; }\n</code></pre>\n\n<p>Note the extra set of braces are for the case you have variable definitions in <code>y</code>. The scope of those must be kept local like in the do-loop case. So, a do-while loop just executes its body at least once. Apart from that, the two loops are identical. So if we apply this rule to your code</p>\n\n<pre><code>do {\n // do something\n} while (condition is true);\n</code></pre>\n\n<p>The corresponding while loop for your do-loop looks like</p>\n\n<pre><code>{\n // do something\n}\nwhile (condition is true) {\n // do something\n}\n</code></pre>\n\n<p>Yes, you see the corresponding while for your do loop differs from your while :) </p>\n"
},
{
"answer_id": 390647,
"author": "PolyThinker",
"author_id": 47707,
"author_profile": "https://Stackoverflow.com/users/47707",
"pm_score": 2,
"selected": false,
"text": "<p>Both conventions are correct if you know how to write the code correctly :)</p>\n\n<p>Usually the use of second convention ( <em>do {} while()</em> ) is meant to avoid have a duplicated statement outside the loop. Consider the following (over simplified) example:</p>\n\n<pre><code>a++;\nwhile (a < n) {\n a++;\n}\n</code></pre>\n\n<p>can be written more concisely using</p>\n\n<pre><code>do {\n a++;\n} while (a < n)\n</code></pre>\n\n<p>Of course, this particular example can be written in an even more concise way as (assuming C syntax)</p>\n\n<pre><code>while (++a < n) {}\n</code></pre>\n\n<p>But I think you can see the point here.</p>\n"
},
{
"answer_id": 995861,
"author": "erikkallen",
"author_id": 47161,
"author_profile": "https://Stackoverflow.com/users/47161",
"pm_score": 1,
"selected": false,
"text": "<p>I guess some people test at the bottom because you could save one or a few machine cycles by doing that 30 years ago.</p>\n"
},
{
"answer_id": 995863,
"author": "Larry Watanabe",
"author_id": 118860,
"author_profile": "https://Stackoverflow.com/users/118860",
"pm_score": 1,
"selected": false,
"text": "<p>To write code that is correct, one basically needs to perform a mental, perhaps informal proof of correctness.</p>\n\n<p>To prove a loop correct, the standard way is to choose a loop invariant, and an induction proof. But skip the complicated words: what you do, informally, is figure out something that is true of each iteration of the loop, and that when the loop is done, what you wanted accomplished is now true. The loop invariant is false at the end, for the loop to terminate.</p>\n\n<p>If the loop conditions map fairly easily to the invariant, and the invariant is at the top of the loop, and one infers that the invariant is true at the next iteration of the loop by working through the code of the loop, then it is easy to figure out that the loop is correct.</p>\n\n<p>However, if the invariant is at the bottom of the loop, then unless you have an assertion just prior to the loop (a good practice) then it becomes more difficult because you have to essentially infer what that invariant should be, and that any code that ran before the loop makes the loop invariant true (since there is no loop precondition, code will execute in the loop). It just becomes that more difficult to prove correct, even if it is an informal in-your-head proof.</p>\n"
},
{
"answer_id": 995884,
"author": "Greg",
"author_id": 42882,
"author_profile": "https://Stackoverflow.com/users/42882",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't really an answer but a reiteration of something one of my lecturers said and it interested me at the time.</p>\n\n<p>The two types of loop while..do and do..while are actually instances of a third more generic loop, which has the test somewhere in the middle. </p>\n\n<pre><code>begin loop\n <Code block A>\n loop condition\n <Code block B>\nend loop\n</code></pre>\n\n<p>Code block A is executed at least once and B is executed zero or more times, but isn't run on the very last (failing) iteration. a while loop is when code block a is empty and a do..while is when code block b is empty. But if you're writing a compiler, you might be interested in generalizing both cases to a loop like this.</p>\n"
},
{
"answer_id": 995978,
"author": "Nefzen",
"author_id": 112830,
"author_profile": "https://Stackoverflow.com/users/112830",
"pm_score": 0,
"selected": false,
"text": "<p>I would say it is bad practice to write if..do..while loops, for the simple reason that this increases the size of the code and causes code duplications. Code duplications are error prone and should be avoided, as any change to one part must be performed on the duplicate as well, which isn't always the case. Also, bigger code means a harder time on the cpu cache. Finally, it handles null cases, and solves head aches.</p>\n\n<p>Only when the first loop is fundamentally different should one use do..while, say, if the code that makes you pass the loop condition (like initialization) is performed in the loop. Otherwise, if it certain that loop will never fall on the first iteration, then yes, a do..while is appropriate.</p>\n"
},
{
"answer_id": 2924621,
"author": "pratik",
"author_id": 352350,
"author_profile": "https://Stackoverflow.com/users/352350",
"pm_score": 0,
"selected": false,
"text": "<p>From my limited knowledge of code generation I think it may be a good idea to write bottom test loops since they enable the compiler to perform loop optimizations better. For bottom test loops it is guaranteed that the loop executes at least once. This means loop invariant code \"dominates\" the exit node. And thus can be safely moved just before the loop starts.</p>\n"
},
{
"answer_id": 3094995,
"author": "Yacoby",
"author_id": 118145,
"author_profile": "https://Stackoverflow.com/users/118145",
"pm_score": 6,
"selected": false,
"text": "<p>Use while loops when you want to test a condition before the first iteration of the loop.</p>\n\n<p>Use do-while loops when you want to test a condition after running the first iteration of the loop.</p>\n\n<p>For example, if you find yourself doing something like either of these snippets:</p>\n\n<pre><code>func();\nwhile (condition) {\n func();\n}\n\n//or:\n\nwhile (true){\n func();\n if (!condition) break;\n}\n</code></pre>\n\n<p>You should rewrite it as:</p>\n\n<pre><code>do{\n func();\n} while(condition);\n</code></pre>\n"
},
{
"answer_id": 3095010,
"author": "Mohit Jain",
"author_id": 179855,
"author_profile": "https://Stackoverflow.com/users/179855",
"pm_score": 3,
"selected": false,
"text": "<p>Yaa..its true.. do while will run atleast one time.\nThats the only difference. Nothing else to debate on this</p>\n"
},
{
"answer_id": 3095307,
"author": "AshleysBrain",
"author_id": 177222,
"author_profile": "https://Stackoverflow.com/users/177222",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a good real-world example I came across recently. Suppose you have a number of processing tasks (like processing elements in an array) and you wish to split the work between one thread per CPU core present. There must be at least one core to be running the current code! So you can use a <code>do... while</code> something like:</p>\n\n<pre><code>do {\n get_tasks_for_core();\n launch_thread();\n} while (cores_remaining());\n</code></pre>\n\n<p>It's almost negligable, but it might be worth considering the performance benefit: it could equally be written as a standard <code>while</code> loop, but that would always make an unnecessary initial comparison that would always evaluate <code>true</code> - and on single-core, the do-while condition branches more predictably (always false, versus alternating true/false for a standard <code>while</code>).</p>\n"
},
{
"answer_id": 3095702,
"author": "Jay",
"author_id": 103206,
"author_profile": "https://Stackoverflow.com/users/103206",
"pm_score": 2,
"selected": false,
"text": "<p>As noted by Piemasons, the difference is whether the loop executes once before doing the test, or if the test is done first so that the body of the loop might never execute.</p>\n\n<p>The key question is which makes sense for your application.</p>\n\n<p>To take two simple examples:</p>\n\n<ol>\n<li><p>Say you're looping through the elements of an array. If the array has no elements, you don't want to process number one of zero. So you should use WHILE.</p></li>\n<li><p>You want to display a message, accept a response, and if the response is invalid, ask again until you get a valid response. So you always want to ask once. You can't test if the response is valid until you get a response, so you have to go through the body of the loop once before you can test the condition. You should use DO/WHILE.</p></li>\n</ol>\n"
},
{
"answer_id": 3376526,
"author": "James McNellis",
"author_id": 151292,
"author_profile": "https://Stackoverflow.com/users/151292",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>Does avoiding <code>do</code>/<code>while</code> really help make my code more readable?</p>\n</blockquote>\n\n<p>No.</p>\n\n<p>If it makes more sense to use a <code>do</code>/<code>while</code> loop, then do so. If you need to execute the body of a loop once before testing the condition, then a <code>do</code>/<code>while</code> loop is probably the most straightforward implementation.</p>\n"
},
{
"answer_id": 3376530,
"author": "Toby",
"author_id": 402107,
"author_profile": "https://Stackoverflow.com/users/402107",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, just like using for instead of while, or foreach instead of for improves readability. That said some circumstances need do while and I agree you would be silly to force those situations into a while loop.</p>\n"
},
{
"answer_id": 3376531,
"author": "Marcelo Cantos",
"author_id": 9990,
"author_profile": "https://Stackoverflow.com/users/9990",
"pm_score": 2,
"selected": false,
"text": "<p>It's more helpful to think in terms of common usage. The vast majority of while loops work quite naturally with <code>while</code>, even if they could be made to work with <code>do...while</code>, so basically you should use it when the difference doesn't matter. I would thus use <code>do...while</code> for the rare scenarios where it provides a noticeable improvement in readability.</p>\n"
},
{
"answer_id": 3376799,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>I tend to prefer do-while loops, myself. If the condition will <i>always</i> be true at the start of the loop, I prefer to test it at the end. To my eye, the whole point of testing conditions (other than assertions) is that one doesn't know the result of the test. If I see a while loop with the condition test at the top, my inclination is to consider the case that the loop executes zero times. If that can never happen, why not code in a way that clearly shows that?</p>\n"
},
{
"answer_id": 3377021,
"author": "Jomu",
"author_id": 315281,
"author_profile": "https://Stackoverflow.com/users/315281",
"pm_score": 0,
"selected": false,
"text": "<p>Generally, it depends on how you structure your code. And as someone already answered, some algorithms need at least one iteration performed. So, to escape additional iteration-count or at-least-one-interation-occured flag - you employ do/while.</p>\n"
},
{
"answer_id": 9221127,
"author": "Mark",
"author_id": 1044742,
"author_profile": "https://Stackoverflow.com/users/1044742",
"pm_score": 2,
"selected": false,
"text": "<pre><code>while( someConditionMayBeFalse ){\n\n// this will never run...\n\n}\n\n\n// then the alternative\n\ndo{\n\n// this will run once even if the condition is false\n\nwhile( someConditionMayBeFalse );\n</code></pre>\n\n<p>The difference is obvious and allows you to have code run and then evaluate the result to see if you have to \"Do it again\" and the other method of while allows you to have a block of script ignored if the conditional is not met.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.
As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:
```
if (condition)
{
do
{
...
} while (same condition);
}
```
or the inverse (`if` inside the `while`), it makes me wonder if they actually wrote it that way or if they added the `if` statement when they realized the loop didn't handle the null case.
I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?
|
I always follow the rule that if it should run zero or more times, test at the beginning, if it must run *once* or more, test at the end. I do not see any logical reason to use the code you listed in your example. It only adds complexity.
|
224,078 |
<p>I am trying to hide some divs before the user prints this giant form, then display the divs again afterward. Thus I want to ignore the rest of the page, and only print the form itself.</p>
<p>Sure I <em>could</em> open a separate page when the user clicks the print button. The only thing is that the form is really long and it would be quite tedious to do that.</p>
<p><br>
Edit: My previous question did not actually reflect what I was looking for. So I changed it to the current one.</p>
<p>Also thanks to all that suggested window.onbeforeprint and window.onafterprint. That was relevant to my edited question.</p>
|
[
{
"answer_id": 224084,
"author": "Micky McQuade",
"author_id": 12908,
"author_profile": "https://Stackoverflow.com/users/12908",
"pm_score": 5,
"selected": false,
"text": "<h2>First, The Ok Way:</h2>\n\n<p>Take a look at window.onbeforeprint and window.onafterprint (the original question asked about how to do it programmatically I believe). </p>\n\n<h2>Now, the Better Way:</h2>\n\n<p>A better way to do this is with a style that is specifically for printing. In other words, your div might look like this:</p>\n\n<pre><code><div class=\"someClass noPrint\">My Info</div>\n</code></pre>\n\n<p>You would then have this in your stylesheet:</p>\n\n<pre><code>.someClass {font-family:arial;}\n@media print {\n .noPrint { display: none; }\n} \n</code></pre>\n\n<h2>Another Option</h2>\n\n<p>You could also put this in a separate stylesheet if you wanted so you don't have to mix styles:</p>\n\n<pre><code><link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\">\n</code></pre>\n\n<p>Your screen stylesheet could have \".someClass\" defined one way and then your print stylesheet could have it defined a completely different way.</p>\n"
},
{
"answer_id": 224088,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to consider creating a style sheet specifically for printing using <a href=\"http://www.alistapart.com/stories/goingtoprint/\" rel=\"nofollow noreferrer\">media=\"print\"</a></p>\n"
},
{
"answer_id": 224089,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 5,
"selected": true,
"text": "<p>IE supports <code>onbeforeprint</code> and <code>onafterprint</code>, but what you really want is a print stylesheet.</p>\n\n<pre><code><link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\">\n</code></pre>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/224078/how-to-print-only-parts-of-a-page#224084\">this answer</a></p>\n"
},
{
"answer_id": 224093,
"author": "spender",
"author_id": 14357,
"author_profile": "https://Stackoverflow.com/users/14357",
"pm_score": 0,
"selected": false,
"text": "<p>You should really implement this as CSS media=print styles. The media attribute of link element can be used to select to which media a stylesheet is applied. Check <a href=\"http://www.alistapart.com/stories/goingtoprint/\" rel=\"nofollow noreferrer\">this article</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
] |
I am trying to hide some divs before the user prints this giant form, then display the divs again afterward. Thus I want to ignore the rest of the page, and only print the form itself.
Sure I *could* open a separate page when the user clicks the print button. The only thing is that the form is really long and it would be quite tedious to do that.
Edit: My previous question did not actually reflect what I was looking for. So I changed it to the current one.
Also thanks to all that suggested window.onbeforeprint and window.onafterprint. That was relevant to my edited question.
|
IE supports `onbeforeprint` and `onafterprint`, but what you really want is a print stylesheet.
```
<link rel="stylesheet" type="text/css" media="print" href="print.css">
```
See also: [this answer](https://stackoverflow.com/questions/224078/how-to-print-only-parts-of-a-page#224084)
|
224,106 |
<p>How do I extend my parent's options array for child classes in PHP?</p>
<p>I have something like this:</p>
<pre><code>class ParentClass {
public $options = array(
'option1'=>'setting1'
);
//The rest of the functions would follow
}
</code></pre>
<p>I would like to append to that options array in a child class without erasing any of the parent options. I've tried doing something like this, but haven't quite got it to work yet:</p>
<pre><code>class ChildClass extends ParentClass {
public $options = parent::options + array(
'option2'=>'setting2'
);
//The rest of the functions would follow
}
</code></pre>
<p>What would be the best way to do something like this?</p>
|
[
{
"answer_id": 224121,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 4,
"selected": true,
"text": "<p>I think it is better practice to initialize this property in the constructor and then you can extend the value in any descendant class:</p>\n\n<pre><code><?php\nclass ParentClass {\n\n public $options;\n public function __construct() {\n $this->options = array(\n 'option1'=>'setting1'\n );\n }\n //The rest of the functions would follow\n}\n\nclass ChildClass extends ParentClass {\n public function __construct() {\n parent::__construct();\n $this->options['option2'] = 'setting2';\n }\n //The rest of the functions would follow\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 224124,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 1,
"selected": false,
"text": "<p>PHP or no, you should have an accessor to do it, so you can call <code>$self->append_elements( 'foo' => 'bar' );</code> and not worry about the internal implementation.</p>\n"
},
{
"answer_id": 224160,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 1,
"selected": false,
"text": "<p>Can you <a href=\"http://php.net/array_merge\" rel=\"nofollow noreferrer\">array_merge</a>?</p>\n\n<p>Assuming you use the ctr to create the class.</p>\n\n<p>E.g.</p>\n\n<pre><code>public function __construct(array $foo)\n{\n $this->options = array_merge(parent::$options, $foo);\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] |
How do I extend my parent's options array for child classes in PHP?
I have something like this:
```
class ParentClass {
public $options = array(
'option1'=>'setting1'
);
//The rest of the functions would follow
}
```
I would like to append to that options array in a child class without erasing any of the parent options. I've tried doing something like this, but haven't quite got it to work yet:
```
class ChildClass extends ParentClass {
public $options = parent::options + array(
'option2'=>'setting2'
);
//The rest of the functions would follow
}
```
What would be the best way to do something like this?
|
I think it is better practice to initialize this property in the constructor and then you can extend the value in any descendant class:
```
<?php
class ParentClass {
public $options;
public function __construct() {
$this->options = array(
'option1'=>'setting1'
);
}
//The rest of the functions would follow
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
$this->options['option2'] = 'setting2';
}
//The rest of the functions would follow
}
?>
```
|
224,128 |
<p>Currently, if I want to apply a method to a group of ActiveRecord objects, I have to structure the call like so:</p>
<pre><code>messages = Message.find(:all)
csv = Message.to_csv(messages)
</code></pre>
<p>How can I define the method so it's structured like so?</p>
<pre><code>messages = Message.find(:all)
csv = messages.to_csv
</code></pre>
<p>This is the current model code:</p>
<pre><code>require 'fastercsv'
class Message < ActiveRecord::Base
def Message.to_csv(messages)
FasterCSV.generate do |csv|
csv << ["from","to", "received"]
for m in messages
csv << [m.from,m.to,m.created_at]
end
end
end
end
</code></pre>
|
[
{
"answer_id": 224140,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a method on your Message class to do something along the lines of...</p>\n\n<p>In your controller....</p>\n\n<pre><code>@csv_file = Message.send_all_to_csv\n</code></pre>\n\n<p>In your model...</p>\n\n<pre><code>require 'fastercsv'\nclass Message < ActiveRecord::Base\n def send_all_to_csv\n @messages = Find.all\n FasterCSV.generate do |csv|\n csv << [\"from\",\"to\", \"received\"]\n for message in @messages\n csv << [message.from,message.to,message.created_at]\n end\n end\n # do something with your csv object (return it to the controller\n # or pass it on to another class method\n end\nend\n</code></pre>\n"
},
{
"answer_id": 224171,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 0,
"selected": false,
"text": "<p>You could define the method directly on the <code>messages</code> object itself, but if you do that, the method would only be available to that specific instance:</p>\n\n<pre><code>def messages.to_csv()\n\n FasterCSV.generate do |csv|\n csv << [\"from\", \"to\", \"received\"]\n self.each { |m| csv << [m.from, m.to, m.created_at] } \n end\n\nend\n</code></pre>\n\n<p>Then you could call it like so:</p>\n\n<pre><code>messages.to_csv\n</code></pre>\n\n<p>I'm a Ruby newbie, so I'm not sure if this is idiomatic Ruby or not: that is, I'm not sure how common or accepted it is to define new methods directly on object instances, I only know it's possible ;-)</p>\n"
},
{
"answer_id": 224350,
"author": "Sam Gibson",
"author_id": 29319,
"author_profile": "https://Stackoverflow.com/users/29319",
"pm_score": 2,
"selected": false,
"text": "<p>FasterCSV patches the Array class and adds a <a href=\"http://fastercsv.rubyforge.org/classes/Array.html#M000003\" rel=\"nofollow noreferrer\">'to_csv'</a> method to it already, but it doesn't do what you want. You could overwrite it yourself by doing something like:</p>\n\n<pre><code>class Array\n def to_csv(options = Hash.new)\n collect { |item| item.to_csv }.join \"\\n\"\n end\nend\n</code></pre>\n\n<p>Or something along those lines, but that's kind of crappy.</p>\n\n<p>Honestly, it makes more sense the way you've done it as a class method on your model.</p>\n"
},
{
"answer_id": 236010,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 3,
"selected": false,
"text": "<p>The following will call to_csv on all instances included in the messages array.</p>\n\n<pre><code>messages = Message.find(:all)\ncsv = messages.map { |message| message.to_csv }\n</code></pre>\n\n<p>In Rails, in Ruby 1.9 or with Symbol#to_proc available through other means, you can also shorten it to:</p>\n\n<pre><code>csv = messages.map(&:to_csv)\n</code></pre>\n\n<p>The longer form is useful when you want to make a more complex operation:</p>\n\n<pre><code>csv = messages.map { |message| \n if message.length < 1000\n message.to_csv\n else\n \"Too long\"\n end\n}\n</code></pre>\n"
},
{
"answer_id": 312304,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 2,
"selected": false,
"text": "<p>Put this in a file in <em>lib/</em>. I would recommend calling it something like <code>base_ext.rb</code></p>\n\n<pre><code>require 'fastercsv'\nclass ActiveRecord::Base\n def self.to_csv(objects, skip_attributes=[])\n FasterCSV.generate do |csv|\n csv << attribute_names - skip_attributes\n objects.each do |object|\n csv << (attribute_names - skip_attributes).map { |a| \"'#{object.attributes[a]}'\" }.join(\", \")\n end\n end\n end\nend\n</code></pre>\n\n<p>After that, go to <em>config/environment.rb</em> and put <code>require 'base_ext'</code> at the bottom of the file to include the new extension. Upon restarting your server you should have access to a <code>to_csv</code> method on all model classes and when you pass it an array of objects should generate a nice CSV format for you.</p>\n"
},
{
"answer_id": 695103,
"author": "james2m",
"author_id": 84330,
"author_profile": "https://Stackoverflow.com/users/84330",
"pm_score": 0,
"selected": false,
"text": "<p>If it is isolated to one AR model I would add a to_custom_csv_array instance method</p>\n\n<pre><code>def to_custom_csv_array\n [self.from,self.to,self.created_at]\nend\n</code></pre>\n\n<p>then override find on the class</p>\n\n<pre><code>def self.find(*args)\n collection = super\n collection.extend(CustomToCSV) if collection.is_a?(Array)\nend\n</code></pre>\n\n<p>and in CustomToCSV define the to_custom_csv to generate the csv</p>\n\n<pre><code>module CustomToCSV\n def to_custom_csv\n FasterCSV.generate do |csv|\n csv << [\"from\",\"to\", \"received\"]\n csv << self.map {|obj| obj.to_custom_csv_array}\n end\n end\nend\n</code></pre>\n\n<p>This is from memory but should work.</p>\n"
},
{
"answer_id": 17447612,
"author": "Zahiduzzaman",
"author_id": 1415344,
"author_profile": "https://Stackoverflow.com/users/1415344",
"pm_score": 0,
"selected": false,
"text": "<p>I know that it is a very old question but just thought to provide a feedback anyway.\ncheck blog <a href=\"http://blog.zahiduzzaman.com/2013/07/adding-tocsv-method-to-active-record.html\" rel=\"nofollow\">http://blog.zahiduzzaman.com/2013/07/adding-tocsv-method-to-active-record.html</a>\njust another way of achieving this</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Currently, if I want to apply a method to a group of ActiveRecord objects, I have to structure the call like so:
```
messages = Message.find(:all)
csv = Message.to_csv(messages)
```
How can I define the method so it's structured like so?
```
messages = Message.find(:all)
csv = messages.to_csv
```
This is the current model code:
```
require 'fastercsv'
class Message < ActiveRecord::Base
def Message.to_csv(messages)
FasterCSV.generate do |csv|
csv << ["from","to", "received"]
for m in messages
csv << [m.from,m.to,m.created_at]
end
end
end
end
```
|
The following will call to\_csv on all instances included in the messages array.
```
messages = Message.find(:all)
csv = messages.map { |message| message.to_csv }
```
In Rails, in Ruby 1.9 or with Symbol#to\_proc available through other means, you can also shorten it to:
```
csv = messages.map(&:to_csv)
```
The longer form is useful when you want to make a more complex operation:
```
csv = messages.map { |message|
if message.length < 1000
message.to_csv
else
"Too long"
end
}
```
|
224,130 |
<p>I'm sure this is going to be a long shot, but I need help with a query involving QuickBooks Items.</p>
<p>I need to query for all QuickBooks Items that are linked to an Income account. Is there an easy way to do this, or do I need to make 2 queries (one for items ans one for accounts) and then check the account reference?</p>
<p>albeit not much, I have this:</p>
<pre>
<code>
IItemQuery query = MsgSetRequest.AppendItemQueryRq();
</code>
</pre>
<p>any ideas would be appreciated. Thanks.</p>
|
[
{
"answer_id": 337047,
"author": "Keith Palmer Jr.",
"author_id": 26133,
"author_profile": "https://Stackoverflow.com/users/26133",
"pm_score": 1,
"selected": false,
"text": "<p>You need to use at least two queries. You'll need to fetch a list of accounts, and then compare the items AccountRef FullName to the income accounts in the list. </p>\n"
},
{
"answer_id": 821905,
"author": "Yishai",
"author_id": 77779,
"author_profile": "https://Stackoverflow.com/users/77779",
"pm_score": 0,
"selected": false,
"text": "<p>Using the XML, at least, if you query all items you can get back the accounts of all of them, and filter for the account that you want. The full name of the account will be included in the item query response if you specifically ask for it in IncludeRetElement.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
I'm sure this is going to be a long shot, but I need help with a query involving QuickBooks Items.
I need to query for all QuickBooks Items that are linked to an Income account. Is there an easy way to do this, or do I need to make 2 queries (one for items ans one for accounts) and then check the account reference?
albeit not much, I have this:
```
IItemQuery query = MsgSetRequest.AppendItemQueryRq();
```
any ideas would be appreciated. Thanks.
|
You need to use at least two queries. You'll need to fetch a list of accounts, and then compare the items AccountRef FullName to the income accounts in the list.
|
224,138 |
<p>In the spirit of questions like <a href="https://stackoverflow.com/questions/224059/do-your-loops-test-at-the-top-or-bottom">Do your loops test at the top or bottom?</a>:</p>
<p>Which style do you use for an <em>infinite</em> loop, and why?</p>
<ul>
<li>while (true) { }</li>
<li>do { } while (true);</li>
<li>for (;;) { }</li>
<li>label: ... goto label;</li>
</ul>
|
[
{
"answer_id": 224142,
"author": "JPrescottSanders",
"author_id": 19444,
"author_profile": "https://Stackoverflow.com/users/19444",
"pm_score": 5,
"selected": false,
"text": "<pre><code>while(true) {}\n</code></pre>\n\n<p>It seems to convey the meaning of the loop most effectively.</p>\n"
},
{
"answer_id": 224144,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 3,
"selected": false,
"text": "<pre><code>while(1)\n{\n//do it \n}\n</code></pre>\n\n<p>That's how I roll.</p>\n"
},
{
"answer_id": 224146,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>I prefer <code>while(1)</code> or <code>while(true)</code> -- it's the clearest. <code>do { } while(true)</code> seems like needless obfuscation. Likewise, <code>for(;;)</code> can be confusing to people that have never seen it before, whereas <code>while(true)</code> is very intuitive. And there's absolutely no reason to do <code>label: ... goto label;</code>, it's just more confusing.</p>\n"
},
{
"answer_id": 224150,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 1,
"selected": false,
"text": "<p>When writing code for myself I use for(;;). Other people tend to be confused by its syntax and so for code that other people must see/use, I use while(true).</p>\n"
},
{
"answer_id": 224164,
"author": "None",
"author_id": 25012,
"author_profile": "https://Stackoverflow.com/users/25012",
"pm_score": 2,
"selected": false,
"text": "<pre><code>10 some l33t code\n20 goto 10\n</code></pre>\n"
},
{
"answer_id": 224166,
"author": "Dustin Getz",
"author_id": 20003,
"author_profile": "https://Stackoverflow.com/users/20003",
"pm_score": 1,
"selected": false,
"text": "<p>offtopic: if you think about what you are trying to express, you usually won't need an infinite loop.</p>\n"
},
{
"answer_id": 224172,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 5,
"selected": false,
"text": "<pre><code>for (;;)\n{\n /* No warnings are generated about constant value in the loop conditional\n plus it is easy to change when you realize you do need limits */ \n}\n</code></pre>\n"
},
{
"answer_id": 224175,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 3,
"selected": false,
"text": "<p>I like to use the <strong>for(;;)</strong> approach because the <strong>MSVC++</strong> compiler <em>complains</em> about while loop approach:</p>\n\n<pre><code>void main()\n{\n while(1) // test.cpp(5) : warning C4127: conditional expression is constant\n {\n }\n\n for(;;)\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 224195,
"author": "Moishe Lettvin",
"author_id": 23786,
"author_profile": "https://Stackoverflow.com/users/23786",
"pm_score": 1,
"selected": false,
"text": "<p><code>for (;;)</code> is what I usually see.</p>\n"
},
{
"answer_id": 224196,
"author": "Michael McCarty",
"author_id": 25007,
"author_profile": "https://Stackoverflow.com/users/25007",
"pm_score": 0,
"selected": false,
"text": "<p>Infinite loops are a bad idea, but in practice that doesn't always hold up.</p>\n\n<p>I prefer while(1) { } but make sure something within the loop can cause it to break out.</p>\n"
},
{
"answer_id": 224197,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 2,
"selected": false,
"text": "<p>I usually use <code>for(;;) { }</code> which I always think of as \"for-ever\".</p>\n\n<p>Some languages offer a <code>repeat { }</code> construct which will natively loop forever. I find the <code>for(;;) { }</code> construct visually the most similar to this because it is so different from the normal <code>for()</code> construct. This is an important attribute for an infinite loop that <code>while(1) { }</code> doesn't really have.</p>\n"
},
{
"answer_id": 224205,
"author": "moo",
"author_id": 23107,
"author_profile": "https://Stackoverflow.com/users/23107",
"pm_score": 1,
"selected": false,
"text": "<pre><code>for(;;);\n</code></pre>\n\n<p>Filler text.</p>\n"
},
{
"answer_id": 224208,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 2,
"selected": false,
"text": "<p>Infinite tail-recursion ;)</p>\n\n<p>It's somewhat compiler-dependant...</p>\n"
},
{
"answer_id": 224216,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>I use <code>for (;;)</code> in C-style languages and <code>while true</code> in languages that don't support that construct.</p>\n\n<p>I learned the <code>for (;;)</code> method in K&R and it has always felt like idiomatic C to me.</p>\n"
},
{
"answer_id": 224257,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I usually use <code>while() {}</code>, but after learning that <code>for(;;) {}</code> isn't some sort of crazy invalid syntax, I'll be sure to use the more unique option.</p>\n\n<p>Differentiates infinite loops from actual conditionals, you see.</p>\n"
},
{
"answer_id": 224736,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 4,
"selected": false,
"text": "<pre><code>#define forever for(;;)\n\nforever {\n /*stuff*/\n}\n</code></pre>\n"
},
{
"answer_id": 226011,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>I now prefer the \"<code>for (;;)</code>\" idiom because it seems to 'stick out' more. I used to use the \"<code>while (true)</code>\" idiom because I thought it expressed intent better, but I've switched over because I think the \"<code>for (;;)</code>\" idiom is well known enough to adequately express intent as well as I believe it's better by being more visible.</p>\n\n<p>Kind of like how Stroustrup made the new casts in C++ purposefully ugly - so they stick out.</p>\n"
},
{
"answer_id": 1772337,
"author": "Dan Moulding",
"author_id": 95706,
"author_profile": "https://Stackoverflow.com/users/95706",
"pm_score": 2,
"selected": false,
"text": "<p>Let the flaming begin...</p>\n\n<p>If the loop is a <em>true</em> infinite loop (i.e. there is no break condition -- only an external event can terminate the thread's/process' execution), then I actually prefer the label and <code>goto</code>. Here's why:</p>\n\n<p>First, the use of <code>while</code>, <code>for</code>, and <code>do ... while</code>, all imply that the loop might terminate. Even if the terminating condition is never achievable, the <em>syntactical meaning</em> of these constructs is that there <strong>is</strong> some termination condition.</p>\n\n<p>Second, using a loop construct introduces an extra level of indentation. I hate indentation that's not necessary. It wastes valuable columnar real-estate.</p>\n\n<p>Third, the only <em>true</em> infinite loop is the one that <em>unconditionally</em> jumps back to the beginning of the loop. Only <code>goto</code> fits that purpose exactly.</p>\n\n<p>The truth is I don't really care that much about it. They all get the job done and most will result in the exact same assembly instructions anyway. <strong>However</strong>, the assembly that's generated will in all probability be an unconditional jump (if you're optimizer is worth a damn), which maps directly to which C construct, kids? That's right... your old friend <code>goto</code>.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28258/"
] |
In the spirit of questions like [Do your loops test at the top or bottom?](https://stackoverflow.com/questions/224059/do-your-loops-test-at-the-top-or-bottom):
Which style do you use for an *infinite* loop, and why?
* while (true) { }
* do { } while (true);
* for (;;) { }
* label: ... goto label;
|
```
while(true) {}
```
It seems to convey the meaning of the loop most effectively.
|
224,155 |
<p>I have something here that is really catching me off guard.</p>
<p>I have an ObservableCollection of T that is filled with items. I also have an event handler attached to the CollectionChanged event.</p>
<p>When you <strong>Clear</strong> the collection it causes an CollectionChanged event with e.Action set to NotifyCollectionChangedAction.Reset. Ok, that's normal. But what is weird is that neither e.OldItems or e.NewItems has anything in it. <strong>I would expect e.OldItems to be filled with all items that were removed from the collection.</strong></p>
<p>Has anyone else seen this? And if so, how have they gotten around it?</p>
<p>Some background: I am using the CollectionChanged event to attach and detach from another event and thus if I don't get any items in e.OldItems ... I won't be able to detach from that event.</p>
<p><br></p>
<p><strong>CLARIFICATION:</strong>
I do know that the documentation doesn't <em>outright</em> state that it has to behave this way. But for every other action, it is notifying me of what it has done. So, my assumption is that it would tell me ... in the case of Clear/Reset as well.</p>
<p><br></p>
<p>Below is the sample code if you wish to reproduce it yourself. First off the xaml:</p>
<pre><code><Window
x:Class="ObservableCollection.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300"
>
<StackPanel>
<Button x:Name="addButton" Content="Add" Width="100" Height="25" Margin="10" Click="addButton_Click"/>
<Button x:Name="moveButton" Content="Move" Width="100" Height="25" Margin="10" Click="moveButton_Click"/>
<Button x:Name="removeButton" Content="Remove" Width="100" Height="25" Margin="10" Click="removeButton_Click"/>
<Button x:Name="replaceButton" Content="Replace" Width="100" Height="25" Margin="10" Click="replaceButton_Click"/>
<Button x:Name="resetButton" Content="Reset" Width="100" Height="25" Margin="10" Click="resetButton_Click"/>
</StackPanel>
</Window>
</code></pre>
<p>Next, the code behind:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace ObservableCollection
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
_integerObservableCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_integerObservableCollection_CollectionChanged);
}
private void _integerObservableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Move:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Replace:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
break;
default:
break;
}
}
private void addButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Add(25);
}
private void moveButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Move(0, 19);
}
private void removeButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.RemoveAt(0);
}
private void replaceButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection[0] = 50;
}
private void resetButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Clear();
}
private ObservableCollection<int> _integerObservableCollection = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
}
}
</code></pre>
|
[
{
"answer_id": 224169,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>Looking at the <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedeventargs_members.aspx\" rel=\"nofollow noreferrer\">NotifyCollectionChangedEventArgs</a>, it appears that OldItems only contains items changed as a result of Replace, Remove, or Move action. It doesn't indicate that it will contain anything on Clear. I suspect that Clear fires the event, but does not registered the removed items and does not invoke the Remove code at all.</p>\n"
},
{
"answer_id": 225225,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 2,
"selected": false,
"text": "<p>This is how ObservableCollection works, you can work around this by keeping your own list outside of the ObservableCollection (adding to the list when action is Add, remove when action is Remove etc.) then you can get all the removed items (or added items) when action is Reset by comparing your list with the ObservableCollection.</p>\n\n<p>Another option is to create your own class that implements IList and INotifyCollectionChanged, then you can attach and detach events from within that class (or set OldItems on Clear if you like) - it's really not difficult, but it is a lot of typing.</p>\n"
},
{
"answer_id": 225590,
"author": "decasteljau",
"author_id": 12082,
"author_profile": "https://Stackoverflow.com/users/12082",
"pm_score": 5,
"selected": false,
"text": "<p>We had the same issue here. The Reset action in CollectionChanged does not include the OldItems. We had a workaround: we used instead the following extension method:</p>\n\n<pre><code>public static void RemoveAll(this IList list)\n{\n while (list.Count > 0)\n {\n list.RemoveAt(list.Count - 1);\n }\n}\n</code></pre>\n\n<p>We ended up not supporting the Clear() function, and throwing a NotSupportedException in CollectionChanged event for Reset actions. The RemoveAll will trigger a Remove action in CollectionChanged event, with the proper OldItems.</p>\n"
},
{
"answer_id": 225778,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, even though I still wish that ObservableCollection behaved as I wished ... the code below is what I ended up doing. Basically, I created a new collection of T called TrulyObservableCollection and overrided the ClearItems method which I then used to raise a Clearing event.</p>\n\n<p>In the code that uses this TrulyObservableCollection, I use this Clearing event to loop through the items <em>that are still in the collection at that point</em> to do the detach on the event that I was wishing to detach from.</p>\n\n<p>Hope this approach helps someone else as well.</p>\n\n<pre><code>public class TrulyObservableCollection<T> : ObservableCollection<T>\n{\n public event EventHandler<EventArgs> Clearing;\n protected virtual void OnClearing(EventArgs e)\n {\n if (Clearing != null)\n Clearing(this, e);\n }\n\n protected override void ClearItems()\n {\n OnClearing(EventArgs.Empty);\n base.ClearItems();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1082900,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I tackled this one in a slightly different manner as I wanted to register to one event and handle all additions and removals in the event handler. I started off overriding the collection changed event and redirecting reset actions to removal actions with a list of items. This all went wrong as I was using the observable collection as an items source for a collection view and got \"Range actions not supported\".</p>\n\n<p>I finally created a new event called CollectionChangedRange which acts in the manner I expected the inbuilt version to act.</p>\n\n<p>I can't imagine why this limitation would be allowed and hope that this post at least stops others from going down the dead end that I did.</p>\n\n<pre><code>/// <summary>\n/// An observable collection with support for addrange and clear\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n[Serializable]\n[TypeConverter(typeof(ExpandableObjectConverter))]\npublic class ObservableCollectionRange<T> : ObservableCollection<T>\n{\n private bool _addingRange;\n\n [field: NonSerialized]\n public event NotifyCollectionChangedEventHandler CollectionChangedRange;\n\n protected virtual void OnCollectionChangedRange(NotifyCollectionChangedEventArgs e)\n {\n if ((CollectionChangedRange == null) || _addingRange) return;\n using (BlockReentrancy())\n {\n CollectionChangedRange(this, e);\n }\n }\n\n public void AddRange(IEnumerable<T> collection)\n {\n CheckReentrancy();\n var newItems = new List<T>();\n if ((collection == null) || (Items == null)) return;\n using (var enumerator = collection.GetEnumerator())\n {\n while (enumerator.MoveNext())\n {\n _addingRange = true;\n Add(enumerator.Current);\n _addingRange = false;\n newItems.Add(enumerator.Current);\n }\n }\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems));\n }\n\n protected override void ClearItems()\n {\n CheckReentrancy();\n var oldItems = new List<T>(this);\n base.ClearItems();\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItems));\n }\n\n protected override void InsertItem(int index, T item)\n {\n CheckReentrancy();\n base.InsertItem(index, item);\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));\n }\n\n protected override void MoveItem(int oldIndex, int newIndex)\n {\n CheckReentrancy();\n var item = base[oldIndex];\n base.MoveItem(oldIndex, newIndex);\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, item, newIndex, oldIndex));\n }\n\n protected override void RemoveItem(int index)\n {\n CheckReentrancy();\n var item = base[index];\n base.RemoveItem(index);\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));\n }\n\n protected override void SetItem(int index, T item)\n {\n CheckReentrancy();\n var oldItem = base[index];\n base.SetItem(index, item);\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, oldItem, item, index));\n }\n}\n\n/// <summary>\n/// A read only observable collection with support for addrange and clear\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n[Serializable]\n[TypeConverter(typeof(ExpandableObjectConverter))]\npublic class ReadOnlyObservableCollectionRange<T> : ReadOnlyObservableCollection<T>\n{\n [field: NonSerialized]\n public event NotifyCollectionChangedEventHandler CollectionChangedRange;\n\n public ReadOnlyObservableCollectionRange(ObservableCollectionRange<T> list) : base(list)\n {\n list.CollectionChangedRange += HandleCollectionChangedRange;\n }\n\n private void HandleCollectionChangedRange(object sender, NotifyCollectionChangedEventArgs e)\n {\n OnCollectionChangedRange(e);\n }\n\n protected virtual void OnCollectionChangedRange(NotifyCollectionChangedEventArgs args)\n {\n if (CollectionChangedRange != null)\n {\n CollectionChangedRange(this, args);\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 1138654,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 1,
"selected": false,
"text": "<p>I was just going through some of the charting code in the Silverlight and WPF toolkits and noticed that they also solved this problem (in a kind of similar way) ... and I thought I would go ahead and post their solution.</p>\n\n<p>Basically, they also created a derived ObservableCollection and overrode ClearItems, calling Remove on each item being cleared.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>/// <summary>\n/// An observable collection that cannot be reset. When clear is called\n/// items are removed individually, giving listeners the chance to detect\n/// each remove event and perform operations such as unhooking event \n/// handlers.\n/// </summary>\n/// <typeparam name=\"T\">The type of item in the collection.</typeparam>\npublic class NoResetObservableCollection<T> : ObservableCollection<T>\n{\n public NoResetObservableCollection()\n {\n }\n\n /// <summary>\n /// Clears all items in the collection by removing them individually.\n /// </summary>\n protected override void ClearItems()\n {\n IList<T> items = new List<T>(this);\n foreach (T item in items)\n {\n Remove(item);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1505868,
"author": "HaxElit",
"author_id": 182703,
"author_profile": "https://Stackoverflow.com/users/182703",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I decided to get dirty with it myself.</p>\n\n<p>Microsoft put a LOT of work into always making sure the NotifyCollectionChangedEventArgs doesn't have any data when calling a reset. I'm assuming this was a performance/memory decision. If you are resetting a collection with 100,000 elements, I'm assuming they didn't want to duplicate all those elements.</p>\n\n<p>But seeing as my collections never have more then 100 elements, I don't see a problem with it.</p>\n\n<p>Anyway I created an inherited class with the following method:</p>\n\n<pre><code>protected override void ClearItems()\n{\n CheckReentrancy();\n List<TItem> oldItems = new List<TItem>(Items);\n\n Items.Clear();\n\n OnPropertyChanged(new PropertyChangedEventArgs(\"Count\"));\n OnPropertyChanged(new PropertyChangedEventArgs(\"Item[]\"));\n\n NotifyCollectionChangedEventArgs e =\n new NotifyCollectionChangedEventArgs\n (\n NotifyCollectionChangedAction.Reset\n );\n\n FieldInfo field =\n e.GetType().GetField\n (\n \"_oldItems\",\n BindingFlags.Instance | BindingFlags.NonPublic\n );\n field.SetValue(e, oldItems);\n\n OnCollectionChanged(e);\n }\n</code></pre>\n"
},
{
"answer_id": 2931145,
"author": "Chris",
"author_id": 353126,
"author_profile": "https://Stackoverflow.com/users/353126",
"pm_score": 2,
"selected": false,
"text": "<p>For the scenario of attaching and detaching event handlers to the elements of the ObservableCollection there is also a \"client-side\" solution. In the event handling code you can check if the sender is in the ObservableCollection using the Contains method. Pro: you can work with any existing ObservableCollection. Cons: the Contains method runs with O(n) where n is the number of elements in the ObservableCollection. So this is a solution for small ObservableCollections.</p>\n\n<p>Another \"client-side\" solution is to use an event handler in the middle. Just register all events to the event handler in the middle. This event handler in turn notifies the real event handler trough a callback or an event. If a Reset action occurs remove the callback or event create a new event handler in the middle and forget about the old one. This approach also works for big ObservableCollections. I used this for the PropertyChanged event (see code below).</p>\n\n<pre><code> /// <summary>\n /// Helper class that allows to \"detach\" all current Eventhandlers by setting\n /// DelegateHandler to null.\n /// </summary>\n public class PropertyChangedDelegator\n {\n /// <summary>\n /// Callback to the real event handling code.\n /// </summary>\n public PropertyChangedEventHandler DelegateHandler;\n /// <summary>\n /// Eventhandler that is registered by the elements.\n /// </summary>\n /// <param name=\"sender\">the element that has been changed.</param>\n /// <param name=\"e\">the event arguments</param>\n public void PropertyChangedHandler(Object sender, PropertyChangedEventArgs e)\n {\n if (DelegateHandler != null)\n {\n DelegateHandler(sender, e);\n }\n else\n {\n INotifyPropertyChanged s = sender as INotifyPropertyChanged;\n if (s != null)\n s.PropertyChanged -= PropertyChangedHandler;\n } \n }\n }\n</code></pre>\n"
},
{
"answer_id": 2963340,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": false,
"text": "<p>It doesn't claim to include the old items, because Reset doesn't mean that the list has been cleared</p>\n\n<p>It means that some dramatic thing has taken place, and the cost of working out the add/removes would most likely exceed the cost of just re-scanning the list from scratch... so that's what you should do.</p>\n\n<p>MSDN suggests an example of the entire collection being re-sorted as a candidate for reset.</p>\n\n<p>To reiterate. <strong>Reset doesn't mean clear</strong>, it means <em>Your assumptions about the list are now invalid. Treat it as if it's an entirely new list</em>. Clear happens to be one instance of this, but there could well be others. </p>\n\n<p>Some examples:<br>\nI've had a list like this with a lot of items in it, and it has been databound to a WPF <code>ListView</code> to display on-screen.<br>\nIf you clear the list and raise the <code>.Reset</code> event, the performance is pretty much instant, but if you instead raise many individual <code>.Remove</code> events, the performance is terrible, as WPF removes the items one by one. \nI've also used <code>.Reset</code> in my own code to indicate that the list has been re-sorted, rather than issuing thousands of individual <code>Move</code> operations. As with Clear, there is a large performance hit when when raising many individual events.</p>\n"
},
{
"answer_id": 3237039,
"author": "Rick Beerendonk",
"author_id": 260821,
"author_profile": "https://Stackoverflow.com/users/260821",
"pm_score": 2,
"selected": false,
"text": "<p>The ObservableCollection as well as the INotifyCollectionChanged interface are clearly written with a specific use in mind: UI building and its specific performance characteristics.</p>\n\n<p>When you want notifications of collection changes then you are generally only interested in Add and Remove events.</p>\n\n<p>I use the following interface:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\n/// <summary>\n/// Notifies listeners of the following situations:\n/// <list type=\"bullet\">\n/// <item>Elements have been added.</item>\n/// <item>Elements are about to be removed.</item>\n/// </list>\n/// </summary>\n/// <typeparam name=\"T\">The type of elements in the collection.</typeparam>\ninterface INotifyCollection<T>\n{\n /// <summary>\n /// Occurs when elements have been added.\n /// </summary>\n event EventHandler<NotifyCollectionEventArgs<T>> Added;\n\n /// <summary>\n /// Occurs when elements are about to be removed.\n /// </summary>\n event EventHandler<NotifyCollectionEventArgs<T>> Removing;\n}\n\n/// <summary>\n/// Provides data for the NotifyCollection event.\n/// </summary>\n/// <typeparam name=\"T\">The type of elements in the collection.</typeparam>\npublic class NotifyCollectionEventArgs<T> : EventArgs\n{\n /// <summary>\n /// Gets or sets the elements.\n /// </summary>\n /// <value>The elements.</value>\n public IEnumerable<T> Items\n {\n get;\n set;\n }\n}\n</code></pre>\n\n<p>I've also written my own overload of Collection where:</p>\n\n<ul>\n<li>ClearItems raises Removing</li>\n<li>InsertItem raises Added</li>\n<li>RemoveItem raises Removing</li>\n<li>SetItem raises Removing and Added</li>\n</ul>\n\n<p>Of course, AddRange can be added as well.</p>\n"
},
{
"answer_id": 5356516,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 1,
"selected": false,
"text": "<p>This is a hot subject ... because in my opinion, Microsoft did not do its job properly ... yet again. Don't misunderstand me, I like Microsoft, but they are not perfect!</p>\n\n<p>I read most of the previous comments. I agree with all those who think that Microsoft did not programmed Clear() properly.</p>\n\n<p>In my opinion, at least, it needs an argument to make it possible to detach objects from an event ... but I also understand the impact of it. Then, I thought up this proposed solution.</p>\n\n<p>I hope it will make everybody happy, or at least, most everyone ...</p>\n\n<p>Eric</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Reflection;\n\nnamespace WpfUtil.Collections\n{\n public static class ObservableCollectionExtension\n {\n public static void RemoveAllOneByOne<T>(this ObservableCollection<T> obsColl)\n {\n foreach (T item in obsColl)\n {\n while (obsColl.Count > 0)\n {\n obsColl.RemoveAt(0);\n }\n }\n }\n\n public static void RemoveAll<T>(this ObservableCollection<T> obsColl)\n {\n if (obsColl.Count > 0)\n {\n List<T> removedItems = new List<T>(obsColl);\n obsColl.Clear();\n\n NotifyCollectionChangedEventArgs e =\n new NotifyCollectionChangedEventArgs\n (\n NotifyCollectionChangedAction.Remove,\n removedItems\n );\n var eventInfo =\n obsColl.GetType().GetField\n (\n \"CollectionChanged\",\n BindingFlags.Instance | BindingFlags.NonPublic\n );\n if (eventInfo != null)\n {\n var eventMember = eventInfo.GetValue(obsColl);\n // note: if eventMember is null\n // nobody registered to the event, you can't call it.\n if (eventMember != null)\n eventMember.GetType().GetMethod(\"Invoke\").\n Invoke(eventMember, new object[] { obsColl, e });\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5567420,
"author": "Dima",
"author_id": 694939,
"author_profile": "https://Stackoverflow.com/users/694939",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedaction(VS.95).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedaction(VS.95).aspx</a></p>\n\n<p>Please read this documentation with your eyes open and your brain turned on.\nMicrosoft did everything right. You must re-scan your collection when it throws a Reset notification for you. You get a Reset notification because throwing Add/Remove for each item (being removed from and added back to collection) is too expensive.</p>\n\n<p>Orion Edwards is completely right (respect, man). Please think wider when reading the documentation.</p>\n"
},
{
"answer_id": 8660754,
"author": "Stéphane",
"author_id": 1119933,
"author_profile": "https://Stackoverflow.com/users/1119933",
"pm_score": 1,
"selected": false,
"text": "<p>To keep it simple why don't you override the ClearItem method and do whatever you want there ie Detach the items from the event.</p>\n\n<pre><code>public class PeopleAttributeList : ObservableCollection<PeopleAttributeDto>, {\n{\n protected override void ClearItems()\n {\n Do what ever you want\n base.ClearItems();\n }\n\n rest of the code omitted\n}\n</code></pre>\n\n<p>Simple, clean, and contain within the collection code.</p>\n"
},
{
"answer_id": 8950505,
"author": "grantnz",
"author_id": 350550,
"author_profile": "https://Stackoverflow.com/users/350550",
"pm_score": 4,
"selected": false,
"text": "<p>Another option is to replace the Reset event with a single Remove event that has all the cleared items in its OldItems property as follows:</p>\n\n<pre><code>public class ObservableCollectionNoReset<T> : ObservableCollection<T>\n{\n protected override void ClearItems()\n {\n List<T> removed = new List<T>(this);\n base.ClearItems();\n base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));\n }\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (e.Action != NotifyCollectionChangedAction.Reset)\n base.OnCollectionChanged(e);\n }\n // Constructors omitted\n ...\n}\n</code></pre>\n\n<p>Advantages:</p>\n\n<ol>\n<li><p>No need to subscribe to an additional event (as required by accepted answer)</p></li>\n<li><p>Doesn't generate an event for each object removed (some other proposed solutions result in multiple Removed events).</p></li>\n<li><p>Subscriber only needs to check NewItems & OldItems on any event to add/remove event handlers as required.</p></li>\n</ol>\n\n<p>Disadvantages:</p>\n\n<ol>\n<li><p>No Reset event</p></li>\n<li><p>Small (?) overhead creating copy of list.</p></li>\n<li><p>???</p></li>\n</ol>\n\n<p>EDIT 2012-02-23</p>\n\n<p>Unfortunately, when bound to WPF list based controls, Clearing a ObservableCollectionNoReset collection with multiple elements will result in an exception \"Range actions not supported\".\nTo be used with controls with this limitation, I changed the ObservableCollectionNoReset class to:</p>\n\n<pre><code>public class ObservableCollectionNoReset<T> : ObservableCollection<T>\n{\n // Some CollectionChanged listeners don't support range actions.\n public Boolean RangeActionsSupported { get; set; }\n\n protected override void ClearItems()\n {\n if (RangeActionsSupported)\n {\n List<T> removed = new List<T>(this);\n base.ClearItems();\n base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));\n }\n else\n {\n while (Count > 0 )\n base.RemoveAt(Count - 1);\n } \n }\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (e.Action != NotifyCollectionChangedAction.Reset)\n base.OnCollectionChanged(e);\n }\n\n public ObservableCollectionNoReset(Boolean rangeActionsSupported = false) \n {\n RangeActionsSupported = rangeActionsSupported;\n }\n\n // Additional constructors omitted.\n }\n</code></pre>\n\n<p>This isn't as efficient when RangeActionsSupported is false (the default) because one Remove notification is generated per object in the collection</p>\n"
},
{
"answer_id": 9416535,
"author": "Alain",
"author_id": 529618,
"author_profile": "https://Stackoverflow.com/users/529618",
"pm_score": 3,
"selected": false,
"text": "<p>I've found a solution that allows the user to both capitalize on the efficiency of adding or removing many items at a time while only firing one event - and satisfy the needs of UIElements to get the Action.Reset event args while all other users would like a list of elements added and removed.</p>\n\n<p>This solution involves overriding the CollectionChanged event. When we go to fire this event, we can actually look at the target of each registered handler and determine their type. Since only ICollectionView classes require <code>NotifyCollectionChangedAction.Reset</code> args when more than one item changes, we can single them out, and give everyone else proper event args that contain the full list of items removed or added. Below is the implementation.</p>\n\n<pre><code>public class BaseObservableCollection<T> : ObservableCollection<T>\n{\n //Flag used to prevent OnCollectionChanged from firing during a bulk operation like Add(IEnumerable<T>) and Clear()\n private bool _SuppressCollectionChanged = false;\n\n /// Overridden so that we may manually call registered handlers and differentiate between those that do and don't require Action.Reset args.\n public override event NotifyCollectionChangedEventHandler CollectionChanged;\n\n public BaseObservableCollection() : base(){}\n public BaseObservableCollection(IEnumerable<T> data) : base(data){}\n\n #region Event Handlers\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if( !_SuppressCollectionChanged )\n {\n base.OnCollectionChanged(e);\n if( CollectionChanged != null )\n CollectionChanged.Invoke(this, e);\n }\n }\n\n //CollectionViews raise an error when they are passed a NotifyCollectionChangedEventArgs that indicates more than\n //one element has been added or removed. They prefer to receive a \"Action=Reset\" notification, but this is not suitable\n //for applications in code, so we actually check the type we're notifying on and pass a customized event args.\n protected virtual void OnCollectionChangedMultiItem(NotifyCollectionChangedEventArgs e)\n {\n NotifyCollectionChangedEventHandler handlers = this.CollectionChanged;\n if( handlers != null )\n foreach( NotifyCollectionChangedEventHandler handler in handlers.GetInvocationList() )\n handler(this, !(handler.Target is ICollectionView) ? e : new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n #endregion\n\n #region Extended Collection Methods\n protected override void ClearItems()\n {\n if( this.Count == 0 ) return;\n\n List<T> removed = new List<T>(this);\n _SuppressCollectionChanged = true;\n base.ClearItems();\n _SuppressCollectionChanged = false;\n OnCollectionChangedMultiItem(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));\n }\n\n public void Add(IEnumerable<T> toAdd)\n {\n if( this == toAdd )\n throw new Exception(\"Invalid operation. This would result in iterating over a collection as it is being modified.\");\n\n _SuppressCollectionChanged = true;\n foreach( T item in toAdd )\n Add(item);\n _SuppressCollectionChanged = false;\n OnCollectionChangedMultiItem(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List<T>(toAdd)));\n }\n\n public void Remove(IEnumerable<T> toRemove)\n {\n if( this == toRemove )\n throw new Exception(\"Invalid operation. This would result in iterating over a collection as it is being modified.\");\n\n _SuppressCollectionChanged = true;\n foreach( T item in toRemove )\n Remove(item);\n _SuppressCollectionChanged = false;\n OnCollectionChangedMultiItem(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new List<T>(toRemove)));\n }\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 16646352,
"author": "Manas",
"author_id": 2401140,
"author_profile": "https://Stackoverflow.com/users/2401140",
"pm_score": -1,
"selected": false,
"text": "<p>If your <code>ObservableCollection</code> is not getting clear, then you may try this below code. it may help you:</p>\n\n<pre><code>private TestEntities context; // This is your context\n\ncontext.Refresh(System.Data.Objects.RefreshMode.StoreWins, context.UserTables); // to refresh the object context\n</code></pre>\n"
},
{
"answer_id": 20110760,
"author": "hypehuman",
"author_id": 1269598,
"author_profile": "https://Stackoverflow.com/users/1269598",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same issue, and this was my solution. It seems to work. Does anyone see any potential problems with this approach?</p>\n\n<pre><code>// overriden so that we can call GetInvocationList\npublic override event NotifyCollectionChangedEventHandler CollectionChanged;\n\nprotected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n{\n NotifyCollectionChangedEventHandler collectionChanged = CollectionChanged;\n if (collectionChanged != null)\n {\n lock (collectionChanged)\n {\n foreach (NotifyCollectionChangedEventHandler handler in collectionChanged.GetInvocationList())\n {\n try\n {\n handler(this, e);\n }\n catch (NotSupportedException ex)\n {\n // this will occur if this collection is used as an ItemsControl.ItemsSource\n if (ex.Message == \"Range actions are not supported.\")\n {\n handler(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n else\n {\n throw ex;\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>Here are some other useful methods in my class:</p>\n\n<pre><code>public void SetItems(IEnumerable<T> newItems)\n{\n Items.Clear();\n foreach (T newItem in newItems)\n {\n Items.Add(newItem);\n }\n NotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n}\n\npublic void AddRange(IEnumerable<T> newItems)\n{\n int index = Count;\n foreach (T item in newItems)\n {\n Items.Add(item);\n }\n NotifyCollectionChangedEventArgs e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List<T>(newItems), index);\n NotifyCollectionChanged(e);\n}\n\npublic void RemoveRange(int startingIndex, int count)\n{\n IList<T> oldItems = new List<T>();\n for (int i = 0; i < count; i++)\n {\n oldItems.Add(Items[startingIndex]);\n Items.RemoveAt(startingIndex);\n }\n NotifyCollectionChangedEventArgs e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new List<T>(oldItems), startingIndex);\n NotifyCollectionChanged(e);\n}\n\n// this needs to be overridden to avoid raising a NotifyCollectionChangedEvent with NotifyCollectionChangedAction.Reset, which our other lists don't support\nnew public void Clear()\n{\n RemoveRange(0, Count);\n}\n\npublic void RemoveWhere(Func<T, bool> criterion)\n{\n List<T> removedItems = null;\n int startingIndex = default(int);\n int contiguousCount = default(int);\n for (int i = 0; i < Count; i++)\n {\n T item = Items[i];\n if (criterion(item))\n {\n if (removedItems == null)\n {\n removedItems = new List<T>();\n startingIndex = i;\n contiguousCount = 0;\n }\n Items.RemoveAt(i);\n removedItems.Add(item);\n contiguousCount++;\n }\n else if (removedItems != null)\n {\n NotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, startingIndex));\n removedItems = null;\n i = startingIndex;\n }\n }\n if (removedItems != null)\n {\n NotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, startingIndex));\n }\n}\n\nprivate void NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)\n{\n OnPropertyChanged(new PropertyChangedEventArgs(\"Count\"));\n OnPropertyChanged(new PropertyChangedEventArgs(\"Item[]\"));\n OnCollectionChanged(e);\n}\n</code></pre>\n"
},
{
"answer_id": 25529403,
"author": "Formentz",
"author_id": 2645207,
"author_profile": "https://Stackoverflow.com/users/2645207",
"pm_score": 0,
"selected": false,
"text": "<p>I found another \"simple\" solution deriving from ObservableCollection, but it is not very elegant because it uses Reflection... If you like it here is my solution:</p>\n\n<pre><code>public class ObservableCollectionClearable<T> : ObservableCollection<T>\n{\n private T[] ClearingItems = null;\n\n protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n {\n switch (e.Action)\n {\n case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:\n if (this.ClearingItems != null)\n {\n ReplaceOldItems(e, this.ClearingItems);\n this.ClearingItems = null;\n }\n break;\n }\n base.OnCollectionChanged(e);\n }\n\n protected override void ClearItems()\n {\n this.ClearingItems = this.ToArray();\n base.ClearItems();\n }\n\n private static void ReplaceOldItems(System.Collections.Specialized.NotifyCollectionChangedEventArgs e, T[] olditems)\n {\n Type t = e.GetType();\n System.Reflection.FieldInfo foldItems = t.GetField(\"_oldItems\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (foldItems != null)\n {\n foldItems.SetValue(e, olditems);\n }\n }\n}\n</code></pre>\n\n<p>Here I save the current elements in an array field in the ClearItems method, then I intercept the call of OnCollectionChanged and overwrite the e._oldItems private field (through Reflections) before launching base.OnCollectionChanged</p>\n"
},
{
"answer_id": 32650327,
"author": "Artem Illarionov",
"author_id": 1376506,
"author_profile": "https://Stackoverflow.com/users/1376506",
"pm_score": 0,
"selected": false,
"text": "<p>You can override ClearItems method and raise event with Remove action and OldItems .</p>\n\n<pre><code>public class ObservableCollection<T> : System.Collections.ObjectModel.ObservableCollection<T>\n{\n protected override void ClearItems()\n {\n CheckReentrancy();\n var items = Items.ToList();\n base.ClearItems();\n OnPropertyChanged(new PropertyChangedEventArgs(\"Count\"));\n OnPropertyChanged(new PropertyChangedEventArgs(\"Item[]\"));\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, items, -1));\n }\n}\n</code></pre>\n\n<p>Part of <code>System.Collections.ObjectModel.ObservableCollection<T></code> realization:</p>\n\n<pre><code>public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged\n{\n protected override void ClearItems()\n {\n CheckReentrancy();\n base.ClearItems();\n OnPropertyChanged(CountString);\n OnPropertyChanged(IndexerName);\n OnCollectionReset();\n }\n\n private void OnPropertyChanged(string propertyName)\n {\n OnPropertyChanged(new PropertyChangedEventArgs(propertyName));\n }\n\n private void OnCollectionReset()\n {\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n\n private const string CountString = \"Count\";\n\n private const string IndexerName = \"Item[]\";\n}\n</code></pre>\n"
},
{
"answer_id": 42713996,
"author": "DeadlyEmbrace",
"author_id": 2017251,
"author_profile": "https://Stackoverflow.com/users/2017251",
"pm_score": 4,
"selected": false,
"text": "<p>Okay, I know this is a very old question but I have come up with a good solution to the issue and thought I would share.\nThis solution takes inspiration from a lot of the great answers here but has the following advantages:</p>\n\n<ul>\n<li>No need to create a new class and override methods from ObservableCollection</li>\n<li>Does not tamper with the workings of NotifyCollectionChanged (so no messing with Reset)</li>\n<li>Does not make use of reflection</li>\n</ul>\n\n<p>Here is the code:</p>\n\n<pre><code> public static void Clear<T>(this ObservableCollection<T> collection, Action<ObservableCollection<T>> unhookAction)\n {\n unhookAction.Invoke(collection);\n collection.Clear();\n }\n</code></pre>\n\n<p>This extension method simply takes an <code>Action</code> which will be invoked before the collection is cleared.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22294/"
] |
I have something here that is really catching me off guard.
I have an ObservableCollection of T that is filled with items. I also have an event handler attached to the CollectionChanged event.
When you **Clear** the collection it causes an CollectionChanged event with e.Action set to NotifyCollectionChangedAction.Reset. Ok, that's normal. But what is weird is that neither e.OldItems or e.NewItems has anything in it. **I would expect e.OldItems to be filled with all items that were removed from the collection.**
Has anyone else seen this? And if so, how have they gotten around it?
Some background: I am using the CollectionChanged event to attach and detach from another event and thus if I don't get any items in e.OldItems ... I won't be able to detach from that event.
**CLARIFICATION:**
I do know that the documentation doesn't *outright* state that it has to behave this way. But for every other action, it is notifying me of what it has done. So, my assumption is that it would tell me ... in the case of Clear/Reset as well.
Below is the sample code if you wish to reproduce it yourself. First off the xaml:
```
<Window
x:Class="ObservableCollection.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300"
>
<StackPanel>
<Button x:Name="addButton" Content="Add" Width="100" Height="25" Margin="10" Click="addButton_Click"/>
<Button x:Name="moveButton" Content="Move" Width="100" Height="25" Margin="10" Click="moveButton_Click"/>
<Button x:Name="removeButton" Content="Remove" Width="100" Height="25" Margin="10" Click="removeButton_Click"/>
<Button x:Name="replaceButton" Content="Replace" Width="100" Height="25" Margin="10" Click="replaceButton_Click"/>
<Button x:Name="resetButton" Content="Reset" Width="100" Height="25" Margin="10" Click="resetButton_Click"/>
</StackPanel>
</Window>
```
Next, the code behind:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace ObservableCollection
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
_integerObservableCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_integerObservableCollection_CollectionChanged);
}
private void _integerObservableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Move:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Replace:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
break;
default:
break;
}
}
private void addButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Add(25);
}
private void moveButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Move(0, 19);
}
private void removeButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.RemoveAt(0);
}
private void replaceButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection[0] = 50;
}
private void resetButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Clear();
}
private ObservableCollection<int> _integerObservableCollection = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
}
}
```
|
Ok, even though I still wish that ObservableCollection behaved as I wished ... the code below is what I ended up doing. Basically, I created a new collection of T called TrulyObservableCollection and overrided the ClearItems method which I then used to raise a Clearing event.
In the code that uses this TrulyObservableCollection, I use this Clearing event to loop through the items *that are still in the collection at that point* to do the detach on the event that I was wishing to detach from.
Hope this approach helps someone else as well.
```
public class TrulyObservableCollection<T> : ObservableCollection<T>
{
public event EventHandler<EventArgs> Clearing;
protected virtual void OnClearing(EventArgs e)
{
if (Clearing != null)
Clearing(this, e);
}
protected override void ClearItems()
{
OnClearing(EventArgs.Empty);
base.ClearItems();
}
}
```
|
224,163 |
<p>I currently capture MiniDumps of unhandled exceptions using <Code>SetUnhandledExceptionFilter</Code> however at times I am getting "R6025: pure virtual function".</p>
<p>I understand how a pure virtual function call happens I am just wondering if it is possible to capture them so I can create a MiniDump at that point.</p>
|
[
{
"answer_id": 224176,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/99552/where-do-pure-virtual-function-call-crashes-come-from#100555\">this answer here</a> to the question <a href=\"https://stackoverflow.com/questions/99552/where-do-pure-virtual-function-call-crashes-come-from\">where do “pure virtual function call” crashes come from?</a>.</p>\n\n<blockquote>\n <p>To help with debugging these kinds of\n problems you can, in various versions\n of MSVC, replace the runtime library's\n purecall handler. You do this by\n providing your own function with this\n signature:</p>\n</blockquote>\n\n<pre><code>int __cdecl _purecall(void)\n</code></pre>\n\n<blockquote>\n <p>and\n linking it before you link the runtime\n library. This gives YOU control of\n what happens when a purecall is\n detected. Once you have control you\n can do something more useful than the\n standard handler. I have a handler\n that can provide a stack trace of\n where the purecall happened; see here:\n <a href=\"http://www.lenholgate.com/archives/000623.html\" rel=\"nofollow noreferrer\">http://www.lenholgate.com/archives/000623.html</a>\n for more details.</p>\n \n <p>(Note you can also call\n <code>_set_purecall_handler()</code> to install your handler in some versions of\n MSVC).</p>\n</blockquote>\n\n<p>So, in your purecall handler, make your minidump.</p>\n"
},
{
"answer_id": 224177,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 5,
"selected": true,
"text": "<p>If you want to catch all crashes you have to do more than just: SetUnhandledExceptionFilter</p>\n\n<p>I would also set the abort handler, the purecall handler, unexpected, terminate, and invalid parameter handler.</p>\n\n<pre><code>#include <signal.h>\n\ninline void signal_handler(int)\n{\n terminator();\n}\n\ninline void terminator() \n{\n int*z = 0; *z=13; \n}\n\ninline void __cdecl invalid_parameter_handler(const wchar_t *, const wchar_t *, const wchar_t *, unsigned int, uintptr_t)\n{\n terminator();\n} \n</code></pre>\n\n<p>And in your main put this:</p>\n\n<pre><code> signal(SIGABRT, signal_handler);\n _set_abort_behavior(0, _WRITE_ABORT_MSG|_CALL_REPORTFAULT);\n\n set_terminate( &terminator );\n set_unexpected( &terminator );\n _set_purecall_handler( &terminator );\n _set_invalid_parameter_handler( &invalid_parameter_handler );\n</code></pre>\n\n<p>The above will send all crashes to your unhandled exception handler. </p>\n"
},
{
"answer_id": 224179,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": -1,
"selected": false,
"text": "<p>Try defining the offending pure virtual. There is nothing in the C++ rules that prohibit you from defining a pure virtual, and you can use this for a number of reasons, the least of which is getting a backtrace on the call. The only caviat is the definition must be outside the declaration (<code>virtual void bla() = 0 { }</code> is not valid).</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1675/"
] |
I currently capture MiniDumps of unhandled exceptions using `SetUnhandledExceptionFilter` however at times I am getting "R6025: pure virtual function".
I understand how a pure virtual function call happens I am just wondering if it is possible to capture them so I can create a MiniDump at that point.
|
If you want to catch all crashes you have to do more than just: SetUnhandledExceptionFilter
I would also set the abort handler, the purecall handler, unexpected, terminate, and invalid parameter handler.
```
#include <signal.h>
inline void signal_handler(int)
{
terminator();
}
inline void terminator()
{
int*z = 0; *z=13;
}
inline void __cdecl invalid_parameter_handler(const wchar_t *, const wchar_t *, const wchar_t *, unsigned int, uintptr_t)
{
terminator();
}
```
And in your main put this:
```
signal(SIGABRT, signal_handler);
_set_abort_behavior(0, _WRITE_ABORT_MSG|_CALL_REPORTFAULT);
set_terminate( &terminator );
set_unexpected( &terminator );
_set_purecall_handler( &terminator );
_set_invalid_parameter_handler( &invalid_parameter_handler );
```
The above will send all crashes to your unhandled exception handler.
|
224,181 |
<p>When I add a reference to <strong>Microsoft.Office.Interop.Excel</strong> on my computer, Visual Studio adds this to the project file:</p>
<pre><code><COMReference Include="Excel">
<Guid>{00020813-0000-0000-C000-000000000046}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>5</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
</COMReference>
</code></pre>
<p>There is another developer on the team who gets errors and needs to add a DLL file to the project called Interop.Excel.dll, which replaces the code above with this in the project file:</p>
<pre><code><Reference Include="Interop.Excel, Version=1.5.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>My Project\Interop.Excel.dll</HintPath>
</Reference>
</code></pre>
<p>This does work on my computer.</p>
<p>Could you please explain the differences between the two methods, which is best, and how to get the first one working on other computers?</p>
|
[
{
"answer_id": 224203,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>I've used Excel automation way more than I would like to admitt, and I have never referenced Interop.Excel.dll. I've always referenced the former. Why is he referencing that, and what errors does he get?</p>\n\n<p>Are you guys referencing the same version of excel (5.0 verses 11.0)? Do you guys have the exact same version of office, service pakcs and all? This could be the differance.</p>\n"
},
{
"answer_id": 317125,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 4,
"selected": false,
"text": "<p>I don't see a problem with your approach either. </p>\n\n<p>Typically VS will generate an interop assembly for COM components automatically when you add a reference to the component. However, when you add a reference to one of the Office components (XP or any later version), a reference to the pregenerated (and optimized) primary interop assembly from Microsoft is added as in your first example. The line </p>\n\n<pre><code><WrapperTool>primary</WrapperTool>\n</code></pre>\n\n<p>means that this PIA is used.</p>\n\n<p>If you correctly added the PIA reference the <em>CopyLocal</em> property of this reference should be set to false and the <em>Path</em> property should be something like</p>\n\n<pre><code>C:\\WINDOWS\\assembly\\GAC\\Microsoft.Office.Interop.Excel\\12.0.0.0__71e9bce111e9429c\\Microsoft.Office.Interop.Excel.dll\n</code></pre>\n\n<p>You will find some more details on interop assemblies in this MSDN <a href=\"http://msdn.microsoft.com/en-us/library/aa679806.aspx\" rel=\"noreferrer\">article</a>.</p>\n\n<p>To get the first method working it is necessary that the Office Primary Interop Assemblies (PIAs) are installed on the machine. There is a redistributable version available from Microsoft: </p>\n\n<ul>\n<li><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=3C9A983A-AC14-4125-8BA0-D36D67E0F4AD&displaylang=en\" rel=\"noreferrer\">Office 2003 PIAs</a></li>\n<li><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=59DAEBAA-BED4-4282-A28C-B864D8BFA513&displaylang=en\" rel=\"noreferrer\">Office 2007 PIAs</a></li>\n</ul>\n\n<p>AFAIK, these PIAs only get installed by the Office setup when the .NET Framework has already been installed, that's why there is a separate redistributable for the PIAs.</p>\n\n<p>Note: Make sure that you reference the version of Office that you are targeting. When targeting several versions of Office, you might get some problems however. A solution in that case might be late binding (if performance is not an issue).</p>\n"
},
{
"answer_id": 317143,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>I found the cleanest way to use it, this also allows for multiple versions of the interop, is to create a shared bin\\Office Interop\\11 or 12\\Microsoft.Office.Interop.Excel.dll\\ and refeferenced them from the project, works a treat for different version</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10786/"
] |
When I add a reference to **Microsoft.Office.Interop.Excel** on my computer, Visual Studio adds this to the project file:
```
<COMReference Include="Excel">
<Guid>{00020813-0000-0000-C000-000000000046}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>5</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
</COMReference>
```
There is another developer on the team who gets errors and needs to add a DLL file to the project called Interop.Excel.dll, which replaces the code above with this in the project file:
```
<Reference Include="Interop.Excel, Version=1.5.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>My Project\Interop.Excel.dll</HintPath>
</Reference>
```
This does work on my computer.
Could you please explain the differences between the two methods, which is best, and how to get the first one working on other computers?
|
I don't see a problem with your approach either.
Typically VS will generate an interop assembly for COM components automatically when you add a reference to the component. However, when you add a reference to one of the Office components (XP or any later version), a reference to the pregenerated (and optimized) primary interop assembly from Microsoft is added as in your first example. The line
```
<WrapperTool>primary</WrapperTool>
```
means that this PIA is used.
If you correctly added the PIA reference the *CopyLocal* property of this reference should be set to false and the *Path* property should be something like
```
C:\WINDOWS\assembly\GAC\Microsoft.Office.Interop.Excel\12.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll
```
You will find some more details on interop assemblies in this MSDN [article](http://msdn.microsoft.com/en-us/library/aa679806.aspx).
To get the first method working it is necessary that the Office Primary Interop Assemblies (PIAs) are installed on the machine. There is a redistributable version available from Microsoft:
* [Office 2003 PIAs](http://www.microsoft.com/downloads/details.aspx?FamilyId=3C9A983A-AC14-4125-8BA0-D36D67E0F4AD&displaylang=en)
* [Office 2007 PIAs](http://www.microsoft.com/downloads/details.aspx?familyid=59DAEBAA-BED4-4282-A28C-B864D8BFA513&displaylang=en)
AFAIK, these PIAs only get installed by the Office setup when the .NET Framework has already been installed, that's why there is a separate redistributable for the PIAs.
Note: Make sure that you reference the version of Office that you are targeting. When targeting several versions of Office, you might get some problems however. A solution in that case might be late binding (if performance is not an issue).
|
224,185 |
<p>I'm experimenting with a personal finance application, and I'm thinking about what approach to take to update running balances when entering a transaction in an account.</p>
<p>Currently the way I'm using involves retrieving all records more recent than the inserted/modified one, and go one by one incrementing their running balance.</p>
<p>For example, given the following transactions:</p>
<p>t1 date = 2008-10-21, amount = 500, running balance = 1000</p>
<p>t2 date = 2008-10-22, amount = 300, running balance = 1300</p>
<p>t3 date = 2008-10-23, amount = 100, running balance = 1400
...</p>
<p>Now suppose I insert a transaction between t1 and t2, then t2 and all subsequent transactions would need their running balances adjusted.</p>
<p>Hehe, now that I wrote this question, I think I know the answer... so I'll leave it here in case it helps someone else (or maybe there's even a better approach?)</p>
<p>First, I get the running balance from the previous transaction, in this case, t1. Then I update all following transactions (which would include the new one):</p>
<pre><code>UPDATE transactions
SET running_balance = running_balance + <AMOUNT>
WHERE date > <t1.date>
</code></pre>
<p>The only issue I see is that now instead of storing only a date, I'll have to store a time too. Although, what would happen if two transactions had the exact same date/time?</p>
<p>PS: I'd prefer solutions not involving propietary features, as I'm using both PostgreSQL and SQLite... Although a Postgre-only solution would be helpful too.</p>
|
[
{
"answer_id": 224199,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 2,
"selected": false,
"text": "<p>Some sort of Identity / Auto-increment columnn in there would be wise as well, purely for the transaction order if anything. </p>\n\n<p>Also in addition to just the date of the transaction, a date that the transaction is inserted into the database (not always the same) would be wise / helpful as well. </p>\n\n<p>These sort of things simply help you arrange things in the system and make it easier to change things i.e. for transactions, at a later time. </p>\n"
},
{
"answer_id": 224536,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a large volume of transactions, then you are better off storing the running balance date-wise or even week/month-wise in a separate table.\nThis was if you are inserting rows for the same date you just need to change the running balance in one row. \nThe querying and reporting will be more trickier as using this running balance you would need to arrive at balances after each transaction, it would be more like taking the last days running balance and adding or subtracting the transaction value.</p>\n"
},
{
"answer_id": 225409,
"author": "Ivan",
"author_id": 16957,
"author_profile": "https://Stackoverflow.com/users/16957",
"pm_score": 1,
"selected": true,
"text": "<p>I think this might work:</p>\n\n<p>I was using both the date and the id to order the transactions, but now I'm going to store both the date and the id on one column, and use that for ordering. So, using comparisons (like >) should always work as expected, right? (as opposed to the situation I describe earlier where two columns have the exact datetime (however unlikely that'd be).</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16957/"
] |
I'm experimenting with a personal finance application, and I'm thinking about what approach to take to update running balances when entering a transaction in an account.
Currently the way I'm using involves retrieving all records more recent than the inserted/modified one, and go one by one incrementing their running balance.
For example, given the following transactions:
t1 date = 2008-10-21, amount = 500, running balance = 1000
t2 date = 2008-10-22, amount = 300, running balance = 1300
t3 date = 2008-10-23, amount = 100, running balance = 1400
...
Now suppose I insert a transaction between t1 and t2, then t2 and all subsequent transactions would need their running balances adjusted.
Hehe, now that I wrote this question, I think I know the answer... so I'll leave it here in case it helps someone else (or maybe there's even a better approach?)
First, I get the running balance from the previous transaction, in this case, t1. Then I update all following transactions (which would include the new one):
```
UPDATE transactions
SET running_balance = running_balance + <AMOUNT>
WHERE date > <t1.date>
```
The only issue I see is that now instead of storing only a date, I'll have to store a time too. Although, what would happen if two transactions had the exact same date/time?
PS: I'd prefer solutions not involving propietary features, as I'm using both PostgreSQL and SQLite... Although a Postgre-only solution would be helpful too.
|
I think this might work:
I was using both the date and the id to order the transactions, but now I'm going to store both the date and the id on one column, and use that for ordering. So, using comparisons (like >) should always work as expected, right? (as opposed to the situation I describe earlier where two columns have the exact datetime (however unlikely that'd be).
|
224,200 |
<p>Thanks a million everyone for everyone's response. Unfortunately, none of the solutions appear to be working on my end, and my guess is that the example I've provided is messed up.</p>
<p>So let me try again.</p>
<p>My table looks like this:</p>
<pre><code> contract project activity
row1 1000 8000 10
row2 1000 8000 20
row3 1000 8001 10
row4 2000 9000 49
row5 2000 9001 49
row6 3000 9000 79
row7 3000 9000 78
</code></pre>
<p>Basically, the query I'm looking for would return "2000,49" for "contract, activity" because only contract #2000 has one, and ONLY one, unique activity value.</p>
<p>Again, thanks a million in advance,
boroatel</p>
|
[
{
"answer_id": 224210,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Updated to use your newly provided data:</strong></p>\n\n<p>The solutions using the original data may be found at the end of this answer.</p>\n\n<p>Using your new data:</p>\n\n<pre><code>DECLARE @T TABLE( [contract] INT, project INT, activity INT )\nINSERT INTO @T VALUES( 1000, 8000, 10 )\nINSERT INTO @T VALUES( 1000, 8000, 20 )\nINSERT INTO @T VALUES( 1000, 8001, 10 )\nINSERT INTO @T VALUES( 2000, 9000, 49 )\nINSERT INTO @T VALUES( 2000, 9001, 49 )\nINSERT INTO @T VALUES( 3000, 9000, 79 )\nINSERT INTO @T VALUES( 3000, 9000, 78 )\n\nSELECT DISTINCT [contract], activity FROM @T AS A WHERE\n (SELECT COUNT( DISTINCT activity ) \n FROM @T AS B WHERE B.[contract] = A.[contract]) = 1\n</code></pre>\n\n<p>returns:\n 2000, 49</p>\n\n<p><strong>Solutions using original data</strong></p>\n\n<p><strong>WARNING:</strong>\nThe following solutions use the data previously given in the question and may not make sense for the current question. I have left them attached for completeness only.</p>\n\n<pre><code>SELECT Col1, Count( col1 ) AS count FROM table \nGROUP BY col1\nHAVING count > 1\n</code></pre>\n\n<p>This should get you a list of all the values in col1 that are not distinct. You can place this in a table var or temp table and join against it.</p>\n\n<p>Here is an example using a sub-query:</p>\n\n<pre><code>DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )\n\nINSERT INTO @t VALUES( 'A', 'B', 'C' );\nINSERT INTO @t VALUES( 'D', 'E', 'F' );\nINSERT INTO @t VALUES( 'A', 'J', 'K' );\nINSERT INTO @t VALUES( 'G', 'H', 'H' );\n\nSELECT * FROM @t\n\nSELECT col1, col2 FROM @t WHERE col1 NOT IN \n (SELECT col1 FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) > 1)\n</code></pre>\n\n<p>This returns:</p>\n\n<pre><code>D E\nG H\n</code></pre>\n\n<p>And another method that users a temp table and join:</p>\n\n<pre><code>DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )\n\nINSERT INTO @t VALUES( 'A', 'B', 'C' );\nINSERT INTO @t VALUES( 'D', 'E', 'F' );\nINSERT INTO @t VALUES( 'A', 'J', 'K' );\nINSERT INTO @t VALUES( 'G', 'H', 'H' );\n\nSELECT * FROM @t\n\nDROP TABLE #temp_table \nSELECT col1 INTO #temp_table\n FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) = 1\n\nSELECT t.col1, t.col2 FROM @t AS t\n INNER JOIN #temp_table AS tt ON t.col1 = tt.col1\n</code></pre>\n\n<p>Also returns:</p>\n\n<pre><code>D E\nG H\n</code></pre>\n"
},
{
"answer_id": 224231,
"author": "mrm",
"author_id": 30191,
"author_profile": "https://Stackoverflow.com/users/30191",
"pm_score": 3,
"selected": false,
"text": "<p>For MySQL:</p>\n\n<pre><code>SELECT contract, activity\nFROM table\nGROUP BY contract\nHAVING COUNT(DISTINCT activity) = 1\n</code></pre>\n"
},
{
"answer_id": 224292,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": 2,
"selected": false,
"text": "<p>Modified!</p>\n\n<pre><code>SELECT distinct contract, activity from @t a\nWHERE (SELECT COUNT(DISTINCT activity) FROM @t b WHERE b.contract = a.contract) = 1\n</code></pre>\n\n<p>And here's another one -- shorter/cleaner without subquery</p>\n\n<pre><code>select contract, max(activity) from @t\ngroup by contract\nhaving count(distinct activity) = 1\n</code></pre>\n"
},
{
"answer_id": 224338,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>select \n contract,\n max (activity) \nfrom\n mytable \ngroup by\n contract \nhaving\n count (activity) = 1\n</code></pre>\n"
},
{
"answer_id": 224351,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming your table of data is called ProjectInfo:</p>\n\n<pre><code>SELECT DISTINCT Contract, Activity\n FROM ProjectInfo\n WHERE Contract = (SELECT Contract\n FROM (SELECT DISTINCT Contract, Activity\n FROM ProjectInfo) AS ContractActivities\n GROUP BY Contract\n HAVING COUNT(*) = 1);\n</code></pre>\n\n<p>The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.</p>\n\n<p>Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.</p>\n"
},
{
"answer_id": 224369,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another option using sql servers count distinct:</p>\n\n<pre><code>DECLARE @T TABLE( [contract] INT, project INT, activity INT )\nINSERT INTO @T VALUES( 1000, 8000, 10 )\nINSERT INTO @T VALUES( 1000, 8000, 20 )\nINSERT INTO @T VALUES( 1000, 8001, 10 )\nINSERT INTO @T VALUES( 2000, 9000, 49 )\nINSERT INTO @T VALUES( 2000, 9001, 49 )\nINSERT INTO @T VALUES( 3000, 9000, 79 )\nINSERT INTO @T VALUES( 3000, 9000, 78 )\n\n\n\nSELECT DISTINCT [contract], activity FROM @T AS A WHERE\n (SELECT COUNT( DISTINCT activity ) \n FROM @T AS B WHERE B.[contract] = A.[contract]) = 1\n</code></pre>\n"
},
{
"answer_id": 224431,
"author": "Hapkido",
"author_id": 27646,
"author_profile": "https://Stackoverflow.com/users/27646",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT DISTINCT Contract, Activity\nFROM Contract WHERE Contract IN (\nSELECT Contract \nFROM Contract\nGROUP BY Contract\nHAVING COUNT( DISTINCT Activity ) = 1 )\n</code></pre>\n"
},
{
"answer_id": 224603,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 2,
"selected": false,
"text": "<p>Utilizing the \"dynamic table\" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following.\nIf your platform doesn't offer an equivalent to the \"dynamic table\" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the \"dynamic table\" to a temp table, and then performing a subsequent select on the temp table.</p>\n\n<pre><code>DECLARE @T TABLE(\n [contract] INT,\n project INT,\n activity INT\n)\n\nINSERT INTO @T VALUES( 1000, 8000, 10 )\nINSERT INTO @T VALUES( 1000, 8000, 20 )\nINSERT INTO @T VALUES( 1000, 8001, 10 )\nINSERT INTO @T VALUES( 2000, 9000, 49 )\nINSERT INTO @T VALUES( 2000, 9001, 49 )\nINSERT INTO @T VALUES( 3000, 9000, 79 )\nINSERT INTO @T VALUES( 3000, 9000, 78 )\n\nSELECT\n [contract],\n [Activity] = max (activity)\nFROM\n (\n SELECT\n [contract],\n [Activity]\n FROM\n @T\n GROUP BY\n [contract],\n [Activity]\n ) t\nGROUP BY\n [contract]\nHAVING count (*) = 1\n</code></pre>\n"
},
{
"answer_id": 251393,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry you're not using PostgreSQL...</p>\n\n<p>SELECT DISTINCT ON contract, activity\n*\nFROM thetable\nORDER BY contract, activity</p>\n\n<p><a href=\"http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT\" rel=\"nofollow noreferrer\">http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT</a></p>\n\n<p>Oh wait. You only want values with exactly one...</p>\n\n<p>SELECT contract, activity, count(<em>) \nFROM thetable GROUP BY contract, activity HAVING count(</em>) = 1</p>\n"
},
{
"answer_id": 251513,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a fan of NOT EXISTS</p>\n\n<pre><code>SELECT DISTINCT contract, activity FROM table t1\nWHERE NOT EXISTS (\n SELECT * FROM table t2\n WHERE t2.contract = t1.contract AND t2.activity != t1.activity\n)\n</code></pre>\n"
},
{
"answer_id": 913160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry old post I know but I had the same issue, couldn't get any of the above to work for me, however I figured it out.</p>\n\n<p>This worked for me:</p>\n\n<p>SELECT DISTINCT [column]As UniqueValues\n FROM [db].[dbo].[table]</p>\n"
},
{
"answer_id": 13415840,
"author": "skygeek",
"author_id": 1115901,
"author_profile": "https://Stackoverflow.com/users/1115901",
"pm_score": 0,
"selected": false,
"text": "<p>SELECT DISTINCT Col1,Col2 FROM Table GROUP BY Col1 HAVING COUNT( DISTINCT Col1 ) = 1</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Thanks a million everyone for everyone's response. Unfortunately, none of the solutions appear to be working on my end, and my guess is that the example I've provided is messed up.
So let me try again.
My table looks like this:
```
contract project activity
row1 1000 8000 10
row2 1000 8000 20
row3 1000 8001 10
row4 2000 9000 49
row5 2000 9001 49
row6 3000 9000 79
row7 3000 9000 78
```
Basically, the query I'm looking for would return "2000,49" for "contract, activity" because only contract #2000 has one, and ONLY one, unique activity value.
Again, thanks a million in advance,
boroatel
|
**Updated to use your newly provided data:**
The solutions using the original data may be found at the end of this answer.
Using your new data:
```
DECLARE @T TABLE( [contract] INT, project INT, activity INT )
INSERT INTO @T VALUES( 1000, 8000, 10 )
INSERT INTO @T VALUES( 1000, 8000, 20 )
INSERT INTO @T VALUES( 1000, 8001, 10 )
INSERT INTO @T VALUES( 2000, 9000, 49 )
INSERT INTO @T VALUES( 2000, 9001, 49 )
INSERT INTO @T VALUES( 3000, 9000, 79 )
INSERT INTO @T VALUES( 3000, 9000, 78 )
SELECT DISTINCT [contract], activity FROM @T AS A WHERE
(SELECT COUNT( DISTINCT activity )
FROM @T AS B WHERE B.[contract] = A.[contract]) = 1
```
returns:
2000, 49
**Solutions using original data**
**WARNING:**
The following solutions use the data previously given in the question and may not make sense for the current question. I have left them attached for completeness only.
```
SELECT Col1, Count( col1 ) AS count FROM table
GROUP BY col1
HAVING count > 1
```
This should get you a list of all the values in col1 that are not distinct. You can place this in a table var or temp table and join against it.
Here is an example using a sub-query:
```
DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )
INSERT INTO @t VALUES( 'A', 'B', 'C' );
INSERT INTO @t VALUES( 'D', 'E', 'F' );
INSERT INTO @t VALUES( 'A', 'J', 'K' );
INSERT INTO @t VALUES( 'G', 'H', 'H' );
SELECT * FROM @t
SELECT col1, col2 FROM @t WHERE col1 NOT IN
(SELECT col1 FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) > 1)
```
This returns:
```
D E
G H
```
And another method that users a temp table and join:
```
DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )
INSERT INTO @t VALUES( 'A', 'B', 'C' );
INSERT INTO @t VALUES( 'D', 'E', 'F' );
INSERT INTO @t VALUES( 'A', 'J', 'K' );
INSERT INTO @t VALUES( 'G', 'H', 'H' );
SELECT * FROM @t
DROP TABLE #temp_table
SELECT col1 INTO #temp_table
FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) = 1
SELECT t.col1, t.col2 FROM @t AS t
INNER JOIN #temp_table AS tt ON t.col1 = tt.col1
```
Also returns:
```
D E
G H
```
|
224,204 |
<p>Another poster asked about <a href="https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom">preferred syntax for infinite loops</a>.</p>
<p>A follow-up question: <i>Why</i> do you use infinite loops in your code? I typically see a construct like this:</p>
<pre><code>for (;;) {
int scoped_variable = getSomeValue();
if (scoped_variable == some_value) {
break;
}
}
</code></pre>
<p>Which lets you get around not being able to see the value of scoped_variable in the <code>for</code> or <code>while</code> clause. What are some other uses for "infinite" loops?</p>
|
[
{
"answer_id": 224209,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 4,
"selected": false,
"text": "<p>I use an infinite loop for the body of my embedded control code, since it is designed to run forever once it is started.</p>\n"
},
{
"answer_id": 224213,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 3,
"selected": false,
"text": "<p>Finite state machines. They're not supposed to end until you reach an end state, at which point you break or return.</p>\n"
},
{
"answer_id": 224215,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 6,
"selected": true,
"text": "<p>A loop like:</p>\n\n<pre><code>while (true)\n{\n // do something\n if (something else) break;\n // do more\n}\n</code></pre>\n\n<p>lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while).</p>\n\n<p>If you've got a complex condition, you might also want to use this style to make the code clearer.</p>\n"
},
{
"answer_id": 224217,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": 0,
"selected": false,
"text": "<p>I used to use them when waiting for multiple threads to complete in c#, but now I use the ThreadPool class.</p>\n"
},
{
"answer_id": 224218,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>One example is in a message pump type scenario, where you want to loop forever processing any messages that come in until told to stop. Another is if you want to take a periodic action then you might write an infinite loop with a sleep in it (though it may be better to use some form of timer for this).</p>\n\n<p>There may be some other places where the loop has to perform a certain amount of work to determine whether it should exit, and it may be cleaner just to use <code>break</code> when this condition is true rather than set some external flag to indicate the loop should exit.</p>\n\n<p>Generally though I think it's better practice to put your exit condition in the loop statement if possible, rather than to make it infinite and exit the loop using a <code>break</code> statement, because the exit condition of the loop is more obvious.</p>\n"
},
{
"answer_id": 224219,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 3,
"selected": false,
"text": "<pre><code>while( 1 )\n{\n game->update();\n game->render();\n}\n</code></pre>\n\n<p><strong>Edit:</strong> That is, my app is fundamentally based around an infinite loop, and I can't be bothered to refactor everything just to have the aesthetic purity of always terminating by falling off the end of main().</p>\n"
},
{
"answer_id": 224228,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 2,
"selected": false,
"text": "<p>That's an incomplete example because it can be refactored to be an end-test loop with no loss of clarity, function or performance.</p>\n\n<pre><code>int scoped_variable;\ndo {\n scoped_variable = getSomeValue();\n} while (scoped_variable != some_value);\n</code></pre>\n\n<p>Infinite loops are most often used when the loop instance <em>doesn't</em> have the termination test at the top or the bottom, in the simplest case. This tends to happen when there is two parts to the loop: code that must execute each time, and code that must only execute between each iteration. This tends to happen in languages like C when doing things like reading from a file or processing a database resultset where a lot has to be done explicitly. Most languages with newer paradigms can structure such code actually into the test.</p>\n"
},
{
"answer_id": 224237,
"author": "Loren Pechtel",
"author_id": 10659,
"author_profile": "https://Stackoverflow.com/users/10659",
"pm_score": 0,
"selected": false,
"text": "<p>Other than embedded systems situations infinite loops always really are:</p>\n\n<pre><code>Repeat\n Something\nUntil Exit_Condition;\n</code></pre>\n\n<p>But sometimes Exit_Condition isn't something that can actually be evaluated at the end of the loop. You could always set a flag, use that flag to skip the rest of the loop and then test it at the end but that means you are testing it at least twice (the code is slightly slower) and personally I find it less clear.</p>\n\n<p>There are times when trading clarity for speed makes sense but something that gives neither clarity nor speed just to be technically correct? Sounds like a bad idea to me. Any competent programmer knows that while (true) means the termination condition is somewhere inside the loop.</p>\n"
},
{
"answer_id": 224242,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 1,
"selected": false,
"text": "<p>There are other questions relating to if/when it's ok to use <code>break</code> in a loop. Let's assume that we agree that it's sometimes ok. In those circumstances (hopefully rare) I would use an infinite loop if there are a number of terminating conditions and no identifiable \"primary\" terminating condition.</p>\n\n<p>It avoids a long series of disjunctions (or's) and also draws the reader's attention to the fact that there may (almost certainly will) be breaks in the loop.</p>\n\n<p>Ultimately it's a matter of taste.</p>\n"
},
{
"answer_id": 224316,
"author": "Chris Kloberdanz",
"author_id": 28714,
"author_profile": "https://Stackoverflow.com/users/28714",
"pm_score": 1,
"selected": false,
"text": "<p>I use them to write Linux daemons / services that loop until kill / other termination signals are received.</p>\n"
},
{
"answer_id": 224914,
"author": "orj",
"author_id": 20480,
"author_profile": "https://Stackoverflow.com/users/20480",
"pm_score": 1,
"selected": false,
"text": "<p>Infinite loops are useful mostly in daemon/service processes or the main loop in a game. You can even get cute with them, eg:</p>\n\n<pre><code>const bool heatDeathOfTheUniverse = false;\ndo \n{\n // stuff\n} while(!heatDeathOfTheUniverse);\n</code></pre>\n\n<p>They should <strong>not</strong> be used to \"wait\" for things like threads as was suggested by <a href=\"https://stackoverflow.com/questions/224204/why-use-infinite-loops#224217\">Fry</a>. You can use the Join method of a thread object for that.</p>\n\n<p>However, if you're in a situation where your tech lead says, \"infinite loops are verboten & so are multiple method/function returns & breaks\" you can also do stuff like this:</p>\n\n<pre><code>bool done = false;\nwhile(!done) \n{\n if(done = AreWeDone()) continue; // continue jumps back to start of the loop \n} \n</code></pre>\n\n<p>Of course if you tech lead is forcing you to do such things you should start looking for a new job.</p>\n\n<p>For more details on the continue keyword see <a href=\"http://msdn.microsoft.com/en-us/library/6e3dc2z3(VS.80).aspx\" rel=\"nofollow noreferrer\">this MSDN</a> article.</p>\n"
},
{
"answer_id": 224927,
"author": "Gary Willoughby",
"author_id": 13227,
"author_profile": "https://Stackoverflow.com/users/13227",
"pm_score": 2,
"selected": false,
"text": "<p>Nearly all apps use an <em>infinite</em> <strong>Main loop</strong>. ;)</p>\n"
},
{
"answer_id": 1184149,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Webservers use an infinite while loop:</p>\n\n<pre><code>while(true)\n{\n //Do something like respond to requests\n}\n</code></pre>\n\n<p>They don't have to end unless you close your webserver application.</p>\n"
},
{
"answer_id": 2918307,
"author": "emory",
"author_id": 348975,
"author_profile": "https://Stackoverflow.com/users/348975",
"pm_score": 2,
"selected": false,
"text": "<p>I would consider using an infinite loop to program the guidance system of a missile. </p>\n\n<pre><code>while ( true ) { go2Target ( ) ; }\n</code></pre>\n\n<p>From the perspective of the missile's guidance computer, the loop once started does repeat until the end of time.</p>\n\n<p>Perhaps a purists would favor</p>\n\n<pre><code>while ( ! blown2Bits ( ) ) { go2Target ( ) ; }\n</code></pre>\n\n<p>but then how do you implement the blow2Bits method? what would it mean if blow2Bits returned true?</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23786/"
] |
Another poster asked about [preferred syntax for infinite loops](https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom).
A follow-up question: *Why* do you use infinite loops in your code? I typically see a construct like this:
```
for (;;) {
int scoped_variable = getSomeValue();
if (scoped_variable == some_value) {
break;
}
}
```
Which lets you get around not being able to see the value of scoped\_variable in the `for` or `while` clause. What are some other uses for "infinite" loops?
|
A loop like:
```
while (true)
{
// do something
if (something else) break;
// do more
}
```
lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while).
If you've got a complex condition, you might also want to use this style to make the code clearer.
|
224,225 |
<p>How would you program a C/C++ application that could run without opening a window or console? </p>
|
[
{
"answer_id": 224226,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "<p><strong>In windows:</strong></p>\n\n<pre><code>#include <windows.h>\n\nint APIENTRY WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPTSTR lpCmdLine,\n int nCmdShow)\n{\n // <-- Program logic here\n return 0;\n} \n</code></pre>\n\n<p>Be sure to use the /SUBSYSTEM linker switch as mentioned by Adam Mitz.</p>\n\n<p><strong>On other platforms:</strong></p>\n\n<pre><code>int main(int argc, char**argv)\n{\n // <-- Program logic here\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 224372,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 6,
"selected": true,
"text": "<p>When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different. </p>\n\n<p>This causes the compiler to create an entry in the executable file format (<a href=\"http://webster.cs.ucr.edu/Page_TechDocs/pe.txt\" rel=\"noreferrer\">PE format</a>) that marks the executable as a windows executable. </p>\n\n<p>Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs. </p>\n\n<p>But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it. </p>\n\n<p>All you need to do, to achieve all this is, </p>\n\n<pre><code>#include <Windows.h>\n\nint WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance, \n LPTSTR lpCmdLine, \n int cmdShow)\n {\n /* do your stuff here. If you return from this function the program ends */\n }\n</code></pre>\n\n<p>The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.</p>\n"
},
{
"answer_id": 224449,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using <strong>MSVC</strong> or <strong>Visual Studio</strong> just use the new <strong>Project Wizard</strong> and select the <strong>Console Application</strong>.</p>\n"
},
{
"answer_id": 224688,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a need to contiguously run your program without having console or window you might find useful <a href=\"http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html\" rel=\"nofollow noreferrer\">deamon on *NIX</a> or <a href=\"http://www.codeproject.com/KB/cs/hoytsoft_servicebase.aspx\" rel=\"nofollow noreferrer\">services on Windows</a>, this .NET example if you need plain win32 just google a little bit for sample.<br>\n Since your question tagged as win32 i assume that services are more relevant for you. </p>\n"
},
{
"answer_id": 226347,
"author": "Vinay",
"author_id": 28641,
"author_profile": "https://Stackoverflow.com/users/28641",
"pm_score": 0,
"selected": false,
"text": "<p>Use Visual Studio wizard to create the Win32 Application. But don't create the window i.e., you remove the window creation function.\nAlternatively we can create Win Service application.</p>\n"
},
{
"answer_id": 14420728,
"author": "crisat",
"author_id": 1993899,
"author_profile": "https://Stackoverflow.com/users/1993899",
"pm_score": 1,
"selected": false,
"text": "<p>In Visual Studio Express 2010 after setting the subsystem to windows (as suggested by user17224), alternatively to changing the main to WinMain (as suggested by user17224 and Brian R. Bondy), one can set the entry function to main in properties, linker, advanced, entry point: just type main in the text box.</p>\n"
},
{
"answer_id": 54832944,
"author": "WndProc",
"author_id": 11053032,
"author_profile": "https://Stackoverflow.com/users/11053032",
"pm_score": 2,
"selected": false,
"text": "<p>This also processes messages:</p>\n\n<pre><code>#include <windows.h>\n#include <stdio.h>\n\nint CALLBACK WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n MSG msg;\n DWORD curThreadId;\n\n curThreadId = GetCurrentThreadId();\n\n // Send messages to self:\n PostThreadMessage(curThreadId, WM_USER, 1, 2);\n PostThreadMessage(curThreadId, WM_USER+1, 3, 4);\n PostThreadMessage(curThreadId, WM_USER+2, 5, 6);\n PostThreadMessage(curThreadId, WM_USER+3, 7, 8);\n PostThreadMessage(curThreadId, WM_QUIT, 9, 10);\n\n while (GetMessage(&msg, NULL, 0, 0)) {\n printf(\"message: %d; wParam: %d; lParam: %d\\n\", msg.message, msg.wParam, msg.lParam);\n }\n\n return (int) msg.wParam;\n} \n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27211/"
] |
How would you program a C/C++ application that could run without opening a window or console?
|
When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different.
This causes the compiler to create an entry in the executable file format ([PE format](http://webster.cs.ucr.edu/Page_TechDocs/pe.txt)) that marks the executable as a windows executable.
Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs.
But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it.
All you need to do, to achieve all this is,
```
#include <Windows.h>
int WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
/* do your stuff here. If you return from this function the program ends */
}
```
The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.
|
224,234 |
<p>I'm using an istream which could be stringstream, ifstream or a user-defined stream type and I need to know if, in the case of an ifstream, it was not opened in binary mode (so I can throw an exception). I have tried the following method:</p>
<pre><code>if ((_is.flags() & ios::binary) == 0)
throw exception(...)
</code></pre>
<p>but no exception is ever thrown. The test fails in this case because _is.flags() returns 0x201 and ios::binary is 0x20. Is there a way to find out if a stream was opened in text mode?</p>
|
[
{
"answer_id": 224258,
"author": "C. Broadbent",
"author_id": 28859,
"author_profile": "https://Stackoverflow.com/users/28859",
"pm_score": 3,
"selected": false,
"text": "<p>Nope, there is no way to test this.</p>\n"
},
{
"answer_id": 224259,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 5,
"selected": true,
"text": "<p>flags() returns <a href=\"http://www.cplusplus.com/reference/iostream/ios_base/fmtflags.html\" rel=\"noreferrer\">ios_base::fmtflags</a> which is formatting flags, whereas binary is an <a href=\"http://www.cplusplus.com/reference/iostream/ios_base/openmode.html\" rel=\"noreferrer\">ios_base::openmode</a> flag. I'm not sure if there is a way to find these out once the stream is already open. I was thinking that maybe there was a virtual member of the streambuf class that could help, but there doesn't really seem to be.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
I'm using an istream which could be stringstream, ifstream or a user-defined stream type and I need to know if, in the case of an ifstream, it was not opened in binary mode (so I can throw an exception). I have tried the following method:
```
if ((_is.flags() & ios::binary) == 0)
throw exception(...)
```
but no exception is ever thrown. The test fails in this case because \_is.flags() returns 0x201 and ios::binary is 0x20. Is there a way to find out if a stream was opened in text mode?
|
flags() returns [ios\_base::fmtflags](http://www.cplusplus.com/reference/iostream/ios_base/fmtflags.html) which is formatting flags, whereas binary is an [ios\_base::openmode](http://www.cplusplus.com/reference/iostream/ios_base/openmode.html) flag. I'm not sure if there is a way to find these out once the stream is already open. I was thinking that maybe there was a virtual member of the streambuf class that could help, but there doesn't really seem to be.
|
224,236 |
<p>I have a string.</p>
<pre><code>string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
</code></pre>
<p>I need to add a newline after every occurence of "@" symbol in the string.</p>
<p>My Output should be like this</p>
<pre><code>fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
</code></pre>
|
[
{
"answer_id": 224244,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 10,
"selected": true,
"text": "<p>Use <code>Environment.NewLine</code> whenever you want in any string. An example:</p>\n\n<pre><code>string text = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n\ntext = text.Replace(\"@\", \"@\" + System.Environment.NewLine);\n</code></pre>\n"
},
{
"answer_id": 224248,
"author": "Jason",
"author_id": 4486,
"author_profile": "https://Stackoverflow.com/users/4486",
"pm_score": 6,
"selected": false,
"text": "<p>You can add a new line character after the @ symbol like so: </p>\n\n<pre><code>string newString = oldString.Replace(\"@\", \"@\\n\"); \n</code></pre>\n\n<p>You can also use the <code>NewLine</code> property in the <code>Environment</code> Class (I think it is Environment).</p>\n"
},
{
"answer_id": 224250,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": false,
"text": "<p>A simple string replace will do the job. Take a look at the example program below:</p>\n\n<pre><code>using System;\n\nnamespace NewLineThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n string str = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n str = str.Replace(\"@\", \"@\" + Environment.NewLine);\n Console.WriteLine(str);\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 224261,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 4,
"selected": false,
"text": "<p>The previous answers come close, but to meet the actual requirement that the <code>@</code> symbol stay close, you'd want that to be <code>str.Replace(\"@\", \"@\" + System.Environment.NewLine)</code>. That will keep the <code>@</code> symbol and add the appropriate newline character(s) for the current platform.</p>\n"
},
{
"answer_id": 224413,
"author": "Benjamin Autin",
"author_id": 1440933,
"author_profile": "https://Stackoverflow.com/users/1440933",
"pm_score": 4,
"selected": false,
"text": "<p>Then just modify the previous answers to:</p>\n\n<pre><code>Console.Write(strToProcess.Replace(\"@\", \"@\" + Environment.NewLine));\n</code></pre>\n\n<p>If you don't want the newlines in the text file, then don't preserve it.</p>\n"
},
{
"answer_id": 225491,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 2,
"selected": false,
"text": "<p>Based on your replies to everyone else, something like this is what you're looking for.</p>\n\n<pre><code>string file = @\"C:\\file.txt\";\nstring strToProcess = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\nstring[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);\n\nusing (StreamWriter writer = new StreamWriter(file))\n{\n foreach (string line in lines)\n {\n writer.WriteLine(line + \"@\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 225580,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 3,
"selected": false,
"text": "<p>as others have said new line char will give you a new line in a text file in windows.\ntry the following:</p>\n\n<pre><code>using System;\nusing System.IO;\n\nstatic class Program\n{\n static void Main()\n {\n WriteToFile\n (\n @\"C:\\test.txt\",\n \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\",\n \"@\"\n );\n\n /*\n output in test.txt in windows =\n fkdfdsfdflkdkfk@\n dfsdfjk72388389@\n kdkfkdfkkl@\n jkdjkfjd@\n jjjk@ \n */\n }\n\n public static void WriteToFile(string filename, string text, string newLineDelim)\n {\n bool equal = Environment.NewLine == \"\\r\\n\";\n\n //Environment.NewLine == \\r\\n = True\n Console.WriteLine(\"Environment.NewLine == \\\\r\\\\n = {0}\", equal);\n\n //replace newLineDelim with newLineDelim + a new line\n //trim to get rid of any new lines chars at the end of the file\n string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();\n\n using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))\n {\n sw.Write(filetext);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4276814,
"author": "Glinas",
"author_id": 520103,
"author_profile": "https://Stackoverflow.com/users/520103",
"pm_score": 2,
"selected": false,
"text": "<pre><code>string str = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\nstr = str.Replace(\"@\", Environment.NewLine);\nrichTextBox1.Text = str;\n</code></pre>\n"
},
{
"answer_id": 34466976,
"author": "TehSpowage",
"author_id": 5717479,
"author_profile": "https://Stackoverflow.com/users/5717479",
"pm_score": 1,
"selected": false,
"text": "<p>You could also use <code>string[] something = text.Split('@')</code>. Make sure you use single quotes to surround the \"@\" to store it as a <code>char</code> type.\nThis will store the characters up to and including each \"@\" as individual words in the array. You can then output each (<code>element + System.Environment.NewLine</code>) using a for loop or write it to a text file using <code>System.IO.File.WriteAllLines([file path + name and extension], [array name])</code>. If the specified file doesn't exist in that location it will be automatically created.</p>\n"
},
{
"answer_id": 47693380,
"author": "Papun Sahoo",
"author_id": 8504431,
"author_profile": "https://Stackoverflow.com/users/8504431",
"pm_score": -1,
"selected": false,
"text": "<pre><code>protected void Button1_Click(object sender, EventArgs e)\n{\n string str = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n str = str.Replace(\"@\", \"@\" + \"<br/>\");\n Response.Write(str); \n}\n</code></pre>\n"
},
{
"answer_id": 48092915,
"author": "FAREH",
"author_id": 1489592,
"author_profile": "https://Stackoverflow.com/users/1489592",
"pm_score": -1,
"selected": false,
"text": "<pre><code>using System;\nusing System.IO;\nusing System.Text;\n\nclass Test\n{\n public static void Main()\n {\n string strToProcess = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n strToProcess.Replace(\"@\", Environment.NewLine);\n Console.WriteLine(strToProcess);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49152020,
"author": "Kathiravan C",
"author_id": 9456644,
"author_profile": "https://Stackoverflow.com/users/9456644",
"pm_score": 2,
"selected": false,
"text": "<pre><code>string strToProcess = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\nvar result = strToProcess.Replace(\"@\", \"@ \\r\\n\");\nConsole.WriteLine(result);\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/TAIFU.png\" rel=\"nofollow noreferrer\">Output</a></p>\n"
},
{
"answer_id": 68949483,
"author": "Mohamed Musthaque",
"author_id": 4121708,
"author_profile": "https://Stackoverflow.com/users/4121708",
"pm_score": 2,
"selected": false,
"text": "<p>Change your string as mentioned below.</p>\n<pre><code>string strToProcess = "fkdfdsfdflkdkfk"+ System.Environment.NewLine +" dfsdfjk72388389"+ System.Environment.NewLine +"kdkfkdfkkl"+ System.Environment.NewLine +"jkdjkfjd"+ System.Environment.NewLine +"jjjk"+ System.Environment.NewLine;\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
I have a string.
```
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
```
I need to add a newline after every occurence of "@" symbol in the string.
My Output should be like this
```
fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
```
|
Use `Environment.NewLine` whenever you want in any string. An example:
```
string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
text = text.Replace("@", "@" + System.Environment.NewLine);
```
|
224,239 |
<p>I have an array of shorts (short[]) that I need to write out to a file. What's the quickest way to do this?</p>
|
[
{
"answer_id": 224251,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 5,
"selected": true,
"text": "<p>Use the BinaryWriter</p>\n\n<pre><code> static void WriteShorts(short[] values, string path)\n {\n using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))\n {\n using (BinaryWriter bw = new BinaryWriter(fs))\n {\n foreach (short value in values)\n {\n bw.Write(value);\n }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 224275,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 2,
"selected": false,
"text": "<p>Following up on Jon B's answer, if your file contains any other data, you might want to prefix the data with the count of values.</p>\n\n<p>i.e.:</p>\n\n<pre><code>static void WriteShorts(short[] values, string path)\n{\n using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))\n {\n using (BinaryWriter bw = new BinaryWriter(fs))\n {\n // Write the number of items\n bw.Write(values.Length);\n\n foreach (short value in values)\n {\n bw.Write(value);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42907226,
"author": "Andreas Zita",
"author_id": 382838,
"author_profile": "https://Stackoverflow.com/users/382838",
"pm_score": 1,
"selected": false,
"text": "<p><strong>BinaryFormatter</strong> is in fact about <strong>10 times faster</strong> both for reads and writes when used with arrays of primitive types (obj.GetType().IsPrimitive), i.e. not for Decimal and String (which are not primitive) and certainly not for any other struct or class where it instead is horribly slow.</p>\n\n<pre><code>[Test]\npublic void TestShortArray()\n{\n var n = 100000000;\n var input = new short[n];\n var r = new Random();\n for (var i = 0; i < n; i++) input[i] = (short)r.Next();\n var bf = new BinaryFormatter();\n var sw = new Stopwatch();\n using (var ms = new MemoryStream())\n {\n sw.Start();\n bf.Serialize(ms, input);\n sw.Stop();\n Console.WriteLine(\"BinaryFormatter serialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n sw.Reset();\n ms.Seek(0, SeekOrigin.Begin);\n sw.Start();\n var output = (short[])bf.Deserialize(ms);\n sw.Stop();\n Console.WriteLine(\"BinaryFormatter deserialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n Assert.AreEqual(input, output);\n }\n sw.Reset();\n using (var ms = new MemoryStream())\n {\n var bw = new BinaryWriter(ms, Encoding.UTF8, true);\n sw.Start();\n bw.Write(input.Length);\n for (var i = 0; i < input.Length; i++) bw.Write(input[i]);\n sw.Stop();\n Console.WriteLine(\"BinaryWriter serialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n sw.Reset();\n ms.Seek(0, SeekOrigin.Begin);\n var br = new BinaryReader(ms, Encoding.UTF8, true);\n sw.Start();\n var length = br.ReadInt32();\n var output = new short[length];\n for (var i = 0; i < length; i++) output[i] = br.ReadInt16();\n sw.Stop();\n Console.WriteLine(\"BinaryReader deserialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n Assert.AreEqual(input, output);\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>BinaryFormatter serialize: 175 ms, 200000028 bytes\nBinaryFormatter deserialize: 79 ms, 200000028 bytes\nBinaryWriter serialize: 1499 ms, 200000004 bytes\nBinaryReader deserialize: 1599 ms, 200000004 bytes\n</code></pre>\n\n<p>So use BinaryFormatter whenever you have an array of a primitive type, or array of arrays but not multi-dim arrays (!). If your datatype is for instance Point3(double) you should fill up a double[] and serialize that instead. Only use BinaryWriter for complex/mixed types, strings, decimals and singular values.</p>\n\n<p>When dealing with byte[] then BinaryFormatter and BinaryWriter is equally performant (and very fast). If you can convert your type to byte-array in an effective way you may get even faster performance this way.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
I have an array of shorts (short[]) that I need to write out to a file. What's the quickest way to do this?
|
Use the BinaryWriter
```
static void WriteShorts(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
foreach (short value in values)
{
bw.Write(value);
}
}
}
}
```
|
224,253 |
<p>I want to change the order of XML using XDocument</p>
<pre><code><root>
<one>1</one>
<two>2</two>
</root>
</code></pre>
<p>I want to change the order so that 2 appears before 1. Is this capability baked in or do I have to do it myself. For example, remove then AddBeforeSelf()?</p>
<p>Thanks</p>
|
[
{
"answer_id": 224299,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 1,
"selected": false,
"text": "<p>This should do the trick. It order the child nodes of the root based on their content and then changes their order in the document. This is likely not the most effective way but judging by your tags you wanted to see it with LINQ.</p>\n\n<pre><code>static void Main(string[] args)\n{\n XDocument doc = new XDocument(\n new XElement(\"root\",\n new XElement(\"one\", 1),\n new XElement(\"two\", 2)\n ));\n\n var results = from XElement el in doc.Element(\"root\").Descendants()\n orderby el.Value descending\n select el;\n\n foreach (var item in results)\n Console.WriteLine(item);\n\n doc.Root.ReplaceAll( results.ToArray());\n\n Console.WriteLine(doc);\n\n Console.ReadKey();\n}\n</code></pre>\n"
},
{
"answer_id": 314928,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 1,
"selected": false,
"text": "<p>Outside of writing C# code to achieve this, you could use XSLT to transform the XML.</p>\n"
},
{
"answer_id": 720918,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Similar to above, but wrapping it in an extension method. In my case this works fine for me as I just want to ensure a certain element order is applied in my document before the user saves the xml.</p>\n\n<pre><code>public static class XElementExtensions\n{\n public static void OrderElements(this XElement parent, params string[] orderedLocalNames)\n { \n List<string> order = new List<string>(orderedLocalNames); \n var orderedNodes = parent.Elements().OrderBy(e => order.IndexOf(e.Name.LocalName) >= 0? order.IndexOf(e.Name.LocalName): Int32.MaxValue);\n parent.ReplaceNodes(orderedNodes);\n }\n}\n// using the extension method before persisting xml\nthis.Root.Element(\"parentNode\").OrderElements(\"one\", \"two\", \"three\", \"four\");\n</code></pre>\n"
},
{
"answer_id": 3941422,
"author": "podeig",
"author_id": 284405,
"author_profile": "https://Stackoverflow.com/users/284405",
"pm_score": 2,
"selected": false,
"text": "<p>Try this solution...</p>\n\n<pre><code>XElement node = ...get the element...\n\n//Move up\nif (node.PreviousNode != null) {\n node.PreviousNode.AddBeforeSelf(node);\n node.Remove();\n}\n\n//Move down\nif (node.NextNode != null) {\n node.NextNode.AddAfterSelf(node);\n node.Remove();\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30210/"
] |
I want to change the order of XML using XDocument
```
<root>
<one>1</one>
<two>2</two>
</root>
```
I want to change the order so that 2 appears before 1. Is this capability baked in or do I have to do it myself. For example, remove then AddBeforeSelf()?
Thanks
|
Similar to above, but wrapping it in an extension method. In my case this works fine for me as I just want to ensure a certain element order is applied in my document before the user saves the xml.
```
public static class XElementExtensions
{
public static void OrderElements(this XElement parent, params string[] orderedLocalNames)
{
List<string> order = new List<string>(orderedLocalNames);
var orderedNodes = parent.Elements().OrderBy(e => order.IndexOf(e.Name.LocalName) >= 0? order.IndexOf(e.Name.LocalName): Int32.MaxValue);
parent.ReplaceNodes(orderedNodes);
}
}
// using the extension method before persisting xml
this.Root.Element("parentNode").OrderElements("one", "two", "three", "four");
```
|
224,295 |
<p>I have two tables, one that contains volunteers, and one that contains venues. <strong>Volunteers are assigned one venue each</strong>.</p>
<p>The id of the venues table (venues.id) is placed within the volunteers table in the venue_id column (volunteers.venue_id).</p>
<p>I know I could get a count of how many matching values are in the volunteers.venue_id column by</p>
<pre><code>SELECT venue_id, COUNT(*) FROM volunteers GROUP BY venue_id
</code></pre>
<p>Why I want to do this: so the user can go in and see how many volunteers are assigned to each venue.</p>
<p>table: volunteers -- columns: id, name, venue_id</p>
<p>table: venues -- columns: id, venue_name</p>
<p>volunteers.venue_id = venues.id</p>
<p>I know this would be a join statement of some sort so it will get a count of each venue, then match up volunteers.venue_id to venues.id and print out the venues.venue_name along with the count.</p>
<p>How would I go about joining the two tables to print out the venue name and next to it, list the count of each volunteer with that venue_id?</p>
|
[
{
"answer_id": 224304,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT venues.venue_name, COUNT(volunteers.*) AS cvolun\n FROM venues\n INNER JOIN volunteers\n ON venues.id = volunteers.venue_id\n</code></pre>\n"
},
{
"answer_id": 224317,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "<p>This will give you all of the venues, with those having no volunteers showing up with a 0 volunteer_count</p>\n\n<pre><code>select venues.venue_name, count(*) as volunteer_count\nfrom venues\nleft outer join volunteers\n on venues.id = volunteers.venue_id\ngroup by venues.venue_name\n</code></pre>\n\n<p>[EDIT] I just realized you asked for MySQL. I can't remember if MySQL uses LEFT JOIN or LEFT OUTER JOIN. The syntax above would be correct for SQLSERVER. The key point is the outer join instead of the inner join to get the venues that have no volunteers.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
I have two tables, one that contains volunteers, and one that contains venues. **Volunteers are assigned one venue each**.
The id of the venues table (venues.id) is placed within the volunteers table in the venue\_id column (volunteers.venue\_id).
I know I could get a count of how many matching values are in the volunteers.venue\_id column by
```
SELECT venue_id, COUNT(*) FROM volunteers GROUP BY venue_id
```
Why I want to do this: so the user can go in and see how many volunteers are assigned to each venue.
table: volunteers -- columns: id, name, venue\_id
table: venues -- columns: id, venue\_name
volunteers.venue\_id = venues.id
I know this would be a join statement of some sort so it will get a count of each venue, then match up volunteers.venue\_id to venues.id and print out the venues.venue\_name along with the count.
How would I go about joining the two tables to print out the venue name and next to it, list the count of each volunteer with that venue\_id?
|
This will give you all of the venues, with those having no volunteers showing up with a 0 volunteer\_count
```
select venues.venue_name, count(*) as volunteer_count
from venues
left outer join volunteers
on venues.id = volunteers.venue_id
group by venues.venue_name
```
[EDIT] I just realized you asked for MySQL. I can't remember if MySQL uses LEFT JOIN or LEFT OUTER JOIN. The syntax above would be correct for SQLSERVER. The key point is the outer join instead of the inner join to get the venues that have no volunteers.
|
224,297 |
<p>I have the following models.</p>
<pre><code># app/models/domain/domain_object.rb
class Domain::DomainObject < ActiveRecord::Base
has_many :links_from, :class_name => "Link", :as => :from, :dependent => :destroy
end
# app/models/link.rb
class Link < ActiveRecord::Base
belongs_to :from, :polymorphic => true
belongs_to :object_value, :polymorphic => true
end
</code></pre>
<p>Problem is, when I do the following, the from_type doesn't prefix the Domain namespace to the model e.g.</p>
<pre><code> Domain::DomainObject.all(:include=> :links_from )
</code></pre>
<p>That causes the following SELECT:</p>
<pre><code> SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'DomainObject')
</code></pre>
<p>The query should be:</p>
<pre><code> SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'Domain::DomainObject')
</code></pre>
<p>because Rails automatically saves the model with the namespace. </p>
<p>I've seen a few recommendations on Rails sites about doing something like this:</p>
<pre><code> belongs_to :from, :polymorphic => true, :class_name => "Domain::DomainObject"
</code></pre>
<p>However, that doesn't appear to work either. </p>
<p>So, is there a better way to do this? Or is this not supported?</p>
|
[
{
"answer_id": 231901,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 4,
"selected": true,
"text": "<p>To fix this, I did a <code>include Domain</code> in the <code>DomainObject</code> model and set <code>ActiveRecord::Base.store_full_sti_class = true</code> in <code>config/environment.rb</code>.</p>\n"
},
{
"answer_id": 37234120,
"author": "progfan",
"author_id": 1998200,
"author_profile": "https://Stackoverflow.com/users/1998200",
"pm_score": 2,
"selected": false,
"text": "<p>hoyhoy's response is the solution. This solved my problem , too (I actually wanted the namespace to be stripped off).</p>\n\n<p>However, I'd recommend that <code>x.store_full_sti_class = true</code> be added to <code>config/environment.rb</code>, only if it is desired globally. I imagine it might not always be required, in which case, we can easily translate the solution to the class level.</p>\n\n<pre><code>class User < ActiveRecord::Base\n self.store_full_sti_class = true\n ...\nend\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] |
I have the following models.
```
# app/models/domain/domain_object.rb
class Domain::DomainObject < ActiveRecord::Base
has_many :links_from, :class_name => "Link", :as => :from, :dependent => :destroy
end
# app/models/link.rb
class Link < ActiveRecord::Base
belongs_to :from, :polymorphic => true
belongs_to :object_value, :polymorphic => true
end
```
Problem is, when I do the following, the from\_type doesn't prefix the Domain namespace to the model e.g.
```
Domain::DomainObject.all(:include=> :links_from )
```
That causes the following SELECT:
```
SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'DomainObject')
```
The query should be:
```
SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'Domain::DomainObject')
```
because Rails automatically saves the model with the namespace.
I've seen a few recommendations on Rails sites about doing something like this:
```
belongs_to :from, :polymorphic => true, :class_name => "Domain::DomainObject"
```
However, that doesn't appear to work either.
So, is there a better way to do this? Or is this not supported?
|
To fix this, I did a `include Domain` in the `DomainObject` model and set `ActiveRecord::Base.store_full_sti_class = true` in `config/environment.rb`.
|
224,311 |
<p>Is there a better way to negate a boolean in Java than a simple if-else?</p>
<pre><code>if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
</code></pre>
|
[
{
"answer_id": 224314,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 10,
"selected": true,
"text": "<pre><code>theBoolean = !theBoolean;\n</code></pre>\n"
},
{
"answer_id": 224380,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<pre><code>theBoolean ^= true;\n</code></pre>\n\n<p>Fewer keystrokes if your variable is longer than four letters</p>\n\n<p><strong>Edit</strong>: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's <strong><em>bitwise XOR</em></strong> as <a href=\"https://www.tutorialspoint.com/Java-Bitwise-Operators\" rel=\"noreferrer\">described here</a>.</p>\n"
},
{
"answer_id": 29409907,
"author": "Nikhil Kumar",
"author_id": 2845282,
"author_profile": "https://Stackoverflow.com/users/2845282",
"pm_score": -1,
"selected": false,
"text": "<p>\nBefore:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>boolean result = isresult();\nif (result) {\n result = false;\n} else {\n result = true;\n}\n</code></pre>\n\n<p>After:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>boolean result = isresult();\nresult ^= true;\n</code></pre>\n"
},
{
"answer_id": 40594008,
"author": "Levite",
"author_id": 1680919,
"author_profile": "https://Stackoverflow.com/users/1680919",
"pm_score": 6,
"selected": false,
"text": "<h1>There are several</h1>\n\n<p><strong>The \"obvious\" way</strong> (for most people)</p>\n\n<pre><code>theBoolean = !theBoolean;\n</code></pre>\n\n<p><strong>The \"shortest\" way</strong> (most of the time)</p>\n\n<pre><code>theBoolean ^= true;\n</code></pre>\n\n<p><strong>The \"most visual\" way</strong> (most uncertainly)</p>\n\n<pre><code>theBoolean = theBoolean ? false : true;\n</code></pre>\n\n<h1>Extra: Toggle and use in a method call</h1>\n\n<pre><code>theMethod( theBoolean ^= true );\n</code></pre>\n\n<p>Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.</p>\n"
},
{
"answer_id": 44861689,
"author": "Steven Spungin",
"author_id": 5093961,
"author_profile": "https://Stackoverflow.com/users/5093961",
"pm_score": 2,
"selected": false,
"text": "<p>If you use Boolean NULL values and consider them false, try this:</p>\n\n<pre><code>static public boolean toggle(Boolean aBoolean) {\n if (aBoolean == null) return true;\n else return !aBoolean;\n}\n</code></pre>\n\n<p>If you are not handing Boolean NULL values, try this:</p>\n\n<pre><code>static public boolean toggle(boolean aBoolean) {\n return !aBoolean;\n}\n</code></pre>\n\n<p>These are the <em>cleanest</em> because they show the intent in the method signature, are easier to read compared to the <em>!</em> operator, and can be easily debugged.</p>\n\n<p>Usage</p>\n\n<pre><code>boolean bTrue = true\nboolean bFalse = false\nboolean bNull = null\n\ntoggle(bTrue) // == false\ntoggle(bFalse) // == true\ntoggle(bNull) // == true\n</code></pre>\n\n<p>Of course, if you use <em>Groovy</em> or a language that allows extension methods, you can register an extension and simply do:</p>\n\n<pre><code>Boolean b = false\nb = b.toggle() // == true\n</code></pre>\n"
},
{
"answer_id": 55638309,
"author": "Will D.",
"author_id": 9591616,
"author_profile": "https://Stackoverflow.com/users/9591616",
"pm_score": -1,
"selected": false,
"text": "<p>If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.</p>\n\n<pre><code>public class Util {\n\n\npublic Util() {}\npublic boolean flip(boolean bool) { return !bool; }\npublic void sop(String str) { System.out.println(str); }\n\n}\n</code></pre>\n\n<p>then just create a Util object \n<code>Util u = new Util();</code>\nand have something for the return <code>System.out.println( u.flip(bool) );</code></p>\n\n<p>If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)</p>\n"
},
{
"answer_id": 57517945,
"author": "Doctor Parameter",
"author_id": 2414189,
"author_profile": "https://Stackoverflow.com/users/2414189",
"pm_score": 3,
"selected": false,
"text": "<p>This answer came up when searching for \"java invert boolean function\". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)</p>\n\n<pre><code>Boolean.valueOf(aBool).equals(false)\n</code></pre>\n\n<p>or alternatively:</p>\n\n<pre><code>Boolean.FALSE.equals(aBool)\n</code></pre>\n\n<p>or </p>\n\n<pre><code>Boolean.FALSE::equals\n</code></pre>\n"
},
{
"answer_id": 62198314,
"author": "Alex",
"author_id": 3512734,
"author_profile": "https://Stackoverflow.com/users/3512734",
"pm_score": 1,
"selected": false,
"text": "<p>The class <code>BooleanUtils</code> supportes the negation of a boolean. You find this class in <a href=\"https://mvnrepository.com/artifact/org.apache.commons/commons-lang3\" rel=\"nofollow noreferrer\">commons-lang:commons-lang</a> </p>\n\n<pre><code>BooleanUtils.negate(theBoolean)\n</code></pre>\n"
},
{
"answer_id": 72028627,
"author": "Dan Morton",
"author_id": 6831227,
"author_profile": "https://Stackoverflow.com/users/6831227",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;\nBoolean inverse = original == null ? null : !original;\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26237/"
] |
Is there a better way to negate a boolean in Java than a simple if-else?
```
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
```
|
```
theBoolean = !theBoolean;
```
|
224,337 |
<p>I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.</p>
<p>However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.</p>
<p>I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.</p>
<p>However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.</p>
<p>Are there any tutorials for making "dynamic panels" or better management of a wizard?</p>
|
[
{
"answer_id": 224800,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 4,
"selected": true,
"text": "<p>Here is a simple example. This way you can make your \"wizard\" work like a finite state machine where states are different pages that are initialized on demand. Also, the data is shared between pages.</p>\n\n<pre><code>import wx\nimport wx.lib.newevent\n\n\n(PageChangeEvent, EVT_PAGE_CHANGE) = wx.lib.newevent.NewEvent()\n\n\nclass Data:\n foo = None\n bar = None\n\n\nclass Page1(wx.Panel):\n def __init__(self, parent, data):\n wx.Panel.__init__(self, parent)\n self.parent = parent\n self.data = data\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(sizer)\n label = wx.StaticText(self, label=\"Page 1 - foo\")\n self.foo = wx.TextCtrl(self)\n goto_page2 = wx.Button(self, label=\"Go to page 2\")\n\n for c in (label, self.foo, goto_page2):\n sizer.Add(c, 0, wx.TOP, 5)\n\n goto_page2.Bind(wx.EVT_BUTTON, self.OnPage2)\n\n def OnPage2(self, event):\n self.data.foo = self.foo.Value\n wx.PostEvent(self.parent, PageChangeEvent(page=Page2))\n\n\nclass Page2(wx.Panel):\n def __init__(self, parent, data):\n wx.Panel.__init__(self, parent)\n self.parent = parent\n self.data = data\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(sizer)\n label = wx.StaticText(self, label=\"Page 2 - bar\")\n self.bar = wx.TextCtrl(self)\n goto_finish = wx.Button(self, label=\"Finish\")\n\n for c in (label, self.bar, goto_finish):\n sizer.Add(c, 0, wx.TOP, 5)\n\n goto_finish.Bind(wx.EVT_BUTTON, self.OnFinish)\n\n def OnFinish(self, event):\n self.data.bar = self.bar.Value\n wx.PostEvent(self.parent, PageChangeEvent(page=finish))\n\n\ndef finish(parent, data):\n wx.MessageBox(\"foo = %s\\nbar = %s\" % (data.foo, data.bar))\n wx.GetApp().ExitMainLoop()\n\n\nclass Test(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.data = Data()\n self.current_page = None\n\n self.Bind(EVT_PAGE_CHANGE, self.OnPageChange)\n wx.PostEvent(self, PageChangeEvent(page=Page1))\n\n def OnPageChange(self, event):\n page = event.page(self, self.data)\n if page == None:\n return\n if self.current_page:\n self.current_page.Destroy()\n self.current_page = page\n page.Layout()\n page.Fit()\n page.Refresh()\n\n\napp = wx.PySimpleApp()\napp.TopWindow = Test()\napp.TopWindow.Show()\napp.MainLoop()\n</code></pre>\n"
},
{
"answer_id": 225479,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p>You could try using a workflow engine like <a href=\"http://www.vivtek.com/wftk/\" rel=\"nofollow noreferrer\">WFTK</a>. In this particular case author has done some work on wx-based apps using WFTK and can probably direct you to examples.</p>\n"
},
{
"answer_id": 247409,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 1,
"selected": false,
"text": "<p>The wxPython demo has an example of a \"dynamic\" wizard. Pages override GetNext() and GetPrev() to show pages dynamically. This shows the basic technique; you can extend it to add and remove pages, change pages on the fly, and rearrange pages dynamically.</p>\n\n<p>The wizard class is just a convenience, though. You can modify it, or create your own implementation. A style that seems popular nowadays is to use an HTML-based presentation; you can emulate this with the wxHtml control, or the IEHtmlWindow control if your app is Windows only.</p>\n"
},
{
"answer_id": 247633,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 0,
"selected": false,
"text": "<p>I'd get rid of wizard in whole. They are the most unpleasant things I've ever used.</p>\n\n<p>The problem that requires a wizard-application where you click 'next' is perhaps a problem where you could apply a better user interface in a bit different manner. Instead of bringing up a dialog with annoying 'next' -button. Do this:</p>\n\n<p>Bring up a page. When the user inserts the information to the page, extend or shorten it according to the input. If your application needs to do some processing to continue, and it's impossible to revert after that, write a new page or disable the earlier section of the current page. When you don't need any input from the user anymore or the app is finished, you can show a button or enable an existing such.</p>\n\n<p>I don't mean you should implement it all in browser. Make simply a scrolling container that can contain buttons and labels in a flat list.</p>\n\n<p>Benefit: The user can just click a tab, and you are encouraged to put all the processing into the end of filling the page.</p>\n"
},
{
"answer_id": 247711,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 0,
"selected": false,
"text": "<p>It should be noted that a Wizard should be the interface for mutli-step, infrequently-performed tasks. The wizard is used to guide the user through something they don't really understand, because they almost never do it.</p>\n\n<p>And if some users might do the task frequently, you want to give those power users a lightweight interface to do the same thing - even if it less self explanatory.</p>\n\n<p>See: <strong><a href=\"http://msdn.microsoft.com/en-us/library/aa511331.aspx#wizards\" rel=\"nofollow noreferrer\">Windows Vista User Experience Guidelines - Top Violations</a></strong></p>\n\n<blockquote>\n <p><strong>Wizards</strong></p>\n \n <p><strong>Consider lightweight alternatives first, such as dialog boxes, task\n panes, or single pages.</strong> Wizards are\n a heavy UI, best used for multi-step,\n infrequently performed task. You don't\n have to use wizards—you can provide\n helpful information and assistance in\n any UI.</p>\n</blockquote>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.
However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.
I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.
However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.
Are there any tutorials for making "dynamic panels" or better management of a wizard?
|
Here is a simple example. This way you can make your "wizard" work like a finite state machine where states are different pages that are initialized on demand. Also, the data is shared between pages.
```
import wx
import wx.lib.newevent
(PageChangeEvent, EVT_PAGE_CHANGE) = wx.lib.newevent.NewEvent()
class Data:
foo = None
bar = None
class Page1(wx.Panel):
def __init__(self, parent, data):
wx.Panel.__init__(self, parent)
self.parent = parent
self.data = data
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
label = wx.StaticText(self, label="Page 1 - foo")
self.foo = wx.TextCtrl(self)
goto_page2 = wx.Button(self, label="Go to page 2")
for c in (label, self.foo, goto_page2):
sizer.Add(c, 0, wx.TOP, 5)
goto_page2.Bind(wx.EVT_BUTTON, self.OnPage2)
def OnPage2(self, event):
self.data.foo = self.foo.Value
wx.PostEvent(self.parent, PageChangeEvent(page=Page2))
class Page2(wx.Panel):
def __init__(self, parent, data):
wx.Panel.__init__(self, parent)
self.parent = parent
self.data = data
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
label = wx.StaticText(self, label="Page 2 - bar")
self.bar = wx.TextCtrl(self)
goto_finish = wx.Button(self, label="Finish")
for c in (label, self.bar, goto_finish):
sizer.Add(c, 0, wx.TOP, 5)
goto_finish.Bind(wx.EVT_BUTTON, self.OnFinish)
def OnFinish(self, event):
self.data.bar = self.bar.Value
wx.PostEvent(self.parent, PageChangeEvent(page=finish))
def finish(parent, data):
wx.MessageBox("foo = %s\nbar = %s" % (data.foo, data.bar))
wx.GetApp().ExitMainLoop()
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.data = Data()
self.current_page = None
self.Bind(EVT_PAGE_CHANGE, self.OnPageChange)
wx.PostEvent(self, PageChangeEvent(page=Page1))
def OnPageChange(self, event):
page = event.page(self, self.data)
if page == None:
return
if self.current_page:
self.current_page.Destroy()
self.current_page = page
page.Layout()
page.Fit()
page.Refresh()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
```
|
224,359 |
<p>What is the best way to delete a database record using LINQ when I have the primary key? </p>
|
[
{
"answer_id": 224363,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>You can map a stored procedure to a method on the DataContext that deletes a record with a given value for the primary key.</p>\n"
},
{
"answer_id": 224367,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 0,
"selected": false,
"text": "<p>I've always used the select-delete approach as it's very straight-forward. As marxidad said, you can map a stored proc if you really want to. I believe there are plans for ESQL to support insert, update and delete operations in the future.</p>\n"
},
{
"answer_id": 224398,
"author": "CVertex",
"author_id": 209,
"author_profile": "https://Stackoverflow.com/users/209",
"pm_score": 2,
"selected": false,
"text": "<p>That approach is acceptable and typical. </p>\n\n<p>It is a little wasteful because you're requesting the whole record. This cannot be avoided given the DeleteOnSubmit method signature. </p>\n\n<p>Why does LINQ to SQL work this way? The answers obvious if you think about tables that do not have primary keys, or use composite keys. LINQ to SQL needs the whole record for the worst case where it needs to match every object property against the table fields. </p>\n\n<p>But as should be asked for all concerns of performance - are you absolutely sure this is a performance issue for you?? Where's your profiling proof?</p>\n\n<p>I haven't tried this yet but there might be a way to achieve the same thing with <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executecommand.aspx\" rel=\"nofollow noreferrer\">DataContext.ExecuteCommand</a>.</p>\n"
},
{
"answer_id": 224401,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up doing a select, but improved my syntax which I think was really my concern:</p>\n\n<p>Old:</p>\n\n<pre><code>var products = from p in db.Products select p;\ndb.Products.DeleteOnSubmit(products.Take(1).Single()); <--seemed nasty\ndb.SubmitChanges();\n</code></pre>\n\n<p>New:</p>\n\n<pre><code>Service service = db.Services.Where(s => s.id == serviceID).FirstOrDefault(); <--nicer\ndb.Services.DeleteOnSubmit(service);\ndb.SubmitChanges();\n</code></pre>\n"
},
{
"answer_id": 224452,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<pre><code> public static Delete(this ITable table, object key)\n { var t = table.GetType();\n var tableName = t.GetCustomAttributes\n (typeof(TableAttribute),false)[0].Name;\n var primaryKey = (from p in t.GetProperties()\n from c in p.GetCustomAttributes\n (typeof(ColumnAttribute),false)\n where c.IsPrimaryKey\n select c.Name).Single();\n using (var cmd = table.Context.Connection.CreateCommand())\n { cmd.CommandText = string.Format( \"DELETE FROM {0} WHERE {1} = @key\"\n ,tableName, primaryKey);\n cmd.Parameters.Add(new SqlParameter(\"@key\", key));\n cmd.ExecuteNonQuery(); \n } \n }\n\n/* ... */\ndataContext.Table1.Delete(id);\n</code></pre>\n"
},
{
"answer_id": 225804,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<p>If you set <strong>update checks</strong> on all your columns to <strong>never</strong> or <strong>when changed</strong>, you can simply attach an instance with the primary key and delete the row without a load.</p>\n\n<pre><code>public void DeleteCustomer(int CustomerID)\n{\n NorthwindContext c = new NorthwindContext c;\n Customer target = new Customer(){CustomerID = CustomerID};\n c.Customers.Attach(target);\n c.Customers.DeleteOnSubmit(target);\n c.SubmitChanges(); \n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] |
What is the best way to delete a database record using LINQ when I have the primary key?
|
If you set **update checks** on all your columns to **never** or **when changed**, you can simply attach an instance with the primary key and delete the row without a load.
```
public void DeleteCustomer(int CustomerID)
{
NorthwindContext c = new NorthwindContext c;
Customer target = new Customer(){CustomerID = CustomerID};
c.Customers.Attach(target);
c.Customers.DeleteOnSubmit(target);
c.SubmitChanges();
}
```
|
224,379 |
<p>I see this all the time in Ruby:</p>
<pre><code>require File.dirname(__FILE__) + "/../../config/environment"
</code></pre>
<p>What does <code>__FILE__</code> mean?</p>
|
[
{
"answer_id": 224383,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": 8,
"selected": true,
"text": "<p>It is a reference to the current file name. In the file <code>foo.rb</code>, <code>__FILE__</code> would be interpreted as <code>\"foo.rb\"</code>.</p>\n\n<p><strong>Edit:</strong> Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in <a href=\"https://stackoverflow.com/questions/224379/what-does-file-mean-in-ruby#comment1243516_224383\">his comment</a>. With these files:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code># test.rb\nputs __FILE__\nrequire './dir2/test.rb'\n</code></pre>\n\n<pre class=\"lang-ruby prettyprint-override\"><code># dir2/test.rb\nputs __FILE__\n</code></pre>\n\n<p>Running <code>ruby test.rb</code> will output</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>test.rb\n/full/path/to/dir2/test.rb\n</code></pre>\n"
},
{
"answer_id": 335191,
"author": "Ethan",
"author_id": 42595,
"author_profile": "https://Stackoverflow.com/users/42595",
"pm_score": 5,
"selected": false,
"text": "<p><code>__FILE__</code> is the filename with extension of the file containing the code being executed.</p>\n\n<p>In <code>foo.rb</code>, <code>__FILE__</code> would be \"foo.rb\".</p>\n\n<p>If <code>foo.rb</code> were in the dir <code>/home/josh</code> then <code>File.dirname(__FILE__)</code> would return <code>/home/josh</code>.</p>\n"
},
{
"answer_id": 784792,
"author": "Matt Wolfe",
"author_id": 94557,
"author_profile": "https://Stackoverflow.com/users/94557",
"pm_score": 4,
"selected": false,
"text": "<p>In Ruby, the Windows version anyways, I just checked and <code>__FILE__</code> does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from. </p>\n\n<p>In PHP <code>__FILE__</code> is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:</p>\n\n<pre><code>File.expand_path(File.dirname(__FILE__) + \"relative/path/to/file\")\n</code></pre>\n\n<p>I should note that in Ruby 1.9.1 <code>__FILE__</code> contains the full path to the file, the above description was for when I used Ruby 1.8.7.</p>\n\n<p>In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.</p>\n"
},
{
"answer_id": 894056,
"author": "Luke Bayes",
"author_id": 105023,
"author_profile": "https://Stackoverflow.com/users/105023",
"pm_score": 6,
"selected": false,
"text": "<p>The value of <code>__FILE__</code> is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to <code>Dir.chdir</code> anywhere else in your application, this path will expand incorrectly.</p>\n\n<pre><code>puts __FILE__\nDir.chdir '../../'\nputs __FILE__\n</code></pre>\n\n<p>One workaround to this problem is to store the expanded value of <code>__FILE__</code> outside of any application code. As long as your <code>require</code> statements are at the top of your definitions (or at least before any calls to <code>Dir.chdir</code>), this value will continue to be useful after changing directories.</p>\n\n<pre><code>$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))\n\n# open class and do some stuff that changes directory\n\nputs $MY_FILE_PATH\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
I see this all the time in Ruby:
```
require File.dirname(__FILE__) + "/../../config/environment"
```
What does `__FILE__` mean?
|
It is a reference to the current file name. In the file `foo.rb`, `__FILE__` would be interpreted as `"foo.rb"`.
**Edit:** Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in [his comment](https://stackoverflow.com/questions/224379/what-does-file-mean-in-ruby#comment1243516_224383). With these files:
```ruby
# test.rb
puts __FILE__
require './dir2/test.rb'
```
```ruby
# dir2/test.rb
puts __FILE__
```
Running `ruby test.rb` will output
```none
test.rb
/full/path/to/dir2/test.rb
```
|
224,397 |
<p>I was taking a look through some open-source C++ code and I noticed a lot of double underscores used within in the code, mainly at the start of variable names.</p>
<pre><code>return __CYGWIN__;
</code></pre>
<p>Just wondering: Is there a reason for this, or is it just some people's code styles? I would think that it makes it hard to read.</p>
|
[
{
"answer_id": 224404,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 3,
"selected": false,
"text": "<p>It's something you're not meant to do in 'normal' code. This ensures that compilers and system libraries can define symbols that won't collide with yours.</p>\n"
},
{
"answer_id": 224414,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": "<p>According to the C++ Standard, identifiers starting with one underscore are reserved for libraries. Identifiers starting with two underscores are reserved for compiler vendors.</p>\n"
},
{
"answer_id": 224420,
"author": "maccullt",
"author_id": 4945,
"author_profile": "https://Stackoverflow.com/users/4945",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap5.html\" rel=\"noreferrer\">Programming in C++, Rules and Recommendations</a> :</p>\n\n<blockquote>\n <p>The use of two underscores (`__') in identifiers is reserved for the compiler's internal use according to the ANSI-C standard.</p>\n \n <p>Underscores (`_') are often used in names of library functions (such as \"_main\" and \"_exit\"). In order to avoid collisions, do not begin an identifier with an underscore.</p>\n</blockquote>\n"
},
{
"answer_id": 224426,
"author": "bog",
"author_id": 20909,
"author_profile": "https://Stackoverflow.com/users/20909",
"pm_score": 4,
"selected": false,
"text": "<p>The foregoing comments are correct. <code>__Symbol__</code> is generally a magic token provided by your helpful compiler (or preprocessor) vendor. Perhaps the most widely-used of these are <code>__FILE__</code> and <code>__LINE__</code>, which are expanded by the C preprocessor to indicate the current filename and line number. That's handy when you want to log some sort of program assertion failure, including the textual location of the error.</p>\n"
},
{
"answer_id": 224429,
"author": "Sqeaky",
"author_id": 17315,
"author_profile": "https://Stackoverflow.com/users/17315",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to libraries which many other people responded about, Some people also name macros or #define values for use with the preprocessor. This would make it easier to work with, and may have allowed bugs in older compilers to be worked around.</p>\n\n<p>Like others mentioned, it helps prevent name collision and helps to delineate between library variables and your own.</p>\n"
},
{
"answer_id": 225294,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 6,
"selected": false,
"text": "<p>Unless they feel that they are \"part of the implementation\", i.e. the standard libraries, then they shouldn't.</p>\n\n<p>The rules are fairly specific, and are slightly more detailed than some others have suggested.</p>\n\n<p>All identifiers that contain a double underscore or start with an underscore followed by an uppercase letter are reserved for the use of the implementation at all scopes, i.e. they might be used for macros.</p>\n\n<p>In addition, all other identifiers which start with an underscore (i.e. not followed by another underscore or an uppercase letter) are reserved for the implementation at the global scope. This means that you can use these identifiers in your own namespaces or in class definitions.</p>\n\n<p>This is why Microsoft use function names with a leading underscore and all in lowercase for many of their core runtime library functions which aren't part of the C++ standard. These function names are guaranteed not to clash with either standard C++ functions or user code functions.</p>\n"
},
{
"answer_id": 56388858,
"author": "RemarkableBucket",
"author_id": 8453543,
"author_profile": "https://Stackoverflow.com/users/8453543",
"pm_score": 3,
"selected": false,
"text": "<h1>Double underscores are reserved to the implementation</h1>\n\n<p>The top voted answer cites <a href=\"https://web.archive.org/web/20180423133417/http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap5.html\" rel=\"noreferrer\">Programming in C++: Rules and Recommendations</a>:</p>\n\n<blockquote>\n <p>\"The use of two underscores (`__') in identifiers is reserved for the compiler's internal use according to the ANSI-C standard.\"</p>\n</blockquote>\n\n<p>However, after reading a few C++ and C standards, I was unable to find any mention of underscores being restricted to <em>just</em> the compiler's internal use. The standards are more general, reserving double underscores for <strong>the implementation</strong>.</p>\n\n<h2>C++</h2>\n\n<p><a href=\"https://timsong-cpp.github.io/cppwp/n4659/lex.name\" rel=\"noreferrer\">C++</a> (current working draft, accessed 2019-5-26) states in <code>lex.name</code>:</p>\n\n<blockquote>\n <ul>\n <li>Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.</li>\n <li>Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.</li>\n </ul>\n</blockquote>\n\n<h2>C</h2>\n\n<p>Although this question is specific to C++, I've cited relevant sections from C standards 99 and 17:</p>\n\n<p><a href=\"https://busybox.net/~landley/c99-draft.html\" rel=\"noreferrer\">C99</a> section 7.1.3</p>\n\n<blockquote>\n <ul>\n <li>All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.</li>\n <li>All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name\n spaces.</li>\n </ul>\n</blockquote>\n\n<p><a href=\"https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf\" rel=\"noreferrer\">C17</a> says the same thing as C99.</p>\n\n<h1>What is <strong>the implementation</strong>?</h1>\n\n<p>For C/C++, the <a href=\"https://en.wikipedia.org/wiki/Programming_language_implementation\" rel=\"noreferrer\">implementation</a> loosely refers to the set resources necessary to produce an executable from user source files. This includes:</p>\n\n<ul>\n<li>preprocessor</li>\n<li>compiler</li>\n<li>linker</li>\n<li>standard library</li>\n</ul>\n\n<h2>Example implementations</h2>\n\n<p>There are a number of different C++ implementations mentioned on <a href=\"https://en.wikipedia.org/wiki/C%2B%2B\" rel=\"noreferrer\">Wikipedia</a>. (no anchor link, ctrl+f \"implementation\")</p>\n\n<p><a href=\"https://digitalmars.com/ctg/contract.html\" rel=\"noreferrer\">Here's an example of Digital Mars' C/C++ implementation reserving some keywords for a feature of theirs.</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
I was taking a look through some open-source C++ code and I noticed a lot of double underscores used within in the code, mainly at the start of variable names.
```
return __CYGWIN__;
```
Just wondering: Is there a reason for this, or is it just some people's code styles? I would think that it makes it hard to read.
|
From [Programming in C++, Rules and Recommendations](http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap5.html) :
>
> The use of two underscores (`\_\_') in identifiers is reserved for the compiler's internal use according to the ANSI-C standard.
>
>
> Underscores (`\_') are often used in names of library functions (such as "\_main" and "\_exit"). In order to avoid collisions, do not begin an identifier with an underscore.
>
>
>
|
224,408 |
<p>Is there a better/simpler way to find the number of images in a directory and output them to a variable?</p>
<pre><code>function dirCount($dir) {
$x = 0;
while (($file = readdir($dir)) !== false) {
if (isImage($file)) {$x = $x + 1}
}
return $x;
}
</code></pre>
<p>This seems like such a long way of doing this, is there no simpler way?</p>
<p><strong>Note:</strong> The isImage() function returns true if the file is an image.</p>
|
[
{
"answer_id": 224439,
"author": "bbxbby",
"author_id": 29230,
"author_profile": "https://Stackoverflow.com/users/29230",
"pm_score": 6,
"selected": true,
"text": "<p>Check out the Standard PHP Library (aka SPL) for DirectoryIterator:</p>\n\n<pre><code>$dir = new DirectoryIterator('/path/to/dir');\nforeach($dir as $file ){\n $x += (isImage($file)) ? 1 : 0;\n}\n</code></pre>\n\n<p>(FYI there is an undocumented function called iterator_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)</p>\n"
},
{
"answer_id": 224464,
"author": "Chris Kloberdanz",
"author_id": 28714,
"author_profile": "https://Stackoverflow.com/users/28714",
"pm_score": 0,
"selected": false,
"text": "<p>Your answer seems about as simple as you can get it. I can't think of a shorter way to it in either PHP or Perl.</p>\n\n<p>You might be able to a system / exec command involving ls, wc, and grep if you are using Linux depending how complex isImage() is.</p>\n\n<p>Regardless, I think what you have is quite sufficient. You only have to write the function once.</p>\n"
},
{
"answer_id": 224505,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 4,
"selected": false,
"text": "<p>This will give you the count of what is in your dir. I'll leave the part about counting only images to you as I am about to fallll aaasssllleeelppppppzzzzzzzzzzzzz.</p>\n\n<pre><code>iterator_count(new DirectoryIterator('path/to/dir/'));\n</code></pre>\n"
},
{
"answer_id": 224509,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>you could use <code>glob</code>...</p>\n\n<pre><code>$count = 0;\nforeach (glob(\"*.*\") as $file) {\n if (isImage($file)) ++$count;\n}\n</code></pre>\n\n<p>or, I'm not sure how well this would suit your needs, but you could do this:</p>\n\n<pre><code>$count = count(glob(\"*.{jpg,png,gif,bmp}\"));\n</code></pre>\n"
},
{
"answer_id": 931870,
"author": "salathe",
"author_id": 113938,
"author_profile": "https://Stackoverflow.com/users/113938",
"pm_score": 1,
"selected": false,
"text": "<p>You could also make use of the SPL to filter the contents of a <code>DirectoryIterator</code> using your <code>isImage</code> function by extending the abstract <code>FilterIterator</code> class.</p>\n\n<pre><code>class ImageIterator extends FilterIterator {\n\n public function __construct($path)\n {\n parent::__construct(new DirectoryIterator($path));\n }\n\n public function accept()\n {\n return isImage($this->getInnerIterator());\n }\n}\n</code></pre>\n\n<p>You could then use <code>iterator_count</code> (or implement the <code>Countable</code> interface and use the native <code>count</code> function) to determine the number of images. For example:</p>\n\n<pre><code>$images = new ImageIterator('/path/to/images');\nprintf('Found %d images!', iterator_count($images));\n</code></pre>\n\n<p>Using this approach, depending on how you need to use this code, it might make more sense to move the <code>isImage</code> function into the <code>ImageIterator</code> class to have everything neatly wrapped up in one place.</p>\n"
},
{
"answer_id": 3905596,
"author": "Josh Dunbar",
"author_id": 472213,
"author_profile": "https://Stackoverflow.com/users/472213",
"pm_score": 2,
"selected": false,
"text": "<p>The aforementioned code </p>\n\n<pre><code>$count = count(glob(\"*.{jpg,png,gif,bmp}\"));\n</code></pre>\n\n<p>is your best best, but the {jpg,png,gif} bit will only work if you append the <code>GLOB_BRACE</code> flag on the end:</p>\n\n<pre><code>$count = count(glob(\"*.{jpg,png,gif,bmp}\", GLOB_BRACE));\n</code></pre>\n"
},
{
"answer_id": 14567412,
"author": "haheute",
"author_id": 2018961,
"author_profile": "https://Stackoverflow.com/users/2018961",
"pm_score": 3,
"selected": false,
"text": "<p>i do it like this:</p>\n\n<pre><code>$files = scandir($dir);\n$x = count($files);\necho $x;\n</code></pre>\n\n<p>but it also counts the . and ..</p>\n"
},
{
"answer_id": 16444356,
"author": "Marc",
"author_id": 1067109,
"author_profile": "https://Stackoverflow.com/users/1067109",
"pm_score": 0,
"selected": false,
"text": "<p>I use this to return a count of ALL files in a directory except . and ..</p>\n\n<pre><code>return count(glob(\"/path/to/file/[!\\.]*\"));\n</code></pre>\n\n<p>Here is <a href=\"http://cowburn.info/2010/04/30/glob-patterns/\" rel=\"nofollow\">a good list of glob filters</a> for file matching purposes.</p>\n"
},
{
"answer_id": 16881552,
"author": "user2444847",
"author_id": 2444847,
"author_profile": "https://Stackoverflow.com/users/2444847",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$nfiles = glob(\"/path/to/file/[!\\\\.]*\");\n\nif ($nfiles !== FALSE){\n\n return count($nfiles);\n\n} else {\n\n return 0;\n\n}\n</code></pre>\n"
},
{
"answer_id": 35602891,
"author": "Shailesh Ladumor",
"author_id": 5974595,
"author_profile": "https://Stackoverflow.com/users/5974595",
"pm_score": 1,
"selected": false,
"text": "<p>I use the following to get the count for all types of files in one directory in Laravel</p>\n\n<pre><code> $dir = public_path('img/');\n $files = glob($dir . '*.*');\n\n if ( $files !== false )\n {\n $total_count = count( $files );\n return $totalCount;\n }\n else\n {\n return 0;\n }\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] |
Is there a better/simpler way to find the number of images in a directory and output them to a variable?
```
function dirCount($dir) {
$x = 0;
while (($file = readdir($dir)) !== false) {
if (isImage($file)) {$x = $x + 1}
}
return $x;
}
```
This seems like such a long way of doing this, is there no simpler way?
**Note:** The isImage() function returns true if the file is an image.
|
Check out the Standard PHP Library (aka SPL) for DirectoryIterator:
```
$dir = new DirectoryIterator('/path/to/dir');
foreach($dir as $file ){
$x += (isImage($file)) ? 1 : 0;
}
```
(FYI there is an undocumented function called iterator\_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)
|
224,410 |
<p>I'm having some trouble getting log4net to work from ASP.NET 3.5. This is the first time I've tried to use log4net, I feel like I'm missing a piece of the puzzle.</p>
<p>My project references the log4net assembly, and as far as I can tell, it is being deployed successfully on my server.</p>
<p>My web.config contains the following:</p>
<pre><code> <configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler
, log4net"
requirePermission="false"/>
</configSections>
<log4net>
<appender name="InfoAppender" type="log4net.Appender.FileAppender">
<file value="..\..\logs\\InfoLog.html" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern
value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<logger name="_Default">
<level value="INFO" />
<appender-ref ref="InfoAppender" />
</logger>
</log4net>
</code></pre>
<p>I'm using the following code to test the logger:</p>
<pre><code>using log4net;
using log4net.Config;
public partial class _Default : System.Web.UI.Page
{
private static readonly ILog log = LogManager.GetLogger("_Default");
protected void Page_Load(object sender, EventArgs e)
{
log.Info("Hello logging world!");
}
}
</code></pre>
<p>In my Global.asax, I'm doing the following:</p>
<pre><code>void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
</code></pre>
<p>At this point, I can't think of what else I might be doing wrong. The directory I'm trying to store the log in is writable, and even if I try different directories I get the same result: no file, no logs.</p>
<p>Any suggestions? :-)</p>
<hr>
<p>Edit: I've tried several different formats for the path & name of the log file, some of which include "..\..\InfoLog.html", "InfoLog.html", "logs\InfoLog.html", etc, just in case someone is wondering if that's the problem.</p>
<hr>
<p>Edit: I've added the root logger node back into the log4net section, I ommitted that on accident when copying from the samples. The root logger node looks like this:</p>
<pre><code><root>
<level value="INFO" />
<appender-ref ref="InfoAppender" />
</root>
</code></pre>
<p>Even with it, however, I'm still having no luck.</p>
|
[
{
"answer_id": 224423,
"author": "CVertex",
"author_id": 209,
"author_profile": "https://Stackoverflow.com/users/209",
"pm_score": 5,
"selected": true,
"text": "<p>The root logger is mandatory I think. I suspect configuration is failing because the root doesn't exist.</p>\n\n<p>Another potential problem is that Configure isn't being pointed to the Web.config.</p>\n\n<p>Try Configure(Server.MapPath(\"~/web.config\")) instead.</p>\n"
},
{
"answer_id": 289160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>This is what i have in Global.ASX. Got it all working in asp.net 3.5</p>\n\n<pre><code><%@ Application Language=\"C#\" %>\n\n<script runat=\"server\">\n\n void Application_Start(object sender, EventArgs e) \n {\n // Code that runs on application startup\n log4net.Config.XmlConfigurator.Configure(); \n }\n\n void Application_End(object sender, EventArgs e) \n {\n // Code that runs on application shutdown\n log4net.LogManager.Shutdown();\n }\n\n void Application_Error(object sender, EventArgs e) \n { \n // Code that runs when an unhandled error occurs\n }\n\n void Session_Start(object sender, EventArgs e) \n {\n // Code that runs when a new session is started\n }\n\n void Session_End(object sender, EventArgs e) \n {\n // Code that runs when a session ends. \n // Note: The Session_End event is raised only when the sessionstate mode\n // is set to InProc in the Web.config file. If session mode is set to StateServer \n // or SQLServer, the event is not raised.\n }\n</script>\n</code></pre>\n"
},
{
"answer_id": 289184,
"author": "Chris",
"author_id": 34942,
"author_profile": "https://Stackoverflow.com/users/34942",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds very much like a file permissions issue to me. If you specify a file name without any path, log4net will write to the root directory of the web application. Try that. Barring any success there, I'd recommend you enable internal log4net debugging by putting the following in your web.config:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key=\"log4net.Internal.Debug\" value=\"true\"/>\n </appSettings>\n</configuration>\n</code></pre>\n\n<p>Then, deploy the app compiled in debug mode and run the <a href=\"https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/programming-and-development/?p=675\" rel=\"nofollow noreferrer\">visual studio remote debugger</a> to see any errors that are thrown.</p>\n"
},
{
"answer_id": 380539,
"author": "Peter Lillevold",
"author_id": 35245,
"author_profile": "https://Stackoverflow.com/users/35245",
"pm_score": 1,
"selected": false,
"text": "<p>Just for info: the file path must be formatted as follows:</p>\n\n<pre><code><file value=\"..\\\\..\\\\logs\\\\InfoLog.html\" />\n</code></pre>\n"
},
{
"answer_id": 380562,
"author": "Pawel Krakowiak",
"author_id": 41420,
"author_profile": "https://Stackoverflow.com/users/41420",
"pm_score": -1,
"selected": false,
"text": "<p>How about creating the logger with the page's type, like this:</p>\n\n<pre><code>private static readonly ILog log = LogManager.GetLogger(typeof(_Default));\n</code></pre>\n"
},
{
"answer_id": 441133,
"author": "Sean Rock",
"author_id": 13551,
"author_profile": "https://Stackoverflow.com/users/13551",
"pm_score": 0,
"selected": false,
"text": "<p>i had the same (frustrating) problem. i moved the root to the top of the log4net config section and it all worked. Also, i too had root and a logger element, this resulted in two lines each time i made a call to the logger. i removed the logger element and simply keep the root and its working great.</p>\n"
},
{
"answer_id": 719598,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 2,
"selected": false,
"text": "<p>Iv just spent 3 hours trying to fix this problem is the end it was the web.config formatting.</p>\n\n<p>I had this, and it didn't work:</p>\n\n<pre><code><section name=\"SubSonicService\" type=\"SubSonic.SubSonicSection, SubSonic\" requirePermission=\"false\"/>\n <section name=\"log4net\"\n type=\"log4net.Config.Log4NetConfigurationSectionHandler\n , log4net\"\n requirePermission=\"false\"/>\n</code></pre>\n\n<p>changing it to this fixed it:</p>\n\n<pre><code> <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" requirePermission=\"false\"/>\n</code></pre>\n\n<p>Annoying!!</p>\n"
},
{
"answer_id": 768261,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 1,
"selected": false,
"text": "<p>A simple configuration tutorial from <a href=\"http://www.codeproject.com/KB/aspnet/log4net.aspx\" rel=\"nofollow noreferrer\">CodeProject</a></p>\n"
},
{
"answer_id": 3860596,
"author": "Herries E",
"author_id": 466398,
"author_profile": "https://Stackoverflow.com/users/466398",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have the Global.asx to run in .net 3.5</p>\n\n<p>this is my code... I configure the log4net in a separate file log4net.config</p>\n\n<pre><code>// Configure log4net using the .config file\n[assembly: log4net.Config.XmlConfigurator(ConfigFile = \"log4net.config\", Watch = true)]\n\n//My Web Services class name\nprivate static readonly log4net.ILog log = log4net.LogManager.GetLogger(\"Service1\");\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18505/"
] |
I'm having some trouble getting log4net to work from ASP.NET 3.5. This is the first time I've tried to use log4net, I feel like I'm missing a piece of the puzzle.
My project references the log4net assembly, and as far as I can tell, it is being deployed successfully on my server.
My web.config contains the following:
```
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler
, log4net"
requirePermission="false"/>
</configSections>
<log4net>
<appender name="InfoAppender" type="log4net.Appender.FileAppender">
<file value="..\..\logs\\InfoLog.html" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern
value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<logger name="_Default">
<level value="INFO" />
<appender-ref ref="InfoAppender" />
</logger>
</log4net>
```
I'm using the following code to test the logger:
```
using log4net;
using log4net.Config;
public partial class _Default : System.Web.UI.Page
{
private static readonly ILog log = LogManager.GetLogger("_Default");
protected void Page_Load(object sender, EventArgs e)
{
log.Info("Hello logging world!");
}
}
```
In my Global.asax, I'm doing the following:
```
void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
```
At this point, I can't think of what else I might be doing wrong. The directory I'm trying to store the log in is writable, and even if I try different directories I get the same result: no file, no logs.
Any suggestions? :-)
---
Edit: I've tried several different formats for the path & name of the log file, some of which include "..\..\InfoLog.html", "InfoLog.html", "logs\InfoLog.html", etc, just in case someone is wondering if that's the problem.
---
Edit: I've added the root logger node back into the log4net section, I ommitted that on accident when copying from the samples. The root logger node looks like this:
```
<root>
<level value="INFO" />
<appender-ref ref="InfoAppender" />
</root>
```
Even with it, however, I'm still having no luck.
|
The root logger is mandatory I think. I suspect configuration is failing because the root doesn't exist.
Another potential problem is that Configure isn't being pointed to the Web.config.
Try Configure(Server.MapPath("~/web.config")) instead.
|
224,421 |
<p>In a <a href="https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom">coding style question about infinite loops</a>, some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant.</p>
<p>This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoiding #ifdef hell. For instance, you can have in your header:</p>
<pre><code>#ifdef CONFIG_FOO
extern int foo_enabled;
#else
#define foo_enabled 0
#endif
</code></pre>
<p>And the code can simply use a conditional and trust the compiler to elide the dead code when CONFIG_FOO isn't defined:</p>
<pre><code>if (foo_enabled) {
...
}
</code></pre>
<p>Instead of having to test for CONFIG_FOO every time foo_enabled is used:</p>
<pre><code>#ifdef CONFIG_FOO
if (foo_enabled) {
...
}
#endif
</code></pre>
<p>This design pattern is used all the time in the Linux kernel (for instance, include/linux/cpumask.h defines several macros to 1 or 0 when SMP is disabled and to a function call when SMP is enabled).</p>
<p>What is the reason for that MSVC warning? Additionally, is there a better way to avoid #ifdef hell without having to disable that warning? Or is it an overly broad warning which should not be enabled in general?</p>
|
[
{
"answer_id": 224427,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>I believe it's to catch things like </p>\n\n<pre><code> if( x=0 )\n</code></pre>\n\n<p>when you meant </p>\n\n<pre><code> if( x==0 )\n</code></pre>\n"
},
{
"answer_id": 224435,
"author": "bog",
"author_id": 20909,
"author_profile": "https://Stackoverflow.com/users/20909",
"pm_score": 0,
"selected": false,
"text": "<p>A simple way to avoid the warning would be:</p>\n\n<pre><code>#ifdef CONFIG_FOO\nextern int foo_enabled;\n#else\nextern int foo_enabled = 0;\n#endif\n</code></pre>\n"
},
{
"answer_id": 224437,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 3,
"selected": false,
"text": "<p>I think the reason for the warning is that you might inadvertently have a more complex expression that evaluates to a constant without realizing it. Suppose you have a declaration like this in a header:</p>\n\n<pre><code>const int x = 0;\n</code></pre>\n\n<p>then later on, far from the declaration of x, you have a condition like:</p>\n\n<pre><code>if (x != 0) ...\n</code></pre>\n\n<p>You might not notice that it's a constant expression. </p>\n"
},
{
"answer_id": 224442,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 4,
"selected": true,
"text": "<p>A warning doesn't automatically mean that code is <em>bad</em>, just suspicious-looking.</p>\n\n<p>Personally I start from a position of enabling all the warnings I can, then turn off any that prove more annoying than useful. That one that fires anytime you cast anything to a bool is usually the first to go.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28258/"
] |
In a [coding style question about infinite loops](https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom), some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant.
This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoiding #ifdef hell. For instance, you can have in your header:
```
#ifdef CONFIG_FOO
extern int foo_enabled;
#else
#define foo_enabled 0
#endif
```
And the code can simply use a conditional and trust the compiler to elide the dead code when CONFIG\_FOO isn't defined:
```
if (foo_enabled) {
...
}
```
Instead of having to test for CONFIG\_FOO every time foo\_enabled is used:
```
#ifdef CONFIG_FOO
if (foo_enabled) {
...
}
#endif
```
This design pattern is used all the time in the Linux kernel (for instance, include/linux/cpumask.h defines several macros to 1 or 0 when SMP is disabled and to a function call when SMP is enabled).
What is the reason for that MSVC warning? Additionally, is there a better way to avoid #ifdef hell without having to disable that warning? Or is it an overly broad warning which should not be enabled in general?
|
A warning doesn't automatically mean that code is *bad*, just suspicious-looking.
Personally I start from a position of enabling all the warnings I can, then turn off any that prove more annoying than useful. That one that fires anytime you cast anything to a bool is usually the first to go.
|
224,453 |
<p>I have a string encrypted in PHP that I would like to decrypt in C#. I used the tutorial below to do the encryption, but am having problems decrypting. Can anyone post an example on how to do this? </p>
<p><a href="http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html" rel="noreferrer">http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html</a></p>
|
[
{
"answer_id": 224524,
"author": "deepcode.co.uk",
"author_id": 20524,
"author_profile": "https://Stackoverflow.com/users/20524",
"pm_score": 5,
"selected": true,
"text": "<p>Hope this helps:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(Decrypt(\"47794945c0230c3d\"));\n }\n\n static string Decrypt(string input)\n {\n TripleDES tripleDes = TripleDES.Create();\n tripleDes.IV = Encoding.ASCII.GetBytes(\"password\");\n tripleDes.Key = Encoding.ASCII.GetBytes(\"passwordDR0wSS@P6660juht\");\n tripleDes.Mode = CipherMode.CBC;\n tripleDes.Padding = PaddingMode.Zeros;\n\n ICryptoTransform crypto = tripleDes.CreateDecryptor();\n byte[] decodedInput = Decoder(input);\n byte[] decryptedBytes = crypto.TransformFinalBlock(decodedInput, 0, decodedInput.Length);\n return Encoding.ASCII.GetString(decryptedBytes);\n }\n\n static byte[] Decoder(string input)\n {\n byte[] bytes = new byte[input.Length/2];\n int targetPosition = 0;\n\n for( int sourcePosition=0; sourcePosition<input.Length; sourcePosition+=2 )\n {\n string hexCode = input.Substring(sourcePosition, 2);\n bytes[targetPosition++] = Byte.Parse(hexCode, NumberStyles.AllowHexSpecifier);\n }\n\n return bytes;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1765846,
"author": "Richard Varno",
"author_id": 214891,
"author_profile": "https://Stackoverflow.com/users/214891",
"pm_score": 4,
"selected": false,
"text": "<p>If you are not tied to tripleDES, but just need to pass encrypted data between php and .net, this will work for you. It's in VB and C# below.</p>\n\n<h3>BEGIN PHP CODE</h3>\n\n<pre><code><?php\n\nini_set('display_errors', 1);\nerror_reporting(E_ALL);\n\n// I blantantly stole, tweaked and happily used this code from: \n// Lord of Ports http://www.experts-exchange.com/M_1736399.html\n\n$ky = 'lkirwf897+22#bbtrm8814z5qq=498j5'; // 32 * 8 = 256 bit key\n$iv = '741952hheeyy66#cs!9hjv887mxx7@8y'; // 32 * 8 = 256 bit iv\n\n$text = \"Here is my data to encrypt!!!\";\n\n$from_vb = \"QBlgcQ2+v3wd8RLjhtu07ZBd8aQWjPMfTc/73TPzlyA=\"; // enter value from vb.net app here to test\n\n$etext = encryptRJ256($ky, $iv, $text);\n$dtext = decryptRJ256($ky, $iv, $etext);\n$vtext = decryptRJ256($ky, $iv, $from_vb);\n\necho \"<HR>orignal string: $text\";\necho \"<HR>encrypted in php: $etext\";\necho \"<HR>decrypted in php: $dtext\";\necho \"<HR>encrypted in vb: $from_vb\";\necho \"<HR>from vb decrypted in php: $vtext\"; \necho \"<HR>If you like it say thanks! richard dot varno at gmail dot com\";\n\nexit;\n\n\nfunction decryptRJ256($key,$iv,$string_to_decrypt)\n{\n $string_to_decrypt = base64_decode($string_to_decrypt);\n $rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);\n $rtn = rtrim($rtn, \"\\0\\4\");\n return($rtn);\n}\n\nfunction encryptRJ256($key,$iv,$string_to_encrypt)\n{\n $rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);\n $rtn = base64_encode($rtn);\n return($rtn);\n} \n?>\n</code></pre>\n\n<h3>BEGIN VB.NET CODE (console app)</h3>\n\n<pre><code>Imports System\nImports System.Text\nImports System.Security.Cryptography\nImports System.IO\n\nModule Module1\n\n ' I blantantly stole, tweaked and happily used this code from: \n ' Lord of Ports http://www.experts-exchange.com/M_1736399.html\n\n Sub Main()\n\n 'Shared 256 bit Key and IV here\n Dim sKy As String = \"lkirwf897+22#bbtrm8814z5qq=498j5\" '32 chr shared ascii string (32 * 8 = 256 bit)\n Dim sIV As String = \"741952hheeyy66#cs!9hjv887mxx7@8y\" '32 chr shared ascii string (32 * 8 = 256 bit)\n\n Dim sTextVal As String = \"Here is my data to encrypt!!!\"\n\n Dim eText As String\n Dim dText As String\n\n eText = EncryptRJ256(sKy, sIV, sTextVal)\n dText = DecryptRJ256(sKy, sIV, eText)\n\n Console.WriteLine(\"key: \" & sKy)\n Console.WriteLine()\n Console.WriteLine(\" iv: \" & sIV)\n Console.WriteLine(\"txt: \" & sTextVal)\n Console.WriteLine(\"encrypted: \" & eText)\n Console.WriteLine(\"decrypted: \" & dText)\n Console.WriteLine(\"If you like it say thanks! richard dot varno at gmail dot com\")\n Console.WriteLine(\"press any key to exit\")\n Console.ReadKey(True)\n\n End Sub\n\n Public Function DecryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_decrypt As String)\n\n Dim sEncryptedString As String = prm_text_to_decrypt\n\n Dim myRijndael As New RijndaelManaged\n myRijndael.Padding = PaddingMode.Zeros\n myRijndael.Mode = CipherMode.CBC\n myRijndael.KeySize = 256\n myRijndael.BlockSize = 256\n\n Dim key() As Byte\n Dim IV() As Byte\n\n key = System.Text.Encoding.ASCII.GetBytes(prm_key)\n IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)\n\n Dim decryptor As ICryptoTransform = myRijndael.CreateDecryptor(key, IV)\n\n Dim sEncrypted As Byte() = Convert.FromBase64String(sEncryptedString)\n\n Dim fromEncrypt() As Byte = New Byte(sEncrypted.Length) {}\n\n Dim msDecrypt As New MemoryStream(sEncrypted)\n Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)\n\n csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)\n\n Return (System.Text.Encoding.ASCII.GetString(fromEncrypt))\n\n End Function\n\n\n Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String)\n\n Dim sToEncrypt As String = prm_text_to_encrypt\n\n Dim myRijndael As New RijndaelManaged\n myRijndael.Padding = PaddingMode.Zeros\n myRijndael.Mode = CipherMode.CBC\n myRijndael.KeySize = 256\n myRijndael.BlockSize = 256\n\n Dim encrypted() As Byte\n Dim toEncrypt() As Byte\n Dim key() As Byte\n Dim IV() As Byte\n\n key = System.Text.Encoding.ASCII.GetBytes(prm_key)\n IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)\n\n Dim encryptor As ICryptoTransform = myRijndael.CreateEncryptor(key, IV)\n\n Dim msEncrypt As New MemoryStream()\n Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)\n\n toEncrypt = System.Text.Encoding.ASCII.GetBytes(sToEncrypt)\n\n csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)\n csEncrypt.FlushFinalBlock()\n\n encrypted = msEncrypt.ToArray()\n\n Return (Convert.ToBase64String(encrypted))\n\n End Function\n\nEnd Module\n</code></pre>\n\n<h3>BEGIN C# ALTERNATIVE (console app)</h3>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\nclass Program {\n static void Main(string[] args) {\n\n //Shared 256 bit Key and IV here\n const string sKy = \"lkirwf897+22#bbtrm8814z5qq=498j5\"; //32 chr shared ascii string (32 * 8 = 256 bit)\n const string sIV = \"741952hheeyy66#cs!9hjv887mxx7@8y\"; //32 chr shared ascii string (32 * 8 = 256 bit)\n\n var sTextVal = \"Here is my data to encrypt!!!\";\n\n var eText = EncryptRJ256(sKy, sIV, sTextVal);\n var dText = DecryptRJ256(sKy, sIV, eText);\n\n Console.WriteLine(\"key: \" + sKy);\n Console.WriteLine();\n Console.WriteLine(\" iv: \" + sIV);\n Console.WriteLine(\"txt: \" + sTextVal);\n Console.WriteLine(\"encrypted: \" + eText);\n Console.WriteLine(\"decrypted: \" + dText);\n Console.WriteLine(\"press any key to exit\");\n Console.ReadKey(true);\n }\n\n public static string DecryptRJ256(string prm_key, string prm_iv, string prm_text_to_decrypt) {\n\n var sEncryptedString = prm_text_to_decrypt;\n\n var myRijndael = new RijndaelManaged() {\n Padding = PaddingMode.Zeros,\n Mode = CipherMode.CBC,\n KeySize = 256,\n BlockSize = 256\n };\n\n var key = Encoding.ASCII.GetBytes(prm_key);\n var IV = Encoding.ASCII.GetBytes(prm_iv);\n\n var decryptor = myRijndael.CreateDecryptor(key, IV);\n\n var sEncrypted = Convert.FromBase64String(sEncryptedString);\n\n var fromEncrypt = new byte[sEncrypted.Length];\n\n var msDecrypt = new MemoryStream(sEncrypted);\n var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);\n\n csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);\n\n return (Encoding.ASCII.GetString(fromEncrypt));\n }\n\n public static string EncryptRJ256(string prm_key, string prm_iv, string prm_text_to_encrypt) {\n\n var sToEncrypt = prm_text_to_encrypt;\n\n var myRijndael = new RijndaelManaged() {\n Padding = PaddingMode.Zeros,\n Mode = CipherMode.CBC,\n KeySize = 256,\n BlockSize = 256\n };\n\n var key = Encoding.ASCII.GetBytes(prm_key);\n var IV = Encoding.ASCII.GetBytes(prm_iv);\n\n var encryptor = myRijndael.CreateEncryptor(key, IV);\n\n var msEncrypt = new MemoryStream();\n var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);\n\n var toEncrypt = Encoding.ASCII.GetBytes(sToEncrypt);\n\n csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);\n csEncrypt.FlushFinalBlock();\n\n var encrypted = msEncrypt.ToArray();\n\n return (Convert.ToBase64String(encrypted));\n }\n\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
I have a string encrypted in PHP that I would like to decrypt in C#. I used the tutorial below to do the encryption, but am having problems decrypting. Can anyone post an example on how to do this?
<http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html>
|
Hope this helps:
```
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Decrypt("47794945c0230c3d"));
}
static string Decrypt(string input)
{
TripleDES tripleDes = TripleDES.Create();
tripleDes.IV = Encoding.ASCII.GetBytes("password");
tripleDes.Key = Encoding.ASCII.GetBytes("passwordDR0wSS@P6660juht");
tripleDes.Mode = CipherMode.CBC;
tripleDes.Padding = PaddingMode.Zeros;
ICryptoTransform crypto = tripleDes.CreateDecryptor();
byte[] decodedInput = Decoder(input);
byte[] decryptedBytes = crypto.TransformFinalBlock(decodedInput, 0, decodedInput.Length);
return Encoding.ASCII.GetString(decryptedBytes);
}
static byte[] Decoder(string input)
{
byte[] bytes = new byte[input.Length/2];
int targetPosition = 0;
for( int sourcePosition=0; sourcePosition<input.Length; sourcePosition+=2 )
{
string hexCode = input.Substring(sourcePosition, 2);
bytes[targetPosition++] = Byte.Parse(hexCode, NumberStyles.AllowHexSpecifier);
}
return bytes;
}
}
```
|
224,467 |
<p>I'm using Microsoft WebTest and want to be able to do something similar to NUnit's <code>Assert.Fail()</code>. The best i have come up with is to <code>throw new webTestException()</code> but this shows in the test results as an <code>Error</code> rather than a <code>Failure</code>. </p>
<p>Other than reflecting on the <code>WebTest</code> to set a private member variable to indicate the failure, is there something I've missed?</p>
<p>EDIT: I have also used the <code>Assert.Fail()</code> method, but this still shows up as an error rather than a failure when used from within WebTest, and the <code>Outcome</code> property is read-only (has no public setter).</p>
<p>EDIT: well now I'm really stumped. I used reflection to set the <code>Outcome</code> property to Failed but the test <em>still</em> passes!</p>
<p>Here's the code that sets the Oucome to failed:</p>
<pre><code>public static class WebTestExtensions
{
public static void Fail(this WebTest test)
{
var method = test.GetType().GetMethod("set_Outcome", BindingFlags.NonPublic | BindingFlags.Instance);
method.Invoke(test, new object[] {Outcome.Fail});
}
}
</code></pre>
<p>and here's the code that I'm trying to fail:</p>
<pre><code> public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
this.Fail();
yield return new WebTestRequest("http://google.com");
}
</code></pre>
<p><code>Outcome</code> is getting set to <code>Oucome.Fail</code> but apparently the WebTest framework doesn't really use this to determine test pass/fail results.</p>
|
[
{
"answer_id": 224472,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>Set the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.webtesting.webtest.outcome.aspx\" rel=\"nofollow noreferrer\">Outcome property</a> to <em>Fail</em>:</p>\n\n<pre><code>Outcome = Outcome.Fail;\n</code></pre>\n\n<p>There's also an <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert.fail.aspx\" rel=\"nofollow noreferrer\"><code>Assert.Fail()</code></a> in the <em>Microsoft.VisualStudio.QualityTools.UnitTestFramework</em> assembly.</p>\n"
},
{
"answer_id": 1042414,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The Outcome property will set the public at vsts 2010 :-)</p>\n"
},
{
"answer_id": 2782006,
"author": "nathandelane",
"author_id": 334511,
"author_profile": "https://Stackoverflow.com/users/334511",
"pm_score": 1,
"selected": false,
"text": "<p>You make a test always fail by adding a validation rule that always fails. For example, you could write a fail validation rule like this:</p>\n\n<pre><code>public class FailValidationRule : ValidationRule\n{\n public override void Validate(object sender, ValidationEventArgs e)\n {\n e.IsValid = false;\n }\n}\n</code></pre>\n\n<p>Then attach the new validation rule you your webtest's ValidateResponse event, like so:</p>\n\n<pre><code>public class CodedWebTest : WebTest\n{\n public override IEnumerator<WebTestRequest> GetRequestEnumerator()\n {\n WebTestRequest request1 = new WebTestRequest(\"http://www.google.com\");\n FailValidationRule failValidation = new FailValidationRule();\n request1.ValidateResponse += new EventHandler<ValidationEventArgs>(failValidation.Validate);\n yield return request1;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2791431,
"author": "Nate Noonen",
"author_id": 285858,
"author_profile": "https://Stackoverflow.com/users/285858",
"pm_score": 0,
"selected": false,
"text": "<p>Set the value of Outcome in the PostWebTest event handler.</p>\n"
},
{
"answer_id": 10510519,
"author": "agentnega",
"author_id": 426028,
"author_profile": "https://Stackoverflow.com/users/426028",
"pm_score": 1,
"selected": false,
"text": "<p>A solution that would work in declarative tests (as well as coded) is:</p>\n\n<ul>\n<li>write a Validation Rule that fails when a certain Context Parameter (e.g. 'FAIL') is present in the Context</li>\n<li>when you want to trigger the failure, set the Context Parameter and call WebTest.Stop()</li>\n<li>add the Validation Rule as a WebTest-level rule (not request-level) so that it runs on all requests</li>\n</ul>\n\n<p>I think that's as concise as it can be done.</p>\n"
},
{
"answer_id": 17027680,
"author": "yvandd",
"author_id": 2471562,
"author_profile": "https://Stackoverflow.com/users/2471562",
"pm_score": 1,
"selected": false,
"text": "<p>First off, I'm working with VB.net, but I also tried to set the outcome to fail before finding out it does not work (which brought me here).</p>\n\n<p>I finally managed to do it by just throwing an exception :</p>\n\n<pre><code>Public Overrides Sub PostRequest(ByVal sender As Object, ByVal e As PostRequestEventArgs)\n\n If YourTest = True Then\n\n Throw New WebTestException(\"My test Failed\")\n\n End If\n\n MyBase.PostRequest(sender, e)\n\n End Sub\n</code></pre>\n\n<p>I know this topic is old but I hope it helps someone anyway :)</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18590/"
] |
I'm using Microsoft WebTest and want to be able to do something similar to NUnit's `Assert.Fail()`. The best i have come up with is to `throw new webTestException()` but this shows in the test results as an `Error` rather than a `Failure`.
Other than reflecting on the `WebTest` to set a private member variable to indicate the failure, is there something I've missed?
EDIT: I have also used the `Assert.Fail()` method, but this still shows up as an error rather than a failure when used from within WebTest, and the `Outcome` property is read-only (has no public setter).
EDIT: well now I'm really stumped. I used reflection to set the `Outcome` property to Failed but the test *still* passes!
Here's the code that sets the Oucome to failed:
```
public static class WebTestExtensions
{
public static void Fail(this WebTest test)
{
var method = test.GetType().GetMethod("set_Outcome", BindingFlags.NonPublic | BindingFlags.Instance);
method.Invoke(test, new object[] {Outcome.Fail});
}
}
```
and here's the code that I'm trying to fail:
```
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
this.Fail();
yield return new WebTestRequest("http://google.com");
}
```
`Outcome` is getting set to `Oucome.Fail` but apparently the WebTest framework doesn't really use this to determine test pass/fail results.
|
Set the [Outcome property](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.webtesting.webtest.outcome.aspx) to *Fail*:
```
Outcome = Outcome.Fail;
```
There's also an [`Assert.Fail()`](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert.fail.aspx) in the *Microsoft.VisualStudio.QualityTools.UnitTestFramework* assembly.
|
224,471 |
<p>Uhm I'm not sure if anyone has encountered this problem <br>
a brief description is on IE6 any <code><select></code> objects get displayed over any other item, even div's... meaning if you have a fancy javascript effect that displays a div that's supposed to be on top of everything (e.g: lightbox, multibox etc..) onclick of a certain element and that div overlaps a <code><select></code> your div get's to be displayed as if it's under the <code><select></code> [on this case a max and minimum z-index doesn't work ]</p>
<p>I've tried googling and found the iframe shim solution <br>
but I wanted some pretty clean alternatives
or better yet has anyone found a better solution?
since the method using iframes uses around 130mb of ram might slow down poor people's machines</p>
|
[
{
"answer_id": 224571,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 1,
"selected": false,
"text": "<p>Prior to IE7 the drop down list was a \"windowed\" control meaning that it was rendered as a control directly by Windows rather than the browser synthesizing it. As such, it wasn't possible for it to support z-indexing against other synthesized controls.</p>\n\n<p>In order to appear over a DDL, you must use another windowed control, like IFRAME. You can also use a little known IE-only feature called window.createPopup() which essentially makes a chromeless popup. It has limitations, like unstoppable click-out, but they are actually kinda helpful if you are building a hover menu system.</p>\n"
},
{
"answer_id": 224615,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 2,
"selected": false,
"text": "<p>There is a plugin for jquery called <a href=\"http://plugins.jquery.com/project/bgiframe\" rel=\"nofollow noreferrer\">bgiframe</a> that makes the iframe method quite easy to implement.</p>\n\n<p>Personally, as a web developer, I'm to the point where I no longer care about the user experience in IE6. I'll make it render as close to \"correct\" as possible, and make sure it's functional, but as far as speed goes, too bad. They can upgrade. IE7 (though still quite slow, compared to every other browser) has been out for 2 years (almost to the day!). IE8 is going to be out shortly. Firefox is available for every platform. Safari is also an option (and super fast). Opera is available for most/every platform. </p>\n\n<p>IE6 was released in over 7 years ago. IMHO, there is no reason to still be using it, other than lazy users and incompetent IT departments (or if you're a web developer). </p>\n"
},
{
"answer_id": 224793,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 4,
"selected": true,
"text": "<p>You don't have to hide every <code>select</code> using a loop. All you need is a CSS rule like:</p>\n\n<pre><code>* html .hideSelects select { visibility: hidden; }\n</code></pre>\n\n<p>And the following JavaScript:</p>\n\n<pre><code>//hide:\ndocument.body.className +=' hideSelects'\n\n//show:\ndocument.body.className = document.body.className.replace(' hideSelects', '');\n</code></pre>\n\n<p>(Or, you can use your favourite <code>addClass</code> / <code>removeClass</code> implementation).</p>\n"
},
{
"answer_id": 309751,
"author": "sprugman",
"author_id": 24197,
"author_profile": "https://Stackoverflow.com/users/24197",
"pm_score": 0,
"selected": false,
"text": "<p>There's also the activex method, which I'm starting to explore. It requires creating conditional code to use an activex control instead of a select box for ie6. There's a <a href=\"http://www.hedgerwow.com/360/bugs/activex-listbox/demo.php\" rel=\"nofollow noreferrer\">demo script</a> showing the technique, which is <a href=\"http://www.devguru.com/features/tutorials/ComboControl/combocontrol.html\" rel=\"nofollow noreferrer\">discussed in more detail here</a>.</p>\n\n<p>Update: it appears that MS Office is required for the active-x control to be on the user's machine. In theory, it might be possible to include that somewhere, somehow, but that's getting a lot messier.</p>\n"
},
{
"answer_id": 310229,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 2,
"selected": false,
"text": "<p>in case anyone is interested, here's some IE shimming code.</p>\n\n<pre><code>* html .shimmed {\n _azimuth: expression(\n this.shimmed = this.shimmed || 'shimmed:'+this.insertAdjacentHTML('beforeBegin','<iframe style=\"filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);position:absolute;top:0px;left:0px;width:100%;height:100%\" frameBorder=0 scrolling=no src=\"javascript:false;document.write('+\"''\"+');\"></iframe>'),\n 'inherit');\n}\n</code></pre>\n\n<p>ref: <a href=\"http://gist.github.com/7372\" rel=\"nofollow noreferrer\">this gist</a> by <a href=\"http://subtlegradient.com/articles/category/css\" rel=\"nofollow noreferrer\">subtleGradient</a> and this <a href=\"http://www.zachleat.com/web/2007/04/24/adventures-in-i-frame-shims-or-how-i-learned-to-love-the-bomb/\" rel=\"nofollow noreferrer\">post by Zach Leatherman</a></p>\n"
},
{
"answer_id": 1751530,
"author": "Chris F.",
"author_id": 199940,
"author_profile": "https://Stackoverflow.com/users/199940",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest and most elegant solution to that annoying IE bug is found at: <a href=\"http://docs.jquery.com/Plugins/bgiframe\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Plugins/bgiframe</a> using jQuery.</p>\n\n<p>I reached that conclusion after trying for 2 days to make it work with WebSphere Portal / Portal Applications where everything is dynamic, including the fly-over menu.</p>\n"
},
{
"answer_id": 5236046,
"author": "Andrew Chaa",
"author_id": 437961,
"author_profile": "https://Stackoverflow.com/users/437961",
"pm_score": 0,
"selected": false,
"text": "<p>I know many people suggested their own tips, but in my case, I just simply hide select using jquery like the below.</p>\n\n<pre><code>$(':date').dateinput({\n format: 'dd/mm/yyyy',\n onBeforeShow: function(event) {\n $('select').hide();\n },\n onHide: function(event) {\n $('select').show();\n }\n});\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24744/"
] |
Uhm I'm not sure if anyone has encountered this problem
a brief description is on IE6 any `<select>` objects get displayed over any other item, even div's... meaning if you have a fancy javascript effect that displays a div that's supposed to be on top of everything (e.g: lightbox, multibox etc..) onclick of a certain element and that div overlaps a `<select>` your div get's to be displayed as if it's under the `<select>` [on this case a max and minimum z-index doesn't work ]
I've tried googling and found the iframe shim solution
but I wanted some pretty clean alternatives
or better yet has anyone found a better solution?
since the method using iframes uses around 130mb of ram might slow down poor people's machines
|
You don't have to hide every `select` using a loop. All you need is a CSS rule like:
```
* html .hideSelects select { visibility: hidden; }
```
And the following JavaScript:
```
//hide:
document.body.className +=' hideSelects'
//show:
document.body.className = document.body.className.replace(' hideSelects', '');
```
(Or, you can use your favourite `addClass` / `removeClass` implementation).
|
224,473 |
<p>I am new to creating Java web applications and came across this problem when trying to interact with my database (called ccdb) through my application:</p>
<p><code>java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ccdb/</code></p>
<p>My application runs on JBoss and uses Hibernate to interact with the MySQL database. I have the MySQL Driver in lib\mysql-connector-java-5.1.6-bin.jar of my project and I have the .jar configured in Eclipse as a "Java EE Module Dependency" so that it gets copied over to web-inf\lib\ when I deploy it to JBoss through Eclipse. I double checked and the driver is definitely in the .war file with the project, so it should be findable, right? </p>
<p>My hibernate.cfg.xml contains this line which should point hibernate to the driver.</p>
<p><code><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property></code></p>
<p>Does anyone know what I need to do to get this to work? Do I have to configure the MySQL database as a JBoss datasource for it to work?</p>
<p>Thanks in advance.</p>
<p>Edit: kauppi's solution works, but I would prefer to have it in lib\ with the other jars, and I'm really curious as to why it won't work that way. Any ideas...?</p>
|
[
{
"answer_id": 224571,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 1,
"selected": false,
"text": "<p>Prior to IE7 the drop down list was a \"windowed\" control meaning that it was rendered as a control directly by Windows rather than the browser synthesizing it. As such, it wasn't possible for it to support z-indexing against other synthesized controls.</p>\n\n<p>In order to appear over a DDL, you must use another windowed control, like IFRAME. You can also use a little known IE-only feature called window.createPopup() which essentially makes a chromeless popup. It has limitations, like unstoppable click-out, but they are actually kinda helpful if you are building a hover menu system.</p>\n"
},
{
"answer_id": 224615,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 2,
"selected": false,
"text": "<p>There is a plugin for jquery called <a href=\"http://plugins.jquery.com/project/bgiframe\" rel=\"nofollow noreferrer\">bgiframe</a> that makes the iframe method quite easy to implement.</p>\n\n<p>Personally, as a web developer, I'm to the point where I no longer care about the user experience in IE6. I'll make it render as close to \"correct\" as possible, and make sure it's functional, but as far as speed goes, too bad. They can upgrade. IE7 (though still quite slow, compared to every other browser) has been out for 2 years (almost to the day!). IE8 is going to be out shortly. Firefox is available for every platform. Safari is also an option (and super fast). Opera is available for most/every platform. </p>\n\n<p>IE6 was released in over 7 years ago. IMHO, there is no reason to still be using it, other than lazy users and incompetent IT departments (or if you're a web developer). </p>\n"
},
{
"answer_id": 224793,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 4,
"selected": true,
"text": "<p>You don't have to hide every <code>select</code> using a loop. All you need is a CSS rule like:</p>\n\n<pre><code>* html .hideSelects select { visibility: hidden; }\n</code></pre>\n\n<p>And the following JavaScript:</p>\n\n<pre><code>//hide:\ndocument.body.className +=' hideSelects'\n\n//show:\ndocument.body.className = document.body.className.replace(' hideSelects', '');\n</code></pre>\n\n<p>(Or, you can use your favourite <code>addClass</code> / <code>removeClass</code> implementation).</p>\n"
},
{
"answer_id": 309751,
"author": "sprugman",
"author_id": 24197,
"author_profile": "https://Stackoverflow.com/users/24197",
"pm_score": 0,
"selected": false,
"text": "<p>There's also the activex method, which I'm starting to explore. It requires creating conditional code to use an activex control instead of a select box for ie6. There's a <a href=\"http://www.hedgerwow.com/360/bugs/activex-listbox/demo.php\" rel=\"nofollow noreferrer\">demo script</a> showing the technique, which is <a href=\"http://www.devguru.com/features/tutorials/ComboControl/combocontrol.html\" rel=\"nofollow noreferrer\">discussed in more detail here</a>.</p>\n\n<p>Update: it appears that MS Office is required for the active-x control to be on the user's machine. In theory, it might be possible to include that somewhere, somehow, but that's getting a lot messier.</p>\n"
},
{
"answer_id": 310229,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 2,
"selected": false,
"text": "<p>in case anyone is interested, here's some IE shimming code.</p>\n\n<pre><code>* html .shimmed {\n _azimuth: expression(\n this.shimmed = this.shimmed || 'shimmed:'+this.insertAdjacentHTML('beforeBegin','<iframe style=\"filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);position:absolute;top:0px;left:0px;width:100%;height:100%\" frameBorder=0 scrolling=no src=\"javascript:false;document.write('+\"''\"+');\"></iframe>'),\n 'inherit');\n}\n</code></pre>\n\n<p>ref: <a href=\"http://gist.github.com/7372\" rel=\"nofollow noreferrer\">this gist</a> by <a href=\"http://subtlegradient.com/articles/category/css\" rel=\"nofollow noreferrer\">subtleGradient</a> and this <a href=\"http://www.zachleat.com/web/2007/04/24/adventures-in-i-frame-shims-or-how-i-learned-to-love-the-bomb/\" rel=\"nofollow noreferrer\">post by Zach Leatherman</a></p>\n"
},
{
"answer_id": 1751530,
"author": "Chris F.",
"author_id": 199940,
"author_profile": "https://Stackoverflow.com/users/199940",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest and most elegant solution to that annoying IE bug is found at: <a href=\"http://docs.jquery.com/Plugins/bgiframe\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Plugins/bgiframe</a> using jQuery.</p>\n\n<p>I reached that conclusion after trying for 2 days to make it work with WebSphere Portal / Portal Applications where everything is dynamic, including the fly-over menu.</p>\n"
},
{
"answer_id": 5236046,
"author": "Andrew Chaa",
"author_id": 437961,
"author_profile": "https://Stackoverflow.com/users/437961",
"pm_score": 0,
"selected": false,
"text": "<p>I know many people suggested their own tips, but in my case, I just simply hide select using jquery like the below.</p>\n\n<pre><code>$(':date').dateinput({\n format: 'dd/mm/yyyy',\n onBeforeShow: function(event) {\n $('select').hide();\n },\n onHide: function(event) {\n $('select').show();\n }\n});\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20177/"
] |
I am new to creating Java web applications and came across this problem when trying to interact with my database (called ccdb) through my application:
`java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ccdb/`
My application runs on JBoss and uses Hibernate to interact with the MySQL database. I have the MySQL Driver in lib\mysql-connector-java-5.1.6-bin.jar of my project and I have the .jar configured in Eclipse as a "Java EE Module Dependency" so that it gets copied over to web-inf\lib\ when I deploy it to JBoss through Eclipse. I double checked and the driver is definitely in the .war file with the project, so it should be findable, right?
My hibernate.cfg.xml contains this line which should point hibernate to the driver.
`<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>`
Does anyone know what I need to do to get this to work? Do I have to configure the MySQL database as a JBoss datasource for it to work?
Thanks in advance.
Edit: kauppi's solution works, but I would prefer to have it in lib\ with the other jars, and I'm really curious as to why it won't work that way. Any ideas...?
|
You don't have to hide every `select` using a loop. All you need is a CSS rule like:
```
* html .hideSelects select { visibility: hidden; }
```
And the following JavaScript:
```
//hide:
document.body.className +=' hideSelects'
//show:
document.body.className = document.body.className.replace(' hideSelects', '');
```
(Or, you can use your favourite `addClass` / `removeClass` implementation).
|
224,475 |
<p>I wonder if is possible to use FTS with LINQ using .NET Framework 3.5. I'm searching around the documentation that I didn't find anything useful yet.</p>
<p>Does anyone have any experience on this?</p>
|
[
{
"answer_id": 224483,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 3,
"selected": false,
"text": "<p>I don't believe so. You can use 'contains' on a field, but it only generates a <code>LIKE</code> query. If you want to use full text I would recommend using a stored proc to do the query then pass it back to LINQ</p>\n"
},
{
"answer_id": 227648,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>No, full text searching is something very specific to sql server (in which text is indexed by words, and queries hit this index versus traversing a character array). Linq does not support this, any .Contains() calls will hit the un-managed string functions but will not benefit from indexing. </p>\n"
},
{
"answer_id": 227656,
"author": "Gabriel Isenberg",
"author_id": 1473493,
"author_profile": "https://Stackoverflow.com/users/1473493",
"pm_score": 4,
"selected": false,
"text": "<p>No. Full text search is not supported by LINQ To SQL.</p>\n\n<p>That said, you <em>can</em> use a stored procedure that utilizes FTS and have the LINQ To SQL query pull data from that.</p>\n"
},
{
"answer_id": 385808,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 7,
"selected": true,
"text": "<p>Yes. However you have to create SQL server function first and call that as by default LINQ will use a like.</p>\n\n<p>This <a href=\"http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx\" rel=\"noreferrer\">blog post</a> which will explain the detail but this is the extract:</p>\n\n<blockquote>\n <p>To get it working you need to create a table valued function that does\n nothing more than a CONTAINSTABLE query based on the keywords you pass\n in,</p>\n\n<pre><code>create function udf_sessionSearch\n (@keywords nvarchar(4000))\nreturns table\nas\n return (select [SessionId],[rank]\n from containstable(Session,(description,title),@keywords))\n</code></pre>\n \n <p>You then add this function to your LINQ 2 SQL model and he presto you\n can now write queries like.</p>\n\n<pre><code> var sessList = from s in DB.Sessions\n join fts in DB.udf_sessionSearch(SearchText) \n on s.sessionId equals fts.SessionId\n select s;\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 4222797,
"author": "Victor Gelmutdinov",
"author_id": 129812,
"author_profile": "https://Stackoverflow.com/users/129812",
"pm_score": 3,
"selected": false,
"text": "<p>if you do not want to create joins and want to simplify your C# code, you can create SQL function and use it in \"from\" clause:</p>\n\n<pre><code>CREATE FUNCTION ad_Search\n(\n @keyword nvarchar(4000)\n)\nRETURNS TABLE\nAS\nRETURN\n(\n select * from Ad where \n (CONTAINS(Description, @keyword) OR CONTAINS(Title, @keyword))\n)\n</code></pre>\n\n<p>After updating your DBML, use it in linq:</p>\n\n<pre><code>string searchKeyword = \"word and subword\";\nvar result = from ad in context.ad_Search(searchKeyword)\n select ad;\n</code></pre>\n\n<p>This will produce simple SQL like this:</p>\n\n<pre><code>SELECT [t0].ID, [t0].Title, [t0].Description\nFROM [dbo].[ad_Search](@p0) AS [t0]\n</code></pre>\n\n<p>This is works in search by several columns as you can see from the ad_Search function implementation.</p>\n"
},
{
"answer_id": 17969124,
"author": "AqD",
"author_id": 2183221,
"author_profile": "https://Stackoverflow.com/users/2183221",
"pm_score": 0,
"selected": false,
"text": "<p>I made a working prototype, for SQL Server's <em>CONTAINS</em> only and no wildcard columns. What it achieves is for you to use <em>CONTAINS</em> like ordinary LINQ functions:</p>\n\n<pre><code>var query = context.CreateObjectSet<MyFile>()\n .Where(file => file.FileName.Contains(\"pdf\")\n && FullTextFunctions.ContainsBinary(file.FileTable_Ref.file_stream, \"Hello\"));\n</code></pre>\n\n<h3>You will need:</h3>\n\n<p>1.Function definitions in code and EDMX to support the <em>CONTAINS</em> keyword.</p>\n\n<p>2.Rewrite EF SQL by EFProviderWrapperToolkit/EFTracingProvider, because CONTAINS is not a function and by default the generated SQL treats its result as <em>bit</em>.</p>\n\n<h3>BUT:</h3>\n\n<p>1.Contains is not really a function and you cannot select boolean results from it. It can only be used in conditions.</p>\n\n<p>2.The SQL rewriting code below is likely to break if queries contain non-parameterized strings with special characters.</p>\n\n<h2>Source of my prototype</h2>\n\n<h3>Function Definitions: (EDMX)</h3>\n\n<p>Under edmx:StorageModels/Schema</p>\n\n<pre><code><Function Name=\"conTAINs\" BuiltIn=\"true\" IsComposable=\"true\" ParameterTypeSemantics=\"AllowImplicitConversion\" ReturnType=\"bit\" Schema=\"dbo\">\n <Parameter Name=\"dataColumn\" Type=\"varbinary\" Mode=\"In\" />\n <Parameter Name=\"keywords\" Type=\"nvarchar\" Mode=\"In\" />\n</Function>\n<Function Name=\"conTAInS\" BuiltIn=\"true\" IsComposable=\"true\" ParameterTypeSemantics=\"AllowImplicitConversion\" ReturnType=\"bit\" Schema=\"dbo\">\n <Parameter Name=\"textColumn\" Type=\"nvarchar\" Mode=\"In\" />\n <Parameter Name=\"keywords\" Type=\"nvarchar\" Mode=\"In\" />\n</Function>\n</code></pre>\n\n<p>PS: the weird cases of chars are used to enable the same function with different parameter types (varbinary and nvarchar)</p>\n\n<h3>Function Definitions: (code)</h3>\n\n<pre><code>using System.Data.Objects.DataClasses;\n\npublic static class FullTextFunctions\n{\n [EdmFunction(\"MyModel.Store\", \"conTAINs\")]\n public static bool ContainsBinary(byte[] dataColumn, string keywords)\n {\n throw new System.NotSupportedException(\"Direct calls are not supported.\");\n }\n\n [EdmFunction(\"MyModel.Store\", \"conTAInS\")]\n public static bool ContainsString(string textColumn, string keywords)\n {\n throw new System.NotSupportedException(\"Direct calls are not supported.\");\n }\n}\n</code></pre>\n\n<p>PS: <em>\"MyModel.Store\"</em> is as same as the value in edmx:StorageModels/Schema/@Namespace</p>\n\n<h3>Rewrite EF SQL: (by EFProviderWrapperToolkit)</h3>\n\n<pre><code>using EFProviderWrapperToolkit;\nusing EFTracingProvider;\n\npublic class TracedMyDataContext : MyDataContext\n{\n public TracedMyDataContext()\n : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(\n \"name=MyDataContext\", \"EFTracingProvider\"))\n {\n var tracingConnection = (EFTracingConnection) ((EntityConnection) Connection).StoreConnection;\n tracingConnection.CommandExecuting += TracedMyDataContext_CommandExecuting;\n }\n\n protected static void TracedMyDataContext_CommandExecuting(object sender, CommandExecutionEventArgs e)\n {\n e.Command.CommandText = FixFullTextContainsBinary(e.Command.CommandText);\n e.Command.CommandText = FixFullTextContainsString(e.Command.CommandText);\n }\n\n\n private static string FixFullTextContainsBinary(string commandText, int startIndex = 0)\n {\n var patternBeg = \"(conTAINs(\";\n var patternEnd = \")) = 1\";\n var exprBeg = commandText.IndexOf(patternBeg, startIndex, StringComparison.Ordinal);\n if (exprBeg == -1)\n return commandText;\n var exprEnd = FindEnd(commandText, exprBeg + patternBeg.Length, ')');\n if (commandText.Substring(exprEnd).StartsWith(patternEnd))\n {\n var newCommandText = commandText.Substring(0, exprEnd + 2) + commandText.Substring(exprEnd + patternEnd.Length);\n return FixFullTextContainsBinary(newCommandText, exprEnd + 2);\n }\n return commandText;\n }\n\n private static string FixFullTextContainsString(string commandText, int startIndex = 0)\n {\n var patternBeg = \"(conTAInS(\";\n var patternEnd = \")) = 1\";\n var exprBeg = commandText.IndexOf(patternBeg, startIndex, StringComparison.Ordinal);\n if (exprBeg == -1)\n return commandText;\n var exprEnd = FindEnd(commandText, exprBeg + patternBeg.Length, ')');\n if (exprEnd != -1 && commandText.Substring(exprEnd).StartsWith(patternEnd))\n {\n var newCommandText = commandText.Substring(0, exprEnd + 2) + commandText.Substring(exprEnd + patternEnd.Length);\n return FixFullTextContainsString(newCommandText, exprEnd + 2);\n }\n return commandText;\n }\n\n private static int FindEnd(string commandText, int startIndex, char endChar)\n {\n // TODO: handle escape chars between parens/squares/quotes\n var lvlParan = 0;\n var lvlSquare = 0;\n var lvlQuoteS = 0;\n var lvlQuoteD = 0;\n for (var i = startIndex; i < commandText.Length; i++)\n {\n var c = commandText[i];\n if (c == endChar && lvlParan == 0 && lvlSquare == 0\n && (lvlQuoteS % 2) == 0 && (lvlQuoteD % 2) == 0)\n return i;\n switch (c)\n {\n case '(':\n ++lvlParan;\n break;\n case ')':\n --lvlParan;\n break;\n case '[':\n ++lvlSquare;\n break;\n case ']':\n --lvlSquare;\n break;\n case '\\'':\n ++lvlQuoteS;\n break;\n case '\"':\n ++lvlQuoteD;\n break;\n }\n }\n return -1;\n }\n}\n</code></pre>\n\n<h3>Enable EFProviderWrapperToolkit:</h3>\n\n<p>If you get it by nuget, it should add these lines into your app.config or web.config:</p>\n\n<pre><code><system.data>\n <DbProviderFactories>\n <add name=\"EFTracingProvider\" invariant=\"EFTracingProvider\" description=\"Tracing Provider Wrapper\" type=\"EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b\" />\n <add name=\"EFProviderWrapper\" invariant=\"EFProviderWrapper\" description=\"Generic Provider Wrapper\" type=\"EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b\" />\n </DbProviderFactories>\n</system.data>\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
] |
I wonder if is possible to use FTS with LINQ using .NET Framework 3.5. I'm searching around the documentation that I didn't find anything useful yet.
Does anyone have any experience on this?
|
Yes. However you have to create SQL server function first and call that as by default LINQ will use a like.
This [blog post](http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx) which will explain the detail but this is the extract:
>
> To get it working you need to create a table valued function that does
> nothing more than a CONTAINSTABLE query based on the keywords you pass
> in,
>
>
>
> ```
> create function udf_sessionSearch
> (@keywords nvarchar(4000))
> returns table
> as
> return (select [SessionId],[rank]
> from containstable(Session,(description,title),@keywords))
>
> ```
>
> You then add this function to your LINQ 2 SQL model and he presto you
> can now write queries like.
>
>
>
> ```
> var sessList = from s in DB.Sessions
> join fts in DB.udf_sessionSearch(SearchText)
> on s.sessionId equals fts.SessionId
> select s;
>
> ```
>
>
|
224,481 |
<p>I am creating a custom UserType in Hibernate for a project. It has been relatively straightforward until I came to the isMutable method. I am trying to figure out what this method means, contract-wise. </p>
<p>Does it mean the class I am creating the UserType for is immutable or does it mean the object that holds a reference to an instance of this class will never point to a different instance?</p>
<p>I found some examples in the <a href="http://www.hibernate.org/37.html" rel="noreferrer">Hibernate Community Wiki</a> where they returned true, because the object itself was mutable - <a href="http://www.hibernate.org/73.html" rel="noreferrer">http://www.hibernate.org/73.html</a>. </p>
<p>Other examples in the community wiki returned false without addressing why, even though they were also mutable.</p>
<p>I have checked the JavaDoc, but it's not very clear either.</p>
<p>From the JavaDoc for <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/usertype/UserType.html" rel="noreferrer">UserType</a>:</p>
<pre><code>public boolean isMutable()
Are objects of this type mutable?
Returns:
boolean
</code></pre>
<p>From JavaDoc for <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/type/Type.html" rel="noreferrer">Type</a>:</p>
<pre><code>public boolean isMutable()
Are objects of this type mutable. (With respect to the referencing
object ... entities and collections are considered immutable because
they manage their own internal state.)
Returns:
boolean
</code></pre>
|
[
{
"answer_id": 224880,
"author": "jmcd",
"author_id": 2285,
"author_profile": "https://Stackoverflow.com/users/2285",
"pm_score": 2,
"selected": false,
"text": "<p>The typical example here is the String class - it is Immutable, i.e. once the string is created you cannot change its contents or state, and if you want to then you're going to have to process it into a new copy. </p>\n\n<p>isMutable returning true means you are saying this object can have its state changed by outside objects, returning false means you will have to copy this object to a new instance makign the changes to state along the way. Or as you said: \"does it mean the object that holds a reference to an instance of this class will never point to a different instance\".</p>\n"
},
{
"answer_id": 1783063,
"author": "Andrew Phillips",
"author_id": 217013,
"author_profile": "https://Stackoverflow.com/users/217013",
"pm_score": 5,
"selected": true,
"text": "<p>Hibernate will treat types marked as \"mutable\" as though they could change (i.e. require an UPDATE) <em>without</em> pointing to a new reference. If you assign a new reference to a Hibernate-loaded property Hibernate will recognize this even if the type is immutable - this happens all the time with, for instance, String fields.\nBut if, say, you have a StringBuilder field and you mark it as <em>immutable</em> Hibernate will <strong>not</strong> notice if you modify the StringBuilder.</p>\n\n<p>See <a href=\"http://blog.xebia.com/2009/11/09/understanding-and-writing-hibernate-user-types/\" rel=\"noreferrer\">this blog post</a> for more details and a sample project.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24290/"
] |
I am creating a custom UserType in Hibernate for a project. It has been relatively straightforward until I came to the isMutable method. I am trying to figure out what this method means, contract-wise.
Does it mean the class I am creating the UserType for is immutable or does it mean the object that holds a reference to an instance of this class will never point to a different instance?
I found some examples in the [Hibernate Community Wiki](http://www.hibernate.org/37.html) where they returned true, because the object itself was mutable - <http://www.hibernate.org/73.html>.
Other examples in the community wiki returned false without addressing why, even though they were also mutable.
I have checked the JavaDoc, but it's not very clear either.
From the JavaDoc for [UserType](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/usertype/UserType.html):
```
public boolean isMutable()
Are objects of this type mutable?
Returns:
boolean
```
From JavaDoc for [Type](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/type/Type.html):
```
public boolean isMutable()
Are objects of this type mutable. (With respect to the referencing
object ... entities and collections are considered immutable because
they manage their own internal state.)
Returns:
boolean
```
|
Hibernate will treat types marked as "mutable" as though they could change (i.e. require an UPDATE) *without* pointing to a new reference. If you assign a new reference to a Hibernate-loaded property Hibernate will recognize this even if the type is immutable - this happens all the time with, for instance, String fields.
But if, say, you have a StringBuilder field and you mark it as *immutable* Hibernate will **not** notice if you modify the StringBuilder.
See [this blog post](http://blog.xebia.com/2009/11/09/understanding-and-writing-hibernate-user-types/) for more details and a sample project.
|
224,484 |
<p>On an ASP.NET MVC (Beta) site that I am developing sometimes calls to ActionLink will return to me URLs containing querying strings. I have isolated the circumstances that produce this behavior, but I still do not understand why, instead of producing a clean URL, it decides to using a query string parameter. I know that functionally they are the same, but for consistency (and appearance) of the URLs this is not what I want. </p>
<p>Here are my routes:</p>
<pre><code>routes.MapRoute(
"Photo Gallery Shortcut",
"group/{groupname}",
new { controller = "Photos", action = "All", Id = "" });
routes.MapRoute(
"Tagged Photos", //since the Tagged action takes an extra parameter, put it first
"group/{groupname}/Photos/Tagged/{tagname}/{sortby}",
new { controller = "Photos", action = "Tagged", Id = "", SortBy = "" });
routes.MapRoute(
"Photo Gallery", //since the Gallery's defualt action is "All" not "Index" its listed seperatly
"group/{groupname}/Photos/{action}/{sortby}",
new { controller = "Photos", action = "All", Id = "", SortBy = "" });
routes.MapRoute(
"Group", //<-- "Group" Category defined above
"group/{groupname}/{controller}/{action}/{id}",
new {controller = "Photos", action = "Index", Id = ""});
</code></pre>
<p>Now the problem only occurs when I am looking at the view described by the route named "Tagged Photos" and execute ActionLink via:</p>
<pre><code>Html.ActionLink<PhotosController>(p => p.All((string)ViewData["group"], ""), "Home")
</code></pre>
<p>Which produces the URL:</p>
<pre><code>http://domain/group/GROUPNAME?sortBy=
</code></pre>
<p>From any other view the URL produced is:</p>
<pre><code>http://domain/group/GROUPNAME
</code></pre>
<p>I have pulled down Phil's <a href="http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx" rel="nofollow noreferrer">ASP.NET Routing Debugger</a>, and everything appears in order. This one has me stumped. Any ideas?</p>
|
[
{
"answer_id": 224519,
"author": "Schotime",
"author_id": 29376,
"author_profile": "https://Stackoverflow.com/users/29376",
"pm_score": 0,
"selected": false,
"text": "<p>I think it is picking up your first Route. It too has the action All. And because the sortby is not specified it is exposing it as a querystring parameter</p>\n\n<p>This will still work with the action method 'All' on the PhotosController, because it just fills the sortby parameter with the query string value.</p>\n\n<p>In the Route Debugger is it executing the 3rd route or the 1st?</p>\n"
},
{
"answer_id": 224711,
"author": "CVertex",
"author_id": 209,
"author_profile": "https://Stackoverflow.com/users/209",
"pm_score": 3,
"selected": true,
"text": "<p>Not sure why different views are producing different URLs.</p>\n\n<p>But you can get rid of that sortBy param by assigning a default value to the first route.</p>\n\n<p>new { sortBy = \"\" }</p>\n\n<p>During generation, if sortBy matches the default, the route engine will skip that parameter (if it's in the query string).</p>\n"
},
{
"answer_id": 225879,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>You're going to have to use named routes here, not action routes, because of the way routing works in ASP.NET, because it does \"first match\", not \"best match\".</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27860/"
] |
On an ASP.NET MVC (Beta) site that I am developing sometimes calls to ActionLink will return to me URLs containing querying strings. I have isolated the circumstances that produce this behavior, but I still do not understand why, instead of producing a clean URL, it decides to using a query string parameter. I know that functionally they are the same, but for consistency (and appearance) of the URLs this is not what I want.
Here are my routes:
```
routes.MapRoute(
"Photo Gallery Shortcut",
"group/{groupname}",
new { controller = "Photos", action = "All", Id = "" });
routes.MapRoute(
"Tagged Photos", //since the Tagged action takes an extra parameter, put it first
"group/{groupname}/Photos/Tagged/{tagname}/{sortby}",
new { controller = "Photos", action = "Tagged", Id = "", SortBy = "" });
routes.MapRoute(
"Photo Gallery", //since the Gallery's defualt action is "All" not "Index" its listed seperatly
"group/{groupname}/Photos/{action}/{sortby}",
new { controller = "Photos", action = "All", Id = "", SortBy = "" });
routes.MapRoute(
"Group", //<-- "Group" Category defined above
"group/{groupname}/{controller}/{action}/{id}",
new {controller = "Photos", action = "Index", Id = ""});
```
Now the problem only occurs when I am looking at the view described by the route named "Tagged Photos" and execute ActionLink via:
```
Html.ActionLink<PhotosController>(p => p.All((string)ViewData["group"], ""), "Home")
```
Which produces the URL:
```
http://domain/group/GROUPNAME?sortBy=
```
From any other view the URL produced is:
```
http://domain/group/GROUPNAME
```
I have pulled down Phil's [ASP.NET Routing Debugger](http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx), and everything appears in order. This one has me stumped. Any ideas?
|
Not sure why different views are producing different URLs.
But you can get rid of that sortBy param by assigning a default value to the first route.
new { sortBy = "" }
During generation, if sortBy matches the default, the route engine will skip that parameter (if it's in the query string).
|
224,485 |
<p>I am using a Cursor in my stored procedure. It works on a database that has a huge number of data. for every item in the cursor i do a update operation. This is taking a huge amount of time to complete. Almost 25min. :( .. Is there anyway i can reduce the time consumed for this?</p>
|
[
{
"answer_id": 224490,
"author": "knightpfhor",
"author_id": 17089,
"author_profile": "https://Stackoverflow.com/users/17089",
"pm_score": 3,
"selected": false,
"text": "<p>The quick answer is not to use a cursor. The most efficient way to update lots of records is to use an update statement. There are not many cases where you have to use a cursor rather than an update statement, you just have to get clever about how you write the update statement.</p>\n\n<p>If you posted a snapshot of your SQL you might get some help to achieve what you're after.</p>\n"
},
{
"answer_id": 224494,
"author": "Lara Dougan",
"author_id": 4081,
"author_profile": "https://Stackoverflow.com/users/4081",
"pm_score": 1,
"selected": false,
"text": "<p>I would avoid using a cursor, and work with views or materialized views if possible. Cursors is something that Microsoft doesn't optimize much in SQL Server, because most of the time, you should be using a more general SQL statement (SELECT, INSERT, UPDATE, DELETE) than with a cursor.</p>\n\n<p>If you cannot perform the same end result even with using views or subqueries, you may want to use a temp table or look at improving the data model.</p>\n\n<p>You don't provide much specific information, so all that I can do is give some general tips.</p>\n"
},
{
"answer_id": 224533,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 0,
"selected": false,
"text": "<p>Are you updating the same data that the cursor is operating over?</p>\n\n<p>What type of cursor? forward only? static? keyset? dynamic?</p>\n"
},
{
"answer_id": 224738,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<p>When you need to do a more complex operation to each row than what a simple update would allow you, you can try:</p>\n\n<ul>\n<li>Write a User Defined Function and use that in the update (probably still slow)</li>\n<li>Put data in a temporary table and use that in an UPDATE ... FROM:</li>\n</ul>\n\n<p>Did you know about the UPDATE ... FROM syntax? It is quite powerful when things get more complex:</p>\n\n<pre><code>UPDATE\n MyTable\nSET\n Col1 = CASE WHEN b.Foo = \"Bar\" THEN LOWER(b.Baz) ELSE \"\" END,\n Col2 = ISNULL(c.Bling, 0) * 100 / Col3\nFROM\n MyTable \n INNER JOIN MySecondTable AS b ON b.Id = MyTable.SecondId\n LEFT JOIN ##MyTempTable AS c ON c.Id = b.ThirdId\nWHERE\n MyTabe.Col3 > 0\n AND b.Foo NOT IS NULL\n AND MyTable.TheDate > GETDATE() - 10\n</code></pre>\n\n<p>The example is completely made-up and may not make much sense, but you get the picture of how to do a more complex update without having to use a cursor. Of course, a temp table would not necessarily be required for it to work. :-)</p>\n"
},
{
"answer_id": 224763,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>The UPDATE...FROM syntax mentioned above is the prefered method. You can also do a sub query such as the following.</p>\n\n<pre><code>UPDATE t1\nSET t1.col1 = (SELECT top 1 col FROM other_table WHERE t1_id = t1.ID AND ...)\nWHERE ...\n</code></pre>\n\n<p>Sometimes this is the only way to do it, as each column update may depend on a differant criteria (or a diferant table), and there may be a \"best case\" that you want to preserve bysing the order by clause.</p>\n"
},
{
"answer_id": 226557,
"author": "Tony",
"author_id": 4943,
"author_profile": "https://Stackoverflow.com/users/4943",
"pm_score": 0,
"selected": false,
"text": "<p>Can you post more information about the type of update you are doing?</p>\n\n<p>Cursors can be very useful in the right context (I use plenty of them), but if you have a choice between a cursor and a set-based operation, set-based is <em>almost</em> always the way to go.</p>\n\n<p>But if you don't have a choice, you don't have a choice. Can't tell without more detail.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
] |
I am using a Cursor in my stored procedure. It works on a database that has a huge number of data. for every item in the cursor i do a update operation. This is taking a huge amount of time to complete. Almost 25min. :( .. Is there anyway i can reduce the time consumed for this?
|
When you need to do a more complex operation to each row than what a simple update would allow you, you can try:
* Write a User Defined Function and use that in the update (probably still slow)
* Put data in a temporary table and use that in an UPDATE ... FROM:
Did you know about the UPDATE ... FROM syntax? It is quite powerful when things get more complex:
```
UPDATE
MyTable
SET
Col1 = CASE WHEN b.Foo = "Bar" THEN LOWER(b.Baz) ELSE "" END,
Col2 = ISNULL(c.Bling, 0) * 100 / Col3
FROM
MyTable
INNER JOIN MySecondTable AS b ON b.Id = MyTable.SecondId
LEFT JOIN ##MyTempTable AS c ON c.Id = b.ThirdId
WHERE
MyTabe.Col3 > 0
AND b.Foo NOT IS NULL
AND MyTable.TheDate > GETDATE() - 10
```
The example is completely made-up and may not make much sense, but you get the picture of how to do a more complex update without having to use a cursor. Of course, a temp table would not necessarily be required for it to work. :-)
|
224,499 |
<p>There are some good examples on how to calculate word frequencies in C#, but none of them are comprehensive and I really need one in VB.NET.</p>
<p>My current approach is limited to one word per frequency count. What is the best way to change this so that I can get a completely accurate word frequency listing?</p>
<pre><code>wordFreq = New Hashtable()
Dim words As String() = Regex.Split(inputText, "(\W)")
For i As Integer = 0 To words.Length - 1
If words(i) <> "" Then
Dim realWord As Boolean = True
For j As Integer = 0 To words(i).Length - 1
If Char.IsLetter(words(i).Chars(j)) = False Then
realWord = False
End If
Next j
If realWord = True Then
If wordFreq.Contains(words(i).ToLower()) Then
wordFreq(words(i).ToLower()) += 1
Else
wordFreq.Add(words(i).ToLower, 1)
End If
End If
End If
Next
Me.wordCount = New SortedList
For Each de As DictionaryEntry In wordFreq
If wordCount.ContainsKey(de.Value) = False Then
wordCount.Add(de.Value, de.Key)
End If
Next
</code></pre>
<p>I'd prefer an actual code snippet, but generic 'oh yeah...use this and run that' would work as well.</p>
|
[
{
"answer_id": 224510,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 1,
"selected": false,
"text": "<p>This might be helpful:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/90580/word-frequency-algorithm-for-natural-language-processing\">Word frequency algorithm for natural language processing</a></p>\n"
},
{
"answer_id": 224514,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 2,
"selected": false,
"text": "<p>This might be what your looking for:</p>\n\n<pre><code> Dim Words = \"Hello World ))))) This is a test Hello World\"\n Dim CountTheWords = From str In Words.Split(\" \") _\n Where Char.IsLetter(str) _\n Group By str Into Count()\n</code></pre>\n\n<p>I have just tested it and it does work</p>\n\n<p>EDIT! I have added code to make sure that it counts only letters and not symbols.</p>\n\n<p>FYI: I found an article on how to use LINQ and target 2.0, its a feels bit dirty but it might help someone <a href=\"http://weblogs.asp.net/fmarguerie/archive/2007/09/05/linq-support-on-net-2-0.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/fmarguerie/archive/2007/09/05/linq-support-on-net-2-0.aspx</a></p>\n"
},
{
"answer_id": 224543,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<pre><code>Public Class CountWords\n\n Public Function WordCount(ByVal str As String) As Dictionary(Of String, Integer)\n Dim ret As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)\n\n Dim word As String = \"\"\n Dim add As Boolean = True\n Dim ch As Char\n\n str = str.ToLower\n For index As Integer = 1 To str.Length - 1 Step index + 1\n ch = str(index)\n If Char.IsLetter(ch) Then\n add = True\n word += ch\n ElseIf add And word.Length Then\n If Not ret.ContainsKey(word) Then\n ret(word) = 1\n Else\n ret(word) += 1\n End If\n word = \"\"\n End If\n Next\n\n Return ret\n End Function\n\nEnd Class\n</code></pre>\n\n<p>Then for a quick demo application, create a winforms app with one multiline textbox called InputBox, one listview called OutputList and one button called CountBtn. In the list view create two columns - \"Word\" and \"Freq.\" Select the \"details\" list type. Add an event handler for CountBtn. Then use this code:</p>\n\n<pre><code>Imports System.Windows.Forms.ListViewItem\n\nPublic Class MainForm\n\n Private WordCounts As CountWords = New CountWords\n\n Private Sub CountBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CountBtn.Click\n OutputList.Items.Clear()\n Dim ret As Dictionary(Of String, Integer) = Me.WordCounts.WordCount(InputBox.Text)\n For Each item As String In ret.Keys\n Dim litem As ListViewItem = New ListViewItem\n litem.Text = item\n Dim csitem As ListViewSubItem = New ListViewSubItem(litem, ret.Item(item).ToString())\n\n litem.SubItems.Add(csitem)\n OutputList.Items.Add(litem)\n\n Word.Width = -1\n Freq.Width = -1\n Next\n End Sub\nEnd Class\n</code></pre>\n\n<p>You did a terrible terrible thing to make me write this in VB and I will never forgive you.</p>\n\n<p>:p</p>\n\n<p>Good luck!</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Fixed blank string bug and case bug</p>\n"
},
{
"answer_id": 224555,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 1,
"selected": false,
"text": "<p>Pretty close, but \\w+ is a good regex to match with (matches word characters only). </p>\n\n<pre><code>Public Function CountWords(ByVal inputText as String) As Dictionary(Of String, Integer)\n Dim frequency As New Dictionary(Of String, Integer)\n\n For Each wordMatch as Match in Regex.Match(inputText, \"\\w+\")\n If frequency.ContainsKey(wordMatch.Value.ToLower()) Then\n frequency(wordMatch.Value.ToLower()) += 1\n Else\n frequency.Add(wordMatch.Value.ToLower(), 1)\n End If\n Next\n Return frequency\nEnd Function\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4965/"
] |
There are some good examples on how to calculate word frequencies in C#, but none of them are comprehensive and I really need one in VB.NET.
My current approach is limited to one word per frequency count. What is the best way to change this so that I can get a completely accurate word frequency listing?
```
wordFreq = New Hashtable()
Dim words As String() = Regex.Split(inputText, "(\W)")
For i As Integer = 0 To words.Length - 1
If words(i) <> "" Then
Dim realWord As Boolean = True
For j As Integer = 0 To words(i).Length - 1
If Char.IsLetter(words(i).Chars(j)) = False Then
realWord = False
End If
Next j
If realWord = True Then
If wordFreq.Contains(words(i).ToLower()) Then
wordFreq(words(i).ToLower()) += 1
Else
wordFreq.Add(words(i).ToLower, 1)
End If
End If
End If
Next
Me.wordCount = New SortedList
For Each de As DictionaryEntry In wordFreq
If wordCount.ContainsKey(de.Value) = False Then
wordCount.Add(de.Value, de.Key)
End If
Next
```
I'd prefer an actual code snippet, but generic 'oh yeah...use this and run that' would work as well.
|
```
Public Class CountWords
Public Function WordCount(ByVal str As String) As Dictionary(Of String, Integer)
Dim ret As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
Dim word As String = ""
Dim add As Boolean = True
Dim ch As Char
str = str.ToLower
For index As Integer = 1 To str.Length - 1 Step index + 1
ch = str(index)
If Char.IsLetter(ch) Then
add = True
word += ch
ElseIf add And word.Length Then
If Not ret.ContainsKey(word) Then
ret(word) = 1
Else
ret(word) += 1
End If
word = ""
End If
Next
Return ret
End Function
End Class
```
Then for a quick demo application, create a winforms app with one multiline textbox called InputBox, one listview called OutputList and one button called CountBtn. In the list view create two columns - "Word" and "Freq." Select the "details" list type. Add an event handler for CountBtn. Then use this code:
```
Imports System.Windows.Forms.ListViewItem
Public Class MainForm
Private WordCounts As CountWords = New CountWords
Private Sub CountBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CountBtn.Click
OutputList.Items.Clear()
Dim ret As Dictionary(Of String, Integer) = Me.WordCounts.WordCount(InputBox.Text)
For Each item As String In ret.Keys
Dim litem As ListViewItem = New ListViewItem
litem.Text = item
Dim csitem As ListViewSubItem = New ListViewSubItem(litem, ret.Item(item).ToString())
litem.SubItems.Add(csitem)
OutputList.Items.Add(litem)
Word.Width = -1
Freq.Width = -1
Next
End Sub
End Class
```
You did a terrible terrible thing to make me write this in VB and I will never forgive you.
:p
Good luck!
**EDIT**
Fixed blank string bug and case bug
|
224,503 |
<p>Short of putting a UIWebView as the back-most layer in my nib file, how can I add a repeating background image to an iPhone app (like the corduroy look in the background of a grouped UITableView)?</p>
<p>Do I need to create an image that's the size of the iPhone's screen and manually repeat it using copy and paste?</p>
|
[
{
"answer_id": 224513,
"author": "Frank Schmitt",
"author_id": 27951,
"author_profile": "https://Stackoverflow.com/users/27951",
"pm_score": 8,
"selected": true,
"text": "<p>Apparently a UIColor is not necessarily a single color, but can be a pattern as well. Confusingly, this is not supported in Interface Builder. </p>\n\n<p>Instead you set the backgroundColor of the view (say, in -viewDidLoad) with the convenience method +colorWithPatternImage: and pass it a UI Image. For Instance:</p>\n\n<pre><code>- (void)viewDidLoad {\n [super viewDidLoad];\n self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@\"gingham.png\"]]; \n}\n</code></pre>\n\n<p>Of course, don't forget to add the image file to your application bundle. </p>\n\n<p>There are also some built-in background pattern \"colors\":</p>\n\n<ul>\n<li>groupTableViewBackgroundColor</li>\n<li>viewFlipsideBackgroundColor</li>\n</ul>\n\n<p>Because the are used globally across all iPhone apps, you incur the double-edged sword of an OS update updating the look and feel of your application (giving it a fresh new look that may or may not work right). </p>\n\n<p>For instance:</p>\n\n<pre><code>- (void)viewDidLoad {\n [super viewDidLoad];\n self.view.backgroundColor = [UIColor groupTableViewBackgroundColor]; \n}\n</code></pre>\n"
},
{
"answer_id": 224972,
"author": "Dan",
"author_id": 9774,
"author_profile": "https://Stackoverflow.com/users/9774",
"pm_score": 2,
"selected": false,
"text": "<p>You should have a look at the QuartzDemo iPhone example code from Apple, specifically QuartzImageDrawing.m. Should use the following method call.</p>\n\n<pre><code>CGContextDrawTiledImage\n</code></pre>\n"
},
{
"answer_id": 226668,
"author": "Chris Craft",
"author_id": 23294,
"author_profile": "https://Stackoverflow.com/users/23294",
"pm_score": 2,
"selected": false,
"text": "<p>You can even have an animated tiled background images that move. :D</p>\n\n<p><a href=\"http://www.appsamuck.com/\" rel=\"nofollow noreferrer\">Apps Amuck</a> has a simple tutorial that show you how to do this on their site.</p>\n\n<p><a href=\"http://appsamuck.com/blog/index.php/2008/10/16/31-days-of-iphone-apps-day-16-world-tour/\" rel=\"nofollow noreferrer\">31 Days of iPhone Apps - Day 16: World Tour</a></p>\n"
},
{
"answer_id": 3234160,
"author": "Son Nguyen",
"author_id": 374885,
"author_profile": "https://Stackoverflow.com/users/374885",
"pm_score": 1,
"selected": false,
"text": "<p>You should use colorWithPatternImage</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27951/"
] |
Short of putting a UIWebView as the back-most layer in my nib file, how can I add a repeating background image to an iPhone app (like the corduroy look in the background of a grouped UITableView)?
Do I need to create an image that's the size of the iPhone's screen and manually repeat it using copy and paste?
|
Apparently a UIColor is not necessarily a single color, but can be a pattern as well. Confusingly, this is not supported in Interface Builder.
Instead you set the backgroundColor of the view (say, in -viewDidLoad) with the convenience method +colorWithPatternImage: and pass it a UI Image. For Instance:
```
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"gingham.png"]];
}
```
Of course, don't forget to add the image file to your application bundle.
There are also some built-in background pattern "colors":
* groupTableViewBackgroundColor
* viewFlipsideBackgroundColor
Because the are used globally across all iPhone apps, you incur the double-edged sword of an OS update updating the look and feel of your application (giving it a fresh new look that may or may not work right).
For instance:
```
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}
```
|
224,504 |
<p>Ok, so I have a Rails app set up on DreamHost and I had it working a while ago and now it's broken. I don't know a lot about deployment environments or anything like that so please forgive my ignorance. Anyway, it looks like the app is crashing at this line in config/environment.rb:</p>
<pre><code>require File.join(File.dirname(__FILE__), 'boot')
</code></pre>
<p>config/boot.rb is pretty much normal, but I'll include it here anyway.</p>
<pre><code># Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
Rails::Initializer.run(:install_gem_spec_stubs)
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => load_error
$stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
end
class << self
def rubygems_version
Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
require 'rubygems'
min_version = '1.1.1'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# All that for this:
Rails.boot!
</code></pre>
<p>Does anyone have any ideas? I am not getting any errors in the log or on the page.</p>
<p>-fREW</p>
|
[
{
"answer_id": 226189,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 1,
"selected": false,
"text": "<p>My guess would be that you're breaking because of a newer version of the Rails gems on Dreamhost. At least, that's been my issue when things have blown up in something like boot.rb.</p>\n\n<p>Try freezing the gems from your development environment into your vendor/rails directory. </p>\n"
},
{
"answer_id": 885592,
"author": "alex",
"author_id": 71953,
"author_profile": "https://Stackoverflow.com/users/71953",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem on DreamHost. Freezing rails and unpacking all gems got me past it.</p>\n\n<pre><code>rake rails:freeze:gems\nrake gems:unpack:dependencies\n</code></pre>\n"
},
{
"answer_id": 2433057,
"author": "Taryn East",
"author_id": 219883,
"author_profile": "https://Stackoverflow.com/users/219883",
"pm_score": 0,
"selected": false,
"text": "<p>Ya - the problem is not really in <code>boot.rb</code> - it's just that <code>boot.rb</code> is where rails is actually loaded.</p>\n\n<p>So you'll get an error like this if you've specified a version of Rails that just doesn't exist on your dreamhost slice. This can happen if you either upgrade your project, start a new project (and forget that you upgraded rails in the meanwhile) or if you're still using an old version of rails and it's now been removed from the dreamhost server that you're on.</p>\n\n<p>To figure out which is is, look in <code>config/environment.rb</code> for the line that'll read something like:</p>\n\n<pre><code>RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION\n</code></pre>\n\n<p>Then ssh to your dreamhost server and type <code>gem list</code> and see if your version is in the list.</p>\n\n<p>If not, you an try several options. Lets say the version you're using is 2.3.4\nTo begin with, try: <code>gem install rails -v=2.3.4</code> then restart. That may be all that is required.\nIf that doesn't work, then try freezing and unpacking the gems (as per the other answer here).</p>\n\n<p>There is also another possibility - that you're actually missing a gem that rails depends on but which is failing silently - eg a dependency on a certain version of rack caught me out once. But you may also have other gem dependencies</p>\n\n<p>If you run <code>rake gems</code> you will be able to list all the gems that your project knows about that it needs - make sure they're installed to begin with.</p>\n\n<p>Then, as a sort of rough smoke-test, try running <code>script/console</code> - if you're missing an important rails gem, <code>script/console</code> won't load and should fail, giving you a notice about the gem you need.</p>\n\n<p><strong>Update</strong>:\nIf you're trying to run v 2.3.5, you may also be suffering from this problem:\n<a href=\"https://stackoverflow.com/questions/1814856/bypassing-rack-version-error-using-rails-2-3-5\">Bypassing rack version error using Rails 2.3.5</a></p>\n\n<p>In which case you'll need to follow the instructions there.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
Ok, so I have a Rails app set up on DreamHost and I had it working a while ago and now it's broken. I don't know a lot about deployment environments or anything like that so please forgive my ignorance. Anyway, it looks like the app is crashing at this line in config/environment.rb:
```
require File.join(File.dirname(__FILE__), 'boot')
```
config/boot.rb is pretty much normal, but I'll include it here anyway.
```
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
Rails::Initializer.run(:install_gem_spec_stubs)
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => load_error
$stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
end
class << self
def rubygems_version
Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
require 'rubygems'
min_version = '1.1.1'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# All that for this:
Rails.boot!
```
Does anyone have any ideas? I am not getting any errors in the log or on the page.
-fREW
|
I had the same problem on DreamHost. Freezing rails and unpacking all gems got me past it.
```
rake rails:freeze:gems
rake gems:unpack:dependencies
```
|
224,512 |
<p>I am working on creating a daemon in Ruby using the daemons gem. I want to add output from the daemon into a log file. I am wondering what is the easiest way to redirect <code>puts</code> from the console to a log file.</p>
|
[
{
"answer_id": 224523,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 4,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>$stdout = File.new( '/tmp/output', 'w' )\n</code></pre>\n\n<p>To restore:</p>\n\n<pre><code>$stdout = STDOUT\n</code></pre>\n"
},
{
"answer_id": 224659,
"author": "Vitalie",
"author_id": 27913,
"author_profile": "https://Stackoverflow.com/users/27913",
"pm_score": 5,
"selected": true,
"text": "<p>I should recommend to use ruby logger, it is better than puts, you can have multiple log levels that you can turn on/off: debug, warn, info,error, etc.</p>\n\n<pre><code> logger = Logger.new(STDOUT)\n logger = Logger.new(\"/var/log/my-daemon.log\")\n</code></pre>\n\n<p>I use runit package to manage ruby services, it has svlogd than will redirect daemon output to log file, here is run script for logger process:</p>\n\n<pre><code>#!/bin/sh\nset -e\n\nLOG=/var/log/my-daemon\n\ntest -d \"$LOG\" || mkdir -p -m2750 \"$LOG\" && chown nobody:adm \"$LOG\"\nexec chpst -unobody svlogd -tt \"$LOG\"\n</code></pre>\n"
},
{
"answer_id": 2480439,
"author": "Eric Walker",
"author_id": 61048,
"author_profile": "https://Stackoverflow.com/users/61048",
"pm_score": 5,
"selected": false,
"text": "<p>If you need to capture both STDERR and STDOUT and don't want to resort to logging:</p>\n<pre><code>$stdout.reopen("my.log", "w")\n$stdout.sync = true\n$stderr.reopen($stdout)\n</code></pre>\n<p>To restore:</p>\n<pre><code>$stdout = STDOUT\n</code></pre>\n"
},
{
"answer_id": 22617214,
"author": "Peterdk",
"author_id": 107029,
"author_profile": "https://Stackoverflow.com/users/107029",
"pm_score": 0,
"selected": false,
"text": "<p>Or you can redefine the <code>puts</code> command? Works probably only in a single file/class</p>\n\n<pre><code>def puts(message)\n #write message to file\nend\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
I am working on creating a daemon in Ruby using the daemons gem. I want to add output from the daemon into a log file. I am wondering what is the easiest way to redirect `puts` from the console to a log file.
|
I should recommend to use ruby logger, it is better than puts, you can have multiple log levels that you can turn on/off: debug, warn, info,error, etc.
```
logger = Logger.new(STDOUT)
logger = Logger.new("/var/log/my-daemon.log")
```
I use runit package to manage ruby services, it has svlogd than will redirect daemon output to log file, here is run script for logger process:
```
#!/bin/sh
set -e
LOG=/var/log/my-daemon
test -d "$LOG" || mkdir -p -m2750 "$LOG" && chown nobody:adm "$LOG"
exec chpst -unobody svlogd -tt "$LOG"
```
|
224,553 |
<p>I want to know how events are used in embedded system code.</p>
<p>Main intention is to know how exactly event flags are set/reset in code. and how to identify which task is using which event flag and which bits of the flag are getting set/reset by each task.</p>
<p>Please put your suggestion or comments about it.</p>
<p>Thanks in advance.</p>
<hr>
<p>(edit 1: copied from clarification in answer below)</p>
<p>Sorry for not specifying the details required. Actually I am interested in the analysis of any application written in C language using vxworks/Itron/OSEK OS. For example there is eventLib library in vxworks to support event handling. I want to know that how one can make use of such system routines to handle events in task. What is event flag(is it global/local...or what ?), how to set bits of any event flag and which can be the possible relationship between task and event flags ??</p>
<p>How task can wait for multiple events in AND and OR mode ??
I came across one example in which the scenario given below looks dangerous, but why ??</p>
<pre><code> Scenarios is ==> *[Task1 : Set(e1), Task2 : Wait(e1) and Set(e2), Task3 : Wait(e2) ]*
</code></pre>
<p>I know that multiple event flags waited by one task or circular dependency between multiple tasks(deadlock) are dangerous cases in task-event relationship, but how above scenario is dangerous, I am not getting it....Kindly explain.</p>
<pre><code> (Are there any more such scenarios possible in task-event handling which should be reviewed in code ?? )
</code></pre>
<p>I hope above information is sufficient ....</p>
|
[
{
"answer_id": 224565,
"author": "Bill Forster",
"author_id": 3955,
"author_profile": "https://Stackoverflow.com/users/3955",
"pm_score": 1,
"selected": false,
"text": "<p>This question needs to provide more context. Embedded systems can be created using a wide range of languages, operating systems (including no operating system), frameworks etc. There is nothing universal about how events are created and handled in an embedded system, just as there is nothing universal about how events are created and handled in computing in general.</p>\n"
},
{
"answer_id": 224567,
"author": "Sean",
"author_id": 29941,
"author_profile": "https://Stackoverflow.com/users/29941",
"pm_score": 2,
"selected": false,
"text": "<p>Many embedded systems use Interrupt Service Routines (ISR) to handle events. You would define an ISR for a given \"flag\" and reset that flag after you handle the event.</p>\n\n<p>For instance say you have a device performing Analog to Digital Conversions (ADC). On the device you could have an ISR that fires each time the ADC completes a conversion and then handle it within the ISR or notify some other task that the data is available (if you want to send it across some communications protocol). After you complete that you would reset the ADC flag so that it can fire again at it's next conversion.</p>\n\n<p>Usually there are a set of ISRs defined in the devices manual. Sometimes they provide general purpose flags that you could also handle as you wish. Each time resetting the flag that caused the routine to fire.</p>\n"
},
{
"answer_id": 224574,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry for not specifying the details required. Actually I am interested in the analysis of any application written in C language using vxworks/Itron/OSEK OS. \nFor example there is eventLib library in vxworks to support event handling. \nI want to know that how one can make use of such system routines to handle events in task. What is event flag(is it global/local...or what ?), how to set bits of any event flag and which can be the possible relationship between task and event flags ??</p>\n\n<p>I hope above information is sufficient ....</p>\n"
},
{
"answer_id": 226698,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 2,
"selected": false,
"text": "<p>The eventLib in VxWorks is similar to signal() in unix -- it can indicate to a different thread that something occurred. If you need to pass data with the event, you may want to use Message Queues instead.</p>\n\n<p>The events are \"global\" between the sender and receiver. Since each sender indicates which task the event is intended for, there can be multiple event masks in the system with each sender/receiver pair having their own interpretation.</p>\n\n<p>A basic example:</p>\n\n<pre><code> #define EVENT1 0x00000001\n #define EVENT2 0x00000002\n #define EVENT3 0x00000004\n ...\n #define EVENT_EXIT 0x80000000\n\n /* Spawn the event handler task (event receiver) */\n rcvTaskId = taskSpawn(\"tRcv\",priority,0,stackSize,handleEvents,0,0,0,0,0,0,0,0,0,0);\n ...\n\n /* Receive thread: Loop to receive events */\n STATUS handleEvents(void)\n {\n UINT32 rcvEventMask = 0xFFFFFFFF;\n\n while(1)\n {\n UINT32 events = 0;\n\n if (eventReceive(rcvEventMask. EVENTS_WAIT_ANY, WAIT_FOREVER, &events) == OK)\n {\n /* Process events */\n if (events & EVENT1)\n handleEvent1();\n if (events & EVENT2)\n handleEvent2();\n ...\n if (events & EVENT_EXIT)\n break;\n }\n }\n\n return OK;\n }\n</code></pre>\n\n<p>The event sender is typically a hardware driver (BSP) or another thread. When a desired action occurs, the driver builds a mask of all pertinent events and sends them to the receiver task. </p>\n\n<p>The sender needs to obtain the taskID of the receiver. The taskID can be a global, </p>\n\n<pre><code>int RcvTaskID = ERROR;\n...\neventSend(RcvTaskID, eventMask);\n</code></pre>\n\n<p>it can be registered with the driver/sender task by the receiver, </p>\n\n<pre><code>static int RcvTaskID = ERROR;\n\nvoid DRIVER_setRcvTaskID(int rcvTaskID)\n{\n RcvTaskID = rcvTaskID;\n}\n...\neventSend(RcvTaskID, eventMask);\n</code></pre>\n\n<p>or the driver/sender task can call a receiver API method to send the event (wrapper).</p>\n\n<pre><code>static int RcvTaskID;\nvoid RECV_sendEvents(UINT32 eventMask)\n{\n eventSend(RcvTaskID, eventMask);\n}\n</code></pre>\n"
},
{
"answer_id": 267711,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "<p>If you're asking how to set, clear, and check the various bits that represent events, this example may help. The basic strategy is to declare a (usually global) variable and use one bit to represent each condition.</p>\n\n<pre><code>unsigned char bit_flags = 0;\n</code></pre>\n\n<p>Now we can assign events to the bits:</p>\n\n<pre><code>#define TIMER_EXPIRED 0x01 // 0000 0001\n#define DATA_READY 0x02 // 0000 0010\n#define BUFFER_OVERFLOW 0x04 // 0000 0100\n</code></pre>\n\n<p>And we can set, clear, and check bits with bitwise operators:</p>\n\n<pre><code>// Bitwise OR: bit_flags | 00000001 sets the first bit.\nbit_flags |= TIMER_EXPIRED; // Set TIMER_EXPIRED bit.\n\n// Bitwise AND w/complement clears bits: flags & 11111101 clears the 2nd bit.\nbit_flags &= ~DATA_READY; // Clear DATA_READY bit.\n\n// Bitwise AND tests a bit. The result is BUFFER_OVERFLOW\n// if the bit is set, 0 if the bit is clear.\nhad_ovflow = bit_flags & BUFFER_OVERFLOW;\n</code></pre>\n\n<p>We can also set or clear combinations of bits:</p>\n\n<pre><code>// Set DATA_READY and BUFFER_OVERFLOW bits.\nbit_flags |= (DATA_READY | BUFFER_OVERFLOW);\n</code></pre>\n\n<p>You'll often see these operations implemented as macros:</p>\n\n<pre><code>#define SET_BITS(bits, data) data |= (bits)\n#define CLEAR_BITS(bits, data) data &= ~(bits)\n#define CHECK_BITS(bits, data) (data & (bits))\n</code></pre>\n\n<p>Also, a note about interrupts and interrupt service routines: they need to run <em>fast</em>, so a typical ISR will simply set a flag, increment a counter, or copy some data and exit immediately. Then you can check the flag and attend to the event at your leisure. You probably do <em>not</em> want to undertake lengthy or error-prone activities in your ISR.</p>\n\n<p>Hope that's helpful!</p>\n"
},
{
"answer_id": 4871153,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": -1,
"selected": false,
"text": "<p>In one family of embedded systems I designed (for a PIC18Fxx micro with ~128KB flash and 3.5KB RAM), I wrote a library to handle up to 16 timers with 1/16-second resolution (measured by a 16Hz pulse input to the CPU). The code is set up to determine whether any timer is in the Expired state or any dedicated wakeup pin is signaling, and if not, sleep until the next timer would expire or a wakeup input changes state. Quite a handy bit of code, though I should in retrospect probably have designed it to work with multiple groups of eight timers rather than one set of 16.</p>\n\n<p>A key aspect of my timing routines which I have found to be useful is that they mostly aren't driven by interrupts; instead I have a 'poll when convenient' routine which updates the timers off a 16Hz counter. While it sometimes feels odd to have timers which aren't run via interrupt, doing things that way avoids the need to worry about interrupts happening at odd times. If the action controlled by a timer wouldn't be able to happen within an interrupt (due to stack nesting and other limitations), there's no need to worry about the timer in an interrupt--just keep track of how much time has passed.</p>\n"
},
{
"answer_id": 8439179,
"author": "ace",
"author_id": 439699,
"author_profile": "https://Stackoverflow.com/users/439699",
"pm_score": 0,
"selected": false,
"text": "<p>If you're interested in using event-driven programming at the embedded level you should really look into <a href=\"http://www.state-machine.com/\" rel=\"nofollow\">QP</a>. It's an excellent lightweight framework and if you get the book \"Practical UML Statecharts in C/C++\" by Miro Samek you find everything from how to handle system events in an embedded linux kernel (ISR's etc) to handling and creating them in a build with QP as your environment. (<a href=\"http://www.state-machine.com/doxygen/qpcpp/struct_q_event.html\" rel=\"nofollow\">Here</a> is a link to an example event).</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to know how events are used in embedded system code.
Main intention is to know how exactly event flags are set/reset in code. and how to identify which task is using which event flag and which bits of the flag are getting set/reset by each task.
Please put your suggestion or comments about it.
Thanks in advance.
---
(edit 1: copied from clarification in answer below)
Sorry for not specifying the details required. Actually I am interested in the analysis of any application written in C language using vxworks/Itron/OSEK OS. For example there is eventLib library in vxworks to support event handling. I want to know that how one can make use of such system routines to handle events in task. What is event flag(is it global/local...or what ?), how to set bits of any event flag and which can be the possible relationship between task and event flags ??
How task can wait for multiple events in AND and OR mode ??
I came across one example in which the scenario given below looks dangerous, but why ??
```
Scenarios is ==> *[Task1 : Set(e1), Task2 : Wait(e1) and Set(e2), Task3 : Wait(e2) ]*
```
I know that multiple event flags waited by one task or circular dependency between multiple tasks(deadlock) are dangerous cases in task-event relationship, but how above scenario is dangerous, I am not getting it....Kindly explain.
```
(Are there any more such scenarios possible in task-event handling which should be reviewed in code ?? )
```
I hope above information is sufficient ....
|
Many embedded systems use Interrupt Service Routines (ISR) to handle events. You would define an ISR for a given "flag" and reset that flag after you handle the event.
For instance say you have a device performing Analog to Digital Conversions (ADC). On the device you could have an ISR that fires each time the ADC completes a conversion and then handle it within the ISR or notify some other task that the data is available (if you want to send it across some communications protocol). After you complete that you would reset the ADC flag so that it can fire again at it's next conversion.
Usually there are a set of ISRs defined in the devices manual. Sometimes they provide general purpose flags that you could also handle as you wish. Each time resetting the flag that caused the routine to fire.
|
224,562 |
<p>I am reading over the K&R book, and am a little stuck.</p>
<p>What is wrong with the following?</p>
<pre><code>void getInput(int* output) {
int c, i;
for(i=0; (c = getchar()) != '\n'; i++)
output[i] = c; // printf("%c", c) prints the c value as expected
output[++i] = '\0';
}
</code></pre>
<p>When I run the program it never gets out of the loop and I have to <kbd>Ctrl+C</kbd> to exit. However if I replace the fifth line with <code>printf("%c", c);</code>, it prints out all the input just fine after hitting enter and creating the new line.</p>
|
[
{
"answer_id": 224575,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 1,
"selected": false,
"text": "<p>It looks correct to me as written except that you don't need to increment i outside of the loop. The i gets incremented right before the loop exits, thus it is already where you want it.</p>\n\n<p>Make sure that a '\\n' is actually making it into c.</p>\n\n<p>Sometimes an '\\n' will get thrown away as a delimiter.</p>\n"
},
{
"answer_id": 224581,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 0,
"selected": false,
"text": "<p>a simple way to risk buffer overflow, because output's size is never passed/checked</p>\n"
},
{
"answer_id": 224600,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>What is wrong with the following?</p>\n</blockquote>\n\n<pre><code>1. void getInput(int* output) {\n</code></pre>\n\n<p>Why is the input argument an int* when what you want to store in an array of characters? \nProbably </p>\n\n<pre><code>void getInput(char* output) {\n</code></pre>\n\n<p>is better. </p>\n\n<p>Also, how do you know that the output pointer is pointing somewhere where you hold enough memory to write the user's input? Maybe you must have the maximum buffer length as an extra parameter to avoid buffer overflow errors as <a href=\"https://stackoverflow.com/questions/224562/basic-c-question#224581\">PW pointed out</a>.</p>\n\n<pre><code>5. output[++i] = '\\0';\n</code></pre>\n\n<p>i has already been incremented an extra time inside the for loop, so you can just do:</p>\n\n<pre><code>output[i] = '\\0';\n</code></pre>\n\n<p>Other than these, the program runs fine and outputs what we input until return.</p>\n\n<p>FWIW, I tested it by calling it like so:</p>\n\n<pre><code> int main(void)\n{\n char o[100];\n getInput(o);\n printf(\"%s\", o);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 224604,
"author": "chris",
"author_id": 26849,
"author_profile": "https://Stackoverflow.com/users/26849",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the complete program with a couple of updates from your input, but it still won't make it out of the loop. BTW this was exercise 1-24 on pg 34</p>\n\n<pre><code>#include <stdio.h>\n\n#define STACK_SIZE 50\n#define MAX_INPUT_SIZE 1000\n#define FALSE 0\n#define TRUE 1\n\nvoid getInput();\nint validInput();\n\nint main() {\n char* userInput[MAX_INPUT_SIZE];\n\n getInput(&userInput);\n\n if (validInput(&userInput) == TRUE)\n printf(\"Compile complete\");\n else\n printf(\"Error\");\n}\n\n// Functions\nvoid getInput(char* output) {\n int c, i;\n for(i=0; (c = getchar()) != '\\n' && c != EOF && i <= MAX_INPUT_SIZE; i++)\n output[i] = c;\n output[i] = '\\0';\n}\n\nint validInput(char* input) {\n char stack[STACK_SIZE];\n int c;\n int j;\n\n for (j=0; (c = input[j]) != '\\0'; ) {\n switch(c){\n case '[': case '(': case '{':\n stack[j++] = c;\n break;\n case ']': case ')': case '}':\n if (c == ']' && stack[j] != '[')\n return FALSE;\n else if (c == '}' && stack[j] != '{')\n return FALSE;\n else if (c == ')' && stack[j] != '(')\n return FALSE;\n\n // decrement the stack's index \n --j;\n break;\n }\n }\n\n return TRUE;\n}\n</code></pre>\n"
},
{
"answer_id": 224708,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using a debugger? You should step through the code in gdb or visual studio or whatever you are using and see what is going on. You said you were a beginner so maybe you hadn't considered that yet - this is a pretty normal debugging technique to use.</p>\n"
},
{
"answer_id": 224724,
"author": "Raz",
"author_id": 5661,
"author_profile": "https://Stackoverflow.com/users/5661",
"pm_score": 1,
"selected": false,
"text": "<p>your last code as posted have 3 errors I can see:</p>\n\n<pre><code>char* userInput[MAX_INPUT_SIZE];\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>char userInput[MAX_INPUT_SIZE+1];\n</code></pre>\n\n<p>(this was already mentioned by Pax Diablo)</p>\n\n<pre><code>getInput(&userInput);\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>getInput( userInput );\n</code></pre>\n\n<p>This last error means you passed to getInput an address inside your call stack. you have a memory overwrite. probably one of your calls to getchar() returnes to the wrong address.</p>\n"
},
{
"answer_id": 228506,
"author": "chris",
"author_id": 26849,
"author_profile": "https://Stackoverflow.com/users/26849",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the final working code. I must say I picked up quite a bit from doing this one. Thanks for the help and pointers.</p>\n\n<p>Any suggestions on how things could be done better?</p>\n\n<pre><code>#include <stdio.h>\n\n#define STACK_SIZE 50\n#define MAX_INPUT_SIZE 1000\n#define FALSE 0\n#define TRUE !FALSE\n\nvoid get_input();\nint valid_input();\n\nint main() {\n char user_input[MAX_INPUT_SIZE + 1]; // +1 for the \\0\n\n get_input(user_input);\n\n if (valid_input(user_input))\n printf(\"Success\\n\");\n else\n printf(\"Error\\n\");\n}\n\n// Functions\nvoid get_input(char* output) {\n int c, i;\n for(i=0; (c = getchar()) != '\\n' && c != EOF && i <= MAX_INPUT_SIZE; i++)\n output[i] = c;\n output[i] = '\\0';\n}\n\nint valid_input(char* input) {\n char stack[STACK_SIZE];\n char c;\n int i = 0;\n int stack_index = -1;\n\n while ((c = input[i]) != '\\0' && i < STACK_SIZE) {\n switch(c){\n case '[': case '(': case '{':\n stack_index++; \n stack[stack_index] = c;\n break;\n case ']': case ')': case '}':\n if ((c == ']' && stack[stack_index] != '[') ||\n (c == '}' && stack[stack_index] != '{') ||\n (c == ')' && stack[stack_index] != '('))\n return FALSE;\n\n // decrement the stack's index now that the closing bracket is found \n stack_index--;\n break;\n }\n i++;\n }\n\n // stack index should be back where it started\n return (stack_index == -1);\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26849/"
] |
I am reading over the K&R book, and am a little stuck.
What is wrong with the following?
```
void getInput(int* output) {
int c, i;
for(i=0; (c = getchar()) != '\n'; i++)
output[i] = c; // printf("%c", c) prints the c value as expected
output[++i] = '\0';
}
```
When I run the program it never gets out of the loop and I have to `Ctrl+C` to exit. However if I replace the fifth line with `printf("%c", c);`, it prints out all the input just fine after hitting enter and creating the new line.
|
>
> What is wrong with the following?
>
>
>
```
1. void getInput(int* output) {
```
Why is the input argument an int\* when what you want to store in an array of characters?
Probably
```
void getInput(char* output) {
```
is better.
Also, how do you know that the output pointer is pointing somewhere where you hold enough memory to write the user's input? Maybe you must have the maximum buffer length as an extra parameter to avoid buffer overflow errors as [PW pointed out](https://stackoverflow.com/questions/224562/basic-c-question#224581).
```
5. output[++i] = '\0';
```
i has already been incremented an extra time inside the for loop, so you can just do:
```
output[i] = '\0';
```
Other than these, the program runs fine and outputs what we input until return.
FWIW, I tested it by calling it like so:
```
int main(void)
{
char o[100];
getInput(o);
printf("%s", o);
return 0;
}
```
|
224,583 |
<p>Do you bother initialising java bean values? Say, for example:</p>
<p>([g|s]etters omitted)</p>
<pre><code>public class SomeClass {
private String foo;
private Date bar;
private Baz someObject;
}
</code></pre>
<p>(Yes, this is a POJO being used as a bean rather than a Java Bean in the strictest sense)</p>
<p>In the empty constructor, do you initialise these members, or simply do nothing? Likewise, would Baz initialise it's members as well?</p>
<p>Or do you just leave them as null?</p>
|
[
{
"answer_id": 224607,
"author": "Maxim Ananyev",
"author_id": 404206,
"author_profile": "https://Stackoverflow.com/users/404206",
"pm_score": 2,
"selected": true,
"text": "<p>It depends on the use case.</p>\n\n<p>If I use properties as service dependencies, they should be initialized to operate properly (btw, Spring DI has handy way to do it). </p>\n\n<p>If I use bean as part of domain model, it is usually illegal state to have some null property. It may not be initialized at startup, but I bother throwing IllegalStateException if some field is null during the business operation. </p>\n"
},
{
"answer_id": 440641,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 0,
"selected": false,
"text": "<p>If at all possible, I initialize variables at declaration if they need to be initialized. These initialization statements actually wind up being called from the constructor.</p>\n\n<p>I do generally leave them as null if there's not a compelling reason to initialize them.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27708/"
] |
Do you bother initialising java bean values? Say, for example:
([g|s]etters omitted)
```
public class SomeClass {
private String foo;
private Date bar;
private Baz someObject;
}
```
(Yes, this is a POJO being used as a bean rather than a Java Bean in the strictest sense)
In the empty constructor, do you initialise these members, or simply do nothing? Likewise, would Baz initialise it's members as well?
Or do you just leave them as null?
|
It depends on the use case.
If I use properties as service dependencies, they should be initialized to operate properly (btw, Spring DI has handy way to do it).
If I use bean as part of domain model, it is usually illegal state to have some null property. It may not be initialized at startup, but I bother throwing IllegalStateException if some field is null during the business operation.
|
224,602 |
<p>Given this HTML:</p>
<pre><code><div>foo</div><div>bar</div><div>baz</div>
</code></pre>
<p>How do you make them display inline like this:</p>
<blockquote>
<p>foo bar baz</p>
</blockquote>
<p>not like this:</p>
<blockquote>
<p>foo<br>
bar<br>
baz </p>
</blockquote>
|
[
{
"answer_id": 224612,
"author": "Randy Sugianto 'Yuku'",
"author_id": 11238,
"author_profile": "https://Stackoverflow.com/users/11238",
"pm_score": 8,
"selected": false,
"text": "<p>Try writing it like this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div { border: 1px solid #CCC; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <div style=\"display: inline\">a</div>\r\n <div style=\"display: inline\">b</div>\r\n <div style=\"display: inline\">c</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 224616,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 2,
"selected": false,
"text": "<pre><code><style type=\"text/css\">\ndiv.inline { display:inline; }\n</style>\n<div class=\"inline\">a</div>\n<div class=\"inline\">b</div>\n<div class=\"inline\">c</div>\n</code></pre>\n"
},
{
"answer_id": 224626,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 9,
"selected": true,
"text": "<p>That's something else then:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div.inline { float:left; }\r\n.clearBoth { clear:both; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"inline\">1<br />2<br />3</div>\r\n<div class=\"inline\">1<br />2<br />3</div>\r\n<div class=\"inline\">1<br />2<br />3</div>\r\n<br class=\"clearBoth\" /><!-- you may or may not need this --></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 224903,
"author": "Pirat",
"author_id": 22326,
"author_profile": "https://Stackoverflow.com/users/22326",
"pm_score": 3,
"selected": false,
"text": "<p><code><span></code> ?</p>\n"
},
{
"answer_id": 403149,
"author": "bochgoch",
"author_id": 50450,
"author_profile": "https://Stackoverflow.com/users/50450",
"pm_score": 8,
"selected": false,
"text": "<p>An inline div is a freak of the web & should be beaten until it becomes a span (at least 9 times out of 10)...</p>\n\n<pre><code><span>foo</span>\n<span>bar</span>\n<span>baz</span>\n</code></pre>\n\n<p>...answers the original question...</p>\n"
},
{
"answer_id": 403161,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 3,
"selected": false,
"text": "<p>As mentioned, display:inline is probably what you want. Some browsers also support inline-blocks. </p>\n\n<p><a href=\"http://www.quirksmode.org/css/display.html#inlineblock\" rel=\"noreferrer\">http://www.quirksmode.org/css/display.html#inlineblock</a></p>\n"
},
{
"answer_id": 403321,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 5,
"selected": false,
"text": "<p>Having read this question and the answers a couple of times, all I can do is assume that there's been quite a bit of editing going on, and my suspicion is that you've been given the incorrect answer based on not providing enough information. My clue comes from the use of <code>br</code> tag.</p>\n\n<p><strong>Apologies to Darryl. I read class=\"inline\" as style=\"display: inline\". You have the right answer, even if you do use semantically questionable class names ;-)</strong> </p>\n\n<p>The miss use of <code>br</code> to provide structural layout rather than for textual layout is far too prevalent for my liking. </p>\n\n<p>If you're wanting to put more than inline elements inside those <code>divs</code> then you should be floating those <code>div</code>s rather than making them inline.</p>\n\n<p>Floated divs:</p>\n\n<pre><code>===== ======= == **** ***** ****** +++++ ++++\n===== ==== ===== ******** ***** ** ++ +++++++\n=== ======== === ******* **** **** \n===== ==== ===== +++++++ ++\n====== == ======\n</code></pre>\n\n<p>Inline divs:</p>\n\n<pre><code>====== ==== ===== ===== == ==== *** ******* ***** ***** \n**** ++++ +++ ++ ++++ ++ +++++++ +++ ++++\n</code></pre>\n\n<p>If you're after the former, then this is your solution and lose those <code>br</code> tags:</p>\n\n<pre><code><div style=\"float: left;\" >\n <p>block level content or <span>inline content</span>.</p>\n <p>block level content or <span>inline content</span>.</p>\n</div>\n<div style=\"float: left;\" >\n <p>block level content or <span>inline content</span>.</p>\n <p>block level content or <span>inline content</span>.</p>\n</div>\n<div style=\"float: left;\" >\n <p>block level content or <span>inline content</span>.</p>\n <p>block level content or <span>inline content</span>.</p>\n</div>\n</code></pre>\n\n<p>note that the width of these divs is fluid, so feel free to put widths on them if you want to control the behavior.</p>\n\n<p>Thanks,\nSteve</p>\n"
},
{
"answer_id": 2027167,
"author": "NFPPW",
"author_id": 246341,
"author_profile": "https://Stackoverflow.com/users/246341",
"pm_score": -1,
"selected": false,
"text": "<p>I just tend to make them fixed widths so that they add up to the total width of the page - probably only works if you are using a fixed width page. Also \"float\".</p>\n"
},
{
"answer_id": 4805310,
"author": "word5150",
"author_id": 590678,
"author_profile": "https://Stackoverflow.com/users/590678",
"pm_score": 2,
"selected": false,
"text": "<p>You need to contain the three divs. Here is an example:</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>div.contain\n{\n margin:3%;\n border: none;\n height: auto;\n width: auto;\n float: left;\n}\n\ndiv.contain div\n{\n display:inline;\n width:200px;\n height:300px;\n padding: 15px;\n margin: auto;\n border:1px solid red;\n background-color:#fffff7;\n -moz-border-radius:25px; /* Firefox */\n border-radius:25px;\n}\n</code></pre>\n\n<p>Note: border-radius attributes are optional and only work in CSS3 compliant browsers.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><div class=\"contain\">\n <div>Foo</div>\n</div>\n\n<div class=\"contain\">\n <div>Bar</div>\n</div>\n\n<div class=\"contain\">\n <div>Baz</div>\n</div>\n</code></pre>\n\n<p>Note that the divs 'foo' 'bar' and 'baz' are each held within the 'contain' div.</p>\n"
},
{
"answer_id": 4976019,
"author": "David Eison",
"author_id": 72670,
"author_profile": "https://Stackoverflow.com/users/72670",
"pm_score": 2,
"selected": false,
"text": "<p>I know people say this is a terrible idea, but it can in practice be useful if you want to do something like tile images with comments underneath them. e.g. Picasaweb uses it to display the thumbnails in an album.<br>\nSee for example/demo <a href=\"http://closure-library.googlecode.com/svn/trunk/closure/goog/demos/inline_block_quirks.html\" rel=\"nofollow\">http://closure-library.googlecode.com/svn/trunk/closure/goog/demos/inline_block_quirks.html</a> ( class goog-inline-block ; I abbreviate it to ib here )</p>\n\n<pre><code>/* below is a set of hacks to make inline-block work right on divs in IE. */\nhtml > body .ib { display:inline-block; }\n.ib {display:inline-block;position:relative;}\n* html .ib { display: inline; }\n:first-child + html .ib { display:inline; }\n</code></pre>\n\n<p>Given that CSS, set your div to class ib, and now it's magically an inline block element.</p>\n"
},
{
"answer_id": 5690467,
"author": "Cam Tullos",
"author_id": 436537,
"author_profile": "https://Stackoverflow.com/users/436537",
"pm_score": 2,
"selected": false,
"text": "<p>I would use spans or float the div left. The only problem with floating is that you have to clear the float afterwards or the containing div must have the overflow style set to auto</p>\n"
},
{
"answer_id": 7484528,
"author": "A. Bender",
"author_id": 954660,
"author_profile": "https://Stackoverflow.com/users/954660",
"pm_score": 3,
"selected": false,
"text": "<p>Just use a wrapper div with \"float: left\" and put boxes inside also containing float: left:</p>\n\n<p>CSS:</p>\n\n<pre><code>wrapperline{\nwidth: 300px;\nfloat: left;\nheight: 60px;\nbackground-color:#CCCCCC;}\n\n.boxinside{\nwidth: 50px;\nfloat: left;\nheight: 50px;\nmargin: 5px;\nbackground-color:#9C0;\nfloat:left;}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code><div class=\"wrapperline\">\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 8766107,
"author": "Paul Sweatte",
"author_id": 1113772,
"author_profile": "https://Stackoverflow.com/users/1113772",
"pm_score": 5,
"selected": false,
"text": "<p>Use <code>display:inline-block</code> with a margin and media query for IE6/7:</p>\n\n<pre><code><html>\n <head>\n <style>\n div { display:inline-block; }\n /* IE6-7 */\n @media,\n {\n div { display: inline; margin-right:10px; }\n }\n </style>\n </head>\n <div>foo</div>\n <div>bar</div>\n <div>baz</div>\n</html>\n</code></pre>\n"
},
{
"answer_id": 12575608,
"author": "omnath",
"author_id": 1839501,
"author_profile": "https://Stackoverflow.com/users/1839501",
"pm_score": 0,
"selected": false,
"text": "<p>we can do this like</p>\n\n<pre><code>.left {\n float:left;\n margin:3px;\n}\n<div class=\"left\">foo</div>\n<div class=\"left\">bar</div>\n<div class=\"left\">baz</div>\n</code></pre>\n"
},
{
"answer_id": 25396475,
"author": "Ipog",
"author_id": 3958650,
"author_profile": "https://Stackoverflow.com/users/3958650",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div class=\"cdiv\">\n<div class=\"inline\"><p>para 1</p></div>\n <div class=\"inline\">\n <p>para 1</p>\n <span>para 2</span>\n <h1>para 3</h1>\n</div>\n <div class=\"inline\"><p>para 1</p></div>\n</code></pre>\n\n<p></p>\n\n<p><a href=\"http://jsfiddle.net/f8L0y5wx/\" rel=\"nofollow\">http://jsfiddle.net/f8L0y5wx/</a></p>\n"
},
{
"answer_id": 27600870,
"author": "flairon",
"author_id": 2007147,
"author_profile": "https://Stackoverflow.com/users/2007147",
"pm_score": 3,
"selected": false,
"text": "<p>ok, for me : </p>\n\n<pre><code><style type=\"text/css\">\n div{\n position: relative;\n display: inline-block;\n width:25px;\n height:25px;\n }\n</style>\n<div>toto</div>\n<div>toto</div>\n<div>toto</div>\n</code></pre>\n"
},
{
"answer_id": 28671130,
"author": "Pankaj Bisht",
"author_id": 3611958,
"author_profile": "https://Stackoverflow.com/users/3611958",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can use this way without using any CSS -</p>\n<pre><code><table>\n <tr>\n <td>foo</td>\n </tr>\n <tr>\n <td>bar</td>\n </tr>\n <tr>\n <td>baz</td>\n </tr>\n</table>\n</code></pre>\n<p>Right now you are using block-level elements that way you are getting an unwanted result. So you can you inline elements like span, small etc.</p>\n<pre><code><span>foo</span><span>bar</span><span>baz</span>\n</code></pre>\n"
},
{
"answer_id": 33629161,
"author": "Hidayt Rahman",
"author_id": 2927228,
"author_profile": "https://Stackoverflow.com/users/2927228",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>You should use <code><span></code> instead of <code><div></code> for correct way of\n <strong>inline</strong>. because div is a block level element, and your requirement is for inline-block level elements.</p>\n</blockquote>\n\n<p>Here is html code as per your requirements : </p>\n\n<pre><code><div class=\"main-div\">\n <div>foo</div>\n <div>bar</div>\n <div>baz</div>`\n</div>\n</code></pre>\n\n<h2>You've two way to do this</h2>\n\n<hr>\n\n<ul>\n<li>using simple <code>display:inline-block;</code></li>\n<li>or using <code>float:left;</code></li>\n</ul>\n\n<p>so you've to change display property <code>display:inline-block;</code> forcefully</p>\n\n<p><strong>Example one</strong></p>\n\n<pre><code>div {\n display: inline-block;\n}\n</code></pre>\n\n<p><strong>Example two</strong> </p>\n\n<pre><code>div {\n float: left;\n}\n</code></pre>\n\n<blockquote>\n <p>you need to clear float</p>\n</blockquote>\n\n<pre><code>.main-div:after {\n content: \"\";\n clear: both;\n display: table;\n}\n</code></pre>\n"
},
{
"answer_id": 35261602,
"author": "Waah Ronald",
"author_id": 5896727,
"author_profile": "https://Stackoverflow.com/users/5896727",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div>foo</div><div>bar</div><div>baz</div>\n//solution 1\n<style>\n #div01, #div02, #div03 {\n float:left;\n width:2%;\n } \n </style>\n <div id=\"div01\">foo</div><div id=\"div02\">bar</div><div id=\"div03\">baz</div>\n\n //solution 2\n\n <style>\n #div01, #div02, #div03 {\n display:inline;\n padding-left:5px;\n } \n</style>\n<div id=\"div01\">foo</div><div id=\"div02\">bar</div><div id=\"div03\">baz</div>\n\n /* I think this would help but if you have any other thoughts just let me knw kk */\n</code></pre>\n"
},
{
"answer_id": 70798931,
"author": "Josiah Mahachi",
"author_id": 14094598,
"author_profile": "https://Stackoverflow.com/users/14094598",
"pm_score": 1,
"selected": false,
"text": "<p>This is what worked for me. I was working with bootstrap and I wanted to have radio buttons inline:</p>\n<pre><code> <div class="form-group form-inline-radio">\n <div class="form-check form-radio-outline form-radio-primary mb-3">\n <input type="radio" name="formRadio4" id="formRadio4" checked="" class="form-check-input">\n <label for="formRadio4" class="form-check-label"> Radio Outline Warning </label>\n </div>\n <div class="form-check form-radio-outline form-radio-primary mb-3">\n <input type="radio" name="formRadio4" id="formRadio4" checked="" class="form-check-input">\n <label for="formRadio4" class="form-check-label"> Radio Outline Warning </label>\n </div>\n </div>\n</code></pre>\n<p>And the CSS:</p>\n<pre><code>.form-inline-radio {\n display: flex;\n overflow: hidden;\n}\n\n.form-check {\n margin-right: 10px;\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
Given this HTML:
```
<div>foo</div><div>bar</div><div>baz</div>
```
How do you make them display inline like this:
>
> foo bar baz
>
>
>
not like this:
>
> foo
>
> bar
>
> baz
>
>
>
|
That's something else then:
```css
div.inline { float:left; }
.clearBoth { clear:both; }
```
```html
<div class="inline">1<br />2<br />3</div>
<div class="inline">1<br />2<br />3</div>
<div class="inline">1<br />2<br />3</div>
<br class="clearBoth" /><!-- you may or may not need this -->
```
|
224,617 |
<p>i have a 3 column datafile and i wanted to use splot to plot the same.
But what i want is that gnuplot plots first row (in some colour, say red) and then pauses for say 0.3 secs and then moves on to plotting next row (in other colour, not in red, say in green), pauses for 0.3 secs and then proceeds to next row....so on n so forth.</p>
<p>Any help will be greately appreciated.</p>
<p>thanks in advance</p>
<p>Regards Pankaj</p>
|
[
{
"answer_id": 224680,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to produce an animation, you better use specialized tools for it (like mplayer).</p>\n\n<p>Use gnuplot to prepare all source images (first one with single row plotted, second - with two lines, etc), then use mplayer or convert (from imagemagic) to produce avi or animated GIF out of source files.</p>\n\n<p>You can use the following shell snippet to produce partial copies of the input file, each with increasing number of lines.</p>\n\n<pre><code>file=\"your input file.dat\"\nlines=$(wc -l $file)\ni=1\nwhile [ $i -le $lines ] ; do\n head -${i} ${file} > ${file%.dat}-${i}lines.dat\ndone\n</code></pre>\n\n<p>Given somefile.dat this will produce files \"somefile-1lines.dat\", \"somefile-2lines.dat\", etc. Then you can use:</p>\n\n<pre><code>for f in *lines.dat ; do\n gnuplot ... $f \ndone\n</code></pre>\n\n<p>to plot them all in sequence.</p>\n\n<p>If my assumption is wrong and all you really want is this pause, then you can try to set things up so that gnuplot will get data from stdin, and then use this scipt (name it paused-input.sh) to pipe input file with pauses after each line:</p>\n\n<pre><code>#!/bin/bash\nwhile read l ; do\n echo \"$l\"\n sleep 1\ndone\n</code></pre>\n\n<p>Then invoke it like this:</p>\n\n<pre><code>(pause-input.sh | gnuplot ...) < somefile.dat\n</code></pre>\n"
},
{
"answer_id": 2343408,
"author": "Pankaj",
"author_id": 282223,
"author_profile": "https://Stackoverflow.com/users/282223",
"pm_score": 2,
"selected": false,
"text": "<p>Good attempt but...\nThis will create as many files as the number of lines in data file.\nThis looks ugly to me.</p>\n\n<p>We can write a shell/perl script to create gnuplot script with commands in it like:</p>\n\n<pre><code>splot x1 y1 z1\npause 1\nreplot x2 y2 z2\npause 1\nreplot x3 y3 z3\npause 1\nreplot x4 y4 z4\n</code></pre>\n\n<p>where xi, yi, zi = coordinates in data file for ith line number.\npause 1 will pause it for one sec.</p>\n\n<p>This is just an idea, though am not sure how to plot coordinates directly instead of supplying a data file to gnuplot.</p>\n"
},
{
"answer_id": 2538780,
"author": "Born2Smile",
"author_id": 250287,
"author_profile": "https://Stackoverflow.com/users/250287",
"pm_score": 0,
"selected": false,
"text": "<p>make a plotfile eg. 'myplotfile.plt'. and put in it all the commands you would normally type in gnuplot to plot your graphs.</p>\n\n<p>then just add the line</p>\n\n<pre><code>!sleep $Number_of_Seconds_to_Pause</code></pre>\n\n<p>to your plot file where you want it to pause, and run it from the terminal with</p>\n\n<pre><code>gnuplot myplotfile.plt</code></pre>\n\n<p>(the extension of the plotfile doesn't matter, if you're on a windows or mac box you might like to use .txt)</p>\n\n<p>example of plotfile:</p>\n\n<pre><code>set title 'x squared'\nplot x**2 title ''\n!sleep 5\nset title 'x cubed'\nplot x**3 title ''\n!sleep 5</code></pre>\n"
},
{
"answer_id": 14205246,
"author": "Hugo Heden",
"author_id": 1956362,
"author_profile": "https://Stackoverflow.com/users/1956362",
"pm_score": 2,
"selected": false,
"text": "<p>To get the effect of drawing each line <em>one at a time</em> (with a little pause in between) is perhaps easier with the current version of gnuplot (it's been over 4 years since this question was posted).</p>\n\n<p>You can use a <code>for</code>-loop, and the <code>every</code> keyword, like this:</p>\n\n<pre><code># Find out the number of lines in the data somehow, \n# for example like this:\nnum_lines=\"`cat my_datafile.d | wc -l`\"\n\n# Plot the first line in the data-file:\nplot './my_datafile.d' every 1::0::0\n\n# For the remaining lines:\ndo for [line_index = 1:num_lines-1] { \n pause 0.3\n # Replot (from the same datafile) each line \n # in the data file from the first one up to \n # the current line_index \n replot '' every 1::0::line_index\n}\n</code></pre>\n\n<p>The <code>every 1::0::line_index</code> part instructs gnuplot -- in each loop -- to draw each and every line (the <code>1</code>) in the data from the first one (the <code>0</code>) up to the current value of of the loop variable <code>line_index</code>. What we are using is the <code><point_incr></code>, <code><start_point></code> and <code><end_point></code> referred to in gnuplot's help text:</p>\n\n<pre><code> gnuplot> help every\n The `every` keyword allows a periodic sampling of a data set to be plotted.\n [...]\n\n Syntax:\n plot 'file' every {<point_incr>}\n {:{<block_incr>}\n {:{<start_point>}\n {:{<start_block>}\n {:{<end_point>}\n {:<end_block>}}}}}\n [...]\n</code></pre>\n\n<p>Version info:</p>\n\n<pre><code>$ gnuplot --version\ngnuplot 4.6 patchlevel 0\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
i have a 3 column datafile and i wanted to use splot to plot the same.
But what i want is that gnuplot plots first row (in some colour, say red) and then pauses for say 0.3 secs and then moves on to plotting next row (in other colour, not in red, say in green), pauses for 0.3 secs and then proceeds to next row....so on n so forth.
Any help will be greately appreciated.
thanks in advance
Regards Pankaj
|
If you want to produce an animation, you better use specialized tools for it (like mplayer).
Use gnuplot to prepare all source images (first one with single row plotted, second - with two lines, etc), then use mplayer or convert (from imagemagic) to produce avi or animated GIF out of source files.
You can use the following shell snippet to produce partial copies of the input file, each with increasing number of lines.
```
file="your input file.dat"
lines=$(wc -l $file)
i=1
while [ $i -le $lines ] ; do
head -${i} ${file} > ${file%.dat}-${i}lines.dat
done
```
Given somefile.dat this will produce files "somefile-1lines.dat", "somefile-2lines.dat", etc. Then you can use:
```
for f in *lines.dat ; do
gnuplot ... $f
done
```
to plot them all in sequence.
If my assumption is wrong and all you really want is this pause, then you can try to set things up so that gnuplot will get data from stdin, and then use this scipt (name it paused-input.sh) to pipe input file with pauses after each line:
```
#!/bin/bash
while read l ; do
echo "$l"
sleep 1
done
```
Then invoke it like this:
```
(pause-input.sh | gnuplot ...) < somefile.dat
```
|
224,624 |
<p>This error comes out whenever I click the datagrid.</p>
<p>The program does fill the datagrid every time data was selected in the combobox.</p>
<p>For example, I choose data1 which has four records in datagrid, and then I click row index no 1. No problem, it will be shown, but when I choose another data again in combobox, for example, Data 2 has only one record then I will again click the datagrid.</p>
<p>This is the time that error will pop up.</p>
<p>Please see the code on how I fill the data grid:</p>
<pre><code>Sub FillDtgPir(ByVal qry As String)
Try
If SQLConn1.State = ConnectionState.Closed Then SQLConn1.Open()
Dim adap As New SqlDataAdapter(qry, SQLConn1)
Me.DtsLineReq1.PRRMS_PIR.Clear()
adap.Fill(Me.DtsLineReq1, "PRRMS_PIR")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
</code></pre>
<p>Is there missing something in the code?</p>
|
[
{
"answer_id": 224632,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 1,
"selected": false,
"text": "<p>If the selected row index is larger than the largest index (number of rows minus one) in the new data, then decrease the row index as necessary before doing the fill? Or check the reason for the exception and decrease the row index instead of displaying the error message?</p>\n"
},
{
"answer_id": 224694,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 0,
"selected": false,
"text": "<p>When refilling the datagrid - make sure you reset the selected row (which is what I'd expect the Clear() to do).</p>\n\n<p>An index outside the bounds of the array is usually caused by you trying to see a row that isn't there anymore. Do you have a pointer to the current row in the datagrid anywhere? </p>\n\n<p>Is anything happening in the datagrid click event?</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This error comes out whenever I click the datagrid.
The program does fill the datagrid every time data was selected in the combobox.
For example, I choose data1 which has four records in datagrid, and then I click row index no 1. No problem, it will be shown, but when I choose another data again in combobox, for example, Data 2 has only one record then I will again click the datagrid.
This is the time that error will pop up.
Please see the code on how I fill the data grid:
```
Sub FillDtgPir(ByVal qry As String)
Try
If SQLConn1.State = ConnectionState.Closed Then SQLConn1.Open()
Dim adap As New SqlDataAdapter(qry, SQLConn1)
Me.DtsLineReq1.PRRMS_PIR.Clear()
adap.Fill(Me.DtsLineReq1, "PRRMS_PIR")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
```
Is there missing something in the code?
|
If the selected row index is larger than the largest index (number of rows minus one) in the new data, then decrease the row index as necessary before doing the fill? Or check the reason for the exception and decrease the row index instead of displaying the error message?
|
224,635 |
<p>I'm trying to program ARM using Eclipse + CDT + yagarto (gnu toolchain) + OpenOCD. In several sample projects (from yagarto site for example) I found linker scripts (*.ld) where a lot of linking information specified (along with sections definitions). Actually I haven't faced this files before (IAR doesn't need them), and I find them somewhat difficult to understand from a first glance. So my question is can I use one single such script file for my target processor (STR710FZ2T6) with all my projects or I have to get familiar in writing this scripts and write them for each project. If I can use single file for all projects for particular target processor can you please advice where I can find such universal one.</p>
|
[
{
"answer_id": 264564,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 0,
"selected": false,
"text": "<p>There is not a universal linker script. These scripts are very important, since they define where in memory (RAM or ROM) the various data and program sections will be placed. There is something equivalent in IAR compilers (xcl files if I remember correctly). You've obviously only used the default ones until now. </p>\n\n<p>There is a nice document about STR7xx called \"Using Open Source Tools for STR7xx Cross\nDevelopment\". You can find a link in yagarto homepage. I recommend that you have a look at it and try to understand how linker files work. There are also some other configuration files that you need to have some understanding of.</p>\n"
},
{
"answer_id": 871532,
"author": "old_timer",
"author_id": 16007,
"author_profile": "https://Stackoverflow.com/users/16007",
"pm_score": 3,
"selected": true,
"text": "<p>My guess is every third person has a different script or solution. There are a number of problems that have to be solved, different linkers are going to solve those in different ways. I think GNU has made it way too difficult if not black magic.</p>\n\n<p>For an embedded system you are often going to have a flash or eeprom or some other form of read only memory to boot from. Like other processors the ARM has a vector table to tell it essentially where the reset code is and interrupt, etc. So that table has to be in a specific place and you have to tell the linker to put it in that specific place (first).</p>\n\n<p>One of the scripts I like to use is:</p>\n\n<pre><code>MEMORY\n{\n bob (RX) : ORIGIN = 0x0000000, LENGTH = 32K\n joe (WAIL) : ORIGIN = 0x2000000, LENGTH = 256K\n}\n\nSECTIONS\n{\n JANE : { startup.o } >bob\n}\n</code></pre>\n\n<p>I usually use ram and rom as names instead of bob and joe but demonstrating here that it doesnt matter what the names are they are just labels.</p>\n\n<p>Another variation on the theme:</p>\n\n<pre><code>MEMORY\n{\n rom(RX) : ORIGIN = 0x00000000, LENGTH = 0x8000\n ram(WAIL) : ORIGIN = 0x20000000, LENGTH = 0x2000\n}\n\nSECTIONS\n{\n .text : { *(.text*) } > rom\n}\n</code></pre>\n\n<p>The first one allows you to put the files on the linker command line in any order but you have to have the vector table in the startup.o file. The latter lets you use whatever filenames but the first file on the linker script needs to have the vector table.</p>\n\n<pre><code>arm-thumb-elf-gcc -Wall $(COPS) vectors.o putget.o blinker2.c -T memmap -o blinker2.elf\n</code></pre>\n\n<p>Or with ld directly</p>\n\n<pre><code>arm-thumb-elf-ld vectors.o putget.o blinker2.o -T memmap -o blinker2.elf\n</code></pre>\n\n<p>The RX tells the linker to put read and execute stuff in that memory section and the WAIL is basically everything else. If you only have one ram for example you can put all the flags RXWAIL on the line that tells where the ram is. Depending on your loader in that case you can rely on the elf file telling the loader where to branch to to start or you can simply make the entry point the beginning of the binary and the loader can be simpler. The arms (not the cortex-m3) have a branch instruction as the first vector for the reset vector so you can just pretend to build a vector table anyway for a ram solution and will just work.</p>\n\n<p>The are a number of problems with this solution that dont happen to bother me. I initialize variables in my code, not during declaration.</p>\n\n<p>This</p>\n\n<pre><code>int rx;\n\nint main ( void )\n{\n rx = 7;\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>int rx=7;\n\nint main ( void )\n{\n</code></pre>\n\n<p>I also never assume that a variable is zero when the code starts I always initialize it to something before I start. Your startup code plus linker script as a team can work together to make it easier to automate the resetting of the bss code and copying non-zero init data from rom to ram on boot. (that int rx=7; above requires some code that copies the value 7 from somewhere in rom and writes it to the memory location in ram allocated for the variable rx so that when main() starts the 7 is there.</p>\n\n<p>My boot code is also quite simple as a result of this method:</p>\n\n<pre><code>.globl _start\n_start:\n b reset\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n\nhang : b hang\n\nreset:\n ldr sp,=0x10004000\n bl main\n b hang\n</code></pre>\n\n<p>You are going to see or read about solutions that allow the startup code and the linker script to work together to not have to hardcode stack pointers, heap space, things like that, again you can put a lot of work into complicated startup code and linker scripts to gain some automation and perhaps save some work, perhaps not. The automation, if/when working can and will reduce human error and that can be a good thing, also if you are switching chips often or trying to write one bit of code that works in a family of chips you may want this automation as well.</p>\n\n<p>My bottom line is YES you can live with only one linker script for all of your ARM work. But you have to tailor your work to that script. You are likely not going to find one script that works with everyones example code. The more complicated the script the harder it will be to borrow. Yes, my scripts above can likely be done on the ld command line, but way back when (gcc 2.95) I couldnt get that to work so developed the minimal script above and have been using them ever since. Had to modify to the second script for some reason but with 4.x.x, certainly 4.4.x I am able to use either one.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14535/"
] |
I'm trying to program ARM using Eclipse + CDT + yagarto (gnu toolchain) + OpenOCD. In several sample projects (from yagarto site for example) I found linker scripts (\*.ld) where a lot of linking information specified (along with sections definitions). Actually I haven't faced this files before (IAR doesn't need them), and I find them somewhat difficult to understand from a first glance. So my question is can I use one single such script file for my target processor (STR710FZ2T6) with all my projects or I have to get familiar in writing this scripts and write them for each project. If I can use single file for all projects for particular target processor can you please advice where I can find such universal one.
|
My guess is every third person has a different script or solution. There are a number of problems that have to be solved, different linkers are going to solve those in different ways. I think GNU has made it way too difficult if not black magic.
For an embedded system you are often going to have a flash or eeprom or some other form of read only memory to boot from. Like other processors the ARM has a vector table to tell it essentially where the reset code is and interrupt, etc. So that table has to be in a specific place and you have to tell the linker to put it in that specific place (first).
One of the scripts I like to use is:
```
MEMORY
{
bob (RX) : ORIGIN = 0x0000000, LENGTH = 32K
joe (WAIL) : ORIGIN = 0x2000000, LENGTH = 256K
}
SECTIONS
{
JANE : { startup.o } >bob
}
```
I usually use ram and rom as names instead of bob and joe but demonstrating here that it doesnt matter what the names are they are just labels.
Another variation on the theme:
```
MEMORY
{
rom(RX) : ORIGIN = 0x00000000, LENGTH = 0x8000
ram(WAIL) : ORIGIN = 0x20000000, LENGTH = 0x2000
}
SECTIONS
{
.text : { *(.text*) } > rom
}
```
The first one allows you to put the files on the linker command line in any order but you have to have the vector table in the startup.o file. The latter lets you use whatever filenames but the first file on the linker script needs to have the vector table.
```
arm-thumb-elf-gcc -Wall $(COPS) vectors.o putget.o blinker2.c -T memmap -o blinker2.elf
```
Or with ld directly
```
arm-thumb-elf-ld vectors.o putget.o blinker2.o -T memmap -o blinker2.elf
```
The RX tells the linker to put read and execute stuff in that memory section and the WAIL is basically everything else. If you only have one ram for example you can put all the flags RXWAIL on the line that tells where the ram is. Depending on your loader in that case you can rely on the elf file telling the loader where to branch to to start or you can simply make the entry point the beginning of the binary and the loader can be simpler. The arms (not the cortex-m3) have a branch instruction as the first vector for the reset vector so you can just pretend to build a vector table anyway for a ram solution and will just work.
The are a number of problems with this solution that dont happen to bother me. I initialize variables in my code, not during declaration.
This
```
int rx;
int main ( void )
{
rx = 7;
```
instead of
```
int rx=7;
int main ( void )
{
```
I also never assume that a variable is zero when the code starts I always initialize it to something before I start. Your startup code plus linker script as a team can work together to make it easier to automate the resetting of the bss code and copying non-zero init data from rom to ram on boot. (that int rx=7; above requires some code that copies the value 7 from somewhere in rom and writes it to the memory location in ram allocated for the variable rx so that when main() starts the 7 is there.
My boot code is also quite simple as a result of this method:
```
.globl _start
_start:
b reset
b hang
b hang
b hang
b hang
b hang
b hang
b hang
b hang
b hang
b hang
b hang
b hang
b hang
b hang
hang : b hang
reset:
ldr sp,=0x10004000
bl main
b hang
```
You are going to see or read about solutions that allow the startup code and the linker script to work together to not have to hardcode stack pointers, heap space, things like that, again you can put a lot of work into complicated startup code and linker scripts to gain some automation and perhaps save some work, perhaps not. The automation, if/when working can and will reduce human error and that can be a good thing, also if you are switching chips often or trying to write one bit of code that works in a family of chips you may want this automation as well.
My bottom line is YES you can live with only one linker script for all of your ARM work. But you have to tailor your work to that script. You are likely not going to find one script that works with everyones example code. The more complicated the script the harder it will be to borrow. Yes, my scripts above can likely be done on the ld command line, but way back when (gcc 2.95) I couldnt get that to work so developed the minimal script above and have been using them ever since. Had to modify to the second script for some reason but with 4.x.x, certainly 4.4.x I am able to use either one.
|
224,637 |
<p>I'm trying to use multiple attributes in my custom tag, e.g.:</p>
<pre><code><mytaglib:mytag firstname="Thadeus" lastname="Jones" />
</code></pre>
<p>How can I access the attributes in the TagHandler code?</p>
|
[
{
"answer_id": 224649,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 1,
"selected": true,
"text": "<p>Not really the answer to what you asked, but I hate (ie have never written) TagHandler's but I love <a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html\" rel=\"nofollow noreferrer\">tag files</a>. Lets you write custom tags using jsp files. You probably know about them and are not available/applicable - but thought I'd mention them just in case.</p>\n"
},
{
"answer_id": 224690,
"author": "LizB",
"author_id": 13616,
"author_profile": "https://Stackoverflow.com/users/13616",
"pm_score": 2,
"selected": false,
"text": "<p>In order to access the parameters your TagHandler class should define the private members and provide accessor methods.</p>\n\n<pre><code>public class TagHandler extends TagSupport {\n private String firstName;\n private String lastName;\n\n public void setFirstName(String firstname) { firstName = firstname; }\n public void setLastName(String lastname) { lastName = lastname;}\n}\n</code></pre>\n\n<p>you can then access the parameters through the TagHandler variables.</p>\n\n<pre><code>public int doStartTag() throws JspException {\n pageContext.getOut().print(lastName + \", \" + firstName);\n}\n</code></pre>\n\n<p>If you still have problems double check your naming conventions, the Java interpeter is trying to guess what the setter method is. So if your parameter is \"FirstName\" than the set method must be \"setFirstName\" if the parameter is \"lastname\" the set parameter must be \"setlastname\". I perfer to follow the former, since it is the standard Java naming convention.</p>\n"
},
{
"answer_id": 45534831,
"author": "Sachindra N. Pandey",
"author_id": 3977387,
"author_profile": "https://Stackoverflow.com/users/3977387",
"pm_score": -1,
"selected": false,
"text": "<p>To demonstrate the solution of this problem lets take an analogy . Suppose we have \"userName\" and \"password\" which is retrieved from index.jsp and we have to pass our data in custom tag attribute. In my case its working</p>\n\n<pre><code><body>\n\n<%\nString name=request.getParameter(\"name\");\nString password=request.getParameter(\"password\");\n%>\n\n<%@ taglib prefix=\"c\" uri=\"/WEB-INF/mytag.tld\" %>\n\n<c:logintag name=\"<%=name %>\" password=\"<%=password %>\"/>\n</code></pre>\n\n<p></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28557/"
] |
I'm trying to use multiple attributes in my custom tag, e.g.:
```
<mytaglib:mytag firstname="Thadeus" lastname="Jones" />
```
How can I access the attributes in the TagHandler code?
|
Not really the answer to what you asked, but I hate (ie have never written) TagHandler's but I love [tag files](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html). Lets you write custom tags using jsp files. You probably know about them and are not available/applicable - but thought I'd mention them just in case.
|
224,646 |
<pre><code>Double out = otherTypes.someMethod(c, c2);
assertEquals((Double)-1.0D, out);
</code></pre>
<p>I get error "Double cannot be resolved" (the Double in assertEquals), is there any way to hack around it except extracting variable?</p>
<p>Is this bug in Java or just very usefull feature that wont be fix?</p>
|
[
{
"answer_id": 224685,
"author": "Johann Zacharee",
"author_id": 24290,
"author_profile": "https://Stackoverflow.com/users/24290",
"pm_score": 2,
"selected": false,
"text": "<p>My variation is similar to jjnguy's</p>\n\n<pre><code>assertEquals(Double.valueOf(-1.0D), out)\n</code></pre>\n\n<p>This biggest difference is Double.valueOf can returned a cached copy rather than having to create a new object.</p>\n"
},
{
"answer_id": 224757,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 3,
"selected": false,
"text": "<p>One important note: Because of the way floating point numbers work, you should never compare two doubles (or floating point numbers generally spoken) for equality directly, always compare if their difference is within a specified delta: <code>abs(double1 - double2) < delta</code>. </p>\n\n<p>JUnit has an <code>assertEquals(double expected, double actual, double delta)</code> method to do exactly that. That said, you should probably use something like </p>\n\n<pre><code>assertEquals(-1.0d, (double) out, 0.000001d)\n</code></pre>\n\n<p>in your code.</p>\n\n<p>You can find more on the tricks and traps of floating point number in for example in one of Brian Goetz's articles: <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp0114/\" rel=\"nofollow noreferrer\">\"Where's your point?\"</a></p>\n"
},
{
"answer_id": 224937,
"author": "jassuncao",
"author_id": 1009,
"author_profile": "https://Stackoverflow.com/users/1009",
"pm_score": 0,
"selected": false,
"text": "<p>My suggestion when you want to check if two doubles are exactly the same:</p>\n\n<pre><code>assertEquals(Double.doubleToLongBits(-1.0), Double.doubleToLongBits(out));\n</code></pre>\n"
},
{
"answer_id": 225335,
"author": "Miserable Variable",
"author_id": 18573,
"author_profile": "https://Stackoverflow.com/users/18573",
"pm_score": 0,
"selected": false,
"text": "<p>This goes through the compiler:</p>\n\n<pre><code>assertEquals(Double.class.cast(-1.0D), out);\n</code></pre>\n"
},
{
"answer_id": 227375,
"author": "Sam",
"author_id": 13979,
"author_profile": "https://Stackoverflow.com/users/13979",
"pm_score": 1,
"selected": false,
"text": "<p>To convert -1.0D to a Double, the best way us usually to use Double.valueOf(-1.0D). The Double class caches the results of calls to valueOf so that you won't always be creating a new object on the heap. But even better is to convert out to a double, which is cheaper. Use <code>out.doubleValue()</code> to get the value as a double. The only caveat is that out might be null, which is a separate case that is probably worth detecting in its own right.</p>\n\n<p>You should also be wary of floating-point inaccuracies when testing direct equality this way. Two numbers that are theoretically equal may not have representations that are exactly equal because there is some rounding error introduced with most floating-point operations. A simple solution that would work in this case is to test if the difference is less than some delta:</p>\n\n<pre><code>assertTrue(Math.abs(-1.0D-out.doubleValue()) < delta);\n</code></pre>\n\n<p>You can also use JUnit's convenience method for doing just this:</p>\n\n<pre><code>assertEquals(-1.0d, out.doubleValue(), delta);\n</code></pre>\n\n<p>Use a very small value for delta, like 10E-10, or something appropriate for your application. In the most general case, if you don't know the range of the values you're comparing, you need to multiply the delta by the relative size of each number, like so:</p>\n\n<pre><code>double tDelta = delta*(Math.abs(-1.0D)+Math.abs(out.doubleValue()));\nassertEquals(-1.0d, out.doubleValue(), tDelta);\n</code></pre>\n\n<p>If you're comparing very huge numbers, you want the allowed delta to be larger, and if you're comparing very small numbers you want the allowed delta to be smaller. But for your case you know one of your parameters beforehand, so you can just hard-code the delta.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
Double out = otherTypes.someMethod(c, c2);
assertEquals((Double)-1.0D, out);
```
I get error "Double cannot be resolved" (the Double in assertEquals), is there any way to hack around it except extracting variable?
Is this bug in Java or just very usefull feature that wont be fix?
|
One important note: Because of the way floating point numbers work, you should never compare two doubles (or floating point numbers generally spoken) for equality directly, always compare if their difference is within a specified delta: `abs(double1 - double2) < delta`.
JUnit has an `assertEquals(double expected, double actual, double delta)` method to do exactly that. That said, you should probably use something like
```
assertEquals(-1.0d, (double) out, 0.000001d)
```
in your code.
You can find more on the tricks and traps of floating point number in for example in one of Brian Goetz's articles: ["Where's your point?"](http://www.ibm.com/developerworks/java/library/j-jtp0114/)
|
224,648 |
<p>What is an external and internal iterator in Java ?</p>
|
[
{
"answer_id": 224657,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>It is about <a href=\"http://gafter.blogspot.com/2007/07/internal-versus-external-iterators.html\" rel=\"nofollow noreferrer\">who controls the iteration</a></p>\n<p>Other details are in this question <a href=\"https://stackoverflow.com/questions/89891/what-are-the-benefits-of-the-iterator-interface-in-java\">What are the benefits of the Iterator interface in Java?</a></p>\n"
},
{
"answer_id": 224663,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 4,
"selected": false,
"text": "<p>I found this <a href=\"http://www.oodesign.com/iterator-pattern.html\" rel=\"nofollow noreferrer\">description</a>:</p>\n\n<p>External vs. internal iterators.</p>\n\n<p>External Iterators - when the iteration is controlled by the collection object we say that we have an external Iterator. </p>\n\n<p>In languages like .net or java it's very easy to create external iterators. In our classical implementation an external iterator is implemented. In the following example an external iterator is used: </p>\n\n<pre><code>// using iterators for a clloection of String objects:\n// using in a for loop\nfor (Iterator it = options.iterator(); it.hasNext(); ) {\n String name = (String)it.next();\n System.out.println(name);\n}\n\n// using in while loop\nIterator name = options.iterator();\n while (name.hasNext() ){\n System.out.println(name.next() );\n }\n\n// using in a for-each loop (syntax available from java 1.5 and above)\n for (Object item : options)\n System.out.println(((String)item));\n</code></pre>\n\n<p>Internal Iterators - When the iterator controls it we have an internal iterator </p>\n\n<p>On the other side implementing and using internal iterators is really difficult. When an internal iterator is used it means that the code is be run is delegated to the aggregate object. For example in languages that offer support for this is easy to call internal iterators:</p>\n\n<pre><code>collection do: [:each | each doSomething] (Smalltalk) \n</code></pre>\n\n<p>The main idea is to pass the code to be executed to the collection. Then the collection will call internally the doSomething method on each of the components. In C++ it's possible to send the doMethod method as a pointer. In C#, .NET or VB.NET it is possible to send the method as a delegate. In java the <code>Functor</code> design pattern has to be used. The main idea is to create a base Interface with only one method (doSomething). Then the method will be implemented in a class which implements the interface and the class will be passed to the collection to iterate. For more details see the <code>Functor</code> design pattern. </p>\n"
},
{
"answer_id": 224675,
"author": "Johann Zacharee",
"author_id": 24290,
"author_profile": "https://Stackoverflow.com/users/24290",
"pm_score": 5,
"selected": false,
"text": "<h1>External Iterator</h1>\n\n<p>When you get an iterator and step over it, that is an external iterator</p>\n\n<pre><code>for (Iterator iter = var.iterator(); iter.hasNext(); ) {\n Object obj = iter.next();\n // Operate on obj\n}\n</code></pre>\n\n<h1>Internal Iterator</h1>\n\n<p>When you pass a function object to a method to run over a list, that is an internal iterator</p>\n\n<pre><code>var.each( new Functor() {\n public void operate(Object arg) {\n arg *= 2;\n }\n});\n</code></pre>\n"
},
{
"answer_id": 51666760,
"author": "Manas Kumar Maharana",
"author_id": 6482564,
"author_profile": "https://Stackoverflow.com/users/6482564",
"pm_score": 0,
"selected": false,
"text": "<p><strong>External Iterator</strong> :- Using this we have to iterate all element one-by-one and do some operation because programmer does have control on that, its a External Iterator.</p>\n\n<p><strong>Internal Iterator</strong> :- Using this we can iterate according to our condition, Programmer can control over on it, its a Internal Iterator .</p>\n\n<p>Lets see one example below :\n<strong>Q - we want to add sum on integer from a list which is equal or more that 5.</strong></p>\n\n<pre><code>package java8;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class IteratorExpr {\n\n public static void main(String[] args) {\n List<Integer> myList = new ArrayList<Integer>();\n for(int i=0; i<10; i++) myList.add(i);\n\n //Get sum of all value which is more than 5 using External Iterator\n int sum = 0;\n for(int no: myList) {\n if(no >=5) {\n sum += no;\n }\n }\n System.out.println(\"Sum of numbers using External api : \"+sum);\n\n int summ = myList.stream()\n .filter(p->p>=5)\n .mapToInt(p->p).sum();\n System.out.println(\"Sum of numbers using internal api : \"+summ);\n }\n\n}\n</code></pre>\n\n<p>Output : </p>\n\n<pre><code>Sum of numbers using External api : 35\nSum of numbers using internal api : 35\n</code></pre>\n"
},
{
"answer_id": 51810958,
"author": "Kishon",
"author_id": 10215524,
"author_profile": "https://Stackoverflow.com/users/10215524",
"pm_score": 1,
"selected": false,
"text": "<p>I found the answer over <a href=\"https://www.quora.com/What-are-differences-between-External-Iterators-vs-Internal-Iterators-in-Java-8\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Internal Iterators manage the iterations in the background. This leaves the programmer to just declaratively code what is meant to be done with the elements of the Collection, rather than managing the iteration and making sure that all the elements are processed one-by-one.\nEx:</p>\n\n<pre><code>public class InternalIterator {\n\n public static void main(String args[]){\n\n List<String> namesList=Arrays.asList(\"Tom\", \"Dick\", \"Harry\");\n\n namesList.forEach(name -> System.out.println(name));//Internal Iteration\n\n }\n\n}\n</code></pre>\n\n<p>With external iterators responsibility of iterating over the elements, and making sure that this iteration takes into account the total number of records, whether more records exist to be iterated and so on lies with the programmer.</p>\n\n<p>Ex:</p>\n\n<pre><code>import java.util.*;\n\npublic class ExternalIterator {\n\n public static void main(String args[]){\n List<String> namesList=Arrays.asList(\"Tom\", \"Dick\", \"Harry\");\n for(String name:namesList){\n System.out.println(name);\n }\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 52987994,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Example of external iterator: </p>\n\n<pre><code>int count = 0;\nIterator<SomeStaff> iterator = allTheStaffs.iterator();\nwhile(iterator.hasNext()) {\n SomeStaff staff = iterator.next();\n if(staff.getSalary() > 25) {\n count++;\n }\n}\n</code></pre>\n\n<p>Example of internal iterator:</p>\n\n<pre><code>long count = allTheStaffs.stream()\n .filter(staff -> staff.getSalary() > 25)\n .count();\n</code></pre>\n\n<p>In images:</p>\n\n<p><a href=\"https://i.stack.imgur.com/556uD.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/556uD.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What is an external and internal iterator in Java ?
|
External Iterator
=================
When you get an iterator and step over it, that is an external iterator
```
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}
```
Internal Iterator
=================
When you pass a function object to a method to run over a list, that is an internal iterator
```
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});
```
|
224,658 |
<p>I implemented a small OOP library in Lua, and two things are not quite right yet. I need your advice!</p>
<h2>How to call super()?</h2>
<p>I need to make a choice. The three arguments I need to resolve a call to super() are:</p>
<ul>
<li>The class from where the call is being made (CallerClass)</li>
<li>The instance to be passed (self)</li>
<li>The name of the method (method)</li>
</ul>
<p>I hesitate between these three forms:</p>
<pre><code>--# Current way:
self:super(CallerClass):method()
--# Variant, which I now find cleaner:
CallerClass:super(self):method()
--# Python style, which is nice too:
super(CallerClass, self):method()
</code></pre>
<p>Which one looks nicer and or easier to remember to you?</p>
<h2>Do I need a Class symbol?</h2>
<p>In the current version, the only concept is a table named <code>Object</code>, which you can subclass. I have another version where I introduced a Class symbol.</p>
<p>Its use is to tell instances from classes. I.e. :</p>
<pre><code>assert(Object:isKindOf(Class))
local object = Object:new()
assert(not object:isKindOf(Class))
</code></pre>
<p>I find it very handy to document and enforce that a method must be called from a class, by starting the method with:</p>
<pre><code>assert(self:isKindOf(Class))
</code></pre>
<p>Is it usefull in Lua? What do you think? Thanks!</p>
|
[
{
"answer_id": 224682,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 2,
"selected": true,
"text": "<pre><code>--# Python style, which is nice too:\nsuper(CallerClass, self):method()\n</code></pre>\n"
},
{
"answer_id": 224684,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 1,
"selected": false,
"text": "<p>I would say have a class object - more info/metadata is better</p>\n"
},
{
"answer_id": 229138,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks Chris, done.</p>\n\n<p>For those interested, the code is published on the Lua Users Wiki, see <a href=\"http://lua-users.org/wiki/ObjectLua\" rel=\"nofollow noreferrer\">ObjectLua</a>.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] |
I implemented a small OOP library in Lua, and two things are not quite right yet. I need your advice!
How to call super()?
--------------------
I need to make a choice. The three arguments I need to resolve a call to super() are:
* The class from where the call is being made (CallerClass)
* The instance to be passed (self)
* The name of the method (method)
I hesitate between these three forms:
```
--# Current way:
self:super(CallerClass):method()
--# Variant, which I now find cleaner:
CallerClass:super(self):method()
--# Python style, which is nice too:
super(CallerClass, self):method()
```
Which one looks nicer and or easier to remember to you?
Do I need a Class symbol?
-------------------------
In the current version, the only concept is a table named `Object`, which you can subclass. I have another version where I introduced a Class symbol.
Its use is to tell instances from classes. I.e. :
```
assert(Object:isKindOf(Class))
local object = Object:new()
assert(not object:isKindOf(Class))
```
I find it very handy to document and enforce that a method must be called from a class, by starting the method with:
```
assert(self:isKindOf(Class))
```
Is it usefull in Lua? What do you think? Thanks!
|
```
--# Python style, which is nice too:
super(CallerClass, self):method()
```
|
224,660 |
<p>Hi Guys could you please help me refactor this so that it is sensibly pythonic.</p>
<pre><code>import sys
import poplib
import string
import StringIO, rfc822
import datetime
import logging
def _dump_pop_emails(self):
self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1]))
self.popinstance = poplib.POP3(self.account[0])
self.logger.info(self.popinstance.getwelcome())
self.popinstance.user(self.account[1])
self.popinstance.pass_(self.account[2])
try:
(numMsgs, totalSize) = self.popinstance.stat()
for thisNum in range(1, numMsgs+1):
(server_msg, body, octets) = self.popinstance.retr(thisNum)
text = string.join(body, '\n')
mesg = StringIO.StringIO(text)
msg = rfc822.Message(mesg)
name, email = msg.getaddr("From")
emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
emailpath = self._replace_whitespace(emailpath)
file = open(emailpath,"wb")
file.write(text)
file.close()
self.popinstance.dele(thisNum)
finally:
self.logger.info(self.popinstance.quit())
def _replace_whitespace(self,name):
name = str(name)
return name.replace(" ", "_")
</code></pre>
<p>Also in the _replace_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing.</p>
<p>Basically I want to write the email to the inbox directory in a standard way.</p>
<p>Am i doing something wrong here?</p>
|
[
{
"answer_id": 224713,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>I don't see anything significant wrong with that code -- is it behaving incorrectly, or are you just looking for general style guidelines?</p>\n\n<p>A few notes:</p>\n\n<ol>\n<li>Instead of <code>logger.info (\"foo %s %s\" % (bar, baz))</code>, use <code>\"foo %s %s\", bar, baz</code>. This avoids the overhead of string formatting if the message won't be printed.</li>\n<li>Put a <code>try...finally</code> around opening <code>emailpath</code>.</li>\n<li>Use <code>'\\n'.join (body)</code>, instead of <code>string.join (body, '\\n')</code>.</li>\n<li>Instead of <code>msg.getaddr(\"From\")</code>, just <code>msg.From</code>.</li>\n</ol>\n"
},
{
"answer_id": 224752,
"author": "Setori",
"author_id": 21537,
"author_profile": "https://Stackoverflow.com/users/21537",
"pm_score": 0,
"selected": false,
"text": "<p>Further to my comment on John's answer</p>\n\n<p>I found out what the issue was, there were illegal characters in the name field and Subject field, which caused python to get the hiccups, as it tried to write the email as a directory, after seeing \":\" and \"/\".</p>\n\n<p>John point number 4 doesnt work! so I left it as before.\nAlso is point no 1 correct, have I implemented your suggestion correctly?</p>\n\n<pre><code>def _dump_pop_emails(self):\n self.logger.info(\"open pop account %s with username: %s\", self.account[0], self.account[1])\n self.popinstance = poplib.POP3(self.account[0])\n self.logger.info(self.popinstance.getwelcome()) \n self.popinstance.user(self.account[1])\n self.popinstance.pass_(self.account[2])\n try:\n (numMsgs, totalSize) = self.popinstance.stat()\n for thisNum in range(1, numMsgs+1):\n (server_msg, body, octets) = self.popinstance.retr(thisNum)\n text = '\\n'.join(body)\n mesg = StringIO.StringIO(text) \n msg = rfc822.Message(mesg)\n name, email = msg.getaddr(\"From\")\n emailpath = str(self._emailpath + self._inboxfolder + \"\\\\\" + self._sanitize_string(email + \" \" + msg.getheader(\"Subject\") + \".eml\"))\n emailpath = self._replace_whitespace(emailpath)\n print emailpath\n file = open(emailpath,\"wb\")\n file.write(text)\n file.close()\n self.popinstance.dele(thisNum)\n finally:\n self.logger.info(self.popinstance.quit())\n\ndef _replace_whitespace(self,name):\n name = str(name)\n return name.replace(\" \", \"_\") \n\ndef _sanitize_string(self,name):\n illegal_chars = \":\", \"/\", \"\\\\\"\n name = str(name)\n for item in illegal_chars:\n name = name.replace(item, \"_\")\n return name\n</code></pre>\n"
},
{
"answer_id": 225029,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 2,
"selected": true,
"text": "<p>This isn't refactoring (it doesn't need refactoring as far as I can see), but some suggestions:</p>\n\n<p>You should use the email package rather than rfc822. Replace rfc822.Message with email.Message, and use email.Utils.parseaddr(msg[\"From\"]) to get the name and email address, and msg[\"Subject\"] to get the subject.</p>\n\n<p>Use os.path.join to create the path. This:</p>\n\n<pre><code>emailpath = str(self._emailpath + self._inboxfolder + \"\\\\\" + email + \"_\" + msg.getheader(\"Subject\") + \".eml\")\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>emailpath = os.path.join(self._emailpath + self._inboxfolder, email + \"_\" + msg.getheader(\"Subject\") + \".eml\")\n</code></pre>\n\n<p>(If self._inboxfolder starts with a slash or self._emailpath ends with one, you could replace the first + with a comma also).</p>\n\n<p>It doesn't really hurt anything, but you should probably not use \"file\" as a variable name, since it shadows a built-in type (checkers like pylint or pychecker would warn you about that).</p>\n\n<p>If you're not using self.popinstance outside of this function (seems unlikely given that you connect and quit within the function), then there's no point making it an attribute of self. Just use \"popinstance\" by itself.</p>\n\n<p>Use xrange instead of range.</p>\n\n<p>Instead of just importing StringIO, do this:</p>\n\n<pre><code>try:\n import cStringIO as StringIO\nexcept ImportError:\n import StringIO\n</code></pre>\n\n<p>If this is a POP mailbox that can be accessed by more than one client at a time, you might want to put a try/except around the RETR call to continue on if you can't retrieve one message.</p>\n\n<p>As John said, use \"\\n\".join rather than string.join, use try/finally to only close the file if it is opened, and pass the logging parameters separately.</p>\n\n<p>The one refactoring issue I could think of would be that you don't really need to parse the whole message, since you're just dumping a copy of the raw bytes, and all you want is the From and Subject headers. You could instead use popinstance.top(0) to get the headers, create the message (blank body) from that, and use that for the headers. Then do a full RETR to get the bytes. This would only be worth doing if your messages were large (and so parsing them took a long time). I would definitely measure before I made this optimisation.</p>\n\n<p>For your function to sanitise for the names, it depends how nice you want the names to be, and how certain you are that the email and subject make the filename unique (seems fairly unlikely). You could do something like:</p>\n\n<pre><code>emailpath = \"\".join([c for c in emailpath if c in (string.letters + string.digits + \"_ \")])\n</code></pre>\n\n<p>And you'd end up with just alphanumeric characters and the underscore and space, which seems like a readable set. Given that your filesystem (with Windows) is probably case insensitive, you could lowercase that also (add .lower() to the end). You could use emailpath.translate if you want something more complex.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
Hi Guys could you please help me refactor this so that it is sensibly pythonic.
```
import sys
import poplib
import string
import StringIO, rfc822
import datetime
import logging
def _dump_pop_emails(self):
self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1]))
self.popinstance = poplib.POP3(self.account[0])
self.logger.info(self.popinstance.getwelcome())
self.popinstance.user(self.account[1])
self.popinstance.pass_(self.account[2])
try:
(numMsgs, totalSize) = self.popinstance.stat()
for thisNum in range(1, numMsgs+1):
(server_msg, body, octets) = self.popinstance.retr(thisNum)
text = string.join(body, '\n')
mesg = StringIO.StringIO(text)
msg = rfc822.Message(mesg)
name, email = msg.getaddr("From")
emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
emailpath = self._replace_whitespace(emailpath)
file = open(emailpath,"wb")
file.write(text)
file.close()
self.popinstance.dele(thisNum)
finally:
self.logger.info(self.popinstance.quit())
def _replace_whitespace(self,name):
name = str(name)
return name.replace(" ", "_")
```
Also in the \_replace\_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing.
Basically I want to write the email to the inbox directory in a standard way.
Am i doing something wrong here?
|
This isn't refactoring (it doesn't need refactoring as far as I can see), but some suggestions:
You should use the email package rather than rfc822. Replace rfc822.Message with email.Message, and use email.Utils.parseaddr(msg["From"]) to get the name and email address, and msg["Subject"] to get the subject.
Use os.path.join to create the path. This:
```
emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
```
Becomes:
```
emailpath = os.path.join(self._emailpath + self._inboxfolder, email + "_" + msg.getheader("Subject") + ".eml")
```
(If self.\_inboxfolder starts with a slash or self.\_emailpath ends with one, you could replace the first + with a comma also).
It doesn't really hurt anything, but you should probably not use "file" as a variable name, since it shadows a built-in type (checkers like pylint or pychecker would warn you about that).
If you're not using self.popinstance outside of this function (seems unlikely given that you connect and quit within the function), then there's no point making it an attribute of self. Just use "popinstance" by itself.
Use xrange instead of range.
Instead of just importing StringIO, do this:
```
try:
import cStringIO as StringIO
except ImportError:
import StringIO
```
If this is a POP mailbox that can be accessed by more than one client at a time, you might want to put a try/except around the RETR call to continue on if you can't retrieve one message.
As John said, use "\n".join rather than string.join, use try/finally to only close the file if it is opened, and pass the logging parameters separately.
The one refactoring issue I could think of would be that you don't really need to parse the whole message, since you're just dumping a copy of the raw bytes, and all you want is the From and Subject headers. You could instead use popinstance.top(0) to get the headers, create the message (blank body) from that, and use that for the headers. Then do a full RETR to get the bytes. This would only be worth doing if your messages were large (and so parsing them took a long time). I would definitely measure before I made this optimisation.
For your function to sanitise for the names, it depends how nice you want the names to be, and how certain you are that the email and subject make the filename unique (seems fairly unlikely). You could do something like:
```
emailpath = "".join([c for c in emailpath if c in (string.letters + string.digits + "_ ")])
```
And you'd end up with just alphanumeric characters and the underscore and space, which seems like a readable set. Given that your filesystem (with Windows) is probably case insensitive, you could lowercase that also (add .lower() to the end). You could use emailpath.translate if you want something more complex.
|
224,662 |
<p>I have a composite control that adds a TextBox and a Label control to its Controls collection. When i try to set the Label's AssociatedControlID to the ClientID of the Textbox i get this error</p>
<pre><code>Unable to find control with id
'ctl00_MainContentPlaceholder_MatrixSetControl_mec50_tb'
that is associated with the Label 'lb'.
</code></pre>
<p>Ok so a little background. I got this main-composite control that dynamically adds a number of 'elements' to its control collection. One of these elements happen to be this 'MatrixTextBox' which is the control consisting of a TextBox and a Label.</p>
<p>I hold the Label and TextBox as protected class variables and init them in CreateChildControls:</p>
<pre><code> ElementTextBox = new TextBox();
ElementTextBox.ID = "tb";
Controls.Add(ElementTextBox);
ElementLabel = new Label();
ElementLabel.ID = "lb";
Controls.Add(ElementLabel);
</code></pre>
<p>I tried setting the</p>
<pre><code>ElementLabel.AssociatedControlID = ElementTextBox.ClientID;
</code></pre>
<p>both right after adding the controls to the Controls collection and even in PreRender - both yield the same error. What am i doing wrong?</p>
|
[
{
"answer_id": 224710,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 4,
"selected": true,
"text": "<p>I think you <strong>mustn't use the ClientID</strong> property of the ElementTextBox, but the <strong>ID</strong>. ClientID is the page-unique ID you'd have to use in Javascript, e.g. in the document.getElementyById and is not the same as the server-side ID - especially if you have a masterpage and/or controls in controls etc.</p>\n\n<p>So it should be:</p>\n\n<pre><code>ElementLabel.AssociatedControlID = ElementTextBox.ID;\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 292789,
"author": "Patrick de Kleijn",
"author_id": 33221,
"author_profile": "https://Stackoverflow.com/users/33221",
"pm_score": 2,
"selected": false,
"text": "<p>Possibly helpful to other readers that encounter the error:</p>\n\n<p>Note that setting AssociatedControlID fails too if you're associating the label with an input control at runtime without explicitly setting the ID of the input control first. This is an issue that requires attention if you are creating multiple textboxes, checkboxes or radiobuttions with labels dynamically.</p>\n\n<pre><code>private void AddRadioButton(PlaceHolder placeholder, string groupname, string text)\n{\n RadioButton radio = new RadioButton();\n radio.GroupName = groupname;\n radio.ID = Guid.NewGuid().ToString(); // Always set an ID.\n\n Label label = new Label();\n label.Text = text;\n label.AssociatedControlID = radio.ID;\n\n placeholder.Controls.Add(radio);\n placeholder.Controls.Add(label);\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
] |
I have a composite control that adds a TextBox and a Label control to its Controls collection. When i try to set the Label's AssociatedControlID to the ClientID of the Textbox i get this error
```
Unable to find control with id
'ctl00_MainContentPlaceholder_MatrixSetControl_mec50_tb'
that is associated with the Label 'lb'.
```
Ok so a little background. I got this main-composite control that dynamically adds a number of 'elements' to its control collection. One of these elements happen to be this 'MatrixTextBox' which is the control consisting of a TextBox and a Label.
I hold the Label and TextBox as protected class variables and init them in CreateChildControls:
```
ElementTextBox = new TextBox();
ElementTextBox.ID = "tb";
Controls.Add(ElementTextBox);
ElementLabel = new Label();
ElementLabel.ID = "lb";
Controls.Add(ElementLabel);
```
I tried setting the
```
ElementLabel.AssociatedControlID = ElementTextBox.ClientID;
```
both right after adding the controls to the Controls collection and even in PreRender - both yield the same error. What am i doing wrong?
|
I think you **mustn't use the ClientID** property of the ElementTextBox, but the **ID**. ClientID is the page-unique ID you'd have to use in Javascript, e.g. in the document.getElementyById and is not the same as the server-side ID - especially if you have a masterpage and/or controls in controls etc.
So it should be:
```
ElementLabel.AssociatedControlID = ElementTextBox.ID;
```
Hope this helps.
|
224,665 |
<p>i want to get datetime for 2days before. i.e) how to subtract 2 days from datetime.now</p>
|
[
{
"answer_id": 224667,
"author": "DocMax",
"author_id": 6234,
"author_profile": "https://Stackoverflow.com/users/6234",
"pm_score": 5,
"selected": false,
"text": "<p>I think you are just looking for:</p>\n\n<pre><code>DateTime.Now.AddDays(-2);\n</code></pre>\n"
},
{
"answer_id": 224673,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 3,
"selected": false,
"text": "<p>or try:</p>\n\n<pre><code>DateTime.Now.Subtract(TimeSpan.FromDays(2));\n</code></pre>\n"
},
{
"answer_id": 224676,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 1,
"selected": false,
"text": "<p>Yet another solution:</p>\n\n<pre><code>DateTime twoDays = DateTime.Now.Subtract(new TimeSpan(2,0,0,0));\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
i want to get datetime for 2days before. i.e) how to subtract 2 days from datetime.now
|
I think you are just looking for:
```
DateTime.Now.AddDays(-2);
```
|
224,687 |
<p>This is sort of a follow-up to <a href="https://stackoverflow.com/questions/223678">this question</a>.</p>
<p>If there are multiple blobs with the same contents, they are only stored once in the git repository because their SHA-1's will be identical. How would one go about finding all duplicate files for a given tree? </p>
<p>Would you have to walk the tree and look for duplicate hashes, or does git provide backlinks from each blob to all files in a tree that reference it?</p>
|
[
{
"answer_id": 224948,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 2,
"selected": false,
"text": "<p>The scripting answers from your linked question pretty much apply here too.</p>\n\n<p>Try the following git command from the root of your git repository.</p>\n\n<pre><code>git ls-tree -r HEAD\n</code></pre>\n\n<p>This generates a recursive list of all 'blobs' in the current HEAD, including their path and their sha1 id.</p>\n\n<p>git doesn't maintain back links from a blob to tree so it would be a scripting task (perl, python?) to parse a <code>git ls-tree -r</code> output and create a summary report of all sha1s that appear more than once in the list.</p>\n"
},
{
"answer_id": 225041,
"author": "lmop",
"author_id": 22260,
"author_profile": "https://Stackoverflow.com/users/22260",
"pm_score": 4,
"selected": true,
"text": "<p>Running this on the codebase I work on was an eye-opener I can tell you!</p>\n\n<pre><code>#!/usr/bin/perl\n\n# usage: git ls-tree -r HEAD | $PROGRAM_NAME\n\nuse strict;\nuse warnings;\n\nmy $sha1_path = {};\n\nwhile (my $line = <STDIN>) {\n chomp $line;\n\n if ($line =~ m{ \\A \\d+ \\s+ \\w+ \\s+ (\\w+) \\s+ (\\S+) \\z }xms) {\n my $sha1 = $1;\n my $path = $2;\n\n push @{$sha1_path->{$sha1}}, $path;\n }\n}\n\nforeach my $sha1 (keys %$sha1_path) {\n if (scalar @{$sha1_path->{$sha1}} > 1) {\n foreach my $path (@{$sha1_path->{$sha1}}) {\n print \"$sha1 $path\\n\";\n }\n\n print '-' x 40, \"\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2743798,
"author": "Romuald Brunet",
"author_id": 286182,
"author_profile": "https://Stackoverflow.com/users/286182",
"pm_score": 3,
"selected": false,
"text": "<p>Just made a one-liner that highlights the duplicates rendered by git <code>ls-tree</code>.<br>\nMight be useful</p>\n\n<pre><code>git ls-tree -r HEAD |\n sort -t ' ' -k 3 |\n perl -ne '$1 && / $1\\t/ && print \"\\e[0;31m\" ; / ([0-9a-f]{40})\\t/; print \"$_\\e[0m\"'\n</code></pre>\n"
},
{
"answer_id": 8408640,
"author": "bsb",
"author_id": 1462529,
"author_profile": "https://Stackoverflow.com/users/1462529",
"pm_score": 5,
"selected": false,
"text": "<pre><code>[alias]\n # find duplicate files from root\n alldupes = !\"git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40\"\n\n # find duplicate files from the current folder (can also be root)\n dupes = !\"cd `pwd`/$GIT_PREFIX && git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40\"\n</code></pre>\n"
},
{
"answer_id": 46964828,
"author": "druud62",
"author_id": 8840510,
"author_profile": "https://Stackoverflow.com/users/8840510",
"pm_score": 0,
"selected": false,
"text": "<p>More general:</p>\n\n<pre><code>( for f in `find .`; do test -f $f && echo $(wc -c <$f) $(md5 -q $f) ; done ) |sort |uniq -c |grep -vE '^\\s*1\\b' |sed 's/.* //' > ~/dup.md5 ; \\\n( for f in `find .`; do test -f $f && echo $(wc -c <$f) $(md5 -q $f) $f; done ) |fgrep -f ~/dup.md5 |sort\n</code></pre>\n"
},
{
"answer_id": 49167126,
"author": "bart",
"author_id": 230899,
"author_profile": "https://Stackoverflow.com/users/230899",
"pm_score": 0,
"selected": false,
"text": "<p>For Windows / PowerShell users:</p>\n\n<pre><code>git ls-tree -r HEAD | group { $_ -replace '.{12}(.{40}).*', '$1' } | ? { $_.Count -gt 1 } | select -expand Group\n</code></pre>\n\n<p>This outputs something like:</p>\n\n<pre><code>100644 blob 8a49bcbae578c405ba2596c06f46fabbbc331c64 filename1\n100644 blob 8a49bcbae578c405ba2596c06f46fabbbc331c64 filename2\n100644 blob c1720b20bb3ad5761c1afb6a3113fbc2ba94994e filename3\n100644 blob c1720b20bb3ad5761c1afb6a3113fbc2ba94994e filename4\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
This is sort of a follow-up to [this question](https://stackoverflow.com/questions/223678).
If there are multiple blobs with the same contents, they are only stored once in the git repository because their SHA-1's will be identical. How would one go about finding all duplicate files for a given tree?
Would you have to walk the tree and look for duplicate hashes, or does git provide backlinks from each blob to all files in a tree that reference it?
|
Running this on the codebase I work on was an eye-opener I can tell you!
```
#!/usr/bin/perl
# usage: git ls-tree -r HEAD | $PROGRAM_NAME
use strict;
use warnings;
my $sha1_path = {};
while (my $line = <STDIN>) {
chomp $line;
if ($line =~ m{ \A \d+ \s+ \w+ \s+ (\w+) \s+ (\S+) \z }xms) {
my $sha1 = $1;
my $path = $2;
push @{$sha1_path->{$sha1}}, $path;
}
}
foreach my $sha1 (keys %$sha1_path) {
if (scalar @{$sha1_path->{$sha1}} > 1) {
foreach my $path (@{$sha1_path->{$sha1}}) {
print "$sha1 $path\n";
}
print '-' x 40, "\n";
}
}
```
|
224,689 |
<p>What are the best practices to do transactions in C# .Net 2.0. What are the classes that should be used? What are the pitfalls to look out for etc. All that commit and rollback stuff. I'm just starting a project where I might need to do some transactions while inserting data into the DB. Any responses or links for even basic stuff about transactions are welcome. </p>
|
[
{
"answer_id": 224699,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 1,
"selected": false,
"text": "<p>if you just need it for db-related stuff, some OR Mappers (e.g. NHibernate) support transactinos out of the box per default.</p>\n"
},
{
"answer_id": 224702,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 9,
"selected": true,
"text": "<p>There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow \"create/use/release\" usage, and doesn't allow cross-db work. An example (formatted for space):</p>\n\n<pre><code>using (IDbTransaction tran = conn.BeginTransaction()) {\n try {\n // your code\n tran.Commit();\n } catch {\n tran.Rollback();\n throw;\n }\n}\n</code></pre>\n\n<p>Not too messy, but limited to our connection \"conn\". If we want to call out to different methods, we now need to pass \"conn\" around.</p>\n\n<p>The alternative is an ambient transaction; new in .NET 2.0, the <a href=\"http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx\" rel=\"noreferrer\">TransactionScope</a> object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).</p>\n\n<p>For example:</p>\n\n<pre><code>using(TransactionScope tran = new TransactionScope()) {\n CallAMethodThatDoesSomeWork();\n CallAMethodThatDoesSomeMoreWork();\n tran.Complete();\n}\n</code></pre>\n\n<p>Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.</p>\n\n<p>If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.</p>\n\n<p>The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).</p>\n\n<p>All in all, a very, very useful object.</p>\n\n<p>Some caveats:</p>\n\n<ul>\n<li>On SQL Server 2000, a TransactionScope will go to DTC immediately; this is fixed in SQL Server 2005 and above, it can use the LTM (much less overhead) until you talk to 2 sources etc, when it is elevated to DTC.</li>\n<li>There is a <a href=\"https://stackoverflow.com/questions/195420/transactionscope-bug-in-net-more-information#195427\">glitch</a> that means you might need to tweak your connection string</li>\n</ul>\n"
},
{
"answer_id": 224707,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 0,
"selected": false,
"text": "<p>It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).</p>\n\n<p>I would use something like </p>\n\n<pre><code>SQLTransaction trans = null;\nusing(trans = new SqlTransaction)\n{\n ...\n Do SQL stuff here passing my trans into my various SQL executers\n ...\n trans.Commit // May not be quite right\n}\n</code></pre>\n\n<p>Any failure will pop you right out of the <code>using</code> and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.</p>\n"
},
{
"answer_id": 224767,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 2,
"selected": false,
"text": "<p>You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.</p>\n"
},
{
"answer_id": 13228090,
"author": "Ali Gholizadeh",
"author_id": 1799521,
"author_profile": "https://Stackoverflow.com/users/1799521",
"pm_score": 4,
"selected": false,
"text": "<pre><code>protected void Button1_Click(object sender, EventArgs e)\n {\n\n\n using (SqlConnection connection1 = new SqlConnection(\"Data Source=.\\\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\\\Database.mdf;Integrated Security=True;User Instance=True\"))\n {\n connection1.Open();\n\n // Start a local transaction.\n SqlTransaction sqlTran = connection1.BeginTransaction();\n\n // Enlist a command in the current transaction.\n SqlCommand command = connection1.CreateCommand();\n command.Transaction = sqlTran;\n\n try\n {\n // Execute two separate commands.\n command.CommandText =\n \"insert into [doctor](drname,drspecialization,drday) values ('a','b','c')\";\n command.ExecuteNonQuery();\n command.CommandText =\n \"insert into [doctor](drname,drspecialization,drday) values ('x','y','z')\";\n command.ExecuteNonQuery();\n\n // Commit the transaction.\n sqlTran.Commit();\n Label3.Text = \"Both records were written to database.\";\n }\n catch (Exception ex)\n {\n // Handle the exception if the transaction fails to commit.\n Label4.Text = ex.Message;\n\n\n try\n {\n // Attempt to roll back the transaction.\n sqlTran.Rollback();\n }\n catch (Exception exRollback)\n {\n // Throws an InvalidOperationException if the connection \n // is closed or the transaction has already been rolled \n // back on the server.\n Label5.Text = exRollback.Message;\n\n }\n }\n }\n\n\n }\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
What are the best practices to do transactions in C# .Net 2.0. What are the classes that should be used? What are the pitfalls to look out for etc. All that commit and rollback stuff. I'm just starting a project where I might need to do some transactions while inserting data into the DB. Any responses or links for even basic stuff about transactions are welcome.
|
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
```
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
```
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the [TransactionScope](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx) object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
```
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
```
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
* On SQL Server 2000, a TransactionScope will go to DTC immediately; this is fixed in SQL Server 2005 and above, it can use the LTM (much less overhead) until you talk to 2 sources etc, when it is elevated to DTC.
* There is a [glitch](https://stackoverflow.com/questions/195420/transactionscope-bug-in-net-more-information#195427) that means you might need to tweak your connection string
|
224,704 |
<p>I ran into a problem while cleaning up some old code. This is the function:</p>
<pre><code>uint32_t ADT::get_connectivity_data( std::vector< std::vector<uint8_t> > &output )
{
output.resize(chunks.size());
for(chunk_vec_t::iterator it = chunks.begin(); it < chunks.end(); ++it)
{
uint32_t success = (*it)->get_connectivity_data(output[it-chunks.begin()]);
}
return TRUE;
}
</code></pre>
<p>What i am interested in doing is cleaning up the for loop to be a lambda expression but quickly got stuck on how exactly I would pass the correct argument to get_connectivity_data. get_connectivity_data takes a std::vector by reference and fills it with some data. output contains a std::vector for each "chunk".</p>
<p>Basically my conclusion for this was that it was substantially easier, cleaner and <em>shorter</em> to leave my code as-is.</p>
<p>EDIT:</p>
<p>So the closest answer to my question as I envisioned it would look was this:</p>
<pre><code> std::for_each( chunks.begin(), chunks.end(),
bind( &chunk_vec_t::value::type::get_connectivity_data,
_1,
output[ std::distance( _1, chunks.begn() ]
)
);
</code></pre>
<p>Yet that code does not compile, I made some modifications to the code to get it to compile but I ran into 2 issues:</p>
<ol>
<li>_ 1 is a smart ptr, and std::distance did not work on it, I think i needed to use &chunks[0] as the start</li>
<li>Since _ 1 is a smart pointer, I had to do: &chunk_vec_t::value_ type::ValueType::get_ connectivity_ data which caused a crash in the VC9 compiler...</li>
</ol>
<p>The answer regarding zip_ iterators looked good until i read more into it and discovered that for this particular use, the amount of extra code needed was substantial (binding this and that, etc).</p>
<p>EDIT2:</p>
<p>I found an acceptable solution that is both low on extraneous syntax and clear, which I've posted here and below.</p>
<pre><code>std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );
</code></pre>
|
[
{
"answer_id": 224739,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>I don't really get what you are driving at with regards to the lambda, but I can make a couple of general suggestions for code cleanup involving STL containers.</p>\n\n<p>Use typedefs of all STL container types:</p>\n\n<pre><code>typedef std::vector<uint8_t> Chunks;\ntypedef std::vector<Chunks> Output;\nuint32_t ADT::get_connectivity_data( Output &output )\n</code></pre>\n\n<p>Since you are talking about using Boost, use <a href=\"http://www.boost.org/doc/libs/1_35_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\">Boost.Foreach</a>:</p>\n\n<pre><code>BOOST_FOREACH(chunk_vec_t::value_type &chunk, chunks)\n uint32_t success =\n chunk->get_connectivity_data(output[std::distance(&chunk, chunks.begin())]);\n</code></pre>\n\n<p>Stab in the dark on the \"lambda\" thing:</p>\n\n<pre><code>typedef const boost::function2<uint32_t, chunk_vec_t::value_type, Chunks>\n GetConnectivity;\nuint32_t ADT::get_connectivity_data(Output &output, GetConnectivity &getConnectivity)\n{\n output.resize(chunks.size());\n BOOST_FOREACH(chunk_vec_t::value_type &chunk, chunks)\n uint32_t success =\n getConnectivity(chunk, output[std::distance(&chunk, chunks.begin())]);\n return TRUE;\n}\n</code></pre>\n\n<p>Then you might call it like:</p>\n\n<pre><code>get_connectivity_data(output,\n boost::bind(&chunk_vec_t::value_type::get_connectivity_data, _1, _2));\n</code></pre>\n"
},
{
"answer_id": 224755,
"author": "endian",
"author_id": 25462,
"author_profile": "https://Stackoverflow.com/users/25462",
"pm_score": 2,
"selected": false,
"text": "<p>I think you were correct in thinking that the best thing to do is leave the code as-is. If you're having a hard time understanding it when (a) you're writing it and (b) you understand the exact problem you're trying to solve, imagine how difficult it will be when someone comes along in 3 years time and has to understand both the problem and the solution that you've written.</p>\n"
},
{
"answer_id": 224884,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 1,
"selected": false,
"text": "<p>What you're actually doing is performing an operation on two containers in parallel. This is what boost::zip_iterator is designed for.</p>\n\n<p>However, the only reason you need to process the containers in parallel is that Chunk::get_connectivity_data takes an out parameter. If it were to return by value (using exceptions to report errors), you could just use an insert iterator.</p>\n"
},
{
"answer_id": 226150,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 2,
"selected": false,
"text": "<p>Without seeing the code for the entire class, it is hard to determine what will work. Personally, I think the BOOST_FOREACH is cleaner in this case, but for reference purposes, I might try doing something like this using lambdas (note I can't test compile)</p>\n\n<pre><code>uint32_t ADT::get_connectivity_data( std::vector< std::vector<uint8_t> > &output )\n{\n using namespace boost::lambda;\n\n output.resize( chunks.size() );\n\n std::for_each( chunks.begin(), chunks.end(), \n bind( &chunk_vec_t::value::type::get_connectivity_data, \n _1, \n output[ std::distance( _1, chunks.begn() ] \n )\n );\n return TRUE;\n}\n</code></pre>\n"
},
{
"answer_id": 227115,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "<p>For some reason, STL beginners always insist in using a vector::iterator instead of the more readable (and constant time) operator[]. The expression <code>it-chunks.begin()</code> should have told the original author that he'd already lost the smartass coder game, and needed a humble index after all:</p>\n\n<pre><code>for (size_t i = 0, size = chunks.size(); i < size; ++i)\n{\n chunks[i]->get_connectivity_data(output[i]);\n} \n</code></pre>\n\n<p>OP might also consider losing the spurious return code and making this a const member function.</p>\n"
},
{
"answer_id": 231060,
"author": "Raindog",
"author_id": 29049,
"author_profile": "https://Stackoverflow.com/users/29049",
"pm_score": 3,
"selected": true,
"text": "<p>After a bit of work I came up with this solution:</p>\n\n<pre><code>std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );\n</code></pre>\n\n<p>It required that I change get_connectivity_data to return std::vector instead of taking one by reference, and it also required that I change the elements of chunks to be boost::shared_ptr instead of Loki::SmartPtr.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29049/"
] |
I ran into a problem while cleaning up some old code. This is the function:
```
uint32_t ADT::get_connectivity_data( std::vector< std::vector<uint8_t> > &output )
{
output.resize(chunks.size());
for(chunk_vec_t::iterator it = chunks.begin(); it < chunks.end(); ++it)
{
uint32_t success = (*it)->get_connectivity_data(output[it-chunks.begin()]);
}
return TRUE;
}
```
What i am interested in doing is cleaning up the for loop to be a lambda expression but quickly got stuck on how exactly I would pass the correct argument to get\_connectivity\_data. get\_connectivity\_data takes a std::vector by reference and fills it with some data. output contains a std::vector for each "chunk".
Basically my conclusion for this was that it was substantially easier, cleaner and *shorter* to leave my code as-is.
EDIT:
So the closest answer to my question as I envisioned it would look was this:
```
std::for_each( chunks.begin(), chunks.end(),
bind( &chunk_vec_t::value::type::get_connectivity_data,
_1,
output[ std::distance( _1, chunks.begn() ]
)
);
```
Yet that code does not compile, I made some modifications to the code to get it to compile but I ran into 2 issues:
1. \_ 1 is a smart ptr, and std::distance did not work on it, I think i needed to use &chunks[0] as the start
2. Since \_ 1 is a smart pointer, I had to do: &chunk\_vec\_t::value\_ type::ValueType::get\_ connectivity\_ data which caused a crash in the VC9 compiler...
The answer regarding zip\_ iterators looked good until i read more into it and discovered that for this particular use, the amount of extra code needed was substantial (binding this and that, etc).
EDIT2:
I found an acceptable solution that is both low on extraneous syntax and clear, which I've posted here and below.
```
std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );
```
|
After a bit of work I came up with this solution:
```
std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );
```
It required that I change get\_connectivity\_data to return std::vector instead of taking one by reference, and it also required that I change the elements of chunks to be boost::shared\_ptr instead of Loki::SmartPtr.
|
224,712 |
<p>I had setup my clients & server for passwordless login.
Like passwordless login by copying RSA key of server to all client's /root/.ssh/id-rsa.pub. but this, I have done manually. I like to automate this process using shell script and providing password to the machines through script.
If this problem is solved then I also want to use rsync to automate push items to all servers.
Can any body help me in this regard.</p>
<p>Thank you</p>
|
[
{
"answer_id": 224716,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>This script comes in Debian (and derivatives) machines, to distribute the keys. It's called ssh-copy-id. You'd use it like this:</p>\n\n<pre><code>ssh-copy-id [-i identity_file] [user@]machine\n</code></pre>\n\n<p>Then you'd enter the password and the copying would be done. You would do this one time only and then could use the rsync over ssh as usual.</p>\n\n<pre><code>#!/bin/sh\n\n# Shell script to install your identity.pub on a remote machine\n# Takes the remote machine name as an argument.\n# Obviously, the remote machine must accept password authentication,\n# or one of the other keys in your ssh-agent, for this to work.\n\nID_FILE=\"${HOME}/.ssh/identity.pub\"\n\nif [ \"-i\" = \"$1\" ]; then\n shift\n # check if we have 2 parameters left, if so the first is the new ID file\n if [ -n \"$2\" ]; then\n if expr \"$1\" : \".*\\.pub\" ; then\n ID_FILE=\"$1\"\n else\n ID_FILE=\"$1.pub\"\n fi\n shift # and this should leave $1 as the target name\n fi\nelse\n if [ x$SSH_AUTH_SOCK != x ] ; then\n GET_ID=\"$GET_ID ssh-add -L\"\n fi\nfi\n\nif [ -z \"`eval $GET_ID`\" ] && [ -r \"${ID_FILE}\" ] ; then\n GET_ID=\"cat ${ID_FILE}\"\nfi\n\nif [ -z \"`eval $GET_ID`\" ]; then\n echo \"$0: ERROR: No identities found\" >&2\n exit 1\nfi\n\nif [ \"$#\" -lt 1 ] || [ \"$1\" = \"-h\" ] || [ \"$1\" = \"--help\" ]; then\n echo \"Usage: $0 [-i [identity_file]] [user@]machine\" >&2\n exit 1\nfi\n\n{ eval \"$GET_ID\" ; } | ssh $1 \"umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys\" || exit 1\n\ncat <<EOF\nNow try logging into the machine, with \"ssh '$1'\", and check in:\n\n .ssh/authorized_keys\n\nto make sure we haven't added extra keys that you weren't expecting.\n\nEOF\n</code></pre>\n"
},
{
"answer_id": 224717,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to push updates/changes to multiple computers in a network then you may want to consider looking at something like <a href=\"http://puppet.reductivelabs.com/\" rel=\"nofollow noreferrer\">Puppet</a> that works outside the normal channels.</p>\n"
},
{
"answer_id": 224731,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 0,
"selected": false,
"text": "<p>you could use expect to log into a remote machine when the <code>.ssh/authorized_keys</code> method is not avaliable. For example:</p>\n\n<pre><code>#!/usr/bin/expect\n\nspawn ssh user@remote-host\nexpect \"*password: $\"\nsend \"YOUR PASSWORD HERE\\n\"\nsend \"bash\\n\"\ninteract\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24813/"
] |
I had setup my clients & server for passwordless login.
Like passwordless login by copying RSA key of server to all client's /root/.ssh/id-rsa.pub. but this, I have done manually. I like to automate this process using shell script and providing password to the machines through script.
If this problem is solved then I also want to use rsync to automate push items to all servers.
Can any body help me in this regard.
Thank you
|
This script comes in Debian (and derivatives) machines, to distribute the keys. It's called ssh-copy-id. You'd use it like this:
```
ssh-copy-id [-i identity_file] [user@]machine
```
Then you'd enter the password and the copying would be done. You would do this one time only and then could use the rsync over ssh as usual.
```
#!/bin/sh
# Shell script to install your identity.pub on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.
ID_FILE="${HOME}/.ssh/identity.pub"
if [ "-i" = "$1" ]; then
shift
# check if we have 2 parameters left, if so the first is the new ID file
if [ -n "$2" ]; then
if expr "$1" : ".*\.pub" ; then
ID_FILE="$1"
else
ID_FILE="$1.pub"
fi
shift # and this should leave $1 as the target name
fi
else
if [ x$SSH_AUTH_SOCK != x ] ; then
GET_ID="$GET_ID ssh-add -L"
fi
fi
if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
GET_ID="cat ${ID_FILE}"
fi
if [ -z "`eval $GET_ID`" ]; then
echo "$0: ERROR: No identities found" >&2
exit 1
fi
if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
exit 1
fi
{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1
cat <<EOF
Now try logging into the machine, with "ssh '$1'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
EOF
```
|
224,721 |
<p>I have the following class:</p>
<pre><code>public abstract class AbstractParent {
static String method() {
return "OriginalOutput";
}
}
</code></pre>
<p>I want to mock this method. I decide to use <a href="http://jmockit.dev.java.net" rel="noreferrer">JMockit</a>. So I create a mock class:</p>
<pre><code>public class MockParent {
static String method() {
return "MOCK";
}
}
</code></pre>
<p>And my test code looks like this:</p>
<pre><code>public class RealParentTest {
@Before
public void setUp() throws Exception {
Mockit.redefineMethods( AbstractParent.class, MockParent.class );
}
@Test
public void testMethod() {
assertEquals(MockParent.method(),AbstractParent.method());
}
}
</code></pre>
<p>Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.</p>
<p><strong>Edit</strong> Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope.</p>
<p><strong>Answer</strong> Only the mock method needs to be public, you can leave the original method as is.</p>
|
[
{
"answer_id": 224773,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 4,
"selected": true,
"text": "<p>Found the solution: you simply need to make the mock's method public (the original method can stay in its original visibility).</p>\n\n<p>I don't know why this works while the original way doesn't (someone who does is more than welcome to chime in), but all you need to do is simply change the mock class in the example above to:</p>\n\n<pre><code>public class MockParent {\n public static String method() {\n return \"MOCK\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4439821,
"author": "Gareth Davis",
"author_id": 31480,
"author_profile": "https://Stackoverflow.com/users/31480",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently the new way to do this is to use <code>MockUp<T></code></p>\n\n<pre><code>new MockUp<AbstractParent>(){\n @Mock String method() {\n return \"MOCK\";\n }\n};\n\nassertEquals(\"MOCK\" AbstractParent.method());\n</code></pre>\n\n<p>Another alternative is apparently to continue with something like <code>MockParent</code> with a <code>@MockClass</code> annonation. Haven't done this myself as the another inline version does the job.</p>\n\n<p>I've implemented this in an example <a href=\"https://github.com/gid79/q224721-jmockit-non-public-methods\" rel=\"nofollow\">project on github</a>.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
I have the following class:
```
public abstract class AbstractParent {
static String method() {
return "OriginalOutput";
}
}
```
I want to mock this method. I decide to use [JMockit](http://jmockit.dev.java.net). So I create a mock class:
```
public class MockParent {
static String method() {
return "MOCK";
}
}
```
And my test code looks like this:
```
public class RealParentTest {
@Before
public void setUp() throws Exception {
Mockit.redefineMethods( AbstractParent.class, MockParent.class );
}
@Test
public void testMethod() {
assertEquals(MockParent.method(),AbstractParent.method());
}
}
```
Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.
**Edit** Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope.
**Answer** Only the mock method needs to be public, you can leave the original method as is.
|
Found the solution: you simply need to make the mock's method public (the original method can stay in its original visibility).
I don't know why this works while the original way doesn't (someone who does is more than welcome to chime in), but all you need to do is simply change the mock class in the example above to:
```
public class MockParent {
public static String method() {
return "MOCK";
}
}
```
|
224,732 |
<p>I have a database with <code>account numbers</code> and <code>card numbers</code>. I match these to a file to <code>update</code> any card numbers to the account number so that I am only working with account numbers.</p>
<p>I created a view linking the table to the account/card database to return the <code>Table ID</code> and the related account number, and now I need to update those records where the ID matches the Account Number.</p>
<p>This is the <code>Sales_Import</code> table, where the <code>account number</code> field needs to be updated:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>LeadID</th>
<th>AccountNumber</th>
</tr>
</thead>
<tbody>
<tr>
<td>147</td>
<td>5807811235</td>
</tr>
<tr>
<td>150</td>
<td>5807811326</td>
</tr>
<tr>
<td>185</td>
<td>7006100100007267039</td>
</tr>
</tbody>
</table>
</div>
<p>And this is the <code>RetrieveAccountNumber</code> table, where I need to update from:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>LeadID</th>
<th>AccountNumber</th>
</tr>
</thead>
<tbody>
<tr>
<td>147</td>
<td>7006100100007266957</td>
</tr>
<tr>
<td>150</td>
<td>7006100100007267039</td>
</tr>
</tbody>
</table>
</div>
<p>I tried the below, but no luck so far:</p>
<pre><code>UPDATE [Sales_Lead].[dbo].[Sales_Import]
SET [AccountNumber] = (SELECT RetrieveAccountNumber.AccountNumber
FROM RetrieveAccountNumber
WHERE [Sales_Lead].[dbo].[Sales_Import]. LeadID =
RetrieveAccountNumber.LeadID)
</code></pre>
<p>It updates the card numbers to account numbers, but the account numbers get replaced by <code>NULL</code></p>
|
[
{
"answer_id": 224740,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 11,
"selected": false,
"text": "<p>I believe an <code>UPDATE FROM</code> with a <code>JOIN</code> will help:</p>\n\n<h2>MS SQL</h2>\n\n<pre><code>UPDATE\n Sales_Import\nSET\n Sales_Import.AccountNumber = RAN.AccountNumber\nFROM\n Sales_Import SI\nINNER JOIN\n RetrieveAccountNumber RAN\nON \n SI.LeadID = RAN.LeadID;\n</code></pre>\n\n<h2>MySQL and MariaDB</h2>\n\n<pre><code>UPDATE\n Sales_Import SI,\n RetrieveAccountNumber RAN\nSET\n SI.AccountNumber = RAN.AccountNumber\nWHERE\n SI.LeadID = RAN.LeadID;\n</code></pre>\n"
},
{
"answer_id": 224742,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": false,
"text": "<p>Seems you are using MSSQL, then, if I remember correctly, it is done like this:</p>\n\n<pre><code>UPDATE [Sales_Lead].[dbo].[Sales_Import] SET [AccountNumber] = \nRetrieveAccountNumber.AccountNumber \nFROM RetrieveAccountNumber \nWHERE [Sales_Lead].[dbo].[Sales_Import].LeadID = RetrieveAccountNumber.LeadID\n</code></pre>\n"
},
{
"answer_id": 224807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Thanks for the responses. I found a solution tho.</p>\n\n<pre><code>UPDATE Sales_Import \nSET AccountNumber = (SELECT RetrieveAccountNumber.AccountNumber \n FROM RetrieveAccountNumber \n WHERE Sales_Import.leadid =RetrieveAccountNumber.LeadID) \nWHERE Sales_Import.leadid = (SELECT RetrieveAccountNumber.LeadID \n FROM RetrieveAccountNumber \n WHERE Sales_Import.leadid = RetrieveAccountNumber.LeadID) \n</code></pre>\n"
},
{
"answer_id": 803651,
"author": "Kjell Andreassen",
"author_id": 97874,
"author_profile": "https://Stackoverflow.com/users/97874",
"pm_score": 5,
"selected": false,
"text": "<p>I had the same problem with <code>foo.new</code> being set to <code>null</code> for rows of <code>foo</code> that had no matching key in <code>bar</code>. I did something like this in Oracle:</p>\n\n<pre>\nupdate foo\nset foo.new = (select bar.new\n from bar \n where foo.key = bar.key)\nwhere exists (select 1\n from bar\n where foo.key = bar.key)\n</pre>\n"
},
{
"answer_id": 2101278,
"author": "Shivkant",
"author_id": 240706,
"author_profile": "https://Stackoverflow.com/users/240706",
"pm_score": 8,
"selected": false,
"text": "<p>The simple Way to copy the content from one table to other is as follow:</p>\n\n<pre><code>UPDATE table2 \nSET table2.col1 = table1.col1, \ntable2.col2 = table1.col2,\n...\nFROM table1, table2 \nWHERE table1.memberid = table2.memberid\n</code></pre>\n\n<p>You can also add the condition to get the particular data copied.</p>\n"
},
{
"answer_id": 9241260,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 7,
"selected": false,
"text": "<p>For SQL Server 2008 + Using <code>MERGE</code> rather than the proprietary <code>UPDATE ... FROM</code> syntax has some appeal. </p>\n\n<p>As well as being standard SQL and thus more portable it also will raise an error in the event of there being multiple joined rows on the source side (and thus multiple possible different values to use in the update) rather than having the final result be undeterministic.</p>\n\n<pre><code>MERGE INTO Sales_Import\n USING RetrieveAccountNumber\n ON Sales_Import.LeadID = RetrieveAccountNumber.LeadID\nWHEN MATCHED THEN\n UPDATE \n SET AccountNumber = RetrieveAccountNumber.AccountNumber;\n</code></pre>\n\n<p>Unfortunately the choice of which to use may not come down purely to preferred style however. The implementation of <code>MERGE</code> in SQL Server has been afflicted with various bugs. Aaron Bertrand has compiled a list of <a href=\"http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/\">the reported ones here</a>.</p>\n"
},
{
"answer_id": 9264291,
"author": "marsanvi",
"author_id": 880252,
"author_profile": "https://Stackoverflow.com/users/880252",
"pm_score": 5,
"selected": false,
"text": "<p>For MySql that works fine:</p>\n\n<pre><code>UPDATE\n Sales_Import SI,RetrieveAccountNumber RAN\nSET\n SI.AccountNumber = RAN.AccountNumber\nWHERE\n SI.LeadID = RAN.LeadID\n</code></pre>\n"
},
{
"answer_id": 10880839,
"author": "user824910",
"author_id": 824910,
"author_profile": "https://Stackoverflow.com/users/824910",
"pm_score": 2,
"selected": false,
"text": "<p>I thought this is a simple example might someone get it easier, </p>\n\n<pre><code> DECLARE @TB1 TABLE\n (\n No Int\n ,Name NVarchar(50)\n )\n\n DECLARE @TB2 TABLE\n (\n No Int\n ,Name NVarchar(50)\n )\n\n INSERT INTO @TB1 VALUES(1,'asdf');\n INSERT INTO @TB1 VALUES(2,'awerq');\n\n\n INSERT INTO @TB2 VALUES(1,';oiup');\n INSERT INTO @TB2 VALUES(2,'lkjhj');\n\n SELECT * FROM @TB1\n\n UPDATE @TB1 SET Name =S.Name\n FROM @TB1 T\n INNER JOIN @TB2 S\n ON S.No = T.No\n\n SELECT * FROM @TB1\n</code></pre>\n"
},
{
"answer_id": 13743594,
"author": "NCP",
"author_id": 1130019,
"author_profile": "https://Stackoverflow.com/users/1130019",
"pm_score": 2,
"selected": false,
"text": "<p>update within the same table:</p>\n\n<pre><code> DECLARE @TB1 TABLE\n (\n No Int\n ,Name NVarchar(50)\n ,linkNo int\n )\n\n DECLARE @TB2 TABLE\n (\n No Int\n ,Name NVarchar(50)\n ,linkNo int\n )\n\n INSERT INTO @TB1 VALUES(1,'changed person data', 0);\n INSERT INTO @TB1 VALUES(2,'old linked data of person', 1);\n\nINSERT INTO @TB2 SELECT * FROM @TB1 WHERE linkNo = 0\n\n\nSELECT * FROM @TB1\nSELECT * FROM @TB2\n\n\n UPDATE @TB1 \n SET Name = T2.Name\n FROM @TB1 T1\n INNER JOIN @TB2 T2 ON T2.No = T1.linkNo\n\n SELECT * FROM @TB1\n</code></pre>\n"
},
{
"answer_id": 24789509,
"author": "petter",
"author_id": 1749695,
"author_profile": "https://Stackoverflow.com/users/1749695",
"pm_score": 6,
"selected": false,
"text": "<p>For PostgreSQL:</p>\n\n<pre><code>UPDATE Sales_Import SI\nSET AccountNumber = RAN.AccountNumber\nFROM RetrieveAccountNumber RAN\nWHERE RAN.LeadID = SI.LeadID; \n</code></pre>\n"
},
{
"answer_id": 29416743,
"author": "CG_DEV",
"author_id": 1426462,
"author_profile": "https://Stackoverflow.com/users/1426462",
"pm_score": 2,
"selected": false,
"text": "<p>This will allow you to update a table based on the column value not being found in another table.</p>\n<pre><code>UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (\n SELECT * \n FROM (\n SELECT table1.id\n FROM table1 \n LEFT JOIN table2 ON ( table2.column = table1.column ) \n WHERE table1.column = 'some_expected_val'\n AND table12.column IS NULL\n ) AS Xalias\n)\n</code></pre>\n<p>This will update a table based on the column value being found in both tables.</p>\n<pre><code>UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (\n SELECT * \n FROM (\n SELECT table1.id\n FROM table1 \n JOIN table2 ON ( table2.column = table1.column ) \n WHERE table1.column = 'some_expected_val'\n ) AS Xalias\n)\n</code></pre>\n"
},
{
"answer_id": 30233811,
"author": "jakentus",
"author_id": 1182664,
"author_profile": "https://Stackoverflow.com/users/1182664",
"pm_score": 3,
"selected": false,
"text": "<p>it works with postgresql</p>\n\n<pre><code>UPDATE application\nSET omts_received_date = (\n SELECT\n date_created\n FROM\n application_history\n WHERE\n application.id = application_history.application_id\n AND application_history.application_status_id = 8\n);\n</code></pre>\n"
},
{
"answer_id": 37779007,
"author": "Dr Inner Join",
"author_id": 6455074,
"author_profile": "https://Stackoverflow.com/users/6455074",
"pm_score": 3,
"selected": false,
"text": "<p>The below SQL someone suggested, does NOT work in SQL Server. This syntax reminds me of my old school class:</p>\n\n<pre><code>UPDATE table2 \nSET table2.col1 = table1.col1, \ntable2.col2 = table1.col2,\n...\nFROM table1, table2 \nWHERE table1.memberid = table2.memberid\n</code></pre>\n\n<p>All other queries using <code>NOT IN</code> or <code>NOT EXISTS</code> are not recommended. NULLs show up because OP compares entire dataset with smaller subset, then of course there will be matching problem. This must be fixed by writing proper SQL with correct <code>JOIN</code> instead of dodging problem by using <code>NOT IN</code>. You might run into other problems by using <code>NOT IN</code> or <code>NOT EXISTS</code> in this case.</p>\n\n<p>My vote for the top one, which is conventional way of updating a table based on another table by joining in SQL Server. Like I said, you cannot use two tables in same <code>UPDATE</code> statement in SQL Server unless you join them first.</p>\n"
},
{
"answer_id": 39212355,
"author": "Tigerjz32",
"author_id": 1556242,
"author_profile": "https://Stackoverflow.com/users/1556242",
"pm_score": 7,
"selected": false,
"text": "<p>Generic answer for future developers. </p>\n\n<h1>SQL Server</h1>\n\n<pre><code>UPDATE \n t1\nSET \n t1.column = t2.column\nFROM \n Table1 t1 \n INNER JOIN Table2 t2 \n ON t1.id = t2.id;\n</code></pre>\n\n<h1>Oracle (and SQL Server)</h1>\n\n<pre><code>UPDATE \n t1\nSET \n t1.colmun = t2.column \nFROM \n Table1 t1, \n Table2 t2 \nWHERE \n t1.ID = t2.ID;\n</code></pre>\n\n<h1>MySQL</h1>\n\n<pre><code>UPDATE \n Table1 t1, \n Table2 t2\nSET \n t1.column = t2.column \nWHERE\n t1.ID = t2.ID;\n</code></pre>\n"
},
{
"answer_id": 40589359,
"author": "Developer",
"author_id": 6757851,
"author_profile": "https://Stackoverflow.com/users/6757851",
"pm_score": 2,
"selected": false,
"text": "<p><strong>try this :</strong></p>\n\n<pre><code>UPDATE\n Table_A\nSET\n Table_A.AccountNumber = Table_B.AccountNumber ,\nFROM\n dbo.Sales_Import AS Table_A\n INNER JOIN dbo.RetrieveAccountNumber AS Table_B\n ON Table_A.LeadID = Table_B.LeadID \nWHERE\n Table_A.LeadID = Table_B.LeadID\n</code></pre>\n"
},
{
"answer_id": 41132526,
"author": "pacreely",
"author_id": 6173015,
"author_profile": "https://Stackoverflow.com/users/6173015",
"pm_score": 0,
"selected": false,
"text": "<p>I'd like to add one extra thing.</p>\n\n<p>Don't update a value with the same value, it generates extra logging and unnecessary overhead. \nSee example below - it will only perform the update on 2 records despite linking on 3.</p>\n\n<pre><code>DROP TABLE #TMP1\nDROP TABLE #TMP2\nCREATE TABLE #TMP1(LeadID Int,AccountNumber NVarchar(50))\nCREATE TABLE #TMP2(LeadID Int,AccountNumber NVarchar(50))\n\nINSERT INTO #TMP1 VALUES\n(147,'5807811235')\n,(150,'5807811326')\n,(185,'7006100100007267039');\n\nINSERT INTO #TMP2 VALUES\n(147,'7006100100007266957')\n,(150,'7006100100007267039')\n,(185,'7006100100007267039');\n\nUPDATE A\nSET A.AccountNumber = B.AccountNumber\nFROM\n #TMP1 A \n INNER JOIN #TMP2 B\n ON\n A.LeadID = B.LeadID\nWHERE\n A.AccountNumber <> B.AccountNumber --DON'T OVERWRITE A VALUE WITH THE SAME VALUE\n\nSELECT * FROM #TMP1\n</code></pre>\n"
},
{
"answer_id": 47251209,
"author": "Gil Baggio",
"author_id": 6037997,
"author_profile": "https://Stackoverflow.com/users/6037997",
"pm_score": 4,
"selected": false,
"text": "<p>Use the following block of query to update Table1 with Table2 based on ID:</p>\n\n<pre><code>UPDATE Sales_Import, RetrieveAccountNumber \nSET Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber \nwhere Sales_Import.LeadID = RetrieveAccountNumber.LeadID;\n</code></pre>\n\n<p>This is the <strong>easiest way</strong> to tackle this problem.</p>\n"
},
{
"answer_id": 48180175,
"author": "Shaw",
"author_id": 6137822,
"author_profile": "https://Stackoverflow.com/users/6137822",
"pm_score": -1,
"selected": false,
"text": "<p>If above answers not working for you try this </p>\n\n<pre><code>Update Sales_Import A left join RetrieveAccountNumber B on A.LeadID = B.LeadID\nSet A.AccountNumber = B.AccountNumber\nwhere A.LeadID = B.LeadID \n</code></pre>\n"
},
{
"answer_id": 52222942,
"author": "Abhimanyu",
"author_id": 1386991,
"author_profile": "https://Stackoverflow.com/users/1386991",
"pm_score": 5,
"selected": false,
"text": "<p>Here's what worked for me in SQL Server:</p>\n\n<pre><code>UPDATE [AspNetUsers] SET\n\n[AspNetUsers].[OrganizationId] = [UserProfile].[OrganizationId],\n[AspNetUsers].[Name] = [UserProfile].[Name]\n\nFROM [AspNetUsers], [UserProfile]\nWHERE [AspNetUsers].[Id] = [UserProfile].[Id];\n</code></pre>\n"
},
{
"answer_id": 54294280,
"author": "Bruno",
"author_id": 10874278,
"author_profile": "https://Stackoverflow.com/users/10874278",
"pm_score": 1,
"selected": false,
"text": "<p>Oracle 11g</p>\n\n<pre><code>merge into Sales_Import\nusing RetrieveAccountNumber\non (Sales_Import.LeadId = RetrieveAccountNumber.LeadId)\nwhen matched then update set Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber;\n</code></pre>\n"
},
{
"answer_id": 55805490,
"author": "saman samadi",
"author_id": 11387413,
"author_profile": "https://Stackoverflow.com/users/11387413",
"pm_score": 4,
"selected": false,
"text": "<p>MS Sql </p>\n\n<pre><code>UPDATE c4 SET Price=cp.Price*p.FactorRate FROM TableNamea_A c4\ninner join TableNamea_B p on c4.Calcid=p.calcid \ninner join TableNamea_A cp on c4.Calcid=cp.calcid \nWHERE c4..Name='MyName';\n</code></pre>\n\n<p>Oracle 11g</p>\n\n<pre><code> MERGE INTO TableNamea_A u \n using\n (\n SELECT c4.TableName_A_ID,(cp.Price*p.FactorRate) as CalcTot \n FROM TableNamea_A c4\n inner join TableNamea_B p on c4.Calcid=p.calcid \n inner join TableNamea_A cp on c4.Calcid=cp.calcid \n WHERE p.Name='MyName' \n ) rt\n on (u.TableNamea_A_ID=rt.TableNamea_B_ID)\n WHEN MATCHED THEN\n Update set Price=CalcTot ;\n</code></pre>\n"
},
{
"answer_id": 55822338,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>In case the tables are in a different databases. (MSSQL)</p>\n\n<pre><code>update database1..Ciudad\nset CiudadDistrito=c2.CiudadDistrito\n\nFROM database1..Ciudad c1\n inner join \n database2..Ciudad c2 on c2.CiudadID=c1.CiudadID\n</code></pre>\n"
},
{
"answer_id": 65393612,
"author": "Shilwant Gupta",
"author_id": 14554291,
"author_profile": "https://Stackoverflow.com/users/14554291",
"pm_score": 3,
"selected": false,
"text": "<p>update from one table to another table on id matched</p>\n<pre><code>UPDATE \n TABLE1 t1, \n TABLE2 t2\nSET \n t1.column_name = t2.column_name \nWHERE\n t1.id = t2.id;\n</code></pre>\n"
},
{
"answer_id": 65593452,
"author": "dobrivoje",
"author_id": 1551368,
"author_profile": "https://Stackoverflow.com/users/1551368",
"pm_score": 2,
"selected": false,
"text": "<p><strong>MYSQL</strong> (This is my preferred way for restoring <strong>all</strong> specific column <code>reasonId</code> values, based on primary key <code>id</code> equivalence)</p>\n<pre><code>UPDATE `site` AS destination \nINNER JOIN `site_copy` AS backupOnTuesday \n ON backupOnTuesday.`id` = destination.`id`\nSET destdestination.`reasonId` = backupOnTuesday.`reasonId`\n</code></pre>\n"
},
{
"answer_id": 66529407,
"author": "ABODE",
"author_id": 7617526,
"author_profile": "https://Stackoverflow.com/users/7617526",
"pm_score": 3,
"selected": false,
"text": "<p>This is the easiest and best have seen for Mysql and Maria DB</p>\n<pre><code>UPDATE table2, table1 SET table2.by_department = table1.department WHERE table1.id = table2.by_id\n</code></pre>\n<p>Note: If you encounter the following error based on your Mysql/Maria DB version "Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences"</p>\n<p>Then run the code like this</p>\n<pre><code>SET SQL_SAFE_UPDATES=0;\nUPDATE table2, table1 SET table2.by_department = table1.department WHERE table1.id = table2.by_id\n</code></pre>\n"
},
{
"answer_id": 70895998,
"author": "Cuado",
"author_id": 6189492,
"author_profile": "https://Stackoverflow.com/users/6189492",
"pm_score": 0,
"selected": false,
"text": "<h4>ORACLE</h4>\n<p>use</p>\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE suppliers\nSET supplier_name = (SELECT customers.customer_name\n FROM customers\n WHERE customers.customer_id = suppliers.supplier_id)\nWHERE EXISTS (SELECT customers.customer_name\n FROM customers\n WHERE customers.customer_id = suppliers.supplier_id);\n\n</code></pre>\n"
},
{
"answer_id": 71217836,
"author": "Pasindu Perera",
"author_id": 7095871,
"author_profile": "https://Stackoverflow.com/users/7095871",
"pm_score": 1,
"selected": false,
"text": "<p>For Oracle SQL try using alias</p>\n<pre><code>UPDATE Sales_Lead.dbo.Sales_Import SI \nSET SI.AccountNumber = (SELECT RAN.AccountNumber FROM RetrieveAccountNumber RAN WHERE RAN.LeadID = SI.LeadID);\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a database with `account numbers` and `card numbers`. I match these to a file to `update` any card numbers to the account number so that I am only working with account numbers.
I created a view linking the table to the account/card database to return the `Table ID` and the related account number, and now I need to update those records where the ID matches the Account Number.
This is the `Sales_Import` table, where the `account number` field needs to be updated:
| LeadID | AccountNumber |
| --- | --- |
| 147 | 5807811235 |
| 150 | 5807811326 |
| 185 | 7006100100007267039 |
And this is the `RetrieveAccountNumber` table, where I need to update from:
| LeadID | AccountNumber |
| --- | --- |
| 147 | 7006100100007266957 |
| 150 | 7006100100007267039 |
I tried the below, but no luck so far:
```
UPDATE [Sales_Lead].[dbo].[Sales_Import]
SET [AccountNumber] = (SELECT RetrieveAccountNumber.AccountNumber
FROM RetrieveAccountNumber
WHERE [Sales_Lead].[dbo].[Sales_Import]. LeadID =
RetrieveAccountNumber.LeadID)
```
It updates the card numbers to account numbers, but the account numbers get replaced by `NULL`
|
I believe an `UPDATE FROM` with a `JOIN` will help:
MS SQL
------
```
UPDATE
Sales_Import
SET
Sales_Import.AccountNumber = RAN.AccountNumber
FROM
Sales_Import SI
INNER JOIN
RetrieveAccountNumber RAN
ON
SI.LeadID = RAN.LeadID;
```
MySQL and MariaDB
-----------------
```
UPDATE
Sales_Import SI,
RetrieveAccountNumber RAN
SET
SI.AccountNumber = RAN.AccountNumber
WHERE
SI.LeadID = RAN.LeadID;
```
|
224,748 |
<p>I'm having trouble with a custom tag:-</p>
<p>org.apache.jasper.JasperException: /custom_tags.jsp(1,0) Unable to find setter method for attribute : firstname</p>
<p>This is my TagHandler class:</p>
<pre><code>package com.cg.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class NameTag extends TagSupport{
public String firstname;
public String lastname;
public void setFirstName(String firstname){
this.firstname=firstname;
}
public void setLastName(String lastname){
this.lastname=lastname;
}
public int doStartTag() throws JspException {
try {
JspWriter out=pageContext.getOut();
out.println( "First name: "+firstname+ "Last name: "+lastname);
} catch (Exception ex) {
throw new JspException("IO problems");
}
return SKIP_BODY;
}
}
</code></pre>
<p>This is my TLD file:</p>
<pre><code>?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.1</tlibversion>
<jspversion>1.1</jspversion>
<shortname>utility</shortname>
<uri>/WEB-INF/nametagdesc.tld</uri>
<info>
A simple tag library for the examples
</info>
<tag>
<name>name</name>
<tagclass>com.cg.tags.NameTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>firstname</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>lastname</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
</code></pre>
<p>And this is my JSP page:</p>
<pre><code><%@ taglib uri="/WEB-INF/nametagdesc.tld" prefix="cg" %>
<cg:name firstname="fname" lastname="lname"/>
</code></pre>
<p>I have checked that the code is recompiled and deployed correctly etc etc....</p>
<p>So, the question is , why can't it find the setter method???</p>
|
[
{
"answer_id": 224833,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 2,
"selected": false,
"text": "<p>The TLD file in your example looks like nonsense, I don't know if it's because you've not formatted it correctly.</p>\n\n<p>The <em>tag</em> element for your custom tag should have an <em>attribute</em> element that corresponds to each attribute you want to expose. Something like:</p>\n\n<pre><code><tag>\n <name>...</name>\n <tag-class>...</tag-class>\n <body-content>...</body-content>\n <display-name>...</display-name>\n <description>...</description>\n\n <attribute>\n <name>firstName</name>\n <required>true</required>\n <rtexprvalue>true</rtexprvalue>\n <description>...</description>\n </attribute>\n</tag>\n</code></pre>\n\n<p>Note that by default attributes are Strings. This can be overridden by adding a <em>type</em> element within the <em>attribute</em> element.</p>\n"
},
{
"answer_id": 224911,
"author": "belugabob",
"author_id": 13397,
"author_profile": "https://Stackoverflow.com/users/13397",
"pm_score": 5,
"selected": true,
"text": "<p>Check the case of the attributes in your tag element - they should match the case of the setter, not the case of the member variables (Which should probably be private, by the way).</p>\n\n<p>The rule is that the attribute name has its first letter capitalised and then the result is prefixed by 'set', to arrive at the setter name.</p>\n\n<p>In your case, you've called the attribute <code>'firstname'</code>, so the rule results in the the JSP compiler looking for the 'setFirstname' method. As you've named your setter <code>'setFirstName'</code> (with a capital 'N'), you should use <code>'firstName'</code> (Also with a capital 'N') for the attribute name.</p>\n\n<p>Apply the same rule to the <code>'lastname'</code> attribute, to arrive at <code>'lastName'</code>, and you should be in business.</p>\n\n<p>P.S. Using a good IDE, like <code>IntelliJ</code>, would have helped in this case, as it would have suggested the valid names for your attributes, saving you a lot of head scratching.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28557/"
] |
I'm having trouble with a custom tag:-
org.apache.jasper.JasperException: /custom\_tags.jsp(1,0) Unable to find setter method for attribute : firstname
This is my TagHandler class:
```
package com.cg.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class NameTag extends TagSupport{
public String firstname;
public String lastname;
public void setFirstName(String firstname){
this.firstname=firstname;
}
public void setLastName(String lastname){
this.lastname=lastname;
}
public int doStartTag() throws JspException {
try {
JspWriter out=pageContext.getOut();
out.println( "First name: "+firstname+ "Last name: "+lastname);
} catch (Exception ex) {
throw new JspException("IO problems");
}
return SKIP_BODY;
}
}
```
This is my TLD file:
```
?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.1</tlibversion>
<jspversion>1.1</jspversion>
<shortname>utility</shortname>
<uri>/WEB-INF/nametagdesc.tld</uri>
<info>
A simple tag library for the examples
</info>
<tag>
<name>name</name>
<tagclass>com.cg.tags.NameTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>firstname</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>lastname</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
```
And this is my JSP page:
```
<%@ taglib uri="/WEB-INF/nametagdesc.tld" prefix="cg" %>
<cg:name firstname="fname" lastname="lname"/>
```
I have checked that the code is recompiled and deployed correctly etc etc....
So, the question is , why can't it find the setter method???
|
Check the case of the attributes in your tag element - they should match the case of the setter, not the case of the member variables (Which should probably be private, by the way).
The rule is that the attribute name has its first letter capitalised and then the result is prefixed by 'set', to arrive at the setter name.
In your case, you've called the attribute `'firstname'`, so the rule results in the the JSP compiler looking for the 'setFirstname' method. As you've named your setter `'setFirstName'` (with a capital 'N'), you should use `'firstName'` (Also with a capital 'N') for the attribute name.
Apply the same rule to the `'lastname'` attribute, to arrive at `'lastName'`, and you should be in business.
P.S. Using a good IDE, like `IntelliJ`, would have helped in this case, as it would have suggested the valid names for your attributes, saving you a lot of head scratching.
|
224,756 |
<p>Our customers application seems to hang with the following stack trace:</p>
<pre><code> java.lang.Thread.State: RUNNABLE
at java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
at java.io.UnixFileSystem.getBooleanAttributes(Unknown Source)
at java.io.File.isFile(Unknown Source)
at org.tmatesoft.svn.core.internal.wc.SVNFileType.getType(SVNFileType.java:118)
at org.tmatesoft.svn.core.internal.wc.SVNFileUtil.createUniqueFile(SVNFileUtil.java:299)
- locked <0x92ebb2a0> (a java.lang.Class for org.tmatesoft.svn.core.internal.wc.SVNFileUtil)
at org.tmatesoft.svn.core.internal.wc.SVNRemoteDiffEditor.createTempFile(SVNRemoteDiffEditor.java:415)
at org.tmatesoft.svn.core.internal.wc.SVNRemoteDiffEditor.applyTextDelta(SVNRemoteDiffEditor.java:255)
</code></pre>
<p>Anyone know what could cause it to hang in isFile?</p>
|
[
{
"answer_id": 224781,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "<p>No idea, but the obvious question of which JDK/JRE comes to mind and what others have you tried...</p>\n"
},
{
"answer_id": 224783,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps the SVN repository is somehow locked All I can do is guess.</p>\n\n<p>Does the application access a subversion repository?</p>\n\n<p>It might be waiting for the repository to be not locked again, who knows its your application.</p>\n"
},
{
"answer_id": 224838,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p><code>getBooleanAttributes0</code> calls <code>stat</code> (or <code>stat64</code>, if available). If you have the OpenJDK source code, this is listed in file <code>jdk/src/solaris/native/java/io/UnixFileSystem_md.c</code>.</p>\n\n<p>So the real question is, why is <code>stat</code> frozen? Is the file being accessed a network file on a server that's down, for example? If this is a reproducible problem, you may wish to use <code>strace</code> to attach to the Java process, just prior to the freezing. Then look in the output for calls to <code>stat</code>, to see what's being accessed.</p>\n"
},
{
"answer_id": 224864,
"author": "staffan",
"author_id": 988,
"author_profile": "https://Stackoverflow.com/users/988",
"pm_score": 3,
"selected": false,
"text": "<p>Looks like the <code>stat</code> call that results from <code>getBooleanAttributes0</code> is blocking. This typically happens because the file is located on an NFS share which is down.</p>\n"
},
{
"answer_id": 2787519,
"author": "James Blackburn",
"author_id": 115144,
"author_profile": "https://Stackoverflow.com/users/115144",
"pm_score": 1,
"selected": false,
"text": "<p>We see this issue in Eclipse when it stats a non-existent file in a NFS automount directory.</p>\n\n<p>If you strace your java process with -f -t -T (follow forks and time) what we see is that <em>most</em> the stats return in a very short time. The ones in the automount directory take two orders of magnitudes longer.</p>\n\n<p>In many cases the OS takes this as an opportunity to context switch the thread out. The result is that the thread performing the stat is not running for a very long time. If your Java code (an Eclipse plugin in our case) is inefficiently stating up the tree recursively for every file, you can end up locking up that thread for a long time.</p>\n\n<p>The solution, is to stop your Java from doing that.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Our customers application seems to hang with the following stack trace:
```
java.lang.Thread.State: RUNNABLE
at java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
at java.io.UnixFileSystem.getBooleanAttributes(Unknown Source)
at java.io.File.isFile(Unknown Source)
at org.tmatesoft.svn.core.internal.wc.SVNFileType.getType(SVNFileType.java:118)
at org.tmatesoft.svn.core.internal.wc.SVNFileUtil.createUniqueFile(SVNFileUtil.java:299)
- locked <0x92ebb2a0> (a java.lang.Class for org.tmatesoft.svn.core.internal.wc.SVNFileUtil)
at org.tmatesoft.svn.core.internal.wc.SVNRemoteDiffEditor.createTempFile(SVNRemoteDiffEditor.java:415)
at org.tmatesoft.svn.core.internal.wc.SVNRemoteDiffEditor.applyTextDelta(SVNRemoteDiffEditor.java:255)
```
Anyone know what could cause it to hang in isFile?
|
`getBooleanAttributes0` calls `stat` (or `stat64`, if available). If you have the OpenJDK source code, this is listed in file `jdk/src/solaris/native/java/io/UnixFileSystem_md.c`.
So the real question is, why is `stat` frozen? Is the file being accessed a network file on a server that's down, for example? If this is a reproducible problem, you may wish to use `strace` to attach to the Java process, just prior to the freezing. Then look in the output for calls to `stat`, to see what's being accessed.
|
224,765 |
<p>I am trying to create a user interface using XAML. However, the file is quickly becoming very large and difficult to work with. What is the best way for splitting it across several files.</p>
<p>I would like to be able to set the content of an element such as a ComboBox to an element that is defined in a different xaml file (but in the same VS project).</p>
<p>thanks</p>
|
[
{
"answer_id": 224803,
"author": "EFrank",
"author_id": 28572,
"author_profile": "https://Stackoverflow.com/users/28572",
"pm_score": 5,
"selected": false,
"text": "<p>You can split up XAML files by using a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.resourcedictionary.aspx\" rel=\"noreferrer\">ResourceDictionary</a>. The ResourceDictionary can be used to merge other files:</p>\n\n<pre><code><Page.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"myresourcedictionary.xaml\"/>\n <ResourceDictionary Source=\"myresourcedictionary2.xaml\"/>\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n</Page.Resources>\n</code></pre>\n\n<p>In the ResourceDictionary, you can also declare Styles that you can use at your elements, such that the main XAML file gets smaller.</p>\n\n<p>Another possibility to get a smaller XAML file is to define your own controls that you then use in your main app.</p>\n"
},
{
"answer_id": 224805,
"author": "Andrey Neverov",
"author_id": 6698,
"author_profile": "https://Stackoverflow.com/users/6698",
"pm_score": -1,
"selected": false,
"text": "<p>Use styles and user controls. Divide your interface on smaller parts and code them in another xaml files.\nExample:</p>\n\n<p><code>\n<Window><br>\n <VeryBigControl><br>\n <VeryBigControl.Style><br>\n ... <!--very long style--><br>\n </VeryBigControl.Style><br>\n .. <!--content of very big control--><br>\n </VeryBigControl<br>\n</Window>\n</code> </p>\n\n<p>divide it into three xaml files:<br>\nWindow.xaml - this will be Window<br>\nVeryBigControl.xaml - this will be UserControl<br>\nVeryBigControlStyle.xaml - this will be resource dictionary<br>\nand so on :)</p>\n"
},
{
"answer_id": 224816,
"author": "stusmith",
"author_id": 6604,
"author_profile": "https://Stackoverflow.com/users/6604",
"pm_score": 7,
"selected": true,
"text": "<p>You can split a large user interface by defining UserControls.</p>\n\n<p>Right-click on the solution tree, choose Add->New Item... then User Control. You can design this in the normal way.</p>\n\n<p>You can then reference your usercontrol in XAML using a namespace declaration. Let's say you want to include your UserControl in a Window. In the following example I've added a UserControl named \"Foo\" to the namespace \"YourCompany.Controls\":</p>\n\n<pre><code><Window x:Class=\"YourCompany.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:Controls=\"clr-namespace:YourCompany.Controls\">\n\n <Controls:Foo ... />\n</code></pre>\n\n<p>For your specific example, you would make use of your usercontrol in a combobox by defining a DataTemplate that displayed the data within your usercontrol.</p>\n"
},
{
"answer_id": 40079551,
"author": "Mike de Klerk",
"author_id": 1567665,
"author_profile": "https://Stackoverflow.com/users/1567665",
"pm_score": 2,
"selected": false,
"text": "<p>You can also create a <a href=\"https://msdn.microsoft.com/en-us/library/system.windows.controls.page(v=vs.110).aspx\" rel=\"nofollow\">Page</a>, instead of a <code>UserControl</code>. A <code>Page</code> can be hosted by the <code>Window</code> or by a <a href=\"https://msdn.microsoft.com/en-us/library/system.windows.controls.frame(v=vs.110).aspx\" rel=\"nofollow\">Frame</a>. Search for the pros and cons of a Page vs UserControl. It depends a bit on your requirements with respect to navigation which will suit your needs best. </p>\n\n<p><a href=\"http://www.c-sharpcorner.com/uploadfile/mahesh/using-xaml-frame-in-wpf857/\" rel=\"nofollow\">Here is an example of using a Page in a Frame.</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18966/"
] |
I am trying to create a user interface using XAML. However, the file is quickly becoming very large and difficult to work with. What is the best way for splitting it across several files.
I would like to be able to set the content of an element such as a ComboBox to an element that is defined in a different xaml file (but in the same VS project).
thanks
|
You can split a large user interface by defining UserControls.
Right-click on the solution tree, choose Add->New Item... then User Control. You can design this in the normal way.
You can then reference your usercontrol in XAML using a namespace declaration. Let's say you want to include your UserControl in a Window. In the following example I've added a UserControl named "Foo" to the namespace "YourCompany.Controls":
```
<Window x:Class="YourCompany.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:YourCompany.Controls">
<Controls:Foo ... />
```
For your specific example, you would make use of your usercontrol in a combobox by defining a DataTemplate that displayed the data within your usercontrol.
|
224,771 |
<p>In python how do you read multiple files from a mysql database using the cursor or loop one by one and store the output in a separate table?</p>
|
[
{
"answer_id": 224801,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>I don't understand your question (what are files?, what's your table structure?), but here goes a simple sample:</p>\n\n<pre><code>>>> import MySQLdb\n>>> conn = MySQLdb.connect(host=\"localhost\",\n user=\"root\",\n password=\"merlin\",\n db=\"files\")\n>>> cursor = conn.cursor()\n>>> cursor.execute(\"SELECT * FROM files\")\n5L\n>>> rows = cursor.fetchall()\n>>> cursor.execute(\"CREATE TABLE destination (file varchar(255))\")\n0L\n>>> for row in rows:\n... cursor.execute(\"INSERT INTO destination VALUES (%s)\" % row[0])\n...\n1L\n1L\n1L\n1L\n1L\n</code></pre>\n"
},
{
"answer_id": 224844,
"author": "unmounted",
"author_id": 11596,
"author_profile": "https://Stackoverflow.com/users/11596",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an example, assuming you have created the table you want to move to, with descriptive names:</p>\n\n<pre><code>>>> import MySQLdb\n>>> conn = MySQLdb.connect(user='username', db='dbname')\n>>> cur = conn.cursor()\n>>> cur.execute('select files from old_table where conditions=met')\n>>> a = cur.fetchall()\n>>> for item in a:\n... cur.execute('update new_table set new_field = %s' % item) # `item` should be tuple with one value, else use \"(item,)\" with comma\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451/"
] |
In python how do you read multiple files from a mysql database using the cursor or loop one by one and store the output in a separate table?
|
I don't understand your question (what are files?, what's your table structure?), but here goes a simple sample:
```
>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",
user="root",
password="merlin",
db="files")
>>> cursor = conn.cursor()
>>> cursor.execute("SELECT * FROM files")
5L
>>> rows = cursor.fetchall()
>>> cursor.execute("CREATE TABLE destination (file varchar(255))")
0L
>>> for row in rows:
... cursor.execute("INSERT INTO destination VALUES (%s)" % row[0])
...
1L
1L
1L
1L
1L
```
|
224,777 |
<p>I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the __declspec(thread) declaration:</p>
<pre><code>__declspec(thread) int lastId = 0;
</code></pre>
<p>However, at the first access of the variable, I get a NullReferenceException.
To be more precise, the declaration is done within a <em>ref class</em> (a .NET class implemented in C++/CLI).</p>
<p>I have already read something about __declspec(thread) does not work with delay loaded DLLs.
Am I using delay loaded DLLs automatically if I use .NET?</p>
|
[
{
"answer_id": 224802,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 4,
"selected": true,
"text": "<p>It seems that __declspec(thread) <a href=\"http://blogs.msdn.com/jeremykuhne/archive/2006/04/19/578670.aspx\" rel=\"nofollow noreferrer\">isn't supported by CLR</a>.</p>\n\n<p>Take in mind that .net threads aren't necesarily native threads, <a href=\"http://blogs.msdn.com/cbrumme/archive/2003/04/15/51351.aspx\" rel=\"nofollow noreferrer\">but can be also fibers</a>, so standard API's for threads don't work on them.</p>\n\n<p>If you have a managed class, then you should use managed threading API's for <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.getnameddataslot(vs.80).aspx\" rel=\"nofollow noreferrer\">thread local storage</a>.</p>\n\n<p>There are a lot of articles regarding this difference. This is just to get you started.</p>\n\n<p>As a tip: You could use the ThreadStatic Attribute instead of the TLS in order to improve <a href=\"http://blogs.msdn.com/ricom/archive/2006/07/18/performance-quiz-10-thread-local-storage-solution.aspx\" rel=\"nofollow noreferrer\">performance</a>. In case you are working with ASP.NET applications, you need to remember <a href=\"http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html\" rel=\"nofollow noreferrer\">some things</a> about TLS.</p>\n"
},
{
"answer_id": 224813,
"author": "Bruce",
"author_id": 6310,
"author_profile": "https://Stackoverflow.com/users/6310",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately not supported. Here's a blog entry with a workaround:</p>\n\n<p><a href=\"http://blogs.msdn.com/jeremykuhne/archive/2006/04/19/578670.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/jeremykuhne/archive/2006/04/19/578670.aspx</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28572/"
] |
I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the \_\_declspec(thread) declaration:
```
__declspec(thread) int lastId = 0;
```
However, at the first access of the variable, I get a NullReferenceException.
To be more precise, the declaration is done within a *ref class* (a .NET class implemented in C++/CLI).
I have already read something about \_\_declspec(thread) does not work with delay loaded DLLs.
Am I using delay loaded DLLs automatically if I use .NET?
|
It seems that \_\_declspec(thread) [isn't supported by CLR](http://blogs.msdn.com/jeremykuhne/archive/2006/04/19/578670.aspx).
Take in mind that .net threads aren't necesarily native threads, [but can be also fibers](http://blogs.msdn.com/cbrumme/archive/2003/04/15/51351.aspx), so standard API's for threads don't work on them.
If you have a managed class, then you should use managed threading API's for [thread local storage](http://msdn.microsoft.com/en-us/library/system.threading.thread.getnameddataslot(vs.80).aspx).
There are a lot of articles regarding this difference. This is just to get you started.
As a tip: You could use the ThreadStatic Attribute instead of the TLS in order to improve [performance](http://blogs.msdn.com/ricom/archive/2006/07/18/performance-quiz-10-thread-local-storage-solution.aspx). In case you are working with ASP.NET applications, you need to remember [some things](http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html) about TLS.
|
224,797 |
<p>I've got the following code to end a process, but I still receive an error code 2 (Access Denied).</p>
<pre><code>strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'MSSEARCH.exe'")
For each objProcess in colProcessList
wscript.echo objProcess.processid
intrc = objProcess.Terminate()
if intrc = 0 then wscript.echo "succesfully killed process" else wscript.echo "Could not kill process. Error code: " & intrc End if
</code></pre>
|
[
{
"answer_id": 224819,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 3,
"selected": true,
"text": "<p>It's quite legitimate to get \"access denied\" for ending a program. If it's a service (which I'm guessing mssearch.exe is), then it is probably running as the \"SYSTEM\" user, which has higher privileges than even the Administrator account.</p>\n\n<p>You can't log on as the SYSTEM account, but you could probably write a service to manage other services...</p>\n"
},
{
"answer_id": 224858,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>As a non-privileged user, you can only end processes you own. In a multiuser environment this can bite you in the ankle, because WMI would return equally named processes from other users as well, unless you write a more specific WQL query.</p>\n\n<p>If your process is a service, and your script runs under a privileged account, you may still need to take \"the regular route\" to stop it, for example using <code>WScript.Shell</code> to call <code>net stop</code> or <code>sc.exe</code>, or, more elegantly, using the <code>Win32_Service</code> class:</p>\n\n<pre><code>Set Services = objWMIService.ExecQuery _\n (\"SELECT * FROM Win32_Service WHERE Name = '\" & ServiceName & \"'\")\n\nFor Each Service In Services\n Service.StopService()\n WSCript.Sleep 2000 ' wait for the service to terminate '\nNext\n</code></pre>\n"
},
{
"answer_id": 224889,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 0,
"selected": false,
"text": "<p>If you look on this page: <a href=\"http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx</a> you would see that error code 2 is access denied instead of file not found</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28139/"
] |
I've got the following code to end a process, but I still receive an error code 2 (Access Denied).
```
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'MSSEARCH.exe'")
For each objProcess in colProcessList
wscript.echo objProcess.processid
intrc = objProcess.Terminate()
if intrc = 0 then wscript.echo "succesfully killed process" else wscript.echo "Could not kill process. Error code: " & intrc End if
```
|
It's quite legitimate to get "access denied" for ending a program. If it's a service (which I'm guessing mssearch.exe is), then it is probably running as the "SYSTEM" user, which has higher privileges than even the Administrator account.
You can't log on as the SYSTEM account, but you could probably write a service to manage other services...
|
224,820 |
<p>I'm trying to figure out how to pass arguments to an anonymous function in JavaScript.</p>
<p>Check out this sample code and I think you will see what I mean:</p>
<pre><code><input type="button" value="Click me" id="myButton" />
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function(myMessage) { alert(myMessage); };
</script>
</code></pre>
<p>When clicking the button the message: <code>it's working</code> should appear. However the <code>myMessage</code> variable inside the anonymous function is null.</p>
<p>jQuery uses a lot of anonymous functions, what is the best way to pass that argument?</p>
|
[
{
"answer_id": 224834,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 7,
"selected": true,
"text": "<p>Your specific case can simply be corrected to be working:</p>\n\n<pre><code><script type=\"text/javascript\">\n var myButton = document.getElementById(\"myButton\");\n var myMessage = \"it's working\";\n myButton.onclick = function() { alert(myMessage); };\n</script>\n</code></pre>\n\n<p>This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.</p>\n\n<p>For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there</p>\n"
},
{
"answer_id": 224835,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 3,
"selected": false,
"text": "<p>By removing the parameter from the anonymous function will be available in the body.</p>\n\n<pre><code> myButton.onclick = function() { alert(myMessage); };\n</code></pre>\n\n<p>For more info search for 'javascript closures'</p>\n"
},
{
"answer_id": 224839,
"author": "jmcd",
"author_id": 2285,
"author_profile": "https://Stackoverflow.com/users/2285",
"pm_score": 5,
"selected": false,
"text": "<p>What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it). </p>\n\n<p>You could do this however:</p>\n\n<pre><code><input type=\"button\" value=\"Click me\" id=\"myButton\"/>\n\n<script type=\"text/javascript\">\n\n var myButton = document.getElementById(\"myButton\");\n\n var myMessage = \"it's working\";\n\n var myDelegate = function(message) {\n alert(message);\n }\n\n myButton.onclick = function() { \n myDelegate(myMessage);\n };\n\n</script>\n</code></pre>\n"
},
{
"answer_id": 224841,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 0,
"selected": false,
"text": "<p>What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).</p>\n"
},
{
"answer_id": 224842,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 0,
"selected": false,
"text": "<p>If you write it like</p>\n\n<pre><code>myButton.onclick = function() { alert(myMessage); };\n</code></pre>\n\n<p>It will work, but I don't know if that answers your questions.</p>\n"
},
{
"answer_id": 224869,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 1,
"selected": false,
"text": "<p>Example:</p>\n\n<pre><code><input type=\"button\" value=\"Click me\" id=\"myButton\">\n<script>\n var myButton = document.getElementById(\"myButton\");\n var test = \"zipzambam\";\n myButton.onclick = function(eventObject) {\n if (!eventObject) {\n eventObject = window.event;\n }\n if (!eventObject.target) {\n eventObject.target = eventObject.srcElement;\n }\n alert(eventObject.target);\n alert(test);\n };\n (function(myMessage) {\n alert(myMessage);\n })(\"Hello\");\n</script>\n</code></pre>\n"
},
{
"answer_id": 224870,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 2,
"selected": false,
"text": "<p>The delegates:</p>\n\n<pre><code>function displayMessage(message, f)\n{\n f(message); // execute function \"f\" with variable \"message\"\n}\n\nfunction alerter(message)\n{\n alert(message);\n}\n\nfunction writer(message)\n{\n document.write(message);\n}\n</code></pre>\n\n<p>Running the displayMessage function:</p>\n\n<pre><code>function runDelegate()\n{\n displayMessage(\"Hello World!\", alerter); // alert message\n\n displayMessage(\"Hello World!\", writer); // write message to DOM\n}\n</code></pre>\n"
},
{
"answer_id": 224882,
"author": "wioota",
"author_id": 11979,
"author_profile": "https://Stackoverflow.com/users/11979",
"pm_score": 3,
"selected": false,
"text": "<p>Event handlers expect one parameter which is the event that was fired. You happen to be renaming that to 'myMessage' and therefore you are alerting the event object rather than your message.</p>\n\n<p>A closure can allow you to reference the variable you have defined outside the function however if you are using Jquery you may want to look at its event specific API e.g.</p>\n\n<p><a href=\"http://docs.jquery.com/Events/bind#typedatafn\" rel=\"noreferrer\">http://docs.jquery.com/Events/bind#typedatafn</a></p>\n\n<p>This has an option for passing in your own data.</p>\n"
},
{
"answer_id": 3834579,
"author": "Un Known",
"author_id": 463271,
"author_profile": "https://Stackoverflow.com/users/463271",
"pm_score": 2,
"selected": false,
"text": "<pre><code><input type=\"button\" value=\"Click me\" id=\"myButton\" />\n\n<script type=\"text/javascript\">\n var myButton = document.getElementById(\"myButton\");\n\n myButton.myMessage = \"it's working\";\n\n myButton.onclick = function() { alert(this.myMessage); };\n\n\n</script>\n</code></pre>\n\n<p>This works in my test suite which includes everything from IE6+. The anonymous function is aware of the object which it belongs to therefore you can pass data <em>with</em> the object that's calling it ( in this case myButton ).</p>\n"
},
{
"answer_id": 3950023,
"author": "Gabriel",
"author_id": 204210,
"author_profile": "https://Stackoverflow.com/users/204210",
"pm_score": 4,
"selected": false,
"text": "<p>The following is a method for using closures to address the issue to which you refer. It also takes into account the fact that may which to change the message over time without affecting the binding. And it uses jQuery to be succinct.</p>\n\n<pre><code>var msg = (function(message){\n var _message = message;\n return {\n say:function(){alert(_message)},\n change:function(message){_message = message}\n };\n})(\"My Message\");\n$(\"#myButton\").click(msg.say);\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29886/"
] |
I'm trying to figure out how to pass arguments to an anonymous function in JavaScript.
Check out this sample code and I think you will see what I mean:
```
<input type="button" value="Click me" id="myButton" />
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function(myMessage) { alert(myMessage); };
</script>
```
When clicking the button the message: `it's working` should appear. However the `myMessage` variable inside the anonymous function is null.
jQuery uses a lot of anonymous functions, what is the best way to pass that argument?
|
Your specific case can simply be corrected to be working:
```
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>
```
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
|
224,830 |
<p>I have a large script file (nearly 300MB, and feasibly bigger in the future) that I am trying to run. It has been suggested in the comments of Gulzar's answer to my <a href="https://stackoverflow.com/questions/222442/sql-server-running-large-script-files">question about it</a> that I should change the script timeout to 0 (no timeout).</p>
<p>What is the best way to set this timeout from within the script? At the moment I have all of this at the top of the script file in the hopes that one of them does something:</p>
<pre><code>sp_configure 'remote login timeout', 600
go
sp_configure 'remote query timeout', 0
go
sp_configure 'query wait', 0
go
reconfigure with override
go
</code></pre>
<p>However, I'm still getting the same result and I can't tell if I'm succeeding in setting the timeout because the response from sqlcmd.exe is the world's least helpful error message:</p>
<blockquote>
<p>Sqlcmd: Error: Scripting error.</p>
</blockquote>
|
[
{
"answer_id": 224955,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "<p>I think there is <strong>no concept of timeout within a SQL script</strong> on SQL Server. You have to set the timeout in the calling layer / client.</p>\n\n<p>According to <a href=\"http://support.microsoft.com/?scid=kb%3Ben-us%3B314530&x=14&y=12\" rel=\"nofollow noreferrer\">this MSDN article</a> you could try to increase the timeout this way:</p>\n\n<pre><code>exec sp_configure 'remote query timeout', 0 \ngo \nreconfigure with override \ngo \n</code></pre>\n\n<p><em>\"Use the remote query timeout option to specify how long, in seconds, a remote operation can take before Microsoft SQL Server times out. The default is 600, which allows a 10-minute wait. This value applies to an outgoing connection initiated by the Database Engine as a remote query. This value has no effect on queries received by the Database Engine.\"</em></p>\n\n<p><em>P.S.: By 300 MB you mean the resulting file is 300 MB? I don't hope that the script file itself is 300 MB. That would be a world record. ;-)</em></p>\n"
},
{
"answer_id": 224956,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 4,
"selected": true,
"text": "<pre><code>sqlcmd -t {n}\n</code></pre>\n\n<p>Where {n} must be a number between 0 and 65535.</p>\n\n<p>Note that your question is a bit misleading since <a href=\"http://blogs.msdn.com/khen1234/archive/2005/10/20/483015.aspx\" rel=\"noreferrer\">the server has no concept of a timeout</a> and therefore you cannot set the timeout within your script. </p>\n\n<p>In your context the timeout is enforced by <strong><a href=\"http://msdn.microsoft.com/en-us/library/ms170572.aspx\" rel=\"noreferrer\">sqlcmd</a></strong></p>\n"
},
{
"answer_id": 666872,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Your solution - Add GO every 100 or 150 lines</p>\n\n<p><a href=\"http://www.red-gate.com/MessageBoard/viewtopic.php?t=8109\" rel=\"noreferrer\">http://www.red-gate.com/MessageBoard/viewtopic.php?t=8109</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
I have a large script file (nearly 300MB, and feasibly bigger in the future) that I am trying to run. It has been suggested in the comments of Gulzar's answer to my [question about it](https://stackoverflow.com/questions/222442/sql-server-running-large-script-files) that I should change the script timeout to 0 (no timeout).
What is the best way to set this timeout from within the script? At the moment I have all of this at the top of the script file in the hopes that one of them does something:
```
sp_configure 'remote login timeout', 600
go
sp_configure 'remote query timeout', 0
go
sp_configure 'query wait', 0
go
reconfigure with override
go
```
However, I'm still getting the same result and I can't tell if I'm succeeding in setting the timeout because the response from sqlcmd.exe is the world's least helpful error message:
>
> Sqlcmd: Error: Scripting error.
>
>
>
|
```
sqlcmd -t {n}
```
Where {n} must be a number between 0 and 65535.
Note that your question is a bit misleading since [the server has no concept of a timeout](http://blogs.msdn.com/khen1234/archive/2005/10/20/483015.aspx) and therefore you cannot set the timeout within your script.
In your context the timeout is enforced by **[sqlcmd](http://msdn.microsoft.com/en-us/library/ms170572.aspx)**
|
224,845 |
<p>I am using the ruby daemons gem to create a custom daemon for my rails project. The only problem is that when I try to start the daemons <code>ruby lib/daemons/test_ctl start</code> that it fails and will not start. The log file has this output.</p>
<pre><code># Logfile created on Wed Oct 22 16:14:23 +0000 2008 by /
*** below you find the most recent exception thrown, this will be likely (but not certainly) the exception that made the application exit abnormally \*\*\*
# MissingSourceFile: no such file to load -- utf8proc_native
*** below you find all exception objects found in memory, some of them may have been thrown in your application, others may just be in memory because they are standard exceptions ***
# NoMemoryError: failed to allocate memory>
# SystemStackError: stack level too deep>
# fatal: exception reentered>
# LoadError: no such file to load -- daemons>
# LoadError: no such file to load -- active_support>
# MissingSourceFile: no such file to load -- lib/string>
# MissingSourceFile: no such file to load -- utf8proc_native>
</code></pre>
<p>It even happens when I generate a daemon (from the rails plugin) and try to run it. Does anybody know how to fix this problem? </p>
|
[
{
"answer_id": 224990,
"author": "Josh Moore",
"author_id": 5004,
"author_profile": "https://Stackoverflow.com/users/5004",
"pm_score": 3,
"selected": true,
"text": "<p>OK, I actually found the answer to this problem. I require two custom files in the <code>config/environment.rb</code>. I used relative path names and because the daemons are executed in the rails main directory it could not find these two files. after making them absolute path it fixed the problem.</p>\n"
},
{
"answer_id": 366241,
"author": "Dave Smylie",
"author_id": 1505600,
"author_profile": "https://Stackoverflow.com/users/1505600",
"pm_score": 1,
"selected": false,
"text": "<p>I just spent 30 minutes trying to solve a similar error when trying to get daemons plugin working: </p>\n\n<pre><code>LoadError: no such file to load -- active_support\n</code></pre>\n\n<p>For some reason, it wasn't finding <code>active_support</code> lib, even though it was installed. (Perhaps due to me having frozen rails).<br>\nIn my case, the solution to this was to use the absolute path for active_support in my<br>\nctl file (eg <code>lib/daemons/mailer_ctl</code>). </p>\n\n<p>I needed to change line 5 from:</p>\n\n<pre><code> require 'active_support'\n</code></pre>\n\n<p>to </p>\n\n<pre><code> require './vendor/rails/activesupport/lib/active_support.rb'\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
I am using the ruby daemons gem to create a custom daemon for my rails project. The only problem is that when I try to start the daemons `ruby lib/daemons/test_ctl start` that it fails and will not start. The log file has this output.
```
# Logfile created on Wed Oct 22 16:14:23 +0000 2008 by /
*** below you find the most recent exception thrown, this will be likely (but not certainly) the exception that made the application exit abnormally \*\*\*
# MissingSourceFile: no such file to load -- utf8proc_native
*** below you find all exception objects found in memory, some of them may have been thrown in your application, others may just be in memory because they are standard exceptions ***
# NoMemoryError: failed to allocate memory>
# SystemStackError: stack level too deep>
# fatal: exception reentered>
# LoadError: no such file to load -- daemons>
# LoadError: no such file to load -- active_support>
# MissingSourceFile: no such file to load -- lib/string>
# MissingSourceFile: no such file to load -- utf8proc_native>
```
It even happens when I generate a daemon (from the rails plugin) and try to run it. Does anybody know how to fix this problem?
|
OK, I actually found the answer to this problem. I require two custom files in the `config/environment.rb`. I used relative path names and because the daemons are executed in the rails main directory it could not find these two files. after making them absolute path it fixed the problem.
|
224,865 |
<p>I'm wondering if there are any simple ways to get a list of all fixed-width (monospaced) fonts installed on a user's system in C#?</p>
<p>I'm using .net 3.5 so have access to the WPF System.Windows.Media namespace and LINQ to get font information, but I'm not sure what I'm looking for.</p>
<p>I want to be able to provide a filtered list of monospaced fonts and/or pick out monospaced fonts from a larger list of fonts (as seen in the VS options dialog).</p>
|
[
{
"answer_id": 224917,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>AFAIK you can't do it using BCL libraries only. You have to use WinAPI interop.</p>\n\n<p>You need to analyze 2 lowest bits of <a href=\"https://msdn.microsoft.com/en-us/library/dd145037(v=vs.85).aspx\" rel=\"nofollow noreferrer\">LOGFONT</a>.lfPitchAndFamily member. There is a constant FIXED_PITCH (means that font is fixed-width) that can be used as a bit mask for lfPitchAndFamily.</p>\n\n<p>Here is a useful article:</p>\n\n<p><a href=\"http://www.catch22.net/tuts/fixed-width-font-enumeration\" rel=\"nofollow noreferrer\">Enumerating Fonts</a></p>\n\n<blockquote>\n <p>Enumerating fonts can be a little\n confusing, and unless you want to\n enumerate all fonts on your system,\n can be a little more difficult than\n MSDN suggests. This article will\n explain exactly the steps you need to\n use to find every fixed-width font on\n your system, and also enumerate every\n possible size for each individual\n font.</p>\n</blockquote>\n"
},
{
"answer_id": 225027,
"author": "Tim Ebenezer",
"author_id": 30273,
"author_profile": "https://Stackoverflow.com/users/30273",
"pm_score": 5,
"selected": true,
"text": "<p>Have a look at:</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/Structures/LOGFONT.html\" rel=\"noreferrer\">http://www.pinvoke.net/default.aspx/Structures/LOGFONT.html</a></p>\n\n<p>Use one of the structures in there, then loop over families, instantiating a Font, and getting the LogFont value and checking lfPitchAndFamily.</p>\n\n<p>The following code is written on the fly and untested, but something like the following should work:</p>\n\n<pre><code>foreach (FontFamily ff in System.Drawing.FontFamily.Families)\n{\n if (ff.IsStyleAvailable(FontStyle.Regular))\n {\n Font font = new Font(ff, 10);\n LOGFONT lf = new LOGFONT();\n font.ToLogFont(lf);\n if (lf.lfPitchAndFamily ^ 1)\n {\n do stuff here......\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8545011,
"author": "Panos Theof",
"author_id": 917341,
"author_profile": "https://Stackoverflow.com/users/917341",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately <strong>ToLogFont</strong> function does not fill <strong>lfPitchAndFamily</strong> field to correct values. In my case it's always 0.</p>\n\n<p>One approximation to detect which fonts might be fixed is the following</p>\n\n<pre><code> foreach ( FontFamily ff in FontFamily.Families ) {\n if ( ff.IsStyleAvailable( FontStyle.Regular ) ) {\n float diff;\n using ( Font font = new Font( ff, 16 ) ) {\n diff = TextRenderer.MeasureText( \"WWW\", font ).Width - TextRenderer.MeasureText( \"...\", font ).Width;\n }\n if ( Math.Abs( diff ) < float.Epsilon * 2 ) {\n Debug.WriteLine( ff.ToString() );\n }\n }\n\n }\n</code></pre>\n\n<p>Keep in mind that they are several false positives, for example Wingdings</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
] |
I'm wondering if there are any simple ways to get a list of all fixed-width (monospaced) fonts installed on a user's system in C#?
I'm using .net 3.5 so have access to the WPF System.Windows.Media namespace and LINQ to get font information, but I'm not sure what I'm looking for.
I want to be able to provide a filtered list of monospaced fonts and/or pick out monospaced fonts from a larger list of fonts (as seen in the VS options dialog).
|
Have a look at:
<http://www.pinvoke.net/default.aspx/Structures/LOGFONT.html>
Use one of the structures in there, then loop over families, instantiating a Font, and getting the LogFont value and checking lfPitchAndFamily.
The following code is written on the fly and untested, but something like the following should work:
```
foreach (FontFamily ff in System.Drawing.FontFamily.Families)
{
if (ff.IsStyleAvailable(FontStyle.Regular))
{
Font font = new Font(ff, 10);
LOGFONT lf = new LOGFONT();
font.ToLogFont(lf);
if (lf.lfPitchAndFamily ^ 1)
{
do stuff here......
}
}
}
```
|
224,868 |
<p>I know it's simple to implement, but I want to reuse something that already exist.</p>
<p>Problem I want to solve is that I load configuration (from XML so I want to cache them) for different pages, roles, ... so the combination of inputs can grow quite much (but in 99% will not). To handle this 1%, I want to have some max number of items in cache...</p>
<p>Till know I have found org.apache.commons.collections.map.LRUMap in apache commons and it looks fine but want to check also something else. Any recommendations?</p>
|
[
{
"answer_id": 224886,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 8,
"selected": true,
"text": "<p>You can use a <a href=\"http://docs.oracle.com/javase/6/docs/api/index.html?java/util/LinkedHashMap.html\" rel=\"noreferrer\">LinkedHashMap</a> (Java 1.4+) :</p>\n\n<pre><code>// Create cache\nfinal int MAX_ENTRIES = 100;\nMap cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {\n // This method is called just after a new entry has been added\n public boolean removeEldestEntry(Map.Entry eldest) {\n return size() > MAX_ENTRIES;\n }\n};\n\n// Add to cache\nObject key = \"key\";\ncache.put(key, object);\n\n// Get object\nObject o = cache.get(key);\nif (o == null && !cache.containsKey(key)) {\n // Object not in cache. If null is not a possible value in the cache,\n // the call to cache.contains(key) is not needed\n}\n\n// If the cache is to be used by multiple threads,\n// the cache must be wrapped with code to synchronize the methods\ncache = (Map)Collections.synchronizedMap(cache);\n</code></pre>\n"
},
{
"answer_id": 7584179,
"author": "Bobby Powers",
"author_id": 367650,
"author_profile": "https://Stackoverflow.com/users/367650",
"pm_score": 5,
"selected": false,
"text": "<p>This is an old question, but for posterity I wanted to list <a href=\"https://github.com/ben-manes/concurrentlinkedhashmap\" rel=\"noreferrer\">ConcurrentLinkedHashMap</a>, which is thread safe, unlike <a href=\"https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/LRUMap.html\" rel=\"noreferrer\">LRUMap</a>. Usage is quite easy:</p>\n\n<pre><code>ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>()\n .maximumWeightedCapacity(1000)\n .build();\n</code></pre>\n\n<p>And the documentation has some good <a href=\"https://github.com/ben-manes/concurrentlinkedhashmap/wiki/ExampleUsage\" rel=\"noreferrer\">examples</a>, like how to make the LRU cache size-based instead of number-of-items based.</p>\n"
},
{
"answer_id": 8589587,
"author": "Daimon",
"author_id": 500103,
"author_profile": "https://Stackoverflow.com/users/500103",
"pm_score": 1,
"selected": false,
"text": "<p>I also had same problem and I haven't found any good libraries... so I've created my own.</p>\n\n<p>simplelrucache provides threadsafe, very simple, non-distributed LRU caching with TTL support. It provides two implementations</p>\n\n<ul>\n<li>Concurrent based on ConcurrentLinkedHashMap</li>\n<li>Synchronized based on LinkedHashMap</li>\n</ul>\n\n<p>You can find it <a href=\"http://code.google.com/p/simplelrucache/\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 9348179,
"author": "Barak",
"author_id": 1219027,
"author_profile": "https://Stackoverflow.com/users/1219027",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://github.com/barakb/Cache\" rel=\"nofollow\">Here</a> is a very simple and easy to use LRU cache in Java.\nAlthough it is short and simple it is production quality.\nThe code is explained (look at the README.md) and has some unit tests.</p>\n"
},
{
"answer_id": 11731495,
"author": "botek",
"author_id": 1564403,
"author_profile": "https://Stackoverflow.com/users/1564403",
"pm_score": 4,
"selected": false,
"text": "<p>Here is my implementation which lets me keep an optimal number of elements in memory.</p>\n\n<p>The point is that I do not need to keep track of what objects are currently being used since I'm using a combination of a LinkedHashMap for the MRU objects and a WeakHashMap for the LRU objects.\nSo the cache capacity is no less than MRU size plus whatever the GC lets me keep. Whenever objects fall off the MRU they go to the LRU for as long as the GC will have them.</p>\n\n<pre><code>public class Cache<K,V> {\nfinal Map<K,V> MRUdata;\nfinal Map<K,V> LRUdata;\n\npublic Cache(final int capacity)\n{\n LRUdata = new WeakHashMap<K, V>();\n\n MRUdata = new LinkedHashMap<K, V>(capacity+1, 1.0f, true) {\n protected boolean removeEldestEntry(Map.Entry<K,V> entry)\n {\n if (this.size() > capacity) {\n LRUdata.put(entry.getKey(), entry.getValue());\n return true;\n }\n return false;\n };\n };\n}\n\npublic synchronized V tryGet(K key)\n{\n V value = MRUdata.get(key);\n if (value!=null)\n return value;\n value = LRUdata.get(key);\n if (value!=null) {\n LRUdata.remove(key);\n MRUdata.put(key, value);\n }\n return value;\n}\n\npublic synchronized void set(K key, V value)\n{\n LRUdata.remove(key);\n MRUdata.put(key, value);\n}\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1128722/"
] |
I know it's simple to implement, but I want to reuse something that already exist.
Problem I want to solve is that I load configuration (from XML so I want to cache them) for different pages, roles, ... so the combination of inputs can grow quite much (but in 99% will not). To handle this 1%, I want to have some max number of items in cache...
Till know I have found org.apache.commons.collections.map.LRUMap in apache commons and it looks fine but want to check also something else. Any recommendations?
|
You can use a [LinkedHashMap](http://docs.oracle.com/javase/6/docs/api/index.html?java/util/LinkedHashMap.html) (Java 1.4+) :
```
// Create cache
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
// This method is called just after a new entry has been added
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
};
// Add to cache
Object key = "key";
cache.put(key, object);
// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
// Object not in cache. If null is not a possible value in the cache,
// the call to cache.contains(key) is not needed
}
// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
```
|
224,875 |
<p>Is it possible to do the equivalent of the following in xslt:</p>
<pre><code>.//TagA[./TagB/[@AttrA='AttrAValue'] = 'TagBValue']
</code></pre>
<p>This is failing within Visual Studio 2008 with the following error:</p>
<pre><code>error: Unexpected token '[' in the expression.
.//TagA[./TagB/ -->[<-- @AttrA='AttrAValue'] = 'TagBValue']
</code></pre>
<p>Should this be working? Is this a problem in the MS implementation of XSLT, or is there a way I can get all TagA nodes that have a TagB node whose AttrA is equal to AttrAValue and whose TagB innerText is equal to TagBValue.</p>
|
[
{
"answer_id": 224886,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 8,
"selected": true,
"text": "<p>You can use a <a href=\"http://docs.oracle.com/javase/6/docs/api/index.html?java/util/LinkedHashMap.html\" rel=\"noreferrer\">LinkedHashMap</a> (Java 1.4+) :</p>\n\n<pre><code>// Create cache\nfinal int MAX_ENTRIES = 100;\nMap cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {\n // This method is called just after a new entry has been added\n public boolean removeEldestEntry(Map.Entry eldest) {\n return size() > MAX_ENTRIES;\n }\n};\n\n// Add to cache\nObject key = \"key\";\ncache.put(key, object);\n\n// Get object\nObject o = cache.get(key);\nif (o == null && !cache.containsKey(key)) {\n // Object not in cache. If null is not a possible value in the cache,\n // the call to cache.contains(key) is not needed\n}\n\n// If the cache is to be used by multiple threads,\n// the cache must be wrapped with code to synchronize the methods\ncache = (Map)Collections.synchronizedMap(cache);\n</code></pre>\n"
},
{
"answer_id": 7584179,
"author": "Bobby Powers",
"author_id": 367650,
"author_profile": "https://Stackoverflow.com/users/367650",
"pm_score": 5,
"selected": false,
"text": "<p>This is an old question, but for posterity I wanted to list <a href=\"https://github.com/ben-manes/concurrentlinkedhashmap\" rel=\"noreferrer\">ConcurrentLinkedHashMap</a>, which is thread safe, unlike <a href=\"https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/LRUMap.html\" rel=\"noreferrer\">LRUMap</a>. Usage is quite easy:</p>\n\n<pre><code>ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>()\n .maximumWeightedCapacity(1000)\n .build();\n</code></pre>\n\n<p>And the documentation has some good <a href=\"https://github.com/ben-manes/concurrentlinkedhashmap/wiki/ExampleUsage\" rel=\"noreferrer\">examples</a>, like how to make the LRU cache size-based instead of number-of-items based.</p>\n"
},
{
"answer_id": 8589587,
"author": "Daimon",
"author_id": 500103,
"author_profile": "https://Stackoverflow.com/users/500103",
"pm_score": 1,
"selected": false,
"text": "<p>I also had same problem and I haven't found any good libraries... so I've created my own.</p>\n\n<p>simplelrucache provides threadsafe, very simple, non-distributed LRU caching with TTL support. It provides two implementations</p>\n\n<ul>\n<li>Concurrent based on ConcurrentLinkedHashMap</li>\n<li>Synchronized based on LinkedHashMap</li>\n</ul>\n\n<p>You can find it <a href=\"http://code.google.com/p/simplelrucache/\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 9348179,
"author": "Barak",
"author_id": 1219027,
"author_profile": "https://Stackoverflow.com/users/1219027",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://github.com/barakb/Cache\" rel=\"nofollow\">Here</a> is a very simple and easy to use LRU cache in Java.\nAlthough it is short and simple it is production quality.\nThe code is explained (look at the README.md) and has some unit tests.</p>\n"
},
{
"answer_id": 11731495,
"author": "botek",
"author_id": 1564403,
"author_profile": "https://Stackoverflow.com/users/1564403",
"pm_score": 4,
"selected": false,
"text": "<p>Here is my implementation which lets me keep an optimal number of elements in memory.</p>\n\n<p>The point is that I do not need to keep track of what objects are currently being used since I'm using a combination of a LinkedHashMap for the MRU objects and a WeakHashMap for the LRU objects.\nSo the cache capacity is no less than MRU size plus whatever the GC lets me keep. Whenever objects fall off the MRU they go to the LRU for as long as the GC will have them.</p>\n\n<pre><code>public class Cache<K,V> {\nfinal Map<K,V> MRUdata;\nfinal Map<K,V> LRUdata;\n\npublic Cache(final int capacity)\n{\n LRUdata = new WeakHashMap<K, V>();\n\n MRUdata = new LinkedHashMap<K, V>(capacity+1, 1.0f, true) {\n protected boolean removeEldestEntry(Map.Entry<K,V> entry)\n {\n if (this.size() > capacity) {\n LRUdata.put(entry.getKey(), entry.getValue());\n return true;\n }\n return false;\n };\n };\n}\n\npublic synchronized V tryGet(K key)\n{\n V value = MRUdata.get(key);\n if (value!=null)\n return value;\n value = LRUdata.get(key);\n if (value!=null) {\n LRUdata.remove(key);\n MRUdata.put(key, value);\n }\n return value;\n}\n\npublic synchronized void set(K key, V value)\n{\n LRUdata.remove(key);\n MRUdata.put(key, value);\n}\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30273/"
] |
Is it possible to do the equivalent of the following in xslt:
```
.//TagA[./TagB/[@AttrA='AttrAValue'] = 'TagBValue']
```
This is failing within Visual Studio 2008 with the following error:
```
error: Unexpected token '[' in the expression.
.//TagA[./TagB/ -->[<-- @AttrA='AttrAValue'] = 'TagBValue']
```
Should this be working? Is this a problem in the MS implementation of XSLT, or is there a way I can get all TagA nodes that have a TagB node whose AttrA is equal to AttrAValue and whose TagB innerText is equal to TagBValue.
|
You can use a [LinkedHashMap](http://docs.oracle.com/javase/6/docs/api/index.html?java/util/LinkedHashMap.html) (Java 1.4+) :
```
// Create cache
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
// This method is called just after a new entry has been added
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
};
// Add to cache
Object key = "key";
cache.put(key, object);
// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
// Object not in cache. If null is not a possible value in the cache,
// the call to cache.contains(key) is not needed
}
// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
```
|
224,878 |
<p>What is the best way to find out whether two number ranges intersect?</p>
<p>My number range is <strong>3023-7430</strong>, now I want to test which of the following number ranges intersect with it: <3000, 3000-6000, 6000-8000, 8000-10000, >10000. The answer should be <strong>3000-6000</strong> and <strong>6000-8000</strong>.</p>
<p>What's the nice, efficient mathematical way to do this in any programming language?</p>
|
[
{
"answer_id": 224897,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 5,
"selected": true,
"text": "<p>Just a pseudo code guess:</p>\n\n<pre><code>Set<Range> determineIntersectedRanges(Range range, Set<Range> setofRangesToTest)\n{\n Set<Range> results;\n foreach (rangeToTest in setofRangesToTest)\n do\n if (rangeToTest.end <range.start) continue; // skip this one, its below our range\n if (rangeToTest.start >range.end) continue; // skip this one, its above our range\n results.add(rangeToTest);\n done\n return results;\n}\n</code></pre>\n"
},
{
"answer_id": 224907,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 3,
"selected": false,
"text": "<p>I would make a Range class and give it a method boolean intersects(Range) . Then you can do a</p>\n\n<pre><code>foreach(Range r : rangeset) { if (range.intersects(r)) res.add(r) }\n</code></pre>\n\n<p>or, if you use some Java 8 style functional programming for clarity:</p>\n\n<pre><code>rangeset.stream().filter(range::intersects).collect(Collectors.toSet())\n</code></pre>\n\n<p>The intersection itself is something like</p>\n\n<pre><code>this.start <= other.end && this.end >= other.start\n</code></pre>\n"
},
{
"answer_id": 225065,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 2,
"selected": false,
"text": "<p>This heavily depends on your ranges. A range can be big or small, and clustered or not clustered. If you have large, clustered ranges (think of \"all positive 32-bit integers that can be divided by 2), the simple approach with Range(lower, upper) will not succeed.</p>\n\n<p>I guess I can say the following:\nif you have little ranges (clustering or not clustering does not matter here), consider bitvectors. These little critters are blazing fast with respect to union, intersection and membership testing, even though iteration over all elements might take a while, depending on the size. Furthermore, because they just use a single bit for each element, they are pretty small, unless you throw huge ranges at them. </p>\n\n<p>if you have fewer, larger ranges, then a class Range as describe by otherswill suffices. This class has the attributes lower and upper and intersection(a,b) is basically b.upper < a.lower or a.upper > b.lower. Union and intersection can be implemented in constant time for single ranges and for compisite ranges, the time grows with the number of sub-ranges (thus you do not want not too many little ranges)</p>\n\n<p>If you have a huge space where your numbers can be, and the ranges are distributed in a nasty fasion, you should take a look at binary decision diagrams (BDDs). These nifty diagrams have two terminal nodes, True and False and decision nodes for each <em>bit</em> of the input. A decision node has a bit it looks at and two following graph nodes -- one for \"bit is one\" and one for \"bit is zero\". Given these conditions, you can encode large ranges in tiny space. All positive integers for arbitrarily large numbers can be encoded in 3 nodes in the graph -- basically a single decision node for the least significant bit which goes to False on 1 and to True on 0. </p>\n\n<p>Intersection and Union are pretty elegant recursive algorithms, for example, the intersection basically takes two corresponding nodes in each BDD, traverse the 1-edge until some result pops up and checks: if one of the results is the False-Terminal, create a 1-branch to the False-terminal in the result BDD. If both are the True-Terminal, create a 1-branch to the True-terminal in the result BDD. If it is something else, create a 1-branch to this something-else in the result BDD. After that, some minimization kicks in (if the 0- and the 1-branch of a node go to the same following BDD / terminal, remove it and pull the incoming transitions to the target) and you are golden. We even went further than that, we worked on simulating addition of sets of integers on BDDs in order to enhance value prediction in order to optimize conditions.</p>\n\n<p>These considerations imply that your operations are bounded by the amount of bits in your number range, that is, by log_2(MAX_NUMBER). Just think of it, you can intersect arbitrary sets of 64-bit-integers in almost constant time. </p>\n\n<p>More information can be for example in the <a href=\"http://en.wikipedia.org/wiki/Binary_decision_diagram\" rel=\"nofollow noreferrer\">Wikipedia</a> and the referenced papers.</p>\n\n<p>Further, if false positives are bearable and you need an existence check only, you can look at Bloom filters. Bloom filters use a vector of hashes in order to check if an element is contained in the represented set. Intersection and Union is constant time. The major problem here is that you get an increasing false-positive rate if you fill up the bloom-filter too much.\nInformation, again, in the <a href=\"http://en.wikipedia.org/wiki/Bloom_filter\" rel=\"nofollow noreferrer\">Wikipedia</a>, for example. </p>\n\n<p>Hach, set representation is a fun field. :)</p>\n"
},
{
"answer_id": 225079,
"author": "Andrea Ambu",
"author_id": 21384,
"author_profile": "https://Stackoverflow.com/users/21384",
"pm_score": 1,
"selected": false,
"text": "<p>In python</p>\n\n<pre><code>class nrange(object):\n def __init__(self, lower = None, upper = None):\n self.lower = lower\n self.upper = upper\n def intersection(self, aRange):\n if self.upper < aRange.lower or aRange.upper < self.lower:\n return None\n else:\n return nrange(max(self.lower,aRange.lower), \\\n min(self.upper,aRange.upper))\n</code></pre>\n"
},
{
"answer_id": 8159816,
"author": "TAN70",
"author_id": 328473,
"author_profile": "https://Stackoverflow.com/users/328473",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using Java\n<a href=\"http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/Range.html#overlapsRange%28org.apache.commons.lang.math.Range%29\" rel=\"nofollow\">Commons Lang Range</a>\nhas a \noverlapsRange(Range range) method.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/476/"
] |
What is the best way to find out whether two number ranges intersect?
My number range is **3023-7430**, now I want to test which of the following number ranges intersect with it: <3000, 3000-6000, 6000-8000, 8000-10000, >10000. The answer should be **3000-6000** and **6000-8000**.
What's the nice, efficient mathematical way to do this in any programming language?
|
Just a pseudo code guess:
```
Set<Range> determineIntersectedRanges(Range range, Set<Range> setofRangesToTest)
{
Set<Range> results;
foreach (rangeToTest in setofRangesToTest)
do
if (rangeToTest.end <range.start) continue; // skip this one, its below our range
if (rangeToTest.start >range.end) continue; // skip this one, its above our range
results.add(rangeToTest);
done
return results;
}
```
|
224,926 |
<p>for example, I have the following xml document:</p>
<pre><code>def CAR_RECORDS = '''
<records>
<car name='HSV Maloo' make='Holden' year='2006'/>
<car name='P50' make='Peel' year='1962'/>
<car name='Royale' make='Bugatti' year='1931'/>
</records>
'''
</code></pre>
<p>and I want to move the car "Royale" up to first one, and insert a new car just after car"HSV Maloo", the result would be:</p>
<pre><code>'''
<records>
<car name='Royale' make='Bugatti' year='1931'/>
<car name='HSV Maloo' make='Holden' year='2006'/>
<car name='My New Car' make='Peel' year='1962'/>
<car name='P50' make='Peel' year='1962'/>
</records>
'''
</code></pre>
<p>How to do it with Groovy? comments are welcome.</p>
|
[
{
"answer_id": 227467,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 2,
"selected": false,
"text": "<p><hand-wave>\n<em>these are not the codz you seek</em>\n</hand-wave></p>\n\n<pre><code>Node root = new XmlParser().parseText(CAR_RECORDS)\nNodeList carNodes = root.car\nNode royale = carNodes[2]\ncarNodes.remove(royale)\ncarNodes.add(0, royale)\ncarNodes.add(2, new Node(root, 'car', [name:'My New Card', make:'Peel', year:'1962']))\n</code></pre>\n\n<p>I don't know if there's a smarter way to create new nodes... but that works for me.</p>\n\n<p>EDIT: uhg... thanks guys... I got lazy and was printing carNodes when i tested this instead of the root... yikes. </p>\n"
},
{
"answer_id": 228505,
"author": "Ted Naleid",
"author_id": 8912,
"author_profile": "https://Stackoverflow.com/users/8912",
"pm_score": 5,
"selected": true,
"text": "<p>I went down a similar route to danb, but ran into problems when actually printing out the resulting XML. Then I realized that the NodeList that was returned by asking the root for all of it's \"car\" children isn't the same list as you get by just asking for the root's children. Even though they happen to be the same lists in this case, they wouldn't always be if there were non \"car\" children under the root. Because of this, reording the list of cars that come back from the query doesn't affect the initial list.</p>\n\n<p>Here's a solution that appends and reorders:</p>\n\n<pre><code>def CAR_RECORDS = '''\n <records>\n <car name='HSV Maloo' make='Holden' year='2006'/>\n <car name='P50' make='Peel' year='1962'/>\n <car name='Royale' make='Bugatti' year='1931'/>\n </records>\n '''\n\ndef carRecords = new XmlParser().parseText(CAR_RECORDS)\n\ndef cars = carRecords.children()\ndef royale = cars.find { it.@name == 'Royale' } \ncars.remove(royale)\ncars.add(0, royale)\ndef newCar = new Node(carRecords, 'car', [name:'My New Car', make:'Peel', year:'1962'])\n\nassert [\"Royale\", \"HSV Maloo\", \"P50\", \"My New Car\"] == carRecords.car*.@name\n\nnew XmlNodePrinter().print(carRecords)\n</code></pre>\n\n<p>The assertion with the propertly ordered cars passes, and the XmlNodePrinter outputs:</p>\n\n<pre><code><records>\n <car year=\"1931\" make=\"Bugatti\" name=\"Royale\"/>\n <car year=\"2006\" make=\"Holden\" name=\"HSV Maloo\"/>\n <car year=\"1962\" make=\"Peel\" name=\"P50\"/>\n <car name=\"My New Car\" make=\"Peel\" year=\"1962\"/>\n</records>\n</code></pre>\n"
},
{
"answer_id": 228905,
"author": "flyisland",
"author_id": 30275,
"author_profile": "https://Stackoverflow.com/users/30275",
"pm_score": 3,
"selected": false,
"text": "<p>ted, maybe you did not notice that I wanted to '''insert a new car just after car\"HSV Maloo\"''', so I modify your code to :</p>\n\n<pre><code>def newCar = new Node(null, 'car', [name:'My New Car', make:'Peel', year:'1962'])\ncars.add(2, newCar)\n\nnew XmlNodePrinter().print(carRecords)\n</code></pre>\n\n<p>now, it works with proper order! thanks to danb & ted.</p>\n\n<pre><code><records>\n <car year=\"1931\" make=\"Bugatti\" name=\"Royale\"/>\n <car year=\"2006\" make=\"Holden\" name=\"HSV Maloo\"/>\n <car name=\"My New Car\" make=\"Peel\" year=\"1962\"/>\n <car year=\"1962\" make=\"Peel\" name=\"P50\"/>\n</records>\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30275/"
] |
for example, I have the following xml document:
```
def CAR_RECORDS = '''
<records>
<car name='HSV Maloo' make='Holden' year='2006'/>
<car name='P50' make='Peel' year='1962'/>
<car name='Royale' make='Bugatti' year='1931'/>
</records>
'''
```
and I want to move the car "Royale" up to first one, and insert a new car just after car"HSV Maloo", the result would be:
```
'''
<records>
<car name='Royale' make='Bugatti' year='1931'/>
<car name='HSV Maloo' make='Holden' year='2006'/>
<car name='My New Car' make='Peel' year='1962'/>
<car name='P50' make='Peel' year='1962'/>
</records>
'''
```
How to do it with Groovy? comments are welcome.
|
I went down a similar route to danb, but ran into problems when actually printing out the resulting XML. Then I realized that the NodeList that was returned by asking the root for all of it's "car" children isn't the same list as you get by just asking for the root's children. Even though they happen to be the same lists in this case, they wouldn't always be if there were non "car" children under the root. Because of this, reording the list of cars that come back from the query doesn't affect the initial list.
Here's a solution that appends and reorders:
```
def CAR_RECORDS = '''
<records>
<car name='HSV Maloo' make='Holden' year='2006'/>
<car name='P50' make='Peel' year='1962'/>
<car name='Royale' make='Bugatti' year='1931'/>
</records>
'''
def carRecords = new XmlParser().parseText(CAR_RECORDS)
def cars = carRecords.children()
def royale = cars.find { it.@name == 'Royale' }
cars.remove(royale)
cars.add(0, royale)
def newCar = new Node(carRecords, 'car', [name:'My New Car', make:'Peel', year:'1962'])
assert ["Royale", "HSV Maloo", "P50", "My New Car"] == carRecords.car*.@name
new XmlNodePrinter().print(carRecords)
```
The assertion with the propertly ordered cars passes, and the XmlNodePrinter outputs:
```
<records>
<car year="1931" make="Bugatti" name="Royale"/>
<car year="2006" make="Holden" name="HSV Maloo"/>
<car year="1962" make="Peel" name="P50"/>
<car name="My New Car" make="Peel" year="1962"/>
</records>
```
|
224,952 |
<p>What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just</p>
<pre><code>String content = new File("test.txt").readFully();
</code></pre>
|
[
{
"answer_id": 224970,
"author": "Lars Westergren",
"author_id": 15627,
"author_profile": "https://Stackoverflow.com/users/15627",
"pm_score": 1,
"selected": false,
"text": "<pre><code>String content = (new RandomAccessFile(new File(\"test.txt\"))).readUTF();\n</code></pre>\n\n<p>Unfortunately Java is very picky about the source file being valid UTF8 though, or you will get an EOFException or UTFDataFormatException.</p>\n"
},
{
"answer_id": 225010,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>You have to create your own function, I suppose. The problem is that Java's read routines (those I know, at least) usually take a buffer argument with a given length.</p>\n\n<p>A solution I saw is to get the size of the file, create a buffer of this size and read the file at once. Hoping the file isn't a gigabyte log or XML file...</p>\n\n<p>The usual way is to have a fixed size buffer or to use readLine and concatenate the results in a StringBuffer/StringBuilder.</p>\n"
},
{
"answer_id": 225022,
"author": "alex",
"author_id": 26787,
"author_profile": "https://Stackoverflow.com/users/26787",
"pm_score": 2,
"selected": false,
"text": "<p>Helper functions. I basically use a few of them, depending on the situation</p>\n\n<ul>\n<li>cat method that pipes an InputStream to an OutputStream</li>\n<li>method that calls cat to a ByteArrayOutputStream and extracts the byte array, enabling quick read of an entire file to a byte array</li>\n<li>Implementation of Iterator<String> that is constructed using a Reader; it wraps it in a BufferedReader and readLine's on next()</li>\n<li>...</li>\n</ul>\n\n<p>Either roll your own or use something out of commons-io or your preferred utility library.</p>\n"
},
{
"answer_id": 225268,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>To give an example of such an helper function:</p>\n\n<pre><code>String[] lines = NioUtils.readInFile(componentxml);\n</code></pre>\n\n<p>The key is to try to close the BufferedReader even if an IOException is thrown.</p>\n\n<pre><code>/**\n * Read lines in a file. <br />\n * File must exist\n * @param f file to be read\n * @return array of lines, empty if file empty\n * @throws IOException if prb during access or closing of the file\n */\npublic static String[] readInFile(final File f) throws IOException\n{\n final ArrayList lines = new ArrayList();\n IOException anioe = null;\n BufferedReader br = null; \n try \n {\n br = new BufferedReader(new FileReader(f));\n String line;\n line = br.readLine();\n while(line != null)\n {\n lines.add(line);\n line = br.readLine();\n }\n br.close();\n br = null;\n } \n catch (final IOException e) \n {\n anioe = e;\n }\n finally\n {\n if(br != null)\n {\n try {\n br.close();\n } catch (final IOException e) {\n anioe = e;\n }\n }\n if(anioe != null)\n {\n throw anioe;\n }\n }\n final String[] myStrings = new String[lines.size()];\n //myStrings = lines.toArray(myStrings);\n System.arraycopy(lines.toArray(), 0, myStrings, 0, lines.size());\n return myStrings;\n}\n</code></pre>\n\n<p>(if you just want a String, change the function to append each lines to a StringBuffer (or StringBuilder in java5 or 6)</p>\n"
},
{
"answer_id": 576468,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think reading using BufferedReader is a good idea because BufferedReader will return just the content of line without the delimeter. When the line contains nothing but newline character, BR will return a null although it still doesn't reach the end of the stream.</p>\n"
},
{
"answer_id": 576475,
"author": "jonathan.cone",
"author_id": 42344,
"author_profile": "https://Stackoverflow.com/users/42344",
"pm_score": 0,
"selected": false,
"text": "<p>String org.apache.commons.io.FileUtils.readFileToString(File file)</p>\n"
},
{
"answer_id": 576480,
"author": "Fabian Steeg",
"author_id": 18154,
"author_profile": "https://Stackoverflow.com/users/18154",
"pm_score": 3,
"selected": false,
"text": "<p>I think using a Scanner is quite OK with regards to conciseness of Java on-board tools:</p>\n\n<pre><code>Scanner s = new Scanner(new File(\"file\"));\nStringBuilder builder = new StringBuilder();\nwhile(s.hasNextLine()) builder.append(s.nextLine());\n</code></pre>\n\n<p>Also, it's quite flexible, too (e.g. regular expressions support, number parsing).</p>\n"
},
{
"answer_id": 576485,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "<p>Pick one from here.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file\">How do I create a Java string from the contents of a file?</a></p>\n\n<p>The favorite was: </p>\n\n<pre><code>private static String readFile(String path) throws IOException {\n FileInputStream stream = new FileInputStream(new File(path));\n try {\n FileChannel fc = stream.getChannel();\n MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());\n /* Instead of using default, pass in a decoder. */\n return CharSet.defaultCharset().decode(bb).toString();\n }\n finally {\n stream.close();\n }\n}\n</code></pre>\n\n<p>Posted by <a href=\"https://stackoverflow.com/users/3474/erickson\">erickson</a></p>\n"
},
{
"answer_id": 577356,
"author": "Brian Agnew",
"author_id": 12960,
"author_profile": "https://Stackoverflow.com/users/12960",
"pm_score": 4,
"selected": true,
"text": "<p>Use the <a href=\"http://commons.apache.org/io/description.html\" rel=\"noreferrer\">Apache Commons IOUtils</a> package. In particular the <code>IOUtils</code> class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc. </p>\n\n<p>e.g.</p>\n\n<pre><code>InputStream is = ...\nString contents = IOUtils.toString(is);\n// or\nList lines = IOUtils.readLines(is)\n</code></pre>\n"
},
{
"answer_id": 41591108,
"author": "Doc Brown",
"author_id": 3198272,
"author_profile": "https://Stackoverflow.com/users/3198272",
"pm_score": 0,
"selected": false,
"text": "<p>Or the Java 8 way:</p>\n\n<pre><code>try {\n String str = new String(Files.readAllBytes(Paths.get(\"myfile.txt\")));\n ...\n} catch (IOException ex) {\n Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);\n}\n</code></pre>\n\n<p>One may pass an appropriate Charset to the String constructor.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
] |
What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just
```
String content = new File("test.txt").readFully();
```
|
Use the [Apache Commons IOUtils](http://commons.apache.org/io/description.html) package. In particular the `IOUtils` class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc.
e.g.
```
InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
```
|
224,969 |
<p>I have a string (char) and I want to extract numbers out of it.</p>
<p>So I have string: <code>1 2 3 4 /0</code><br>
And now I want some variables, so I can use them as integer: <code>a=1, a=2, a=3, a=4</code></p>
<p>How can I do that?</p>
|
[
{
"answer_id": 224994,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 2,
"selected": false,
"text": "<p>sscanf() can do that.</p>\n\n<pre><code>#include <stdio.h>\n\nint main(void)\n{\n int a, b, c, d;\n sscanf(\"1 2 3 4\", \"%d %d %d %d\", &a, &b, &c, &d);\n printf(\"%d,%d,%d,%d\\n\", a, b, c, d);\n}\n</code></pre>\n"
},
{
"answer_id": 224995,
"author": "HS.",
"author_id": 1398,
"author_profile": "https://Stackoverflow.com/users/1398",
"pm_score": 3,
"selected": true,
"text": "<p>If the string always contains 4 numbers delimited with spaces, then it could be done with sscanf:</p>\n\n<pre><code>sscanf(string, \"%d %d %d %d\", &a, &b, &c, &d);\n</code></pre>\n\n<p>If the count of numbers varies, then you would need to parse the string.</p>\n\n<p>Please clarify your question accordingly.</p>\n"
},
{
"answer_id": 225003,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 2,
"selected": false,
"text": "<p>As others have noted, if you know how many numbers to expect, sscanf is the easiest solution. Otherwise, the following sketches a more general solution:</p>\n\n<p>First tokenize the string by spaces. The standard C method for this is <a href=\"http://www.gnu.org/software/libtool/manual/libc/Finding-Tokens-in-a-String.html\" rel=\"nofollow noreferrer\">strtok()</a>:</p>\n\n<pre><code>char* copy;\nchar* token;\n\ncopy = strdup(string); /* strtok modifies the string, so we need a copy */\n\ntoken = strtok(copy, \" \");\nwhile(token!=NULL){\n /* token now points to one number.\n token = strtok(copy, \" \"); \n}\n</code></pre>\n\n<p>Then convert the string to integers. <a href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/atoi.html\" rel=\"nofollow noreferrer\">atoi()</a> will do that.</p>\n"
},
{
"answer_id": 225012,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 2,
"selected": false,
"text": "<p>The answers given so far are correct, as long as your string is formatted the way you expect. You should always check the return value of sscanf to make sure things worked okay. sscanf returns the number of conversions successfully performed, in the above case 4.</p>\n\n<pre><code>if (4 != sscanf(buf, \"%d %d %d %d\", &a, &b, &c, &d))\n{\n /* deal with error */\n}\n</code></pre>\n\n<p>If buf was \"1 2 3\" or \"1 2 a b\" or something, sscanf would return a short item count.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/224969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a string (char) and I want to extract numbers out of it.
So I have string: `1 2 3 4 /0`
And now I want some variables, so I can use them as integer: `a=1, a=2, a=3, a=4`
How can I do that?
|
If the string always contains 4 numbers delimited with spaces, then it could be done with sscanf:
```
sscanf(string, "%d %d %d %d", &a, &b, &c, &d);
```
If the count of numbers varies, then you would need to parse the string.
Please clarify your question accordingly.
|
225,045 |
<p>I've been reading up on conditional-style expressions in ruby. However I came across one I couldn't quite understand to define the classic FizzBuzz problem. I understand the FizzBuzz problem and even wrote my own before finding the following quick solution utilising the ternary operator. If someone can explain to me how this chain works to satisfy the FizzBuzz problem it would be very much appreciated :)</p>
<pre><code>for i in 0...100
puts i%3==0 ? i%5==0 ? "FizzBuzz" : "Buzz" : i%5==0 ? "Fizz" : i
end
</code></pre>
|
[
{
"answer_id": 225055,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "<p>Some parentheses might help:</p>\n\n<pre><code>puts (i%3 == 0) ? ((i%5 == 0) ? \"FizzBuzz\" : \"Buzz\") : ((i%5 == 0) ? \"Fizz\" : i)\n</code></pre>\n\n<p>So, if i is divisible by 3, then it checks whether i is also divisible by 5. If so, it prints \"FizzBuzz\" otherwise just \"Buzz\". If i is not divisible by three, then it checks divisibility by 5 again and prints \"Fizz\" if so, otherwise just i.</p>\n"
},
{
"answer_id": 225056,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 1,
"selected": false,
"text": "<p>the flow is:</p>\n\n<pre><code>if (i%3 == 0) { // multiple of 3\n if (i%5 == 0) { // multiple of 3 and 5\n puts \"FizzBuzz\"\n } else { // not multiple of 5, only of 3\n puts \"Buzz\"\n }\n} else ( // not multiple of 3\n if (i%5 == 0) { // multiple of 5, not of 3\n puts \"Fizz\"\n } else { // multiple of neither 5 nor 3\n puts i\n }\n}\n</code></pre>\n"
},
{
"answer_id": 225059,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 2,
"selected": false,
"text": "<p>The ternary is a basic if-then structure. </p>\n\n<p>The above is equivalent to...</p>\n\n<pre><code>if i%3 ==0\n if i%5 == 0\n \"FizzBuzz\"\n else\n \"Buzz\"\nelse\n if i%5 == 0\n \"Fizz\"\n else\n i\n</code></pre>\n\n<p>Or, using some parens...</p>\n\n<pre><code>puts i%3==0 ? ( i%5==0 ? \"FizzBuzz\" : \"Buzz\" ) : ( i%5==0 ? \"Fizz\" : i )\n</code></pre>\n"
},
{
"answer_id": 225084,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a description of the FizzBuzz problem as stated in this <a href=\"http://www.codinghorror.com/blog/archives/000781.html\" rel=\"noreferrer\">Jeff Atwood article</a>.</p>\n\n<blockquote>\n <p>Write a program that prints the\n numbers from 1 to 100. But for\n multiples of three print \"Fizz\"\n instead of the number and for the\n multiples of five print \"Buzz\". For\n numbers which are multiples of both\n three and five print \"FizzBuzz\".</p>\n</blockquote>\n\n<p>A <a href=\"http://en.wikipedia.org/wiki/Ternary_operation\" rel=\"noreferrer\">ternary operator</a> is shorthand writing for an if-else statement. The general format is:</p>\n\n<pre>\ncond ? evaluate_if_cond_is_true : evaluate_if_cond_is_false\n</pre>\n\n<p>So if I write:</p>\n\n<pre><code>int isEven = (i % 2 == 0) ? 1 : 0;\n</code></pre>\n\n<p>Is equivalent to the following code:</p>\n\n<pre><code>if (i % 2 == 0) {\n isEven = 1;\n} else {\n isEven = 0;\n}\n</code></pre>\n\n<p>Where cond is <code>i % 2 == 0</code>, evaluate_if_cond_is_true is <code>1</code> and evaluate_if_cond_is_false is <code>0</code>.</p>\n\n<p>The nice thing about ternary operators is that they can be combined. This means that the statement to execute when either condition evaluates to true or false can be another ternary operator.</p>\n\n<p>Let put the entire condition in a more readable fashion:</p>\n\n<pre><code>i%3==0 ?\n i%5==0 ?\n \"FizzBuzz\"\n : \"Buzz\"\n : i%5==0 ?\n \"Fizz\"\n : i\n</code></pre>\n\n<p>And mapping this to if-else statements is easy with the rules explained above:</p>\n\n<pre><code>if (i%3==0) {\n if (i%5==0) {\n \"FizzBuzz\"\n } else {\n \"Buzz\"\n }\n} else {\n if (i%5==0) {\n \"Fizz\"\n } else {\n i\n }\n}\n</code></pre>\n\n<p>This is not valid code but because the result of the ternary operator is inlined in the result expression it is used as input for the puts command.</p>\n"
},
{
"answer_id": 227308,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 3,
"selected": false,
"text": "<p>For fun, here's another way:</p>\n\n<pre><code>puts (1..100).map {|i| (fb = [[\"Fizz\"][i%3],[\"Buzz\"][i%5]].compact.join).empty? ? i : fb}\n</code></pre>\n\n<p>And another:</p>\n\n<pre><code>(1..100).zip([nil,nil,\"Fizz\"]*34,[nil,nil,nil,nil,\"Buzz\"]*20).map {|a,b,c| b || c ? [b,c].join : a}\n</code></pre>\n"
},
{
"answer_id": 59937599,
"author": "user3225968",
"author_id": 3225968,
"author_profile": "https://Stackoverflow.com/users/3225968",
"pm_score": 0,
"selected": false,
"text": "<p>Just for fun. If you wanted to do it in C#. Here's a simple way. It basically starts with your for loop that will print numbers from 1 to 100. It then asks if your index \"i\" is divisible by 3 and 5 if true then print to the console \"FizzBuzz\". Else if your index \"i\" is divisible by 3 if true then print to the console \"Fizz\". Else if your index \"i\" is divisible by 5 if true then print to the console \"Buzz\". Else just print out \"i\" which is your integer. I added tabbing for better readability. </p>\n\n<pre><code>for(int i = 1; i <= 100; i++) {\n string result = (i % 3 == 0 && i % 5 == 0) ? \n \"FizzBuzz\" : \n (i % 3 == 0) ? \n \"Fizz\" : \n (i % 5 == 0) ? \n \"Buzz\" : \n i.ToString();\n Console.WriteLine(result);\n }\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2294/"
] |
I've been reading up on conditional-style expressions in ruby. However I came across one I couldn't quite understand to define the classic FizzBuzz problem. I understand the FizzBuzz problem and even wrote my own before finding the following quick solution utilising the ternary operator. If someone can explain to me how this chain works to satisfy the FizzBuzz problem it would be very much appreciated :)
```
for i in 0...100
puts i%3==0 ? i%5==0 ? "FizzBuzz" : "Buzz" : i%5==0 ? "Fizz" : i
end
```
|
Some parentheses might help:
```
puts (i%3 == 0) ? ((i%5 == 0) ? "FizzBuzz" : "Buzz") : ((i%5 == 0) ? "Fizz" : i)
```
So, if i is divisible by 3, then it checks whether i is also divisible by 5. If so, it prints "FizzBuzz" otherwise just "Buzz". If i is not divisible by three, then it checks divisibility by 5 again and prints "Fizz" if so, otherwise just i.
|
225,080 |
<p>I'm trying to configure an ejabberd installation, using LDAP authentication, but I just can't login, even with the admin user.
This is part of my ejabberd.cfg file:</p>
<pre><code>%...
{auth_method, ldap}.
{ldap_servers, ["server2000.tek2000.local"]}.
{ldap_port,389}.
{ldap_uidattr, "uid"}.
{ldap_base, "dc=server2000,dc=tek2000,dc=com"}.
{ldap_rootdn, "[email protected]"}.
{ldap_password, "secret"}.
%...
</code></pre>
<p>What am I missing?</p>
<p>I must say that, with OpenFire, I can connect using this credentials/configuration.</p>
<p>I'm using Spark as my client application.</p>
<p>Thanks</p>
|
[
{
"answer_id": 225077,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "<p>Use a <a href=\"http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html\" rel=\"noreferrer\">ByteArrayOutputStream</a> and then get the data out of that using <a href=\"http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()\" rel=\"noreferrer\">toByteArray()</a>. This won't test <em>how</em> it writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.</p>\n"
},
{
"answer_id": 225857,
"author": "eljenso",
"author_id": 30316,
"author_profile": "https://Stackoverflow.com/users/30316",
"pm_score": 2,
"selected": false,
"text": "<p>If you can pass a Writer to XmlWriter, I would pass it a <code>StringWriter</code>. You can query the <code>StringWriter</code>'s contents using <code>toString()</code> on it.</p>\n\n<p>If you have to pass an <code>OutputStream</code>, you can pass a <code>ByteArrayOutputStream</code> and you can also call <code>toString()</code> on it to get its contents as a String.</p>\n\n<p>Then you can code something like:</p>\n\n<pre><code>public void testSomething()\n{\n Writer sw = new StringWriter();\n XmlWriter xw = new XmlWriter(sw);\n ...\n xw.writeString(\"foo\");\n ...\n assertEquals(\"...<aTag>foo</aTag>...\", sw.toString());\n}\n</code></pre>\n"
},
{
"answer_id": 39474680,
"author": "Dherik",
"author_id": 2387977,
"author_profile": "https://Stackoverflow.com/users/2387977",
"pm_score": 2,
"selected": false,
"text": "<p>It's simple. As @JonSkeet said:</p>\n\n<pre><code>ByteArrayOutputStream baos = new ByteArrayOutputStream();\n// pass the baos to be writed with \"value\", for this example\nbyte[] byteArray = baos.toByteArray();\nAssert.assertEquals(\"value\", new String(byteArray));\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019426/"
] |
I'm trying to configure an ejabberd installation, using LDAP authentication, but I just can't login, even with the admin user.
This is part of my ejabberd.cfg file:
```
%...
{auth_method, ldap}.
{ldap_servers, ["server2000.tek2000.local"]}.
{ldap_port,389}.
{ldap_uidattr, "uid"}.
{ldap_base, "dc=server2000,dc=tek2000,dc=com"}.
{ldap_rootdn, "[email protected]"}.
{ldap_password, "secret"}.
%...
```
What am I missing?
I must say that, with OpenFire, I can connect using this credentials/configuration.
I'm using Spark as my client application.
Thanks
|
Use a [ByteArrayOutputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html) and then get the data out of that using [toByteArray()](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()). This won't test *how* it writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.
|
225,086 |
<p>Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format</p>
<pre><code>Sun, 06 Nov 1994 08:49:37 GMT
</code></pre>
<p>Using <code>strftime</code> does not work, since the strings are locale-dependant. Do I have to build the string by hand?</p>
|
[
{
"answer_id": 225101,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 2,
"selected": false,
"text": "<p>You can set LC_TIME to force stftime() to use a specific locale:</p>\n\n<pre><code>>>> locale.setlocale(locale.LC_TIME, 'en_US')\n'en_US'\n>>> datetime.datetime.now().strftime(locale.nl_langinfo(locale.D_T_FMT))\n'Wed 22 Oct 2008 06:05:39 AM '\n</code></pre>\n"
},
{
"answer_id": 225106,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 8,
"selected": true,
"text": "<p>You can use wsgiref.handlers.format_date_time from the stdlib which does not rely on locale settings</p>\n\n<pre><code>from wsgiref.handlers import format_date_time\nfrom datetime import datetime\nfrom time import mktime\n\nnow = datetime.now()\nstamp = mktime(now.timetuple())\nprint format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:40 GMT\n</code></pre>\n\n<p>You can use email.utils.formatdate from the stdlib which does not rely on locale settings </p>\n\n<pre><code>from email.utils import formatdate\nfrom datetime import datetime\nfrom time import mktime\n\nnow = datetime.now()\nstamp = mktime(now.timetuple())\nprint formatdate(\n timeval = stamp,\n localtime = False,\n usegmt = True\n) #--> Wed, 22 Oct 2008 10:55:46 GMT\n</code></pre>\n\n<p>If you can set the locale process wide then you can do:</p>\n\n<pre><code>import locale, datetime\n\nlocale.setlocale(locale.LC_TIME, 'en_US')\ndatetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')\n</code></pre>\n\n<p>If you don't want to set the locale process wide you could use <a href=\"http://babel.edgewall.org/\" rel=\"noreferrer\">Babel</a> <a href=\"http://babel.edgewall.org/wiki/Documentation/dates.html\" rel=\"noreferrer\">date formating</a></p>\n\n<pre><code>from datetime import datetime\nfrom babel.dates import format_datetime\n\nnow = datetime.utcnow()\nformat = 'EEE, dd LLL yyyy hh:mm:ss'\nprint format_datetime(now, format, locale='en') + ' GMT'\n</code></pre>\n\n<p>A manual way to format it which is identical with wsgiref.handlers.format_date_time is:</p>\n\n<pre><code>def httpdate(dt):\n \"\"\"Return a string representation of a date according to RFC 1123\n (HTTP/1.1).\n\n The supplied date must be in UTC.\n\n \"\"\"\n weekday = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"][dt.weekday()]\n month = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\",\n \"Oct\", \"Nov\", \"Dec\"][dt.month - 1]\n return \"%s, %02d %s %04d %02d:%02d:%02d GMT\" % (weekday, dt.day, month,\n dt.year, dt.hour, dt.minute, dt.second)\n</code></pre>\n"
},
{
"answer_id": 225177,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 6,
"selected": false,
"text": "<p>You can use the formatdate() function from the Python standard email module:</p>\n\n<pre><code>from email.utils import formatdate\nprint formatdate(timeval=None, localtime=False, usegmt=True)\n</code></pre>\n\n<p>Gives the current time in the desired format:</p>\n\n<pre><code>Wed, 22 Oct 2008 10:32:33 GMT\n</code></pre>\n\n<p>In fact, this function does it \"by hand\" without using strftime()</p>\n"
},
{
"answer_id": 225191,
"author": "Sebastian Rittau",
"author_id": 7779,
"author_profile": "https://Stackoverflow.com/users/7779",
"pm_score": 1,
"selected": false,
"text": "<p>Well, here is a manual function to format it:</p>\n\n<pre><code>def httpdate(dt):\n \"\"\"Return a string representation of a date according to RFC 1123\n (HTTP/1.1).\n\n The supplied date must be in UTC.\n\n \"\"\"\n weekday = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"][dt.weekday()]\n month = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\",\n \"Oct\", \"Nov\", \"Dec\"][dt.month - 1]\n return \"%s, %02d %s %04d %02d:%02d:%02d GMT\" % (weekday, dt.day, month,\n dt.year, dt.hour, dt.minute, dt.second)\n</code></pre>\n"
},
{
"answer_id": 37191167,
"author": "Antoine Pinsard",
"author_id": 1529346,
"author_profile": "https://Stackoverflow.com/users/1529346",
"pm_score": 4,
"selected": false,
"text": "<p>If anybody reading this is working on a <strong>Django</strong> project, Django provides a function <a href=\"https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.http.http_date\" rel=\"noreferrer\"><code>django.utils.http.http_date(epoch_seconds)</code></a>.</p>\n\n<pre><code>from django.utils.http import http_date\n\nsome_datetime = some_object.last_update\nresponse['Last-Modified'] = http_date(some_datetime.timestamp())\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7779/"
] |
Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format
```
Sun, 06 Nov 1994 08:49:37 GMT
```
Using `strftime` does not work, since the strings are locale-dependant. Do I have to build the string by hand?
|
You can use wsgiref.handlers.format\_date\_time from the stdlib which does not rely on locale settings
```
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
now = datetime.now()
stamp = mktime(now.timetuple())
print format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:40 GMT
```
You can use email.utils.formatdate from the stdlib which does not rely on locale settings
```
from email.utils import formatdate
from datetime import datetime
from time import mktime
now = datetime.now()
stamp = mktime(now.timetuple())
print formatdate(
timeval = stamp,
localtime = False,
usegmt = True
) #--> Wed, 22 Oct 2008 10:55:46 GMT
```
If you can set the locale process wide then you can do:
```
import locale, datetime
locale.setlocale(locale.LC_TIME, 'en_US')
datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
```
If you don't want to set the locale process wide you could use [Babel](http://babel.edgewall.org/) [date formating](http://babel.edgewall.org/wiki/Documentation/dates.html)
```
from datetime import datetime
from babel.dates import format_datetime
now = datetime.utcnow()
format = 'EEE, dd LLL yyyy hh:mm:ss'
print format_datetime(now, format, locale='en') + ' GMT'
```
A manual way to format it which is identical with wsgiref.handlers.format\_date\_time is:
```
def httpdate(dt):
"""Return a string representation of a date according to RFC 1123
(HTTP/1.1).
The supplied date must be in UTC.
"""
weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][dt.month - 1]
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
dt.year, dt.hour, dt.minute, dt.second)
```
|
225,089 |
<p>Why can't we initialize members inside a structure ?</p>
<p>example:</p>
<pre><code>struct s {
int i = 10;
};
</code></pre>
|
[
{
"answer_id": 225092,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 5,
"selected": false,
"text": "<p>If you want to initialize <strong>non-static</strong> members in <code>struct</code> <strong>declaration</strong>:</p>\n\n<p>In C++ (not C), <code>structs</code> are almost synonymous to classes and can have members initialized in the constructor.</p>\n\n<pre><code>struct s {\n int i;\n\n s(): i(10)\n {\n }\n};\n</code></pre>\n\n<p>If you want to initialize an <strong>instance</strong>:</p>\n\n<p>In C or C++:</p>\n\n<pre><code>struct s {\n int i;\n};\n\n...\n\nstruct s s_instance = { 10 };\n</code></pre>\n\n<p>C99 also has a feature called designated initializers:</p>\n\n<pre><code>struct s {\n int i;\n};\n\n...\n\nstruct s s_instance = {\n .i = 10,\n};\n</code></pre>\n\n<p>There is also a GNU C extension which is very similar to C99 designated initializers, but it's better to use something more portable:</p>\n\n<pre><code>struct s s_instance = {\n i: 10,\n};\n</code></pre>\n"
},
{
"answer_id": 225100,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Edit2:</strong> This answer was written in 2008 and relates to C++98. The rules for member initialization have changed in subsequent versions of the language. </p>\n\n<p><strong>Edit:</strong> The question was originally tagged <code>c++</code> but the poster said it's regarding <code>c</code> so I re-tagged the question, I'm leaving the answer though...</p>\n\n<p>In C++ a <code>struct</code> is just a <code>class</code> which defaults for <code>public</code> rather than <code>private</code> for members and inheritance. </p>\n\n<p>C++ only allows <code>static const</code> integral members to be initialized inline, other members must be initialized in the constructor, or if the <code>struct</code> is a <a href=\"http://en.wikipedia.org/wiki/Plain_Old_Data_Structures\" rel=\"nofollow noreferrer\">POD</a> in an initialization list (when declaring the variable).</p>\n\n<pre><code>struct bad {\n static int answer = 42; // Error! not const\n const char* question = \"what is life?\"; // Error! not const or integral\n};\n\nstruct good {\n static const int answer = 42; // OK\n const char* question;\n good() \n : question(\"what is life?\") // initialization list\n { }\n};\n\nstruct pod { // plain old data\n int answer;\n const char* question;\n};\npod p = { 42, \"what is life?\" };\n</code></pre>\n"
},
{
"answer_id": 226228,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "<p>The direct answer is because the structure definition declares a type and not a variable that can be initialized. Your example is:</p>\n\n<pre><code>struct s { int i=10; };\n</code></pre>\n\n<p>This does not declare any variable - it defines a type. To declare a variable, you would add a name between the <code>}</code> and the <code>;</code>, and then you would initialize it afterwards:</p>\n\n<pre><code>struct s { int i; } t = { 10 };\n</code></pre>\n\n<p>As Checkers noted, in C99, you can also use designated initializers (which is a wonderful improvement -- one day, C will catch up with the other features that Fortran 66 had for data initialization, primarily repeating initializers a specifiable number of times). With this simple structure, there is no benefit. If you have a structure with, say, 20 members and only needed to initialize one of them (say because you have a flag that indicates that the rest of the structure is, or is not, initialized), it is more useful:</p>\n\n<pre><code>struct s { int i; } t = { .i = 10 };\n</code></pre>\n\n<p>This notation can also be used to initialize unions, to choose which element of the union is initialized.</p>\n"
},
{
"answer_id": 35995008,
"author": "Anup Raj Dubey",
"author_id": 6062241,
"author_profile": "https://Stackoverflow.com/users/6062241",
"pm_score": 2,
"selected": false,
"text": "<p>We can't initialize because when we declared any structure than actually what we do, just inform compiler about their presence i.e no memory allocated for that and if we initialize member with no memory for that. Normally what happens when we initialize any variable that depends on the place where we declared variable compiler allocate memory for that variable.</p>\n\n<pre><code>int a = 10;\n</code></pre>\n\n<ul>\n<li>if it's auto than in stack memory going to allocate </li>\n<li>if it's global than in data sections memory going to allocate</li>\n</ul>\n\n<p>So what memory is required to hold that data but in case of structure no memory is there so not possible to initialize it.</p>\n"
},
{
"answer_id": 37550773,
"author": "Turtlesoft",
"author_id": 6405633,
"author_profile": "https://Stackoverflow.com/users/6405633",
"pm_score": 4,
"selected": false,
"text": "<p>Note that in C++ 11, the following declaration is now allowed:</p>\n\n<pre><code>struct s {\n int i = 10;\n};\n</code></pre>\n\n<p>This is an old question, but it ranks high in Google and might as well be clarified.</p>\n"
},
{
"answer_id": 37551021,
"author": "Ajay Sivan",
"author_id": 5780058,
"author_profile": "https://Stackoverflow.com/users/5780058",
"pm_score": 0,
"selected": false,
"text": "<p>As you said it's just a member not a variable. When you declare a variable the compiler will also provide memory space for those variables where you can put values. In the case a of a struct member the compiler is not giving memory space for it, so you cannot assign values to struct members unless you create a variable of that struct type.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21599/"
] |
Why can't we initialize members inside a structure ?
example:
```
struct s {
int i = 10;
};
```
|
If you want to initialize **non-static** members in `struct` **declaration**:
In C++ (not C), `structs` are almost synonymous to classes and can have members initialized in the constructor.
```
struct s {
int i;
s(): i(10)
{
}
};
```
If you want to initialize an **instance**:
In C or C++:
```
struct s {
int i;
};
...
struct s s_instance = { 10 };
```
C99 also has a feature called designated initializers:
```
struct s {
int i;
};
...
struct s s_instance = {
.i = 10,
};
```
There is also a GNU C extension which is very similar to C99 designated initializers, but it's better to use something more portable:
```
struct s s_instance = {
i: 10,
};
```
|
225,096 |
<p>I'm starting to look into the whole world of RJS and Prototype/jQuery in Rails and am a little bit confused. There seems to be no clear line of where to use one or the other.</p>
<p>Say I wanted one of the "Active, Hot, Week" tabs like the ones here on SO. When pressing one of them, I want to remove a CSS class (like "active-tab") from the one I was on and add it to the one I clicked on. Then I also want to reload the div containing the items and put in the new items into it.</p>
<p>Seems the class-changing thing would be easiest to do in pure javascript, say put the code in application.js and then updating the div with the content would obviously be easiest in RJS. But what <em>should</em> one do?</p>
|
[
{
"answer_id": 225306,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": 2,
"selected": true,
"text": "<p>If you want to give users that ability to link to the generated page directly, then definitly go for a static page. Using AJAX breaks the back button unless you use something like <a href=\"http://code.google.com/p/reallysimplehistory/\" rel=\"nofollow noreferrer\">Really Simple History</a> (<a href=\"http://code.google.com/p/reallysimplehistory/wiki/ReleaseNotesVersionZeroPointSix\" rel=\"nofollow noreferrer\">which is not 100% cross browser</a>), so <a href=\"http://ajaxian.com/archives/ajaxified-body-when-to-refresh-the-page\" rel=\"nofollow noreferrer\">going the JS route with your page navigation</a> will almost certainly cause some of your users problems.</p>\n\n<p>That said, what you have discussed already would be fine, I think - just have a class change in your RJS file, then you might even find it useful to update the div contents using page.replace and a partial:</p>\n\n<pre><code>page.replace(dom_id, :partial => @page_content);\n</code></pre>\n"
},
{
"answer_id": 225342,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 2,
"selected": false,
"text": "<p>If you're comfortable with writing JavaScript then by all means use JavaScript. There's nothing wrong with that; you don't have to use RJS just because it exists. In fact you'll probably find that its abstractions get in the way.</p>\n\n<p>However, if you'd rather write Ruby code that generates JavaScript, just as you write Ruby code that generates SQL in ActiveRecord Migrations, then RJS is the right tool for the job. Or you can use both: RJS for fairly simple things and then drop down to JavaScript for more complex behaviour. Use what feels right to you.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9191/"
] |
I'm starting to look into the whole world of RJS and Prototype/jQuery in Rails and am a little bit confused. There seems to be no clear line of where to use one or the other.
Say I wanted one of the "Active, Hot, Week" tabs like the ones here on SO. When pressing one of them, I want to remove a CSS class (like "active-tab") from the one I was on and add it to the one I clicked on. Then I also want to reload the div containing the items and put in the new items into it.
Seems the class-changing thing would be easiest to do in pure javascript, say put the code in application.js and then updating the div with the content would obviously be easiest in RJS. But what *should* one do?
|
If you want to give users that ability to link to the generated page directly, then definitly go for a static page. Using AJAX breaks the back button unless you use something like [Really Simple History](http://code.google.com/p/reallysimplehistory/) ([which is not 100% cross browser](http://code.google.com/p/reallysimplehistory/wiki/ReleaseNotesVersionZeroPointSix)), so [going the JS route with your page navigation](http://ajaxian.com/archives/ajaxified-body-when-to-refresh-the-page) will almost certainly cause some of your users problems.
That said, what you have discussed already would be fine, I think - just have a class change in your RJS file, then you might even find it useful to update the div contents using page.replace and a partial:
```
page.replace(dom_id, :partial => @page_content);
```
|
225,103 |
<p>I'm writing a MUD engine and I've just started on the game object model, which needs to be extensible.</p>
<p>I need help mainly because what I've done feels messy, but I can't think of a another solution that works better.</p>
<p>I have a class called <code>MudObject</code>, and another class called <code>Container</code>, A container can contain multiple <code>MudObjects</code>, but is a <code>MudObject</code> itself, however <code>MudObject</code>s need to know what they are contained in.</p>
<p>So they look something like this:</p>
<pre><code>public abstract class MudObject
{
Container containedBy;
}
public abstract class Container : MudObject
{
List<MudObject> Contains;
}
</code></pre>
<p><em>(please note these are just example and some qualifiers and access modifiers, properties and such are missed off)</em></p>
<p>Now just this in itself seems messy, but lets add something else to the mix:</p>
<p><code>Item</code> is a <code>MudObject</code> that all visual items (such as weapons) will be inherited from, however some of these need to be containers too (like chests). But theres no such as multiple inheritance in c#, So it comes down to interfaces, the best choice would be to make the container an interface (as far as I can see) However there was a reason I didn't want it to be, that being that adding an <code>MudObject</code> to a container will cause the container to update the <code>MudObject</code>s <code>.containedBy</code> value.</p>
<p>Any ideas that would make this work, or am I falling into the trap of making things too complicated?<br>
If so what else could you suggest?</p>
|
[
{
"answer_id": 225120,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>What you want is quite reasonable: it's no different from Windows form controls, which can itself be a container of other controls.</p>\n\n<p>What you do need to do is create your own implementation of <code>List<MudObject></code>:</p>\n\n<pre><code>public class MudObjectList : List<MudObject>\n</code></pre>\n\n<p>which implements, among other things, the add functionality:</p>\n\n<pre><code>public void new Add(MudObject obj)\n{\n obj.ContainedBy = this;\n base.Add(obj);\n}\n</code></pre>\n\n<p><em>Note: this method shadows, instead of overrides, the old Add functionality</em></p>\n\n<p>In this way you immediately populate the ContainedBy attribute upon adding. Of course it's implied that your ContainedBy can be <code>null</code>, which means that it is the top level object.</p>\n\n<p>Finally, I don't think there's a need to make separate <code>MudObject</code> and <code>Container</code> classes, since being a container looks intrinsic to a <code>MudObject</code> (the ff uses C# 3.0 automatic properties):</p>\n\n<pre><code>public abstract class MudObject\n{\n MudObject ContainedBy { get; set; }\n MudObjectList Contains { get; set; }\n}\n</code></pre>\n"
},
{
"answer_id": 225124,
"author": "Jon Grant",
"author_id": 18774,
"author_profile": "https://Stackoverflow.com/users/18774",
"pm_score": 0,
"selected": false,
"text": "<p>Why not make all MudObjects containers? ...or at least, have the ability to contain other objects, in terms of your class code. E.g.</p>\n\n<pre><code>public abstract class MudObject\n{\n MudObject containedBy;\n List<MudObject> contains;\n}\n</code></pre>\n\n<p>You can then set some sort of flag on the object itself to identify whether the players are able to actually put things into or out of the object themselves, rather than using the type of the object to figure it out.</p>\n"
},
{
"answer_id": 225125,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, it is a bad idea for something to be both an item <em>and</em> a container. This breaks a number of binding scenarios that make assumptions about IList; so for a chest, I might be tempted to have an Items property <em>on</em> the chest that is the collection, but let the chest just be a chest.</p>\n\n<p>However, for the question as asked...</p>\n\n<p>I would be tempted to make the MudObject the interface... that way, you can use something like the following, which gives you a generic container of any concrete objects, along with automatic parenting:</p>\n\n<pre><code>public interface IMudObject\n{\n IMudObject Container { get; set; }\n /* etc */\n}\n\npublic class MudContainer<T> : Collection<T>, IMudObject\n where T : IMudObject\n{\n\n public IMudObject Container { get; set; }\n\n protected override void ClearItems()\n {\n foreach (T item in this)\n {\n RemoveAsContainer(item);\n }\n base.ClearItems();\n }\n\n protected override void InsertItem(int index, T item)\n {\n SetAsContainer(item);\n base.InsertItem(index, item);\n }\n\n protected override void RemoveItem(int index)\n {\n RemoveAsContainer(this[index]);\n base.RemoveItem(index); \n }\n protected override void SetItem(int index, T item)\n {\n RemoveAsContainer(this[index]);\n SetAsContainer(item);\n base.SetItem(index, item);\n }\n\n void RemoveAsContainer(T item)\n {\n if (item != null && ReferenceEquals(item.Container, this))\n {\n item.Container = null;\n }\n }\n void SetAsContainer(T item)\n {\n if (item.Container != null)\n {\n throw new InvalidOperationException(\"Already owned!\");\n }\n item.Container = this;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 225127,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<p>I think you are overcomplicating. If MudObjects can contain other MudObjects, the single base class you need should be along these lines:</p>\n\n<pre><code>public abstract class MudObject\n{ \n MudObject containedBy; //technically Parent\n List<MudObject> Contains; //children\n}\n</code></pre>\n\n<p>This is similar to the way WinForms and ASP.NET works. Many container controls are both controls, and can contain a collection of subcontrols.</p>\n"
},
{
"answer_id": 225182,
"author": "Sekhat",
"author_id": 1610,
"author_profile": "https://Stackoverflow.com/users/1610",
"pm_score": 0,
"selected": false,
"text": "<p>Going with the idea of composition over inheritance answer which seems to have vanished.</p>\n\n<p>Perhaps I could do something more like this</p>\n\n<pre><code>public class Container<T> where T : MudObject\n{\n List<T> Contains;\n MudObject containerOwner;\n\n public Container(MudObject owner)\n {\n containerOwner = owner;\n }\n // Other methods to handle parent association\n}\n\npublic interface IMudContainer<T> where T : MudObject\n{\n Container<T> Contains { get; }\n}\n\npublic class MudObjectThatContainsStuff : IMudContainer\n{\n public MudObjectThatContainsStuff()\n {\n Contains = new Container<MudObject>(this);\n }\n\n public Contains { get; }\n}\n</code></pre>\n"
},
{
"answer_id": 225264,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 0,
"selected": false,
"text": "<p>Along the lines of Marc's answer, write a couple of classes that maintain a bidirectional parent-child relationship under the hood.</p>\n"
},
{
"answer_id": 227244,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 2,
"selected": true,
"text": "<p>What you're asking for is reasonable, and is the <a href=\"http://home.earthlink.net/~huston2/dp/composite.html\" rel=\"nofollow noreferrer\">Composite Design Pattern</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610/"
] |
I'm writing a MUD engine and I've just started on the game object model, which needs to be extensible.
I need help mainly because what I've done feels messy, but I can't think of a another solution that works better.
I have a class called `MudObject`, and another class called `Container`, A container can contain multiple `MudObjects`, but is a `MudObject` itself, however `MudObject`s need to know what they are contained in.
So they look something like this:
```
public abstract class MudObject
{
Container containedBy;
}
public abstract class Container : MudObject
{
List<MudObject> Contains;
}
```
*(please note these are just example and some qualifiers and access modifiers, properties and such are missed off)*
Now just this in itself seems messy, but lets add something else to the mix:
`Item` is a `MudObject` that all visual items (such as weapons) will be inherited from, however some of these need to be containers too (like chests). But theres no such as multiple inheritance in c#, So it comes down to interfaces, the best choice would be to make the container an interface (as far as I can see) However there was a reason I didn't want it to be, that being that adding an `MudObject` to a container will cause the container to update the `MudObject`s `.containedBy` value.
Any ideas that would make this work, or am I falling into the trap of making things too complicated?
If so what else could you suggest?
|
What you're asking for is reasonable, and is the [Composite Design Pattern](http://home.earthlink.net/~huston2/dp/composite.html)
|
225,114 |
<pre><code><td title="this is a really long line that I'm going to truncate">this is a really long line that I'm going to trunc ...</td>
</code></pre>
<p>Is this the correct way to do it?</p>
|
[
{
"answer_id": 225131,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, that's how you supposed to assign tooltips to html elements. I wouldn't use it on <td> though. Although I haven't tested it, I have the feeling that you might run into issues on some browsers if you use it on table rows/cells directly since these elements have somewhat different behaviour from other elements. You should rather use it on more \"regular\" elements, for example <div>, <span>, <img> or <input>.</p>\n"
},
{
"answer_id": 225165,
"author": "Abbas",
"author_id": 4714,
"author_profile": "https://Stackoverflow.com/users/4714",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>title</code> attribute doesn't work inside the <code>td</code> tag. Enclose the text within a span tag instead:</p>\n\n<pre><code><td>\n <span title=\"this is a really long line that I'm going to truncate\">this is a really long line that I'm going to trunc ...</span>\n</td>\n</code></pre>\n"
},
{
"answer_id": 225166,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with @DrJokepu, the <code>title</code> attribute is the way to do this, but probably not on the <code>TD</code> element, try the <code>ABBR</code> element, that's what it's for, or failing that, a simple <code>SPAN</code> is probably best.</p>\n"
},
{
"answer_id": 225239,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 2,
"selected": false,
"text": "<p>There is a maximum length for the title. It's around 80 characters (tested on FF2).</p>\n\n<p>So if your text is really long the title won't help. There are several good css/javascript tooltip solutions that will show whatever you need.</p>\n"
},
{
"answer_id": 225269,
"author": "Jeremy Holt",
"author_id": 30046,
"author_profile": "https://Stackoverflow.com/users/30046",
"pm_score": 0,
"selected": false,
"text": "<p>How would you format the text to show a line break? In IE 7.0 </p>\n\n<pre><code><title=\"long line of text\\nanotherlong line of text\" />\n</code></pre>\n\n<p>works as expected - but in Firefix 3.01 the \"\\n\" is changed to a space. Using <code><br/></code> doesn't help either.</p>\n"
},
{
"answer_id": 225270,
"author": "Steve",
"author_id": 21559,
"author_profile": "https://Stackoverflow.com/users/21559",
"pm_score": 0,
"selected": false,
"text": "<p>FF2 has a bug preventing it from displaying long titles: <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=45375\" rel=\"nofollow noreferrer\">https://bugzilla.mozilla.org/show_bug.cgi?id=45375</a></p>\n\n<p>Isn't title a core attribute? So it is valid on pretty much every tag (bar few eg. html, head etc.)</p>\n"
},
{
"answer_id": 232658,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 0,
"selected": false,
"text": "<p>If you want some control over the tooltip you could try modifying this to your needs \n<a href=\"http://evolutionarygoo.com/blog/?p=45\" rel=\"nofollow noreferrer\">css Tooltip</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
<td title="this is a really long line that I'm going to truncate">this is a really long line that I'm going to trunc ...</td>
```
Is this the correct way to do it?
|
The `title` attribute doesn't work inside the `td` tag. Enclose the text within a span tag instead:
```
<td>
<span title="this is a really long line that I'm going to truncate">this is a really long line that I'm going to trunc ...</span>
</td>
```
|
225,130 |
<p>I'm tryint to post to a ADO.NET Data Service but the parameters seems to get lost along the way.</p>
<p>I got something like:</p>
<pre><code>[WebInvoke(Method="POST")]
public int MyMethod(int foo, string bar) {...}
</code></pre>
<p>and I make an ajax-call using prototype.js as:</p>
<pre><code>var args = {foo: 4, bar: "'test'"};
new Ajax.Requst(baseurl + 'MyMethod',
method: 'POST',
parameters: args,
onSuccess: jadda,
onFailure: jidda
}
</code></pre>
<p>If I replace "method: 'POST'" with "method: 'GET'" and "WebInvoke(Method="POST")" with "WebGet" everything works but now (using post) all I get is:</p>
<blockquote>
<p>Bad Request - Error in query syntax.</p>
</blockquote>
<p>from the service.</p>
<p>The only fix (that I don't want to use) is to send all parameters in the URL even when I perform a post. Any ideas are welcome. </p>
|
[
{
"answer_id": 225164,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to use POST, you need to specify the parameters to be wrapped in the request in WebInvoke attribute unless the parameters contains on object (e.g. message contract). This makes sense since there is no way to serialize the parameters without wrapped in either json or xml.</p>\n\n<p>Unwrapped which is not XML indeed as missing root element</p>\n\n<pre><code><foo>1</foo>\n<bar>abc</bar>\n</code></pre>\n\n<p>Wrapped, valid XML</p>\n\n<pre><code><Request>\n <foo>1</foo>\n <bar>abc</bar>\n</Request>\n</code></pre>\n\n<p>This sample also applies to JSON</p>\n"
},
{
"answer_id": 225388,
"author": "finnsson",
"author_id": 24044,
"author_profile": "https://Stackoverflow.com/users/24044",
"pm_score": 0,
"selected": false,
"text": "<p>Are you saying that I should wrap the parameters i the javascript like</p>\n\n<pre><code>var args = {Request: {foo: 3, bar: \"'test'\"}}\n</code></pre>\n\n<p>or am I missing something?</p>\n\n<p>I've tried to add:</p>\n\n<pre><code>ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped\n</code></pre>\n\n<p>to the WebInvoke-attribute but with no result. I've tried to set \"Content-Type\" (in js POST ajax-call) to \"application/x-www-form-urlencoding\" and \"application/json; charset=utf-8\" but with no result.</p>\n"
},
{
"answer_id": 364513,
"author": "John Foster",
"author_id": 45859,
"author_profile": "https://Stackoverflow.com/users/45859",
"pm_score": 3,
"selected": true,
"text": "<p>WCF and ASMX webservices tend to be a bit choosey about the request body, when you specify args the request is usually encoded as a form post i.e. foo=4&bar=test instead you need to specify the javascript literal:-</p>\n\n<pre><code> new Ajax.Request(baseurl + 'MyMethod', {\n method: 'POST',\n postBody: '{\"foo\":4, \"bar\":\"test\"}',\n encoding: \"UTF-8\",\n contentType: \"application/json;\",\n onSuccess: function(result) {\n alert(result.responseJSON.d); \n },\n onFailure: function() {\n alert(\"Error\");\n }\n });\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24044/"
] |
I'm tryint to post to a ADO.NET Data Service but the parameters seems to get lost along the way.
I got something like:
```
[WebInvoke(Method="POST")]
public int MyMethod(int foo, string bar) {...}
```
and I make an ajax-call using prototype.js as:
```
var args = {foo: 4, bar: "'test'"};
new Ajax.Requst(baseurl + 'MyMethod',
method: 'POST',
parameters: args,
onSuccess: jadda,
onFailure: jidda
}
```
If I replace "method: 'POST'" with "method: 'GET'" and "WebInvoke(Method="POST")" with "WebGet" everything works but now (using post) all I get is:
>
> Bad Request - Error in query syntax.
>
>
>
from the service.
The only fix (that I don't want to use) is to send all parameters in the URL even when I perform a post. Any ideas are welcome.
|
WCF and ASMX webservices tend to be a bit choosey about the request body, when you specify args the request is usually encoded as a form post i.e. foo=4&bar=test instead you need to specify the javascript literal:-
```
new Ajax.Request(baseurl + 'MyMethod', {
method: 'POST',
postBody: '{"foo":4, "bar":"test"}',
encoding: "UTF-8",
contentType: "application/json;",
onSuccess: function(result) {
alert(result.responseJSON.d);
},
onFailure: function() {
alert("Error");
}
});
```
|
225,149 |
<p>Guys, I’ve been writing code for 15+ years, but managed to avoid “Web Development” until 3 months ago.</p>
<p>I have inherited a legacy Asp.net application (started in .net 1.1, we’re now on .Net 2.0), it’s the administration tool for our product.</p>
<p>In several places the admin tool simply maintains long lists of values.</p>
<p>The list (could be 200+ items) appear in a GridView (Page A), user clicks an edit button for an item, this brings them to an edit page for the item (Page B) where they can change the value (or values, an item in the list may be associated with several values e.g. name and address and preferred colour, breed of cat . . .)</p>
<p>Currently when the user presses “Save” on Page B, we redirect back to Page A. The page opens at the top of the list, this annoys the user as often several items in sequence will need to be configured together, and the user needs to 1. Remember which item they just edited, 2. scroll down to that item</p>
<p>What I want to do is have the list bring the user back to the item they just edited, as often several items in sequence will need to be configured together.</p>
<p><strong>Fastest Gun Stop</strong> . . . and keep reading</p>
<ol>
<li>Suggestions on the lines of “regroup the items so there are fewer in the list” will be considered unhelpful</li>
<li>Valid points that .Net 3.5 does this automatically, will be considered unhelpful by me (but post them anyway, it may help some other poor fool)</li>
<li>I think I could do this by posting the Id of the edited item when re-loading Page A, and scrolling the grid to this point, however <strong>My Question is</strong> . . .</li>
</ol>
<p>Is there a feature to do this that I don’t know about (and what is it)
and/or<br>
What is the accepted way of doing this?</p>
<p>Thanks in advance
B. Worrier</p>
|
[
{
"answer_id": 225187,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest way you can do is to pass back an id from PageB in the querystring in the URL while redirecting back to PageA after saving in PageB.</p>\n\n<p>e.g. www.example.com/PageA.aspx?editedId=89</p>\n\n<p>and in PageLoad of PageA, you can check if this is from the editing detail page by examineing whether there is a valid value in HttpContext.Current.QueryStrubg[\"editedId\"],\nif there was, it means it is from PageB.\nYou can use this value to highlight or select the row in the datagrid easily</p>\n\n<p><strong>Fastest Gun Stop . . .</strong> and keep reading...</p>\n\n<p>A good control allows you to edit multiple rows at the same time on same page for example on PageA, and save them together. Check you Telerik control for datagrid. You'd love it.</p>\n"
},
{
"answer_id": 225215,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 3,
"selected": true,
"text": "<p>This could be achieved using Anchor Tags.\nWhen you output your elements on Page A, set an anchor tag next to each element like follows:</p>\n\n<pre><code><a name=\"#175\"></a>\n</code></pre>\n\n<p>Where this item would be item id 175.\nThen when you redirect back to PageA, add a \"#175\" onto the end of the url</p>\n\n<pre><code>Response.Redirect(\"PageA.aspx#175\");\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18797/"
] |
Guys, I’ve been writing code for 15+ years, but managed to avoid “Web Development” until 3 months ago.
I have inherited a legacy Asp.net application (started in .net 1.1, we’re now on .Net 2.0), it’s the administration tool for our product.
In several places the admin tool simply maintains long lists of values.
The list (could be 200+ items) appear in a GridView (Page A), user clicks an edit button for an item, this brings them to an edit page for the item (Page B) where they can change the value (or values, an item in the list may be associated with several values e.g. name and address and preferred colour, breed of cat . . .)
Currently when the user presses “Save” on Page B, we redirect back to Page A. The page opens at the top of the list, this annoys the user as often several items in sequence will need to be configured together, and the user needs to 1. Remember which item they just edited, 2. scroll down to that item
What I want to do is have the list bring the user back to the item they just edited, as often several items in sequence will need to be configured together.
**Fastest Gun Stop** . . . and keep reading
1. Suggestions on the lines of “regroup the items so there are fewer in the list” will be considered unhelpful
2. Valid points that .Net 3.5 does this automatically, will be considered unhelpful by me (but post them anyway, it may help some other poor fool)
3. I think I could do this by posting the Id of the edited item when re-loading Page A, and scrolling the grid to this point, however **My Question is** . . .
Is there a feature to do this that I don’t know about (and what is it)
and/or
What is the accepted way of doing this?
Thanks in advance
B. Worrier
|
This could be achieved using Anchor Tags.
When you output your elements on Page A, set an anchor tag next to each element like follows:
```
<a name="#175"></a>
```
Where this item would be item id 175.
Then when you redirect back to PageA, add a "#175" onto the end of the url
```
Response.Redirect("PageA.aspx#175");
```
|
225,233 |
<p>No I'm not being a wise guy ...</p>
<p>For those fortunate enough to not know the My class: It's something that was <strong>added in VB 2005 (and doesn't exist in C#) and is best described as a 'speeddial for the .net framework'.</strong>
Supposed to make life easier for newbies who won't read which framework classes they should be using</p>
<pre><code>Dim contents As String
contents = My.Computer.FileSystem.ReadAllText("c:\mytextfile.txt")
</code></pre>
<p>Instead of this:</p>
<pre><code>Dim contents As String
contents = IO.File.ReadAllText("c:\mytextfile.txt")
</code></pre>
<p>My Question: <strong>Where is the MSDN documentation page for which speeddial button maps to what.. ?</strong><br>
By choosing the name of the feature as My - they've just made searching a whole lot more fun that it needs to be. I need to code in C# and can't bear the fun of translating the training/how-to office prog videos which exclusively deal in VB.</p>
<p>More on this from the Dans</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc163972.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc163972.aspx</a></li>
<li><a href="http://blogs.msdn.com/danielfe/archive/2005/06/14/429092.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/danielfe/archive/2005/06/14/429092.aspx</a></li>
</ul>
<p>Juval Lowy ported My as That in C# as an interim solution. Don't ask me why...</p>
|
[
{
"answer_id": 225255,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>It's the \"My namespace\" rather than the \"My class\" which may aid searching.</p>\n\n<p>So far I've found this: <a href=\"http://msdn.microsoft.com/en-us/vbasic/ms789188.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/vbasic/ms789188.aspx</a> but it's not ideal. Looking for more...</p>\n\n<p>EDIT: I think <a href=\"http://msdn.microsoft.com/en-us/library/5btzf5yk.aspx\" rel=\"nofollow noreferrer\">\"Developing with My\"</a> is effectively the root of the documentation.</p>\n"
},
{
"answer_id": 225259,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.myservices.aspx\" rel=\"nofollow noreferrer\">This</a> looks promising - it is a detailed account of the MyServices area (that provides My in VB)</p>\n\n<p>Some more is <a href=\"http://msdn.microsoft.com/en-us/vbasic/ms789188.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 225261,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>Different features inside the <code>My</code> namespace behave very differently and are implemented using different techniques. There's not “one” documentation for them, unfortunately.</p>\n\n<p>Many of the shortcut methods refer to classes within the Microsoft.VisualBasic.dll. You can of course reference this from C#.</p>\n\n<p>Some mappings (by no means complete):</p>\n\n<ul>\n<li><p><code>My.Application</code> => <code>Microsoft.VisualBasic.ApplicationServices.ApplicationBase</code></p>\n\n<p>This class is inherited from to produce the Application Framework of VB.</p></li>\n<li><code>My.Computer</code> => <code>Microsoft.VisualBasic.Devices.ServerComputer</code></li>\n<li><code>My.User</code> => <code>Microsoft.VisualBasic.ApplicationServices.User</code></li>\n<li><code>My.Settings</code> => Maps directly to C#'s <code>RootNamespace.Properties.Settings</code></li>\n<li><code>My.Resources</code> => Maps directly to C#'s <code>RootNamespace.Properties.Resources</code></li>\n</ul>\n"
},
{
"answer_id": 225272,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 1,
"selected": false,
"text": "<p>The official reference for the My namespace can be found <a href=\"http://msdn.microsoft.com/en-us/library/8ffec36z.aspx\" rel=\"nofollow noreferrer\">here</a> on MSDN.</p>\n\n<p>Unfortunately, it doesn't describe which 'real' Framework features the My shortcuts map to (although this isn't too hard to figure out in most cases).</p>\n\n<p>As a further annoyance, the source code isn't released as part of the .NET Reference Source either (same situation as with Microsoft.VisualBasic, even though being able to check the source would do a lot to demystify this part of the Framework...)</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
] |
No I'm not being a wise guy ...
For those fortunate enough to not know the My class: It's something that was **added in VB 2005 (and doesn't exist in C#) and is best described as a 'speeddial for the .net framework'.**
Supposed to make life easier for newbies who won't read which framework classes they should be using
```
Dim contents As String
contents = My.Computer.FileSystem.ReadAllText("c:\mytextfile.txt")
```
Instead of this:
```
Dim contents As String
contents = IO.File.ReadAllText("c:\mytextfile.txt")
```
My Question: **Where is the MSDN documentation page for which speeddial button maps to what.. ?**
By choosing the name of the feature as My - they've just made searching a whole lot more fun that it needs to be. I need to code in C# and can't bear the fun of translating the training/how-to office prog videos which exclusively deal in VB.
More on this from the Dans
* <http://msdn.microsoft.com/en-us/magazine/cc163972.aspx>
* <http://blogs.msdn.com/danielfe/archive/2005/06/14/429092.aspx>
Juval Lowy ported My as That in C# as an interim solution. Don't ask me why...
|
It's the "My namespace" rather than the "My class" which may aid searching.
So far I've found this: <http://msdn.microsoft.com/en-us/vbasic/ms789188.aspx> but it's not ideal. Looking for more...
EDIT: I think ["Developing with My"](http://msdn.microsoft.com/en-us/library/5btzf5yk.aspx) is effectively the root of the documentation.
|
225,250 |
<p>I have a 3rd-party library which for various reasons I don't wish to link against yet. I don't want to butcher my code though to remove all reference to its API, so I'd like to generate a dummy implementation of it.</p>
<p>Is there any tool I can use which spits out empty definitions of classes given their header files? It's fine to return nulls, false and 0 by default. I don't want to do anything on-the-fly or anything clever - the mock object libraries I've looked at appear quite heavy-weight? Ideally I want something to use like</p>
<pre><code>$ generate-definition my_header.h > dummy_implemtation.cpp
</code></pre>
<p>I'm using Linux, GCC4.1</p>
|
[
{
"answer_id": 226368,
"author": "Vinay",
"author_id": 28641,
"author_profile": "https://Stackoverflow.com/users/28641",
"pm_score": 0,
"selected": false,
"text": "<p>Create one test application which reads the header file and creates the source file. Test application should parse the header file to know the function names.</p>\n"
},
{
"answer_id": 226459,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 1,
"selected": false,
"text": "<p>This is a harder problem than you might like, as parsing C++ can quickly become a difficult task. Your best bet would be to pick an existing parser with a nice interface.</p>\n\n<p>A quick search found <a href=\"http://compilers.iecc.com/comparch/article/06-09-169\" rel=\"nofollow noreferrer\">this thread</a> which has many recommendations for parsers to do something similar.</p>\n\n<p>At the very worst you might be able to use SWIG --> Python, and then use reflection on that to print a dummy implementation.</p>\n\n<p>Sorry this is only a half-answer, but I don't think there is an existing tool to do this (other than a mocking framework, which is probably the same amount of work as using a parser).</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23434/"
] |
I have a 3rd-party library which for various reasons I don't wish to link against yet. I don't want to butcher my code though to remove all reference to its API, so I'd like to generate a dummy implementation of it.
Is there any tool I can use which spits out empty definitions of classes given their header files? It's fine to return nulls, false and 0 by default. I don't want to do anything on-the-fly or anything clever - the mock object libraries I've looked at appear quite heavy-weight? Ideally I want something to use like
```
$ generate-definition my_header.h > dummy_implemtation.cpp
```
I'm using Linux, GCC4.1
|
This is a harder problem than you might like, as parsing C++ can quickly become a difficult task. Your best bet would be to pick an existing parser with a nice interface.
A quick search found [this thread](http://compilers.iecc.com/comparch/article/06-09-169) which has many recommendations for parsers to do something similar.
At the very worst you might be able to use SWIG --> Python, and then use reflection on that to print a dummy implementation.
Sorry this is only a half-answer, but I don't think there is an existing tool to do this (other than a mocking framework, which is probably the same amount of work as using a parser).
|
225,263 |
<p>Lets say I have a single object of type Car which I want to render as HTML:</p>
<pre><code>class Car {
public int Wheels { get; set; }
public string Model { get; set; }
}
</code></pre>
<p>I don't want to use the ASP.NET Repeater or ListView controls to bind because it seems too verbose. I just have the one object. But I still want to be able to use the databinding syntax so I won't have to use Labels or Literals. Something like:</p>
<pre><code><div>
Wheels: <%# (int)Eval("Wheels") %><br />
Model: <%# (string)Eval("Model") %>
</div>
</code></pre>
<p>Does anybody know about a control out there that does just that?</p>
<p>And I am not ready to switch to ASP.NET MVC just yet.</p>
<hr>
<p>Unfortunately, the DetailsView control doesn't satisfy my needs because it doesn't seem to support the template-style syntax that I am after. It, too, needs to be bound to a DataSource object of a kind.</p>
<p>I liked better the solution Maxim and Torkel suggested. I will try to go for that.</p>
|
[
{
"answer_id": 225278,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 6,
"selected": true,
"text": "<p>if the page is about a specific item (For exemple, Car.aspx?CarID=ABC123), I normally have a public property on the page called \"CurrentCar\"</p>\n\n<pre><code>public Car CurrentCar { get; set; }\n</code></pre>\n\n<p>And I can then have the following:</p>\n\n<pre><code><div>\n Wheels: <%= CurrentCar.Wheels %><br />\n Model: <%= CurrentCar.Model %>\n</div>\n</code></pre>\n\n<p>That allow you to have type safety. Just make sure to have a valid object assigned before the actual rendering.</p>\n"
},
{
"answer_id": 225297,
"author": "Torkel",
"author_id": 24425,
"author_profile": "https://Stackoverflow.com/users/24425",
"pm_score": 3,
"selected": false,
"text": "<p>I would suggest you make car a protected property on the page, this will allow you to access it directly in the aspx page:</p>\n\n<pre><code><div>\n Wheels: <%= Car.Wheels %>\n Wheels: <%= Car.Models %>\n</div>\n</code></pre>\n\n<p>This approach is actually better for single item databinding scenarios as the \"binding\" is strongly typed. </p>\n"
},
{
"answer_id": 225416,
"author": "JacobE",
"author_id": 30056,
"author_profile": "https://Stackoverflow.com/users/30056",
"pm_score": 0,
"selected": false,
"text": "<p>One drawback of the protected property solution is that you cannot use it to bind to properties of controls.</p>\n\n<p>For example, the following would not work:</p>\n\n<pre><code><asp:Label ID=\"Label1\" Text=\"Probably a truck\" Visible='<%# CurrentCart.Wheels > 4 %>' runat=\"server\" />\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30056/"
] |
Lets say I have a single object of type Car which I want to render as HTML:
```
class Car {
public int Wheels { get; set; }
public string Model { get; set; }
}
```
I don't want to use the ASP.NET Repeater or ListView controls to bind because it seems too verbose. I just have the one object. But I still want to be able to use the databinding syntax so I won't have to use Labels or Literals. Something like:
```
<div>
Wheels: <%# (int)Eval("Wheels") %><br />
Model: <%# (string)Eval("Model") %>
</div>
```
Does anybody know about a control out there that does just that?
And I am not ready to switch to ASP.NET MVC just yet.
---
Unfortunately, the DetailsView control doesn't satisfy my needs because it doesn't seem to support the template-style syntax that I am after. It, too, needs to be bound to a DataSource object of a kind.
I liked better the solution Maxim and Torkel suggested. I will try to go for that.
|
if the page is about a specific item (For exemple, Car.aspx?CarID=ABC123), I normally have a public property on the page called "CurrentCar"
```
public Car CurrentCar { get; set; }
```
And I can then have the following:
```
<div>
Wheels: <%= CurrentCar.Wheels %><br />
Model: <%= CurrentCar.Model %>
</div>
```
That allow you to have type safety. Just make sure to have a valid object assigned before the actual rendering.
|
225,291 |
<p>I have been using git to keep two copies of my project in sync, one is my local box, the other the test server.
This is an issue which occurs when I log onto our remote development server using ssh;</p>
<pre><code>git clone [email protected]:/home/chris/myproject
Initialized empty Git repository in /tmp/myproject/.git/
Password:
bash: git-upload-pack: command not found
fatal: The remote end hung up unexpectedly
fetch-pack from '[email protected]:/home/chris/myproject' failed.
</code></pre>
<p>(the file-names have been changed to protect the guilty... !) </p>
<p>Both boxes run Solaris 10 AMD. I have done some digging, if I add <code>--upload-pack=$(which git-upload-pack)</code> the command works, (and proves that <code>$PATH</code> contains the path to 'git-upload-pack' as per the RTFM solution) but this is really annoying, plus 'git push' doesn't work, because I don't think there is a <code>--unpack=</code> option. </p>
<p>Incidentally, all the git commands work fine from my local box, it is the same version of the software (1.5.4.2), installed on the same NFS mount at <code>/usr/local/bin</code>. </p>
<p>Can anybody help?</p>
|
[
{
"answer_id": 225315,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 8,
"selected": true,
"text": "<p>Make sure <code>git-upload-pack</code> is on the path from a non-login shell. (On my machine it's in <code>/usr/bin</code>).</p>\n\n<p>To see what your path looks like on the remote machine from a non-login shell, try this:</p>\n\n<pre><code>ssh you@remotemachine echo \\$PATH\n</code></pre>\n\n<p>(That works in Bash, Zsh, and tcsh, and probably other shells too.)</p>\n\n<p>If the path it gives back doesn't include the directory that has <code>git-upload-pack</code>, you need to fix it by setting it in <code>.bashrc</code> (for Bash), <code>.zshenv</code> (for Zsh), <code>.cshrc</code> (for tcsh) or equivalent for your shell.</p>\n\n<p>You will need to make this change on the remote machine.</p>\n\n<p>If you're not sure which path you need to add to your remote <code>PATH</code>, you can find it with this command (you need to run this on the remote machine):</p>\n\n<p><code>which git-upload-pack</code></p>\n\n<p>On my machine that prints <code>/usr/bin/git-upload-pack</code>. So in this case, <code>/usr/bin</code> is the path you need to make sure is in your remote non-login shell <code>PATH</code>.</p>\n"
},
{
"answer_id": 412921,
"author": "Skeletron",
"author_id": 51616,
"author_profile": "https://Stackoverflow.com/users/51616",
"pm_score": 3,
"selected": false,
"text": "<p>Matt's solution didn't work for me on OS X, but Paul's did.</p>\n\n<p>The short version from Paul's link is:</p>\n\n<p>Created <code>/usr/local/bin/ssh_session</code> with the following text:</p>\n\n<pre><code>#!/bin/bash\nexport SSH_SESSION=1\nif [ -z \"$SSH_ORIGINAL_COMMAND\" ] ; then\n export SSH_LOGIN=1\n exec login -fp \"$USER\"\nelse\n export SSH_LOGIN=\n [ -r /etc/profile ] && source /etc/profile\n [ -r ~/.profile ] && source ~/.profile\n eval exec \"$SSH_ORIGINAL_COMMAND\"\nfi\n</code></pre>\n\n<p>Execute:</p>\n\n<blockquote>\n <p><code>chmod +x /usr/local/bin/ssh_session</code></p>\n</blockquote>\n\n<p>Add the following to <code>/etc/sshd_config</code>:</p>\n\n<blockquote>\n <p>ForceCommand /usr/local/bin/ssh_session</p>\n</blockquote>\n"
},
{
"answer_id": 550145,
"author": "Andy",
"author_id": 66542,
"author_profile": "https://Stackoverflow.com/users/66542",
"pm_score": 5,
"selected": false,
"text": "<p>I found and used (successfully) this fix:</p>\n\n<pre><code># Fix it with symlinks in /usr/bin\n$ cd /usr/bin/\n$ sudo ln -s /[path/to/git]/bin/git* .\n</code></pre>\n\n<p>Thanks to <a href=\"http://marc.info/?l=git&m=122146743006470&w=2\" rel=\"noreferrer\">Paul Johnston</a>.</p>\n"
},
{
"answer_id": 573417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>For bash, it needs to be put into .bashrc not .bash_profile (.bash_profile is also only for login shells).</p>\n"
},
{
"answer_id": 652089,
"author": "Stefan Lundström",
"author_id": 78757,
"author_profile": "https://Stackoverflow.com/users/78757",
"pm_score": 1,
"selected": false,
"text": "<p>Like Johan pointed out many times its .bashrc that's needed:</p>\n\n<p>ln -s .bash_profile .bashrc </p>\n"
},
{
"answer_id": 684760,
"author": "Ric Tokyo",
"author_id": 42019,
"author_profile": "https://Stackoverflow.com/users/42019",
"pm_score": 3,
"selected": false,
"text": "<p>I got these errors with the MsysGit version.</p>\n\n<p>After following all advice I could find here and elsewhere, I ended up: </p>\n\n<blockquote>\n <p>installing the Cygwin version of Git</p>\n</blockquote>\n\n<p>on the server (Win XP with Cygwin SSHD), this finally fixed it. </p>\n\n<p>I still use the MsysGit version client side </p>\n\n<blockquote>\n <p>..in fact, its the only way it works\n for me, since I get POSIX errors with\n the Cygwin Git pull from that same\n sshd server</p>\n</blockquote>\n\n<p>I suspect some work is still needed this side of Git use.. \n(ssh+ease of pull/push in Windows)</p>\n"
},
{
"answer_id": 1269309,
"author": "miknight",
"author_id": 120993,
"author_profile": "https://Stackoverflow.com/users/120993",
"pm_score": 0,
"selected": false,
"text": "<p>For zsh you need to put it in this file: ~/.zshenv</p>\n\n<p>For example, on OS X using the git-core package from MacPorts:</p>\n\n<p>$ echo 'export PATH=/opt/local/sbin:/opt/local/bin:$PATH' > ~/.zshenv</p>\n"
},
{
"answer_id": 1647238,
"author": "Brian Hawkins",
"author_id": 112699,
"author_profile": "https://Stackoverflow.com/users/112699",
"pm_score": 6,
"selected": false,
"text": "<p>You can also use the \"-u\" option to specify the path. I find this helpful on machines where my .bashrc doesn't get sourced in non-interactive sessions. For example, </p>\n\n<pre><code>git clone -u /home/you/bin/git-upload-pack you@machine:code\n</code></pre>\n"
},
{
"answer_id": 2276525,
"author": "tom",
"author_id": 274764,
"author_profile": "https://Stackoverflow.com/users/274764",
"pm_score": 4,
"selected": false,
"text": "<p>Mac OS X and some other Unixes at least have the user path compiled into sshd for security reasons so those of us that install git as /usr/local/git/{bin,lib,...} can run into trouble as the git executables are not in the precompiled path. To override this I prefer to edit my /etc/sshd_config changing:</p>\n\n<pre><code>#PermitUserEnvironment no\n</code></pre>\n\n<p>to</p>\n\n<pre><code>PermitUserEnvironment yes\n</code></pre>\n\n<p>and then create ~/.ssh/environment files as needed. My git users have the following in their ~/.ssh/environment file:</p>\n\n<pre><code>PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/git/bin\n</code></pre>\n\n<p>Note variable expansion does not occur when the ~/.ssh/environment file is read so:</p>\n\n<pre><code>PATH=$PATH:/usr/local/git/bin\n</code></pre>\n\n<p>will not work.</p>\n"
},
{
"answer_id": 6495787,
"author": "Garrett",
"author_id": 243434,
"author_profile": "https://Stackoverflow.com/users/243434",
"pm_score": 6,
"selected": false,
"text": "<p>Building on <a href=\"https://stackoverflow.com/questions/225291/git-upload-pack-command-not-found-how-to-fix-this-correctly/1647238#1647238\">Brian's answer</a>, the upload-pack path can be set permanently by running the following commands after cloning, which eliminates the need for <code>--upload-pack</code> on subsequent pull/fetch requests. Similarly, setting receive-pack eliminates the need for <code>--receive-pack</code> on push requests.</p>\n\n<pre><code>git config remote.origin.uploadpack /path/to/git-upload-pack\ngit config remote.origin.receivepack /path/to/git-receive-pack\n</code></pre>\n\n<p>These two commands are equivalent to adding the following lines to a repo's <code>.git/config</code>.</p>\n\n<pre><code>[remote \"origin\"]\n uploadpack = /path/to/git-upload-pack\n receivepack = /path/to/git-receive-pack\n</code></pre>\n\n<p>Frequent users of <code>clone -u</code> may be interested in the following aliases. myclone should be self-explanatory. myfetch/mypull/mypush can be used on repos whose config hasn't been modified as described above by replacing <code>git push</code> with <code>git mypush</code>, and so on.</p>\n\n<pre><code>[alias]\n myclone = clone --upload-pack /path/to/git-upload-pack\n myfetch = fetch --upload-pack /path/to/git-upload-pack\n mypull = pull --upload-pack /path/to/git-upload-pack\n mypush = push --receive-pack /path/to/git-receive-pack\n</code></pre>\n"
},
{
"answer_id": 7252746,
"author": "RAVolt",
"author_id": 72930,
"author_profile": "https://Stackoverflow.com/users/72930",
"pm_score": 0,
"selected": false,
"text": "<p>I have been having issues connecting to a Gitolite repo using SSH from Windows and it turned out that my problem was PLINK! It kept asking me for a password, but the ssh gitolite@[host] would return the repo list fine.</p>\n\n<p>Check your environment variable: GIT_SSH. If it is set to Plink, then try it without any value (\"set GIT_SSH=\") and see if that works.</p>\n"
},
{
"answer_id": 7558586,
"author": "Dennis",
"author_id": 605890,
"author_profile": "https://Stackoverflow.com/users/605890",
"pm_score": 1,
"selected": false,
"text": "<p>You must add the</p>\n\n<pre><code>export PATH=/opt/git/bin:$PATH\n</code></pre>\n\n<p>before this line in the .bashrc:</p>\n\n<pre><code># If not running interactively, don't do anything\n[ -z \"$PS1\" ] && return\n</code></pre>\n\n<p>Otherwise all export statements will not be executed (<a href=\"https://stackoverflow.com/questions/940533/how-do-i-set-path-such-that-ssh-userhost-command-works/941995#941995\">see here</a>).</p>\n"
},
{
"answer_id": 15719508,
"author": "Yeison",
"author_id": 707107,
"author_profile": "https://Stackoverflow.com/users/707107",
"pm_score": 0,
"selected": false,
"text": "<p>Add the location of your <code>git-upload-pack</code> to the remote git user's .bashrc file.</p>\n"
},
{
"answer_id": 57731220,
"author": "felixc",
"author_id": 3554727,
"author_profile": "https://Stackoverflow.com/users/3554727",
"pm_score": 1,
"selected": false,
"text": "<p>My case is on Win 10 with GIT bash and I don't have a GIT under standard location. Instead I have git under /app/local/bin.\nI used the commands provided by @Garrett but need to change the path to start with double /:</p>\n\n<pre><code>git config remote.origin.uploadpack //path/to/git-upload-pack\ngit config remote.origin.receivepack //path/to/git-receive-pack\n</code></pre>\n\n<p>Otherwise the GIT will add your Windows GIT path in front.</p>\n"
},
{
"answer_id": 62334743,
"author": "truefusion",
"author_id": 4020848,
"author_profile": "https://Stackoverflow.com/users/4020848",
"pm_score": 1,
"selected": false,
"text": "<p>It may be as simple as installing git on the remote host (like it was in my case).</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>sudo apt-get install git\n</code></pre>\n\n<p>Or equivalent for other package management systems.</p>\n"
},
{
"answer_id": 72233199,
"author": "Snekse",
"author_id": 378151,
"author_profile": "https://Stackoverflow.com/users/378151",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using <strong>GitHub Enterprise</strong>, make sure the repo is <code>public</code>, not <code>internal</code>. There may be other ways to solve this for an internal repo, but this was the quickest way to solve the problem without involving more time and people.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24508/"
] |
I have been using git to keep two copies of my project in sync, one is my local box, the other the test server.
This is an issue which occurs when I log onto our remote development server using ssh;
```
git clone [email protected]:/home/chris/myproject
Initialized empty Git repository in /tmp/myproject/.git/
Password:
bash: git-upload-pack: command not found
fatal: The remote end hung up unexpectedly
fetch-pack from '[email protected]:/home/chris/myproject' failed.
```
(the file-names have been changed to protect the guilty... !)
Both boxes run Solaris 10 AMD. I have done some digging, if I add `--upload-pack=$(which git-upload-pack)` the command works, (and proves that `$PATH` contains the path to 'git-upload-pack' as per the RTFM solution) but this is really annoying, plus 'git push' doesn't work, because I don't think there is a `--unpack=` option.
Incidentally, all the git commands work fine from my local box, it is the same version of the software (1.5.4.2), installed on the same NFS mount at `/usr/local/bin`.
Can anybody help?
|
Make sure `git-upload-pack` is on the path from a non-login shell. (On my machine it's in `/usr/bin`).
To see what your path looks like on the remote machine from a non-login shell, try this:
```
ssh you@remotemachine echo \$PATH
```
(That works in Bash, Zsh, and tcsh, and probably other shells too.)
If the path it gives back doesn't include the directory that has `git-upload-pack`, you need to fix it by setting it in `.bashrc` (for Bash), `.zshenv` (for Zsh), `.cshrc` (for tcsh) or equivalent for your shell.
You will need to make this change on the remote machine.
If you're not sure which path you need to add to your remote `PATH`, you can find it with this command (you need to run this on the remote machine):
`which git-upload-pack`
On my machine that prints `/usr/bin/git-upload-pack`. So in this case, `/usr/bin` is the path you need to make sure is in your remote non-login shell `PATH`.
|
225,309 |
<p>Today i stumbled upon an interesting performance problem with a stored procedure running on Sql Server 2005 SP2 in a db running on compatible level of 80 (SQL2000).</p>
<p>The proc runs about 8 Minutes and the execution plan shows the usage of an index with an actual row count of 1.339.241.423 which is about factor 1000 higher than the "real" actual rowcount of the table itself which is 1.144.640 as shown correctly by estimated row count. So the actual row count given by the query plan optimizer is definitly wrong!</p>
<p><img src="https://i.stack.imgur.com/kESKH.png" alt="alt text"></p>
<p>Interestingly enough, when i copy the procs parameter values inside the proc to local variables and than use the local variables in the actual query, everything works fine - the proc runs 18 seconds and the execution plan shows the right actual row count.</p>
<p><strong>EDIT:</strong> As suggested by TrickyNixon, this seems to be a sign of the parameter sniffing problem. But actually, i get in both cases exact the same execution plan. Same indices are beeing used in the same order. The only difference i see is the way to high actual row count on the PK_ED_Transitions index when directly using the parametervalues.</p>
<p>I have done dbcc dbreindex and UPDATE STATISTICS already without any success.
dbcc show_statistics shows good data for the index, too.</p>
<p>The proc is created WITH RECOMPILE so every time it runs a new execution plan is getting compiled.</p>
<p>To be more specific - this one runs fast:</p>
<pre><code>CREATE Proc [dbo].[myProc](
@Param datetime
)
WITH RECOMPILE
as
set nocount on
declare @local datetime
set @local = @Param
select
some columns
from
table1
where
column = @local
group by
some other columns
</code></pre>
<p>And this version runs terribly slow, but produces exactly the same execution plan (besides the too high actual row count on an used index):</p>
<pre><code>CREATE Proc [dbo].[myProc](
@Param datetime
)
WITH RECOMPILE
as
set nocount on
select
some columns
from
table1
where
column = @Param
group by
some other columns
</code></pre>
<p>Any ideas?
Anybody out there who knows where Sql Server gets the actual row count value from when calculating query plans?</p>
<p><strong>Update</strong>: I tried the query on another server woth copat mode set to 90 (Sql2005). Its the same behavior. I think i will open up an ms support call, because this looks to me like a bug.</p>
|
[
{
"answer_id": 225401,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>To me it still sounds as if the statistics were incorrect. Rebuilding the indexes does not necessarily update them.</p>\n\n<p>Have you already tried an explicit <code>UPDATE STATISTICS</code> for the affected tables?</p>\n"
},
{
"answer_id": 225537,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like a case of Parameter Sniffing. Here's an excellent explanation along with possible solutions: <a href=\"http://blogs.msdn.com/queryoptteam/archive/2006/03/31/565991.aspx\" rel=\"nofollow noreferrer\">I Smell a Parameter!</a> </p>\n\n<p>Here's another StackOverflow thread that addresses it: <a href=\"https://stackoverflow.com/questions/211355/parameter-sniffing-or-spoofing-in-sql-server\">Parameter Sniffing (or Spoofing) in SQL Server</a></p>\n"
},
{
"answer_id": 225932,
"author": "Brent Ozar",
"author_id": 26837,
"author_profile": "https://Stackoverflow.com/users/26837",
"pm_score": 2,
"selected": false,
"text": "<p>When you're checking execution plans of the stored proc against the copy/paste query, are you using the estimated plans or the actual plans? Make sure to click Query, Include Execution Plan, and then run each query. Compare those plans and see what the differences are.</p>\n"
},
{
"answer_id": 227271,
"author": "Rick",
"author_id": 14138,
"author_profile": "https://Stackoverflow.com/users/14138",
"pm_score": 0,
"selected": false,
"text": "<p>Have you run <strong>sp_spaceused</strong> to check if SQL Server's got the right summary for that table? I believe in SQL 2000 the engine used to use that sort of metadata when building execution plans. We used to have to run <strong>DBCC UPDATEUSAGE</strong> weekly to update the metadata on some of the rapidly changing tables, as SQL Server was choosing the wrong indexes due to the incorrect row count data.</p>\n\n<p>You're running SQL 2005, and BOL says that in 2005 you shouldn't have to run UpdateUsage anymore, but since you're in 2000 compat mode you might find that it is still required.</p>\n"
},
{
"answer_id": 229392,
"author": "Jan",
"author_id": 25727,
"author_profile": "https://Stackoverflow.com/users/25727",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, finally i got to it myself.</p>\n\n<p>The two query plans are different in a small detail which i missed at first. the slow one uses a nested loops operator to join two subqueries together. And that results in the high number at current row count on the index scan operator which is simply the result of multiplicating the number of rows of input a with number of rows of input b.</p>\n\n<p>I still don't know why the optimizer decides to use the nested loops instead of a hash match which runs 1000 timer faster in this case, but i could handle my problem by creating a new index, so that the engine does an index seek statt instead of an index scan under the nested loops.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25727/"
] |
Today i stumbled upon an interesting performance problem with a stored procedure running on Sql Server 2005 SP2 in a db running on compatible level of 80 (SQL2000).
The proc runs about 8 Minutes and the execution plan shows the usage of an index with an actual row count of 1.339.241.423 which is about factor 1000 higher than the "real" actual rowcount of the table itself which is 1.144.640 as shown correctly by estimated row count. So the actual row count given by the query plan optimizer is definitly wrong!

Interestingly enough, when i copy the procs parameter values inside the proc to local variables and than use the local variables in the actual query, everything works fine - the proc runs 18 seconds and the execution plan shows the right actual row count.
**EDIT:** As suggested by TrickyNixon, this seems to be a sign of the parameter sniffing problem. But actually, i get in both cases exact the same execution plan. Same indices are beeing used in the same order. The only difference i see is the way to high actual row count on the PK\_ED\_Transitions index when directly using the parametervalues.
I have done dbcc dbreindex and UPDATE STATISTICS already without any success.
dbcc show\_statistics shows good data for the index, too.
The proc is created WITH RECOMPILE so every time it runs a new execution plan is getting compiled.
To be more specific - this one runs fast:
```
CREATE Proc [dbo].[myProc](
@Param datetime
)
WITH RECOMPILE
as
set nocount on
declare @local datetime
set @local = @Param
select
some columns
from
table1
where
column = @local
group by
some other columns
```
And this version runs terribly slow, but produces exactly the same execution plan (besides the too high actual row count on an used index):
```
CREATE Proc [dbo].[myProc](
@Param datetime
)
WITH RECOMPILE
as
set nocount on
select
some columns
from
table1
where
column = @Param
group by
some other columns
```
Any ideas?
Anybody out there who knows where Sql Server gets the actual row count value from when calculating query plans?
**Update**: I tried the query on another server woth copat mode set to 90 (Sql2005). Its the same behavior. I think i will open up an ms support call, because this looks to me like a bug.
|
Ok, finally i got to it myself.
The two query plans are different in a small detail which i missed at first. the slow one uses a nested loops operator to join two subqueries together. And that results in the high number at current row count on the index scan operator which is simply the result of multiplicating the number of rows of input a with number of rows of input b.
I still don't know why the optimizer decides to use the nested loops instead of a hash match which runs 1000 timer faster in this case, but i could handle my problem by creating a new index, so that the engine does an index seek statt instead of an index scan under the nested loops.
|
225,327 |
<p>Currently I am working with a <strong>custom</strong> regular expression validator <em>(unfortunately)</em>.</p>
<p>I am trying to set the Regex pattern using a server side inline script like this:</p>
<pre><code>ValidationExpression="<%= RegExStrings.SomePattern %>"
</code></pre>
<p>However, the script is not resolving to server side code. Instead it is being interpreted literally and I end up with something like this in the rendered markup:</p>
<pre><code>ctl00_DefaultContent_regexValidatorInvitation.validationexpression = "<%= RegExStrings.SomePattern %>";
</code></pre>
<p>Any clues as to why this is not resolving properly?</p>
|
[
{
"answer_id": 225343,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 0,
"selected": false,
"text": "<p>Values in a web control do not render server side code.\nRather set that from the Code Behind</p>\n\n<pre><code>RegExValidator1.ValidationExpression = RegExStrings.SomePattern;\n</code></pre>\n"
},
{
"answer_id": 225351,
"author": "PhilGriffin",
"author_id": 29294,
"author_profile": "https://Stackoverflow.com/users/29294",
"pm_score": 0,
"selected": false,
"text": "<p>It's being taken as a literal string, try</p>\n\n<p>ValidationExpression='<%= RegExStrings.SomePattern %>'</p>\n\n<p>Edit: The above doesn't work, I've tried to see how to do this without success,I usually set properties in the code-behind and only use this syntax for databinding when I have to. I'd be interested to know if it can be done too. </p>\n"
},
{
"answer_id": 225638,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 0,
"selected": false,
"text": "<p>If your regular expression validator has the runat=\"server\" attribute, then change it from the code behind. It would be much easier.</p>\n"
},
{
"answer_id": 487844,
"author": "MarkD",
"author_id": 59773,
"author_profile": "https://Stackoverflow.com/users/59773",
"pm_score": 2,
"selected": false,
"text": "<p>But why is this? I can reproduce your problem using a simple aspx page as below:</p>\n\n<pre><code><%@ Page language=\"c#\" AutoEventWireup=\"true\" %>\n<html>\n <body >\n <form id=\"Form1\" method=\"post\" runat=\"server\" action=\"?<%=Request.QueryString%>\">\n Query String value: <%=Request.QueryString %>\n <br />\n <input type=submit />\n </form>\n </body>\n</html>\n</code></pre>\n\n<p>This displays the following after submitting the form:</p>\n\n<blockquote>\n <p>Query String value:\n %3c%25=Request.QueryString%25%3e</p>\n</blockquote>\n\n<p>For some reason, the inline code is not executed when the\nrunat=\"server\" is present. The strange thing is I have 3 machines\nthat do not behave this way and one that does, so I can only assume\nthat this is an IIS/.NET config issue, possibly caused by a recent MS\nUpdate. The software I have installed recently on the machine\nexhibiting this behaviour is:\nVisual Studio 2008\nWSE 3.0\nIE8 RC1</p>\n\n<p>I wonder if any of these have caused this? </p>\n"
},
{
"answer_id": 487930,
"author": "devstuff",
"author_id": 41321,
"author_profile": "https://Stackoverflow.com/users/41321",
"pm_score": 0,
"selected": false,
"text": "<p>You're using a databinding expression on a control that is not databound. You need to call DataBind(), or use an ExpressionBuilder implementation. A simple ExpressionBuilder for binding to arbitary code can be found at <a href=\"http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx</a></p>\n"
},
{
"answer_id": 488018,
"author": "MarkD",
"author_id": 59773,
"author_profile": "https://Stackoverflow.com/users/59773",
"pm_score": 1,
"selected": false,
"text": "<p>devstuff, that doesn't explain why this works on 3 of my machines, but not a 4th one, does it? They are all using the same .NET Framework version and IIS settings (I believe, having checked as many as I coukd)</p>\n"
},
{
"answer_id": 491388,
"author": "MarkD",
"author_id": 59773,
"author_profile": "https://Stackoverflow.com/users/59773",
"pm_score": 1,
"selected": false,
"text": "<p>I've uninstalled the .NET framework while investigating this (3.5 then 3.0 and 2.0) - I then had no problems after \nInstalling each of the following:\n.net framework 2.0 \n.net framework 2.0 SP1\n.net framework 3.0 \n.net framework 3.0 SP1\n.net framework 3.5 </p>\n\n<p>But after I installed .net framework 3.5 SP1 the behaviour returned – I guess this is the issue. I have raised this with Microsoft and will update this thread when I get a response. </p>\n"
},
{
"answer_id": 564601,
"author": "MarkD",
"author_id": 59773,
"author_profile": "https://Stackoverflow.com/users/59773",
"pm_score": 3,
"selected": true,
"text": "<p>This has now been cleared up my MS. The issue I discovered was caused by the fact that the \"action\" attribute in server forms had no effect prior to .NET 2 SP2, but now can be set. Code render blocks have never worked in attribute values - this is explained towards the end of this post.</p>\n\n<p>This was a consequence of a deliberate change in behaviour introduced in Microsoft .NET Framework 3.5 SP1. Prior to the service pack, action and method attributes on server side FORM tags could not be over-ridden. If specified they would be replaced by ASP.NET with \"POST\" and \"page name\".</p>\n\n<p>Previously, the ASP.NET page parser did not prevent one specifying these attributes although the documentation advised against it for the action attribute:\n<a href=\"http://msdn.microsoft.com/en-us/library/k33801s3.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/k33801s3.aspx</a></p>\n\n<p>In particular the comment (in the context of the FORM element):</p>\n\n<p>• \"The opening tag must not contain an action attribute. ASP.NET sets these attributes dynamically when the page is processed, overriding any settings that you might make. \"</p>\n\n<p>The issue that was originally reported by Josh, where the code block was not being interpreted is not new behaviour but is a known bug - code render blocks cannot be used within server control attributes. This is reported as a \"Connect\" bug:\n<a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=109257\" rel=\"nofollow noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=109257</a>\nwhich contains the following:\n\" Attributes of server controls cannot take an inline expression as value. This explains the unexpected behaviour as seen with: \" <link href=\"<%=RootPath %> ...\" However, inline code can be used for values of attributes.\"</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11702/"
] |
Currently I am working with a **custom** regular expression validator *(unfortunately)*.
I am trying to set the Regex pattern using a server side inline script like this:
```
ValidationExpression="<%= RegExStrings.SomePattern %>"
```
However, the script is not resolving to server side code. Instead it is being interpreted literally and I end up with something like this in the rendered markup:
```
ctl00_DefaultContent_regexValidatorInvitation.validationexpression = "<%= RegExStrings.SomePattern %>";
```
Any clues as to why this is not resolving properly?
|
This has now been cleared up my MS. The issue I discovered was caused by the fact that the "action" attribute in server forms had no effect prior to .NET 2 SP2, but now can be set. Code render blocks have never worked in attribute values - this is explained towards the end of this post.
This was a consequence of a deliberate change in behaviour introduced in Microsoft .NET Framework 3.5 SP1. Prior to the service pack, action and method attributes on server side FORM tags could not be over-ridden. If specified they would be replaced by ASP.NET with "POST" and "page name".
Previously, the ASP.NET page parser did not prevent one specifying these attributes although the documentation advised against it for the action attribute:
<http://msdn.microsoft.com/en-us/library/k33801s3.aspx>
In particular the comment (in the context of the FORM element):
• "The opening tag must not contain an action attribute. ASP.NET sets these attributes dynamically when the page is processed, overriding any settings that you might make. "
The issue that was originally reported by Josh, where the code block was not being interpreted is not new behaviour but is a known bug - code render blocks cannot be used within server control attributes. This is reported as a "Connect" bug:
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=109257>
which contains the following:
" Attributes of server controls cannot take an inline expression as value. This explains the unexpected behaviour as seen with: " <link href="<%=RootPath %> ..." However, inline code can be used for values of attributes."
|
225,330 |
<p>I'm writing a tool to report information about .NET applications deployed across environments and regions within my client's systems.</p>
<p>I'd like to read the values of assembly attributes in these assemblies.</p>
<p>This can be achieved using <code>Assembly.ReflectionOnlyLoad</code>, however even this approach keeps the assembly loaded. The issue here is that I cannot load two assemblies that have the same name from different paths, so naturally I can't compare the same application deployed in different systems.</p>
<p>At this point I'm assuming the solution will involve using temporary <code>AppDomain</code>s.</p>
<p>Can someone detail how to load an assembly into another <code>AppDomain</code>, read the attributes from it and then unload the <code>AppDomain</code>?</p>
<p>This needs to work for assemblies on the file system as well as those at URL addresses.</p>
|
[
{
"answer_id": 225355,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 7,
"selected": true,
"text": "<p>From the <a href=\"http://msdn.microsoft.com/en-us/library/0et80c7k.aspx\" rel=\"noreferrer\">MSDN documentation of System.Reflection.Assembly.ReflectionOnlyLoad (String)</a> :</p>\n\n<blockquote>\n <p>The reflection-only context is no\n different from other contexts.\n Assemblies that are loaded into the\n context can be unloaded only by\n unloading the application domain.</p>\n</blockquote>\n\n<p>So, I am afraid the only way to unload an assembly is unloading the application domain.\nTo create a new AppDomain and load assemblies into it:</p>\n\n<pre><code>public void TempLoadAssembly()\n{\n AppDomain tempDomain = AppDomain.CreateDomain(\"TemporaryAppDomain\");\n tempDomain.DoCallBack(LoaderCallback);\n AppDomain.Unload(tempDomain);\n}\n\nprivate void LoaderCallback()\n{\n Assembly.ReflectionOnlyLoad(\"YourAssembly\");\n // Do your stuff here\n}\n</code></pre>\n"
},
{
"answer_id": 225369,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to use <a href=\"http://msdn.microsoft.com/en-us/library/ms404434.aspx\" rel=\"nofollow noreferrer\">Unmanaged Metadata API</a>, which is COM and can easily be used from .NET application with some kind of wrapper. </p>\n"
},
{
"answer_id": 225385,
"author": "Albert",
"author_id": 24065,
"author_profile": "https://Stackoverflow.com/users/24065",
"pm_score": 2,
"selected": false,
"text": "<p>You have to use application domains, there's no other way to unload an assembly. Basically you have to use code like this:</p>\n\n<pre>\n\nAppDomain tempDomain = AppDomain.CreateDomain(\"Temp Domain\");\ntempDomain.Load(assembly);\nAppDomain.Unload(tempDomain);\n\n</pre>\n"
},
{
"answer_id": 733467,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 3,
"selected": false,
"text": "<p>Whilst not really about unloading assemblies, if you're just trying to get the version number of a file you can use <code>System.Diagnostics.FileVersionInfo</code>.</p>\n\n<pre><code>var info = FileVersionInfo.GetVersionInfo(path);\n</code></pre>\n\n<p><code>FileVersionInfo</code> has the following properties:</p>\n\n<pre><code>public string Comments { get; }\npublic string CompanyName { get; }\npublic int FileBuildPart { get; }\npublic string FileDescription { get; }\npublic int FileMajorPart { get; }\npublic int FileMinorPart { get; }\npublic string FileName { get; }\npublic int FilePrivatePart { get; }\npublic string FileVersion { get; }\npublic string InternalName { get; }\npublic bool IsDebug { get; }\npublic bool IsPatched { get; }\npublic bool IsPreRelease { get; }\npublic bool IsPrivateBuild { get; }\npublic bool IsSpecialBuild { get; }\npublic string Language { get; }\npublic string LegalCopyright { get; }\npublic string LegalTrademarks { get; }\npublic string OriginalFilename { get; }\npublic string PrivateBuild { get; }\npublic int ProductBuildPart { get; }\npublic int ProductMajorPart { get; }\npublic int ProductMinorPart { get; }\npublic string ProductName { get; }\npublic int ProductPrivatePart { get; }\npublic string ProductVersion { get; }\npublic string SpecialBuild { get; }\n</code></pre>\n"
},
{
"answer_id": 37970043,
"author": "Artiom",
"author_id": 797249,
"author_profile": "https://Stackoverflow.com/users/797249",
"pm_score": 3,
"selected": false,
"text": "<p>You can create an instance in the new AppDomain and execute your code in that instance. </p>\n\n<pre><code>var settings = new AppDomainSetup\n{\n ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,\n};\nvar childDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString(), null, settings);\n\n var handle = Activator.CreateInstance(childDomain,\n typeof(ReferenceLoader).Assembly.FullName,\n typeof(ReferenceLoader).FullName,\n false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.CurrentCulture, new object[0]);\n\n\nvar loader = (ReferenceLoader)handle.Unwrap();\n\n//This operation is executed in the new AppDomain\nvar paths = loader.LoadReferences(assemblyPath);\n\n\nAppDomain.Unload(childDomain);\n</code></pre>\n\n<p>Here is the ReferenceLoader</p>\n\n<pre><code>public class ReferenceLoader : MarshalByRefObject\n{\n public string[] LoadReferences(string assemblyPath)\n {\n var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyPath);\n var paths = assembly.GetReferencedAssemblies().Select(x => x.FullName).ToArray();\n return paths;\n }\n}\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24874/"
] |
I'm writing a tool to report information about .NET applications deployed across environments and regions within my client's systems.
I'd like to read the values of assembly attributes in these assemblies.
This can be achieved using `Assembly.ReflectionOnlyLoad`, however even this approach keeps the assembly loaded. The issue here is that I cannot load two assemblies that have the same name from different paths, so naturally I can't compare the same application deployed in different systems.
At this point I'm assuming the solution will involve using temporary `AppDomain`s.
Can someone detail how to load an assembly into another `AppDomain`, read the attributes from it and then unload the `AppDomain`?
This needs to work for assemblies on the file system as well as those at URL addresses.
|
From the [MSDN documentation of System.Reflection.Assembly.ReflectionOnlyLoad (String)](http://msdn.microsoft.com/en-us/library/0et80c7k.aspx) :
>
> The reflection-only context is no
> different from other contexts.
> Assemblies that are loaded into the
> context can be unloaded only by
> unloading the application domain.
>
>
>
So, I am afraid the only way to unload an assembly is unloading the application domain.
To create a new AppDomain and load assemblies into it:
```
public void TempLoadAssembly()
{
AppDomain tempDomain = AppDomain.CreateDomain("TemporaryAppDomain");
tempDomain.DoCallBack(LoaderCallback);
AppDomain.Unload(tempDomain);
}
private void LoaderCallback()
{
Assembly.ReflectionOnlyLoad("YourAssembly");
// Do your stuff here
}
```
|
225,337 |
<p>What regex pattern would need I to pass to <code>java.lang.String.split()</code> to split a String into an Array of substrings using all whitespace characters (<code>' '</code>, <code>'\t'</code>, <code>'\n'</code>, etc.) as delimiters?</p>
|
[
{
"answer_id": 225349,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "<p>\"\\\\s+\" should do the trick</p>\n"
},
{
"answer_id": 225354,
"author": "glenatron",
"author_id": 15394,
"author_profile": "https://Stackoverflow.com/users/15394",
"pm_score": 7,
"selected": false,
"text": "<p>In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember:</p>\n\n<p><code>\\w</code> - Matches any word character. </p>\n\n<p><code>\\W</code> - Matches any nonword character. </p>\n\n<p><code>\\s</code> - Matches any white-space character. </p>\n\n<p><code>\\S</code> - Matches anything but white-space characters. </p>\n\n<p><code>\\d</code> - Matches any digit. </p>\n\n<p><code>\\D</code> - Matches anything except digits.</p>\n\n<p>A search for \"Regex Cheatsheets\" should reward you with a whole lot of useful summaries.</p>\n"
},
{
"answer_id": 225360,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 11,
"selected": true,
"text": "<p>Something in the lines of</p>\n<pre><code>myString.split("\\\\s+");\n</code></pre>\n<p>This groups all white spaces as a delimiter.</p>\n<p>So if I have the string:</p>\n<pre><code>"Hello[space character][tab character]World"\n</code></pre>\n<p>This should yield the strings <code>"Hello"</code> and <code>"World"</code> and omit the empty space between the <code>[space]</code> and the <code>[tab]</code>.</p>\n<p>As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send <em>that</em> to be parsed. What you want, is the literal <code>"\\s"</code>, which means, you need to pass <code>"\\\\s"</code>. It can get a bit confusing.</p>\n<p>The <code>\\\\s</code> is equivalent to <code>[ \\\\t\\\\n\\\\x0B\\\\f\\\\r]</code>.</p>\n"
},
{
"answer_id": 9274100,
"author": "Rishabh",
"author_id": 1208677,
"author_profile": "https://Stackoverflow.com/users/1208677",
"pm_score": 1,
"selected": false,
"text": "<p>Since it is a regular expression, and i'm assuming u would also not want non-alphanumeric chars like commas, dots, etc that could be surrounded by blanks (e.g. \"one , two\" should give [one][two]), it should be:</p>\n\n<pre><code>myString.split(/[\\s\\W]+/)\n</code></pre>\n"
},
{
"answer_id": 9525071,
"author": "Mike Manard",
"author_id": 835445,
"author_profile": "https://Stackoverflow.com/users/835445",
"pm_score": 6,
"selected": false,
"text": "<p>To get this working <strong>in Javascript</strong>, I had to do the following:</p>\n\n<pre><code>myString.split(/\\s+/g)\n</code></pre>\n"
},
{
"answer_id": 20314841,
"author": "Felix Scheffer",
"author_id": 569040,
"author_profile": "https://Stackoverflow.com/users/569040",
"pm_score": 3,
"selected": false,
"text": "<p>Apache Commons Lang has a method to split a string with whitespace characters as delimiters:</p>\n\n<pre><code>StringUtils.split(\"abc def\")\n</code></pre>\n\n<p><a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split(java.lang.String)\">http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split(java.lang.String)</a></p>\n\n<p>This might be easier to use than a regex pattern.</p>\n"
},
{
"answer_id": 25607143,
"author": "RajeshVijayakumar",
"author_id": 1369752,
"author_profile": "https://Stackoverflow.com/users/1369752",
"pm_score": 1,
"selected": false,
"text": "<p>you can split a string by line break by using the following statement :</p>\n\n<pre><code> String textStr[] = yourString.split(\"\\\\r?\\\\n\");\n</code></pre>\n\n<p>you can split a string by Whitespace by using the following statement :</p>\n\n<pre><code>String textStr[] = yourString.split(\"\\\\s+\");\n</code></pre>\n"
},
{
"answer_id": 25736267,
"author": "jake_astub",
"author_id": 2569695,
"author_profile": "https://Stackoverflow.com/users/2569695",
"pm_score": 4,
"selected": false,
"text": "<p>Also you may have a UniCode non-breaking space xA0...</p>\n\n<pre><code>String[] elements = s.split(\"[\\\\s\\\\xA0]+\"); //include uniCode non-breaking\n</code></pre>\n"
},
{
"answer_id": 29585829,
"author": "Olivia Liao",
"author_id": 4083888,
"author_profile": "https://Stackoverflow.com/users/4083888",
"pm_score": 1,
"selected": false,
"text": "<pre><code>String str = \"Hello World\";\nString res[] = str.split(\"\\\\s+\");\n</code></pre>\n"
},
{
"answer_id": 36340734,
"author": "Arrow",
"author_id": 6120088,
"author_profile": "https://Stackoverflow.com/users/6120088",
"pm_score": 3,
"selected": false,
"text": "<pre><code>String string = \"Ram is going to school\";\nString[] arrayOfString = string.split(\"\\\\s+\");\n</code></pre>\n"
},
{
"answer_id": 40220586,
"author": "Risith Ravisara",
"author_id": 5951926,
"author_profile": "https://Stackoverflow.com/users/5951926",
"pm_score": -1,
"selected": false,
"text": "<p>Study this code.. good luck</p>\n\n<pre><code> import java.util.*;\nclass Demo{\n public static void main(String args[]){\n Scanner input = new Scanner(System.in);\n System.out.print(\"Input String : \");\n String s1 = input.nextLine(); \n String[] tokens = s1.split(\"[\\\\s\\\\xA0]+\"); \n System.out.println(tokens.length); \n for(String s : tokens){\n System.out.println(s);\n\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 63441506,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "<p>To split a string with <em><strong>any Unicode whitespace</strong></em>, you need to use</p>\n<pre><code>s.split("(?U)\\\\s+")\n ^^^^\n</code></pre>\n<p>The <code>(?U)</code> inline embedded flag option is the equivalent of <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#UNICODE_CHARACTER_CLASS\" rel=\"nofollow noreferrer\"><code>Pattern.UNICODE_CHARACTER_CLASS</code></a> that enables <code>\\s</code> shorthand character class to match any characters from the whitespace Unicode category.</p>\n<p>If you want to split with whitespace and <strong>keep the whitespaces in the resulting array</strong>, use</p>\n<pre><code>s.split("(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)")\n</code></pre>\n<p>See the <a href=\"https://regex101.com/r/I2yoEt/2\" rel=\"nofollow noreferrer\">regex demo</a>. See <a href=\"https://ideone.com/d2ZflI\" rel=\"nofollow noreferrer\">Java demo</a>:</p>\n<pre><code>String s = "Hello\\t World\\u00A0»";\nSystem.out.println(Arrays.toString(s.split("(?U)\\\\s+"))); // => [Hello, World, »]\nSystem.out.println(Arrays.toString(s.split("(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)")));\n// => [Hello, , World, , »]\n</code></pre>\n"
},
{
"answer_id": 65836075,
"author": "SKL",
"author_id": 11638492,
"author_profile": "https://Stackoverflow.com/users/11638492",
"pm_score": 2,
"selected": false,
"text": "<p><strong>All you need is</strong> to split using the one of the special character of Java Ragex Engine,</p>\n<p>and that is- <strong>WhiteSpace Character</strong></p>\n<ul>\n<li><strong>\\d</strong> Represents a digit: <code>[0-9]</code></li>\n<li><strong>\\D</strong> Represents a non-digit: <code>[^0-9]</code></li>\n<li><strong>\\s</strong> Represents a <strong>whitespace character</strong> including <code>[ \\t\\n\\x0B\\f\\r]</code></li>\n<li><strong>\\S</strong> Represents a non-whitespace character as <code>[^\\s]</code></li>\n<li><strong>\\v</strong> Represents a vertical whitespace character as <code>[\\n\\x0B\\f\\r\\x85\\u2028\\u2029]</code></li>\n<li><strong>\\V</strong> Represents a non-vertical whitespace character as <code>[^\\v]</code></li>\n<li><strong>\\w</strong> Represents a word character as <code>[a-zA-Z_0-9]</code></li>\n<li><strong>\\W</strong> Represents a non-word character as <code>[^\\w]</code></li>\n</ul>\n<p><strong>Here, the key point</strong> to remember is that the small leter character <code>\\s</code> represents all types of white spaces including a single space <code>[ ]</code> , tab characters <code>[ ]</code> or anything similar.</p>\n<p>So, if you'll try will something like this-</p>\n<pre><code>String theString = "Java<a space><a tab>Programming"\nString []allParts = theString.split("\\\\s+");\n</code></pre>\n<p>You will get the desired output.</p>\n<hr />\n<p><strong>Some Very Useful Links:</strong></p>\n<ul>\n<li><a href=\"https://shubhamklogic.com/how-to-use-split-in-java-a-modern-guide/\" rel=\"nofollow noreferrer\">Split() method Best Examples</a></li>\n<li><a href=\"https://regexr.com/\" rel=\"nofollow noreferrer\">Regexr</a></li>\n<li><a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split\" rel=\"nofollow noreferrer\">split-Java 11</a></li>\n<li><a href=\"https://www.regular-expressions.info/\" rel=\"nofollow noreferrer\">RegularExpInfo</a></li>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow noreferrer\">PatternClass</a></li>\n</ul>\n<hr />\n<p><strong>Hope, this might help you the best!!!</strong></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30323/"
] |
What regex pattern would need I to pass to `java.lang.String.split()` to split a String into an Array of substrings using all whitespace characters (`' '`, `'\t'`, `'\n'`, etc.) as delimiters?
|
Something in the lines of
```
myString.split("\\s+");
```
This groups all white spaces as a delimiter.
So if I have the string:
```
"Hello[space character][tab character]World"
```
This should yield the strings `"Hello"` and `"World"` and omit the empty space between the `[space]` and the `[tab]`.
As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send *that* to be parsed. What you want, is the literal `"\s"`, which means, you need to pass `"\\s"`. It can get a bit confusing.
The `\\s` is equivalent to `[ \\t\\n\\x0B\\f\\r]`.
|
225,357 |
<p>I have to develop a system to <strong>monitor</strong> the <strong>generation/transmission</strong> of reports.</p>
<ul>
<li>System data will be stored in database tables (Sybase)</li>
<li>Reports will be generated with different schedules ("mon-fri 10pm", "sat 5am", "1st day of the month", etc.)</li>
<li>System will just monitor that the reports were created. It will not create the reports itself.</li>
<li>System will notify appropriate personnel when a report did not finish.</li>
<li>System will maintain a log of all generated reports</li>
</ul>
<p>Anyone know of a good(tried and proven) table(s) design for storing the task shedules?. I already have an idea, but I don't want reinvent the wheel.</p>
|
[
{
"answer_id": 225349,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "<p>\"\\\\s+\" should do the trick</p>\n"
},
{
"answer_id": 225354,
"author": "glenatron",
"author_id": 15394,
"author_profile": "https://Stackoverflow.com/users/15394",
"pm_score": 7,
"selected": false,
"text": "<p>In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember:</p>\n\n<p><code>\\w</code> - Matches any word character. </p>\n\n<p><code>\\W</code> - Matches any nonword character. </p>\n\n<p><code>\\s</code> - Matches any white-space character. </p>\n\n<p><code>\\S</code> - Matches anything but white-space characters. </p>\n\n<p><code>\\d</code> - Matches any digit. </p>\n\n<p><code>\\D</code> - Matches anything except digits.</p>\n\n<p>A search for \"Regex Cheatsheets\" should reward you with a whole lot of useful summaries.</p>\n"
},
{
"answer_id": 225360,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 11,
"selected": true,
"text": "<p>Something in the lines of</p>\n<pre><code>myString.split("\\\\s+");\n</code></pre>\n<p>This groups all white spaces as a delimiter.</p>\n<p>So if I have the string:</p>\n<pre><code>"Hello[space character][tab character]World"\n</code></pre>\n<p>This should yield the strings <code>"Hello"</code> and <code>"World"</code> and omit the empty space between the <code>[space]</code> and the <code>[tab]</code>.</p>\n<p>As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send <em>that</em> to be parsed. What you want, is the literal <code>"\\s"</code>, which means, you need to pass <code>"\\\\s"</code>. It can get a bit confusing.</p>\n<p>The <code>\\\\s</code> is equivalent to <code>[ \\\\t\\\\n\\\\x0B\\\\f\\\\r]</code>.</p>\n"
},
{
"answer_id": 9274100,
"author": "Rishabh",
"author_id": 1208677,
"author_profile": "https://Stackoverflow.com/users/1208677",
"pm_score": 1,
"selected": false,
"text": "<p>Since it is a regular expression, and i'm assuming u would also not want non-alphanumeric chars like commas, dots, etc that could be surrounded by blanks (e.g. \"one , two\" should give [one][two]), it should be:</p>\n\n<pre><code>myString.split(/[\\s\\W]+/)\n</code></pre>\n"
},
{
"answer_id": 9525071,
"author": "Mike Manard",
"author_id": 835445,
"author_profile": "https://Stackoverflow.com/users/835445",
"pm_score": 6,
"selected": false,
"text": "<p>To get this working <strong>in Javascript</strong>, I had to do the following:</p>\n\n<pre><code>myString.split(/\\s+/g)\n</code></pre>\n"
},
{
"answer_id": 20314841,
"author": "Felix Scheffer",
"author_id": 569040,
"author_profile": "https://Stackoverflow.com/users/569040",
"pm_score": 3,
"selected": false,
"text": "<p>Apache Commons Lang has a method to split a string with whitespace characters as delimiters:</p>\n\n<pre><code>StringUtils.split(\"abc def\")\n</code></pre>\n\n<p><a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split(java.lang.String)\">http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split(java.lang.String)</a></p>\n\n<p>This might be easier to use than a regex pattern.</p>\n"
},
{
"answer_id": 25607143,
"author": "RajeshVijayakumar",
"author_id": 1369752,
"author_profile": "https://Stackoverflow.com/users/1369752",
"pm_score": 1,
"selected": false,
"text": "<p>you can split a string by line break by using the following statement :</p>\n\n<pre><code> String textStr[] = yourString.split(\"\\\\r?\\\\n\");\n</code></pre>\n\n<p>you can split a string by Whitespace by using the following statement :</p>\n\n<pre><code>String textStr[] = yourString.split(\"\\\\s+\");\n</code></pre>\n"
},
{
"answer_id": 25736267,
"author": "jake_astub",
"author_id": 2569695,
"author_profile": "https://Stackoverflow.com/users/2569695",
"pm_score": 4,
"selected": false,
"text": "<p>Also you may have a UniCode non-breaking space xA0...</p>\n\n<pre><code>String[] elements = s.split(\"[\\\\s\\\\xA0]+\"); //include uniCode non-breaking\n</code></pre>\n"
},
{
"answer_id": 29585829,
"author": "Olivia Liao",
"author_id": 4083888,
"author_profile": "https://Stackoverflow.com/users/4083888",
"pm_score": 1,
"selected": false,
"text": "<pre><code>String str = \"Hello World\";\nString res[] = str.split(\"\\\\s+\");\n</code></pre>\n"
},
{
"answer_id": 36340734,
"author": "Arrow",
"author_id": 6120088,
"author_profile": "https://Stackoverflow.com/users/6120088",
"pm_score": 3,
"selected": false,
"text": "<pre><code>String string = \"Ram is going to school\";\nString[] arrayOfString = string.split(\"\\\\s+\");\n</code></pre>\n"
},
{
"answer_id": 40220586,
"author": "Risith Ravisara",
"author_id": 5951926,
"author_profile": "https://Stackoverflow.com/users/5951926",
"pm_score": -1,
"selected": false,
"text": "<p>Study this code.. good luck</p>\n\n<pre><code> import java.util.*;\nclass Demo{\n public static void main(String args[]){\n Scanner input = new Scanner(System.in);\n System.out.print(\"Input String : \");\n String s1 = input.nextLine(); \n String[] tokens = s1.split(\"[\\\\s\\\\xA0]+\"); \n System.out.println(tokens.length); \n for(String s : tokens){\n System.out.println(s);\n\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 63441506,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "<p>To split a string with <em><strong>any Unicode whitespace</strong></em>, you need to use</p>\n<pre><code>s.split("(?U)\\\\s+")\n ^^^^\n</code></pre>\n<p>The <code>(?U)</code> inline embedded flag option is the equivalent of <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#UNICODE_CHARACTER_CLASS\" rel=\"nofollow noreferrer\"><code>Pattern.UNICODE_CHARACTER_CLASS</code></a> that enables <code>\\s</code> shorthand character class to match any characters from the whitespace Unicode category.</p>\n<p>If you want to split with whitespace and <strong>keep the whitespaces in the resulting array</strong>, use</p>\n<pre><code>s.split("(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)")\n</code></pre>\n<p>See the <a href=\"https://regex101.com/r/I2yoEt/2\" rel=\"nofollow noreferrer\">regex demo</a>. See <a href=\"https://ideone.com/d2ZflI\" rel=\"nofollow noreferrer\">Java demo</a>:</p>\n<pre><code>String s = "Hello\\t World\\u00A0»";\nSystem.out.println(Arrays.toString(s.split("(?U)\\\\s+"))); // => [Hello, World, »]\nSystem.out.println(Arrays.toString(s.split("(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)")));\n// => [Hello, , World, , »]\n</code></pre>\n"
},
{
"answer_id": 65836075,
"author": "SKL",
"author_id": 11638492,
"author_profile": "https://Stackoverflow.com/users/11638492",
"pm_score": 2,
"selected": false,
"text": "<p><strong>All you need is</strong> to split using the one of the special character of Java Ragex Engine,</p>\n<p>and that is- <strong>WhiteSpace Character</strong></p>\n<ul>\n<li><strong>\\d</strong> Represents a digit: <code>[0-9]</code></li>\n<li><strong>\\D</strong> Represents a non-digit: <code>[^0-9]</code></li>\n<li><strong>\\s</strong> Represents a <strong>whitespace character</strong> including <code>[ \\t\\n\\x0B\\f\\r]</code></li>\n<li><strong>\\S</strong> Represents a non-whitespace character as <code>[^\\s]</code></li>\n<li><strong>\\v</strong> Represents a vertical whitespace character as <code>[\\n\\x0B\\f\\r\\x85\\u2028\\u2029]</code></li>\n<li><strong>\\V</strong> Represents a non-vertical whitespace character as <code>[^\\v]</code></li>\n<li><strong>\\w</strong> Represents a word character as <code>[a-zA-Z_0-9]</code></li>\n<li><strong>\\W</strong> Represents a non-word character as <code>[^\\w]</code></li>\n</ul>\n<p><strong>Here, the key point</strong> to remember is that the small leter character <code>\\s</code> represents all types of white spaces including a single space <code>[ ]</code> , tab characters <code>[ ]</code> or anything similar.</p>\n<p>So, if you'll try will something like this-</p>\n<pre><code>String theString = "Java<a space><a tab>Programming"\nString []allParts = theString.split("\\\\s+");\n</code></pre>\n<p>You will get the desired output.</p>\n<hr />\n<p><strong>Some Very Useful Links:</strong></p>\n<ul>\n<li><a href=\"https://shubhamklogic.com/how-to-use-split-in-java-a-modern-guide/\" rel=\"nofollow noreferrer\">Split() method Best Examples</a></li>\n<li><a href=\"https://regexr.com/\" rel=\"nofollow noreferrer\">Regexr</a></li>\n<li><a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split\" rel=\"nofollow noreferrer\">split-Java 11</a></li>\n<li><a href=\"https://www.regular-expressions.info/\" rel=\"nofollow noreferrer\">RegularExpInfo</a></li>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow noreferrer\">PatternClass</a></li>\n</ul>\n<hr />\n<p><strong>Hope, this might help you the best!!!</strong></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
I have to develop a system to **monitor** the **generation/transmission** of reports.
* System data will be stored in database tables (Sybase)
* Reports will be generated with different schedules ("mon-fri 10pm", "sat 5am", "1st day of the month", etc.)
* System will just monitor that the reports were created. It will not create the reports itself.
* System will notify appropriate personnel when a report did not finish.
* System will maintain a log of all generated reports
Anyone know of a good(tried and proven) table(s) design for storing the task shedules?. I already have an idea, but I don't want reinvent the wheel.
|
Something in the lines of
```
myString.split("\\s+");
```
This groups all white spaces as a delimiter.
So if I have the string:
```
"Hello[space character][tab character]World"
```
This should yield the strings `"Hello"` and `"World"` and omit the empty space between the `[space]` and the `[tab]`.
As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send *that* to be parsed. What you want, is the literal `"\s"`, which means, you need to pass `"\\s"`. It can get a bit confusing.
The `\\s` is equivalent to `[ \\t\\n\\x0B\\f\\r]`.
|
225,362 |
<p>I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492'). </p>
<p>In other words, I need to add correct amount of leading zeros to the number.</p>
<pre><code>int n = 999;
string str = some_function(n,6);
//str = '000999'
</code></pre>
<p>Is there a function like this in C++?</p>
|
[
{
"answer_id": 225372,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 2,
"selected": false,
"text": "<p>There are many ways of doing this. The simplest would be:</p>\n\n<pre><code>int n = 999;\nchar buffer[256]; sprintf(buffer, \"%06d\", n);\nstring str(buffer);\n</code></pre>\n"
},
{
"answer_id": 225373,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 1,
"selected": false,
"text": "<p>sprintf is the C-like way of doing this, which also works in C++.</p>\n\n<p>In C++, a combination of a stringstream and stream output formatting (see <a href=\"http://www.arachnoid.com/cpptutor/student3.html\" rel=\"nofollow noreferrer\">http://www.arachnoid.com/cpptutor/student3.html</a> ) will do the job.</p>\n"
},
{
"answer_id": 225389,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 4,
"selected": false,
"text": "<pre><code>char str[7];\nsnprintf (str, 7, \"%06d\", n);\n</code></pre>\n\n<p>See <a href=\"http://libslack.org/manpages/snprintf.3.html\" rel=\"noreferrer\">snprintf</a></p>\n"
},
{
"answer_id": 225435,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 7,
"selected": true,
"text": "<p>or using the stringstreams:</p>\n\n<pre><code>#include <sstream>\n#include <iomanip>\n\nstd::stringstream ss;\nss << std::setw(10) << std::setfill('0') << i;\nstd::string s = ss.str();\n</code></pre>\n\n<p>I compiled the information I found on <a href=\"http://www.arachnoid.com/cpptutor/student3.html\" rel=\"noreferrer\">arachnoid.com</a> because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.</p>\n"
},
{
"answer_id": 225451,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 2,
"selected": false,
"text": "<p>stringstream will do (<a href=\"https://stackoverflow.com/questions/225362/convert-a-number-to-a-string-with-specified-length-in-c#225435\">as xtofl pointed out</a>). <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html#printf_directives\" rel=\"nofollow noreferrer\">Boost format</a> is a more convenient replacement for snprintf.</p>\n"
},
{
"answer_id": 225536,
"author": "sep",
"author_id": 30333,
"author_profile": "https://Stackoverflow.com/users/30333",
"pm_score": 2,
"selected": false,
"text": "<p>This method doesn't use streams nor sprintf. Other than having locking problems, streams incur a performance overhead and is really an overkill. For streams the overhead comes from the need to construct the steam and stream buffer. For sprintf, the overhead comes from needing to interpret the format string. This works even when <em>n</em> is negative or when the string representation of <em>n</em> is longer than <em>len</em>. This is the FASTEST solution.</p>\n\n<pre><code>inline string some_function(int n, int len)\n{\n string result(len--, '0');\n for (int val=(n<0)?-n:n; len>=0&&val!=0; --len,val/=10)\n result[len]='0'+val%10;\n if (len>=0&&n<0) result[0]='-';\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 226719,
"author": "Len Holgate",
"author_id": 7925,
"author_profile": "https://Stackoverflow.com/users/7925",
"pm_score": 4,
"selected": false,
"text": "<p>One thing that you <strong>may</strong> want to be aware of is the potential locking that may go on when you use the <code>stringstream</code> approach. In the STL that ships with Visual Studio 2008, at least, there are many locks taken out and released as various locale information is used during formatting. This may, or may not, be an issue for you depending on how many threads you have that might be concurrently converting numbers to strings... </p>\n\n<p>The <code>sprintf</code> version doesn't take any locks (at least according to the lock monitoring tool that I'm developing at the moment...) and so might be 'better' for use in concurrent situations.</p>\n\n<p>I only noticed this because my tool recently spat out the 'locale' locks as being amongst the most contended for locks in my server system; it came as a bit of a surprise and may cause me to revise the approach that I've been taking (i.e. move back towards <code>sprintf</code> from <code>stringstream</code>)...</p>\n"
},
{
"answer_id": 51307984,
"author": "lubgr",
"author_id": 9593596,
"author_profile": "https://Stackoverflow.com/users/9593596",
"pm_score": 2,
"selected": false,
"text": "<p>This is an old thread, but as <a href=\"http://fmtlib.net/latest/index.html\" rel=\"nofollow noreferrer\">fmt</a> might make it into the standard, here is an additional solution:</p>\n\n<pre><code>#include <fmt/format.h>\n\nint n = 999;\n\nconst auto str = fmt::format(\"{:0>{}}\", n, 6);\n</code></pre>\n\n<p>Note that the <code>fmt::format(\"{:0>6}\", n)</code> works equally well when the desired width is known at compile time. Another option is <a href=\"https://abseil.io\" rel=\"nofollow noreferrer\">abseil</a>:</p>\n\n<pre><code>#include <absl/strings/str_format.h>\n\nint n = 999;\n\nconst auto str = absl::StrFormat(\"%0*d\", 6, n);\n</code></pre>\n\n<p>Again, <code>abs::StrFormat(\"%06d\", n)</code> is possible. <a href=\"https://www.boost.org/doc/libs/1_67_0/libs/format/\" rel=\"nofollow noreferrer\">boost format</a> is another tool for this problem:</p>\n\n<pre><code>#include <boost/format.hpp>\n\nint n = 999;\n\nconst auto str = boost::str(boost::format(\"%06d\") % n);\n</code></pre>\n\n<p>Unfortunately, variable width specifier as arguments chained with the <code>%</code> operator are unsupported, this requires a format string setup (e.g. <code>const std::string fmt = \"%0\" + std::to_string(6) + \"d\";</code>).</p>\n\n<p>In terms of performance, abseil and fmt claim to be very attractive and faster than boost. In any case, all three solutions should be more efficient than <code>std::stringstream</code> approaches, and other than the <code>std::*printf</code> family, they do not sacrifice type safety.</p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26276/"
] |
I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492').
In other words, I need to add correct amount of leading zeros to the number.
```
int n = 999;
string str = some_function(n,6);
//str = '000999'
```
Is there a function like this in C++?
|
or using the stringstreams:
```
#include <sstream>
#include <iomanip>
std::stringstream ss;
ss << std::setw(10) << std::setfill('0') << i;
std::string s = ss.str();
```
I compiled the information I found on [arachnoid.com](http://www.arachnoid.com/cpptutor/student3.html) because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.
|
225,367 |
<p>Yes, I know you could use regular objects as associative arrays in JavaScript, but I'd like to use something closer to java's Map's implementation (HashMap, LinkedHashMap etc). Something that could have any kind of data used as key. Are there any good hash(code/table) in JavaScript implementation out there?</p>
|
[
{
"answer_id": 225403,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 6,
"selected": true,
"text": "<p>In javascript, <strong>objects are literally a hash implementation</strong>. A Java HashMap will be a little bit of a fake-out, so I'd <strong>challenge you</strong> to re-think your needs.</p>\n\n<p>The <strong>straight answer is no</strong>, I don't believe that there is a great implementation of Java's HashMap in javascript. If there is, it's bound to be part of a library that you may or may not want to use, and you certainly <strong>don't need to include a library</strong> just to have a little hash table.</p>\n\n<p>So let's go ahead and write one, just to <strong>examine the problem</strong>. You can use it if you like. We'll just start by writing a constructor, and we'll piggyback off of Array, which is Object, but has some useful methods that will keep this example from getting too tedious:</p>\n\n<pre><code>function HashMap () {\n var obj = [];\n return obj;\n}\n\nvar myHashMap = HashMap();\n</code></pre>\n\n<p>We'll add some methods straight from the world of Java, but translate into javascript as we go...</p>\n\n<pre><code>function HashMap() {\n var obj = [];\n obj.size = function () {\n return this.length;\n };\n obj.isEmpty = function () {\n return this.length === 0;\n };\n obj.containsKey = function (key) {\n for (var i = 0; i < this.length; i++) {\n if (this[i].key === key) {\n return i;\n }\n }\n return -1;\n };\n obj.get = function (key) {\n var index = this.containsKey(key);\n if (index > -1) {\n return this[index].value;\n }\n };\n obj.put = function (key, value) {\n if (this.containsKey(key) !== -1) {\n return this.get(key);\n }\n this.push({'key': key, 'value': value});\n };\n obj.clear = function () {\n this = null; // Just kidding...\n };\n return obj;\n}\n</code></pre>\n\n<p>We could continue to build it out, but I think it's the wrong approach. At the end of the day, we end up using what javascript provides behind the scenes, because we just simply don't have the HashMap type. In the process of <strong>pretending</strong>, it lends itself to all kinds of <strong>extra work</strong>. </p>\n\n<p>It's a bit ironic that one of the things that makes javascript such an interesting and diverse language is the ease with which it handles this kind of <strong>wrestling</strong>. We can literally do anything we'd like, and the quick example here does nothing if it doesn't illustrate the deceptive power of the language. Yet given that power, it seems <strong>best not to use it</strong>.</p>\n\n<p>I just think javascript wants to be lighter. My personal recommendation is that you re-examine the problem before you try implement a proper Java HashMap. <strong>Javascript neither wants nor affords for one</strong>.</p>\n\n<p><strong>Remember the native alternative</strong>:</p>\n\n<pre><code>var map = [{}, 'string', 4, {}];\n</code></pre>\n\n<p>..so fast and easy by comparison.</p>\n\n<p>On the other hand, I don't believe that there are any hard-and-fast answers here. This implementation really <strong>may be a perfectly acceptable solution</strong>. If you feel you can use it, I'd say <strong>give it a whirl</strong>. But I'd never use it if I felt that we have <strong>reasonably simpler and more natural means</strong> at our disposal.. which I'm almost certain that we do.</p>\n\n<p><strong>Sidenote:</strong>\nIs efficiency related to style? Notice the <strong>performance hit</strong>.. there's a big O staring us in the face at HashMap.put()... The less-than-optimal performance probably isn't a show-stopper here, and you'd probably need to be doing something very ambitious or have a large set of data before you'd even notice a performance hickup a modern browser. It's just interesting to note that operations tend to become less efficient when you're working against the grain, almost as if there is a natural entropy at work. Javascript is a high level language, and should offer efficient solutions when we keep in line with its conventions, just as a HashMap in Java will be a much more natural and high performing choice.</p>\n"
},
{
"answer_id": 225589,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a naive implementation I just put together - as keparo mentioned in a comment, one of the big issues is equality checking:</p>\n\n<pre><code>var ObjectMap = function()\n{\n this._keys = [];\n this._values = [];\n};\n\nObjectMap.prototype.clear = function()\n{\n this._keys = [];\n this._values = [];\n};\n\nObjectMap.prototype.get = function(key)\n{\n var index = this._indexOf(key, this._keys);\n if (index != -1)\n {\n return this._values[index];\n }\n return undefined;\n};\n\nObjectMap.prototype.hasKey = function(key)\n{\n return (this._indexOf(key, this._keys) != -1);\n};\n\nObjectMap.prototype.hasValue = function(value)\n{\n return (this._indexOf(value, this._values) != -1);\n};\n\nObjectMap.prototype.put = function(key, value)\n{\n var index = this._indexOf(key, this._keys);\n if (index == -1)\n {\n index = this._keys.length;\n }\n\n this._keys[index] = key;\n this._values[index] = value;\n};\n\nObjectMap.prototype.remove = function(key)\n{\n var index = this._indexOf(key, this._keys);\n if (index != -1)\n {\n this._keys.splice(index, 1);\n this._values.splice(index, 1);\n }\n};\n\nObjectMap.prototype.size = function()\n{\n return this._keys.length;\n};\n\nObjectMap.prototype._indexOf = function(item, list)\n{\n for (var i = 0, l = list.length; i < l; i++)\n {\n if (this._equals(list[i], item))\n {\n return i;\n }\n }\n return -1;\n};\n\nObjectMap.prototype._equals = function(a, b)\n{\n if (a === b)\n {\n return true;\n }\n\n // Custom objects can implement an equals method\n if (typeof a.equals == \"function\" &&\n typeof b.equals == \"function\")\n {\n return a.equals(b);\n }\n\n // Arrays are equal if they're the same length and their contents are equal\n if (a instanceof Array && b instanceof Array)\n {\n if (a.length != b.length)\n {\n return false;\n }\n\n for (var i = 0, l = a.length; i < l; i++)\n {\n if (!this._equals(a[i], b[i]))\n {\n return false;\n }\n }\n\n return true;\n }\n\n // Checking object properties - objects are equal if they have all the same\n // properties and they're all equal.\n var seenProperties = {};\n for (var prop in a)\n {\n if (a.hasOwnProperty(prop))\n {\n if (!b.hasOwnProperty(prop))\n {\n return false;\n }\n\n if (!this._equals(a[prop], b[prop]))\n {\n return false;\n }\n\n seenProperties[prop] = true;\n }\n }\n\n for (var prop in b)\n {\n if (!(prop in seenProperties) && b.hasOwnProperty(prop))\n {\n if (!a.hasOwnProperty(prop))\n {\n return false;\n }\n\n if (!this._equals(b[prop], a[prop]))\n {\n return false;\n }\n }\n }\n\n return true;\n};\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>>>> var map = new ObjectMap();\n>>> var o = {a: 1, b: [1,2], c: true};\n>>> map.put(o, \"buns\");\n>>> map.get(o)\n\"buns\"\n>>> map.get({a: 1, b: [1,2], c: true});\n\"buns\"\n>>> map.get({a: 1, b: [1,2], c: true, d:\"hi\"});\n>>> var a = [1,2,3];\n>>> map.put(a, \"cheese\");\n>>> map.get(a);\n\"cheese\"\n>>> map.get([1,2,3]);\n\"cheese\"\n>>> map.get([1,2,3,4]);\n>>> var d = new Date();\n>>> map.put(d, \"toast\");\n>>> map.get(d);\n\"toast\"\n>>> map.get(new Date(d.valueOf()));\n\"toast\"\n</code></pre>\n\n<p>This is in no way a complete implementation, just a pointer for a way to implement such an object. For example, looking at what I've given, you would also need to add constructor property checks before the object property check, as this currently works:</p>\n\n<pre><code>>>> function TestObject(a) { this.a = a; };\n>>> var t = new TestObject(\"sandwich\");\n>>> map.put(t, \"butter\");\n>>> map.get({a: \"sandwich\"})\n\"butter\"\n</code></pre>\n"
},
{
"answer_id": 225923,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 1,
"selected": false,
"text": "<p>Note that java collections using \"any kind of object\" as a key isn't quite right. Yes, you can use any object, but unless that object has good hashcode() and equals() implementations then it won't work well. The base Object class has a default implementation for these, but for custom classes to work (effectively) as hashtable keys you need to override them. Javascript has no equivalent (that I know of).</p>\n\n<p>To create a hashtable in javascript that can (effectively) use arbitrary objects as the key you'd need to enforce something similar on the objects you use, at least if you want to keep the performance gains of a hashtable. If you can enforce a 'hashcode()' method that returns a String, then you can just use an Object under the hood as the actual hashtable.</p>\n\n<p>Otherwise, you'd need to so something like the other solutions posted, which as of right now do not perform like hashtables. They both do O(n) searches over the list to try and find the key, which pretty much defeats the purpose of a hashtable (hashtables are generally constant time for get/put).</p>\n"
},
{
"answer_id": 868728,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 3,
"selected": false,
"text": "<p>I have released a standalone JavaScript hash table implementation that goes further than those listed here.</p>\n\n<p><a href=\"http://www.timdown.co.uk/jshashtable/\" rel=\"noreferrer\">http://www.timdown.co.uk/jshashtable/</a></p>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540/"
] |
Yes, I know you could use regular objects as associative arrays in JavaScript, but I'd like to use something closer to java's Map's implementation (HashMap, LinkedHashMap etc). Something that could have any kind of data used as key. Are there any good hash(code/table) in JavaScript implementation out there?
|
In javascript, **objects are literally a hash implementation**. A Java HashMap will be a little bit of a fake-out, so I'd **challenge you** to re-think your needs.
The **straight answer is no**, I don't believe that there is a great implementation of Java's HashMap in javascript. If there is, it's bound to be part of a library that you may or may not want to use, and you certainly **don't need to include a library** just to have a little hash table.
So let's go ahead and write one, just to **examine the problem**. You can use it if you like. We'll just start by writing a constructor, and we'll piggyback off of Array, which is Object, but has some useful methods that will keep this example from getting too tedious:
```
function HashMap () {
var obj = [];
return obj;
}
var myHashMap = HashMap();
```
We'll add some methods straight from the world of Java, but translate into javascript as we go...
```
function HashMap() {
var obj = [];
obj.size = function () {
return this.length;
};
obj.isEmpty = function () {
return this.length === 0;
};
obj.containsKey = function (key) {
for (var i = 0; i < this.length; i++) {
if (this[i].key === key) {
return i;
}
}
return -1;
};
obj.get = function (key) {
var index = this.containsKey(key);
if (index > -1) {
return this[index].value;
}
};
obj.put = function (key, value) {
if (this.containsKey(key) !== -1) {
return this.get(key);
}
this.push({'key': key, 'value': value});
};
obj.clear = function () {
this = null; // Just kidding...
};
return obj;
}
```
We could continue to build it out, but I think it's the wrong approach. At the end of the day, we end up using what javascript provides behind the scenes, because we just simply don't have the HashMap type. In the process of **pretending**, it lends itself to all kinds of **extra work**.
It's a bit ironic that one of the things that makes javascript such an interesting and diverse language is the ease with which it handles this kind of **wrestling**. We can literally do anything we'd like, and the quick example here does nothing if it doesn't illustrate the deceptive power of the language. Yet given that power, it seems **best not to use it**.
I just think javascript wants to be lighter. My personal recommendation is that you re-examine the problem before you try implement a proper Java HashMap. **Javascript neither wants nor affords for one**.
**Remember the native alternative**:
```
var map = [{}, 'string', 4, {}];
```
..so fast and easy by comparison.
On the other hand, I don't believe that there are any hard-and-fast answers here. This implementation really **may be a perfectly acceptable solution**. If you feel you can use it, I'd say **give it a whirl**. But I'd never use it if I felt that we have **reasonably simpler and more natural means** at our disposal.. which I'm almost certain that we do.
**Sidenote:**
Is efficiency related to style? Notice the **performance hit**.. there's a big O staring us in the face at HashMap.put()... The less-than-optimal performance probably isn't a show-stopper here, and you'd probably need to be doing something very ambitious or have a large set of data before you'd even notice a performance hickup a modern browser. It's just interesting to note that operations tend to become less efficient when you're working against the grain, almost as if there is a natural entropy at work. Javascript is a high level language, and should offer efficient solutions when we keep in line with its conventions, just as a HashMap in Java will be a much more natural and high performing choice.
|
225,371 |
<p>How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?</p>
<pre><code>$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);
$C = array_intersect($A,$B); //equals (1,2,3,4)
$A = array_diff($A,$B); //equals (5,6,7,8)
</code></pre>
<p>Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.</p>
|
[
{
"answer_id": 225678,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 6,
"selected": true,
"text": "<p>You've got it. Just use <code>array_diff</code> or <code>array_intersect</code>. Doesn't get much easier than that.</p>\n\n<p><strong>Edit:</strong>\nFor example:</p>\n\n<pre><code>$arr_1 = array_diff($arr_1, $arr_2);\n$arr_2 = array_diff($arr_2, $arr_1);\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/8691348/2210140\">Source</a></p>\n"
},
{
"answer_id": 226112,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 2,
"selected": false,
"text": "<p>See also <a href=\"http://us.php.net/array_unique\" rel=\"nofollow noreferrer\">array_unique</a>. If you concatenate the two arrays, it will then yank all duplicates.</p>\n"
},
{
"answer_id": 231676,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "<p>Hey, even better solution: <a href=\"http://us.php.net/manual/en/function.array-uintersect.php\" rel=\"nofollow noreferrer\">array _ uintersect.</a>\nThis let's you compare the arrays as per array_intersect but then it lets you compare the data with a callback function.</p>\n"
},
{
"answer_id": 31980965,
"author": "Ashfaq Hussain",
"author_id": 5030989,
"author_profile": "https://Stackoverflow.com/users/5030989",
"pm_score": -1,
"selected": false,
"text": "<p>Try to this</p>\n\n<pre><code>$a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');\n$b = array(1=>'a',6=>'b',2=>'y',3=>'z');\n$c = array_intersect($a, $b);\n\n$result = array_diff($a, $c);\nprint_r($result);\n</code></pre>\n"
},
{
"answer_id": 39369882,
"author": "Kalpesh Bhaliya",
"author_id": 6804657,
"author_profile": "https://Stackoverflow.com/users/6804657",
"pm_score": 3,
"selected": false,
"text": "<p>Dear easy and clean way</p>\n\n<pre><code>$clean1 = array_diff($array1, $array2); \n$clean2 = array_diff($array2, $array1); \n$final_output = array_merge($clean1, $clean2);\n</code></pre>\n"
}
] |
2008/10/22
|
[
"https://Stackoverflow.com/questions/225371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] |
How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?
```
$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);
$C = array_intersect($A,$B); //equals (1,2,3,4)
$A = array_diff($A,$B); //equals (5,6,7,8)
```
Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.
|
You've got it. Just use `array_diff` or `array_intersect`. Doesn't get much easier than that.
**Edit:**
For example:
```
$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);
```
[Source](https://stackoverflow.com/a/8691348/2210140)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.