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
|
---|---|---|---|---|---|---|
173,366 |
<p>V8's documentation explains <a href="http://code.google.com/apis/v8/embed.html#dynamic" rel="noreferrer">how to create a Javascript object that wraps a C++ object</a>. The Javascript object holds on to a pointer to a C++ object instance. My question is, let's say you create the C++ object on the heap, how can you get a notification when the Javascript object is collected by the gc, so you can free the heap allocated C++ object?</p>
|
[
{
"answer_id": 175500,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>In general, if a garbage-collected language can hold references to resources outside of the language engine (files, sockets, or in your case C++ objects), you should provide a 'close' method to release that resource ASAP, no point waiting until the GC thinks it's worthwhile to destroy your object.</p>\n\n<p>it gets worse if your C++ object is memory-hungry and the garbage-collected object is just a reference: you might allocate thousands of objects, and the GC only sees a few KB's of tiny objects, not enough to trigger collection; while the C++ side is struggling with tens of megabytes of stale objects.</p>\n"
},
{
"answer_id": 176095,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 0,
"selected": false,
"text": "<p>Do all your work in some closed scope (of object or function).\nThen you can safely remove the C++ object when you went out of scope. GC doesn't check pointers for existence of pointed objects. </p>\n"
},
{
"answer_id": 176380,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 6,
"selected": true,
"text": "<p>The trick is to create a <code>Persistent</code> handle (second bullet point from the linked-to API reference: \"<code>Persistent</code> handles are not held on a stack and are deleted only when you specifically remove them. ... Use a persistent handle when you need to keep a reference to an object for more than one function call, or when handle lifetimes do not correspond to C++ scopes.\"), and call <code>MakeWeak()</code> on it, passing a callback function that will do the necessary cleanup (\"A persistent handle can be made weak, using <code>Persistent::MakeWeak</code>, to trigger a callback from the garbage collector when the only references to an object are from weak persistent handles.\" -- that is, when all \"regular\" handles have gone out of scope and when the garbage collector is about to delete the object).</p>\n\n<p>The <code>Persistent::MakeWeak</code> method signature is:</p>\n\n<pre><code>void MakeWeak(void* parameters, WeakReferenceCallback callback);\n</code></pre>\n\n<p>Where <code>WeakReferenceCallback</code> is defined as a pointer-to-function taking two parameters:</p>\n\n<pre><code>typedef void (*WeakReferenceCallback)(Persistent<Object> object,\n void* parameter);\n</code></pre>\n\n<p>These are found in the v8.h header file distributed with V8 as the public API.</p>\n\n<p>You would want the function you pass to <code>MakeWeak</code> to clean up the <code>Persistent<Object></code> object parameter that will get passed to it when it's called as a callback. The <code>void* parameter</code> parameter can be ignored (or the <code>void* parameter</code> can point to a C++ structure that holds the objects that need cleaning up):</p>\n\n<pre><code>void CleanupV8Point(Persistent<Object> object, void*)\n{\n // do whatever cleanup on object that you're looking for\n object.destroyCppObjects();\n}\n\nParameter<ObjectTemplate> my_obj(ObjectTemplate::New());\n\n// when the Javascript part of my_obj is about to be collected\n// we'll have V8 call CleanupV8Point(my_obj)\nmy_obj.MakeWeak(NULL, &CleanupV8Point);\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1892/"
] |
V8's documentation explains [how to create a Javascript object that wraps a C++ object](http://code.google.com/apis/v8/embed.html#dynamic). The Javascript object holds on to a pointer to a C++ object instance. My question is, let's say you create the C++ object on the heap, how can you get a notification when the Javascript object is collected by the gc, so you can free the heap allocated C++ object?
|
The trick is to create a `Persistent` handle (second bullet point from the linked-to API reference: "`Persistent` handles are not held on a stack and are deleted only when you specifically remove them. ... Use a persistent handle when you need to keep a reference to an object for more than one function call, or when handle lifetimes do not correspond to C++ scopes."), and call `MakeWeak()` on it, passing a callback function that will do the necessary cleanup ("A persistent handle can be made weak, using `Persistent::MakeWeak`, to trigger a callback from the garbage collector when the only references to an object are from weak persistent handles." -- that is, when all "regular" handles have gone out of scope and when the garbage collector is about to delete the object).
The `Persistent::MakeWeak` method signature is:
```
void MakeWeak(void* parameters, WeakReferenceCallback callback);
```
Where `WeakReferenceCallback` is defined as a pointer-to-function taking two parameters:
```
typedef void (*WeakReferenceCallback)(Persistent<Object> object,
void* parameter);
```
These are found in the v8.h header file distributed with V8 as the public API.
You would want the function you pass to `MakeWeak` to clean up the `Persistent<Object>` object parameter that will get passed to it when it's called as a callback. The `void* parameter` parameter can be ignored (or the `void* parameter` can point to a C++ structure that holds the objects that need cleaning up):
```
void CleanupV8Point(Persistent<Object> object, void*)
{
// do whatever cleanup on object that you're looking for
object.destroyCppObjects();
}
Parameter<ObjectTemplate> my_obj(ObjectTemplate::New());
// when the Javascript part of my_obj is about to be collected
// we'll have V8 call CleanupV8Point(my_obj)
my_obj.MakeWeak(NULL, &CleanupV8Point);
```
|
173,389 |
<p>I've build my WinForm app on windows machine and the app is working
ok. When I user nhibernate 1.2.1 the app also worked on linux machine
using mono, but now when i upgraded app to nhibernate 2.0.1 it works
only in windows.
I've get error:
NHibernate.InvalidProxyTypeException: The following types may not be
used as proxies:
xxxx.Data.Dao.Credit : method obj_address should be virtual
......
Can anyone help me with this problem? </p>
|
[
{
"answer_id": 173528,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>This might be of interest:</p>\n\n<p><a href=\"http://softwaredevscott.spaces.live.com/blog/cns!1A9E939F7373F3B7!251.entry\" rel=\"nofollow noreferrer\">http://softwaredevscott.spaces.live.com/blog/cns!1A9E939F7373F3B7!251.entry</a></p>\n"
},
{
"answer_id": 402192,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm also on mono trying to use NHibernate. Most forums seem to say setting the string to virtual will fix the problem, but this hasn't worked for me. What is curious is that my error is almost identical - </p>\n\n<p>\"\" method obj_address should be virtual</p>\n\n<p>This makes me think the proxy \"address\" is reserved for something else. Try changing the name of this column?</p>\n"
},
{
"answer_id": 531023,
"author": "jrwren",
"author_id": 16998,
"author_profile": "https://Stackoverflow.com/users/16998",
"pm_score": 1,
"selected": false,
"text": "<p>You can try and disable the NHibernate Config proxy validator. it seems to not work with mono.</p>\n\n<p>You can do this by adding:\n<code><property name=\"use_proxy_validator\">false</property></code> in your app/web.config nhibernate section.</p>\n\n<p>For an example config with this property set, see here:\n<a href=\"http://www.mail-archive.com/[email protected]/msg02109.html\" rel=\"nofollow noreferrer\">http://www.mail-archive.com/[email protected]/msg02109.html</a></p>\n\n<p>or modify this:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<configuration>\n <configSections>\n <section name=\"hibernate-configuration\"\n type=\"NHibernate.Cfg.ConfigurationSectionHandler, NHibernate\" />\n </configSections>\n\n <hibernate-configuration xmlns=\"urn:nhibernate-configuration-2.2\">\n <session-factory>\n <!--\n <property name=\"dialect\">NHibernate.Dialect.MsSql2005Dialect</property>\n <property name=\"connection.provider\">NHibernate.Connection.DriverConnectionProvider</property>\n <property name=\"connection.driver_class\">NHibernate.Driver.SqlClientDriver</property>\n <property name=\"connection.connection_string\">Data Source=YOUR_DB_SERVER;Database=Northwind;User ID=YOUR_USERNAME;Password=YOUR_PASSWORD;</property>\n <property name=\"connection.isolation\">ReadCommitted</property>\n <property name=\"default_schema\">Northwind.dbo</property>\n -->\n <!--\n <property name=\"dialect\">NHibernate.Dialect.SQLiteDialect</property>\n <property name=\"connection.provider\">NHibernate.Connection.DriverConnectionProvider</property>\n <property name=\"connection.driver_class\">NHibernate.Driver.SQLiteDriver</property>\n <property name=\"connection.connection_string\">Data Source=nhibernate.db;Version=3</property>\n <property name=\"query.substitutions\">true=1;false=0</property>\n -->\n <!-- mysql\n <property name=\"dialect\">NHibernate.Dialect.MySQLDialect</property>\n <property name=\"connection.provider\">NHibernate.Connection.DriverConnectionProvider</property>\n <property name=\"connection.driver_class\">NHibernate.Driver.MySqlDataDriver</property>\n <property name=\"connection.connection_string\">Database=test</property>\n -->\n <property name=\"connection.provider\">NHibernate.Connection.DriverConnectionProvider</property>\n <property name=\"connection.driver_class\">NHibernate.Driver.NpgsqlDriver</property>\n <property name=\"connection.connection_string\">Server=localhost;database=test;User id=jrwren;password=yourpasswordhere.</property>\n <property name=\"dialect\">NHibernate.Dialect.PostgreSQLDialect</property>\n <property name=\"use_proxy_validator\">false</property>\n <!-- HBM Mapping Files -->\n <mapping assembly=\"Test.exe\" />\n </session-factory>\n </hibernate-configuration>\n\n</configuration>\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've build my WinForm app on windows machine and the app is working
ok. When I user nhibernate 1.2.1 the app also worked on linux machine
using mono, but now when i upgraded app to nhibernate 2.0.1 it works
only in windows.
I've get error:
NHibernate.InvalidProxyTypeException: The following types may not be
used as proxies:
xxxx.Data.Dao.Credit : method obj\_address should be virtual
......
Can anyone help me with this problem?
|
You can try and disable the NHibernate Config proxy validator. it seems to not work with mono.
You can do this by adding:
`<property name="use_proxy_validator">false</property>` in your app/web.config nhibernate section.
For an example config with this property set, see here:
<http://www.mail-archive.com/[email protected]/msg02109.html>
or modify this:
```
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<!--
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=YOUR_DB_SERVER;Database=Northwind;User ID=YOUR_USERNAME;Password=YOUR_PASSWORD;</property>
<property name="connection.isolation">ReadCommitted</property>
<property name="default_schema">Northwind.dbo</property>
-->
<!--
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
<property name="connection.connection_string">Data Source=nhibernate.db;Version=3</property>
<property name="query.substitutions">true=1;false=0</property>
-->
<!-- mysql
<property name="dialect">NHibernate.Dialect.MySQLDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
<property name="connection.connection_string">Database=test</property>
-->
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
<property name="connection.connection_string">Server=localhost;database=test;User id=jrwren;password=yourpasswordhere.</property>
<property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
<property name="use_proxy_validator">false</property>
<!-- HBM Mapping Files -->
<mapping assembly="Test.exe" />
</session-factory>
</hibernate-configuration>
</configuration>
```
|
173,400 |
<p>PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array <em>"is a list"</em> (contains only numeric keys starting from 0)?</p>
<p>Basically, I want to be able to differentiate between this:</p>
<pre><code>$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
</code></pre>
<p>and this:</p>
<pre><code>$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
</code></pre>
|
[
{
"answer_id": 173412,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>Unless PHP has a builtin for that, you won't be able to do it in less than O(n) - enumerating over all the keys and checking for integer type. In fact, you also want to make sure there are no holes, so your algorithm might look like:</p>\n\n<pre><code>for i in 0 to len(your_array):\n if not defined(your-array[i]):\n # this is not an array array, it's an associative array :)\n</code></pre>\n\n<p>But why bother? Just assume the array is of the type you expect. If it isn't, it will just blow up in your face - that's dynamic programming for you! Test your code and all will be well...</p>\n"
},
{
"answer_id": 173435,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": -1,
"selected": false,
"text": "<p>One cheap and dirty way would be to check like this:</p>\n\n<pre><code>isset($myArray[count($myArray) - 1])\n</code></pre>\n\n<p>...you might get a false positive if your array is like this:</p>\n\n<pre><code>$myArray = array(\"1\" => \"apple\", \"b\" => \"banana\");\n</code></pre>\n\n<p>A more thorough way might be to check the keys:</p>\n\n<pre><code>function arrayIsAssociative($myArray) {\n foreach (array_keys($myArray) as $ind => $key) {\n if (!is_numeric($key) || (isset($myArray[$ind + 1]) && $myArray[$ind + 1] != $key + 1)) {\n return true;\n }\n }\n return false;\n}\n// this will only return true if all the keys are numeric AND sequential, which\n// is what you get when you define an array like this:\n// array(\"a\", \"b\", \"c\", \"d\", \"e\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function arrayIsAssociative($myArray) {\n $l = count($myArray);\n for ($i = 0; $i < $l, ++$i) {\n if (!isset($myArray[$i])) return true;\n }\n return false;\n}\n// this will return a false positive on an array like this:\n$x = array(1 => \"b\", 0 => \"a\", 2 => \"c\", 4 => \"e\", 3 => \"d\");\n</code></pre>\n"
},
{
"answer_id": 173443,
"author": "scronide",
"author_id": 22844,
"author_profile": "https://Stackoverflow.com/users/22844",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function is_associative($arr) {\n return (array_merge($arr) !== $arr || count(array_filter($arr, 'is_string', ARRAY_FILTER_USE_KEY)) > 0);\n}\n</code></pre>\n"
},
{
"answer_id": 173479,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 11,
"selected": true,
"text": "<p>You have asked two questions that are not quite equivalent:</p>\n\n<ul>\n<li>Firstly, how to determine whether an array has only numeric keys</li>\n<li>Secondly, how to determine whether an array has <em>sequential</em> numeric keys, starting from 0</li>\n</ul>\n\n<p>Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)</p>\n\n<p>The first question (simply checking that all keys are numeric) is <a href=\"https://stackoverflow.com/a/4254008/1709587\">answered well by Captain kurO</a>.</p>\n\n<p>For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function isAssoc(array $arr)\n{\n if (array() === $arr) return false;\n return array_keys($arr) !== range(0, count($arr) - 1);\n}\n\nvar_dump(isAssoc(['a', 'b', 'c'])); // false\nvar_dump(isAssoc([\"0\" => 'a', \"1\" => 'b', \"2\" => 'c'])); // false\nvar_dump(isAssoc([\"1\" => 'a', \"0\" => 'b', \"2\" => 'c'])); // true\nvar_dump(isAssoc([\"a\" => 'a', \"b\" => 'b', \"c\" => 'c'])); // true\n</code></pre>\n"
},
{
"answer_id": 173589,
"author": "null",
"author_id": 25411,
"author_profile": "https://Stackoverflow.com/users/25411",
"pm_score": -1,
"selected": false,
"text": "<p>If your looking for just non-numeric keys (no matter the order) then you may want to try</p>\n\n<pre><code>function IsAssociative($array)\n{\n return preg_match('/[a-z]/i', implode(array_keys($array)));\n}\n</code></pre>\n"
},
{
"answer_id": 173735,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another way to do this.</p>\n\n<pre><code>function array_isassociative($array)\n{\n // Create new Array, Make it the same size as the input array\n $compareArray = array_pad(array(), count($array), 0);\n\n // Compare the two array_keys\n return (count(array_diff_key($array, $compareArray))) ? true : false;\n\n}\n</code></pre>\n"
},
{
"answer_id": 265144,
"author": "Dave Marshall",
"author_id": 1248,
"author_profile": "https://Stackoverflow.com/users/1248",
"pm_score": 7,
"selected": false,
"text": "<p>Surely this is a better alternative.</p>\n\n<pre><code><?php\n$arr = array(1,2,3,4);\n$isIndexed = array_values($arr) === $arr;\n</code></pre>\n"
},
{
"answer_id": 265173,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function isAssoc($arr)\n{\n $a = array_keys($arr);\n for($i = 0, $t = count($a); $i < $t; $i++)\n {\n if($a[$i] != $i)\n {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 524978,
"author": "Bretticus",
"author_id": 411075,
"author_profile": "https://Stackoverflow.com/users/411075",
"pm_score": -1,
"selected": false,
"text": "<p>I just use the key() function. Observe:</p>\n\n<pre><code><?php\nvar_dump(key(array('hello'=>'world', 'hello'=>'world'))); //string(5) \"hello\"\nvar_dump(key(array('world', 'world'))); //int(0)\nvar_dump(key(array(\"0\" => 'a', \"1\" => 'b', \"2\" => 'c'))); //int(0) who makes string sequetial keys anyway????\n?>\n</code></pre>\n\n<p>Thus, just by checking for false, you can determine whether an array is associative or not.</p>\n"
},
{
"answer_id": 652760,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Actually the most efficient way is thus:</p>\n<pre><code>function is_assoc($array){\n $keys = array_keys($array);\n return $keys !== array_keys($keys);\n}\n</code></pre>\n<p>This works because it compares the keys (which for a sequential array are always 0,1,2 etc) to the keys of the keys (which will <em>always</em> be 0,1,2 etc).</p>\n<p>Laravel use <a href=\"https://github.com/laravel/framework/blob/8.x/src/Illuminate/Collections/Arr.php#L389\" rel=\"noreferrer\">this approach</a>.</p>\n"
},
{
"answer_id": 869220,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I compare the difference between the keys of the array and the keys of the result of array_values() of the array, which will always be an array with integer indices. If the keys are the same, it's not an associative array.<br></p>\n\n<pre><code>function isHash($array) {\n if (!is_array($array)) return false;\n $diff = array_diff_assoc($array, array_values($array));\n return (empty($diff)) ? false : true;\n}\n</code></pre>\n"
},
{
"answer_id": 2444661,
"author": "dsims",
"author_id": 293640,
"author_profile": "https://Stackoverflow.com/users/293640",
"pm_score": 5,
"selected": false,
"text": "<pre><code>function checkAssoc($array){\n return ctype_digit( implode('', array_keys($array) ) );\n}\n</code></pre>\n"
},
{
"answer_id": 3883417,
"author": "podperson",
"author_id": 438186,
"author_profile": "https://Stackoverflow.com/users/438186",
"pm_score": 4,
"selected": false,
"text": "<p>I've used both <code>array_keys($obj) !== range(0, count($obj) - 1)</code> and <code>array_values($arr) !== $arr</code> (which are duals of each other, although the second is cheaper than the first) but both fail for very large arrays.</p>\n\n<p>This is because <code>array_keys</code> and <code>array_values</code> are both very costly operations (since they build a whole new array of size roughly that of the original).</p>\n\n<p>The following function is more robust than the methods provided above:</p>\n\n<pre><code>function array_type( $obj ){\n $last_key = -1;\n $type = 'index';\n foreach( $obj as $key => $val ){\n if( !is_int( $key ) || $key < 0 ){\n return 'assoc';\n }\n if( $key !== $last_key + 1 ){\n $type = 'sparse';\n }\n $last_key = $key;\n }\n return $type;\n}\n</code></pre>\n\n<p>Also note that if you don't care to differentiate sparse arrays from associative arrays you can simply return <code>'assoc'</code> from both <code>if</code> blocks.</p>\n\n<p>Finally, while this might seem much less \"elegant\" than a lot of \"solutions\" on this page, in practice it is vastly more efficient. Almost any associative array will be detected instantly. Only indexed arrays will get checked exhaustively, and the methods outlined above not only check indexed arrays exhaustively, they duplicate them.</p>\n"
},
{
"answer_id": 3886942,
"author": "LazNiko",
"author_id": 412686,
"author_profile": "https://Stackoverflow.com/users/412686",
"pm_score": 3,
"selected": false,
"text": "<p>This function can handle:</p>\n\n<ul>\n<li>array with holes in index (e.g. 1,2,4,5,8,10) </li>\n<li>array with \"0x\" keys: e.g. key '08' is associative while key '8' is sequential.</li>\n</ul>\n\n<p>the idea is simple: if one of the keys is NOT an integer, it is associative array, otherwise it's sequential.</p>\n\n<pre><code>function is_asso($a){\n foreach(array_keys($a) as $key) {if (!is_int($key)) return TRUE;}\n return FALSE;\n}\n</code></pre>\n"
},
{
"answer_id": 4254008,
"author": "Captain kurO",
"author_id": 356912,
"author_profile": "https://Stackoverflow.com/users/356912",
"pm_score": 9,
"selected": false,
"text": "<p>To merely check whether the array has non-integer keys (not whether the array is sequentially-indexed or zero-indexed):</p>\n\n<pre><code>function has_string_keys(array $array) {\n return count(array_filter(array_keys($array), 'is_string')) > 0;\n}\n</code></pre>\n\n<p>If there is at least one string key, <code>$array</code> will be regarded as an associative array.</p>\n"
},
{
"answer_id": 4903360,
"author": "Kat Lim Ruiz",
"author_id": 603865,
"author_profile": "https://Stackoverflow.com/users/603865",
"pm_score": 2,
"selected": false,
"text": "<p>Could this be the solution?</p>\n\n<pre><code> public static function isArrayAssociative(array $array) {\n reset($array);\n return !is_int(key($array));\n }\n</code></pre>\n\n<p>The caveat is obviously that the array cursor is reset but I'd say probably the function is used before the array is even traversed or used.</p>\n"
},
{
"answer_id": 5721315,
"author": "Sophie McCarrell",
"author_id": 680761,
"author_profile": "https://Stackoverflow.com/users/680761",
"pm_score": 0,
"selected": false,
"text": "<p>Modification on the most popular answer.<br>\nThis takes a little more processing, but is more accurate. </p>\n\n<pre><code><?php\n//$a is a subset of $b\nfunction isSubset($a, $b)\n{\n foreach($a =>$v)\n if(array_search($v, $b) === false)\n return false;\n\n return true;\n\n //less effecient, clearer implementation. (uses === for comparison)\n //return array_intersect($a, $b) === $a;\n}\n\nfunction isAssoc($arr)\n{\n return !isSubset(array_keys($arr), range(0, count($arr) - 1));\n}\n\nvar_dump(isAssoc(array('a', 'b', 'c'))); // false\nvar_dump(isAssoc(array(1 => 'a', 0 => 'b', 2 => 'c'))); // false\nvar_dump(isAssoc(array(\"0\" => 'a', \"1\" => 'b', \"2\" => 'c'))); // false \n//(use === in isSubset to get 'true' for above statement)\nvar_dump(isAssoc(array(\"a\" => 'a', \"b\" => 'b', \"c\" => 'c'))); // true\n?>\n</code></pre>\n"
},
{
"answer_id": 5969617,
"author": "squirrel",
"author_id": 645436,
"author_profile": "https://Stackoverflow.com/users/645436",
"pm_score": 6,
"selected": false,
"text": "<p>Many commenters in this question don't understand how arrays work in PHP. From the <a href=\"http://www.php.net/manual/en/language.types.array.php\" rel=\"noreferrer\">array documentation</a>:</p>\n\n<blockquote>\n <p>A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. \"8\" will be interpreted as 8, while \"08\" will be interpreted as \"08\"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.</p>\n</blockquote>\n\n<p>In other words, there is no such thing as an array key of \"8\" because it will always be (silently) converted to the integer 8. So trying to differentiate between integers and numeric strings is unnecessary.</p>\n\n<p>If you want the most efficient way to check an array for non-integer keys without making a copy of part of the array (like array_keys() does) or all of it (like foreach does):</p>\n\n<pre><code>function keyedNext( &$arr, &$k){\n $k = key($arr);\n return next($arr);\n}\n\nfor ($k = key(reset($my_array)); is_int($k); keyedNext($my_array,$k))\n $onlyIntKeys = is_null($k);\n</code></pre>\n\n<p>This works because key() returns NULL when the current array position is invalid and NULL can never be a valid key (if you try to use NULL as an array key it gets silently converted to \"\").</p>\n"
},
{
"answer_id": 6462524,
"author": "hornetbzz",
"author_id": 461212,
"author_profile": "https://Stackoverflow.com/users/461212",
"pm_score": -1,
"selected": false,
"text": "<p>Another variant not shown yet, as it's simply not accepting numerical keys, but I like Greg's one very much : </p>\n\n<pre><code> /* Returns true if $var associative array */ \n function is_associative_array( $array ) { \n return is_array($array) && !is_numeric(implode('', array_keys($array))); \n }\n</code></pre>\n"
},
{
"answer_id": 6795076,
"author": "AL the X",
"author_id": 126992,
"author_profile": "https://Stackoverflow.com/users/126992",
"pm_score": 2,
"selected": false,
"text": "<p>Here's the method I use:</p>\n\n<pre><code>function is_associative ( $a )\n{\n return in_array(false, array_map('is_numeric', array_keys($a)));\n}\n\nassert( true === is_associative(array(1, 2, 3, 4)) );\n\nassert( false === is_associative(array('foo' => 'bar', 'bar' => 'baz')) );\n\nassert( false === is_associative(array(1, 2, 3, 'foo' => 'bar')) );\n</code></pre>\n\n<p>Note that this doesn't account for special cases like:</p>\n\n<pre><code>$a = array( 1, 2, 3, 4 );\n\nunset($a[1]);\n\nassert( true === is_associative($a) );\n</code></pre>\n\n<p>Sorry, can't help you with that. It's also somewhat performant for decently sized arrays, as it doesn't make needless copies. It is these little things that makes Python and Ruby so much nicer to write in... :P</p>\n"
},
{
"answer_id": 6894050,
"author": "Sergey Shuchkin",
"author_id": 594867,
"author_profile": "https://Stackoverflow.com/users/594867",
"pm_score": -1,
"selected": false,
"text": "<p>Best function to detect associative array (hash array)</p>\n\n<pre><code><?php\nfunction is_assoc($arr) { return (array_values($arr) !== $arr); }\n?>\n</code></pre>\n"
},
{
"answer_id": 6968499,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Speed-wise:</strong></p>\n\n<pre><code>function isAssoc($array)\n{\n return ($array !== array_values($array));\n}\n</code></pre>\n\n<p><strong>Memory-wise:</strong></p>\n\n<pre><code>function isAssoc($array)\n{\n $array = array_keys($array); return ($array !== array_keys($array));\n}\n</code></pre>\n"
},
{
"answer_id": 7049956,
"author": "sexytrends",
"author_id": 892971,
"author_profile": "https://Stackoverflow.com/users/892971",
"pm_score": -1,
"selected": false,
"text": "<p>Simple and performance friendly solution which only checks the first key.</p>\n\n<pre><code>function isAssoc($arr = NULL)\n{\n if ($arr && is_array($arr))\n {\n foreach ($arr as $key => $val)\n {\n if (is_numeric($key)) { return true; }\n\n break;\n }\n }\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 7293257,
"author": "Galileo_Galilei",
"author_id": 627114,
"author_profile": "https://Stackoverflow.com/users/627114",
"pm_score": -1,
"selected": false,
"text": "<p>I met this problem once again some days ago and i thought to take advantage of the array_merge special property: </p>\n\n<blockquote>\n <p>If the input arrays have the same <strong>string keys</strong>, then the later value for <strong>that key will overwrite the previous one</strong>. If, however, the arrays contain <strong>numeric keys</strong>, the <strong>later value will not overwrite the original value, but will be appended</strong>. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. \n So why not to use: </p>\n</blockquote>\n\n<pre><code>function Is_Indexed_Arr($arr){\n $arr_copy = $arr;\n if((2*count($arr)) == count(array_merge($arr, $arr_copy))){\n return 1;\n }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 8542459,
"author": "GO.exe",
"author_id": 1050728,
"author_profile": "https://Stackoverflow.com/users/1050728",
"pm_score": -1,
"selected": false,
"text": "<p>My solution is to get keys of an array like below and check that if the key is not integer:</p>\n\n<pre><code>private function is_hash($array) {\n foreach($array as $key => $value) {\n return ! is_int($key);\n }\n return false;\n}\n</code></pre>\n\n<p>It is wrong to get array_keys of a hash array like below:</p>\n\n<pre><code>array_keys(array(\n \"abc\" => \"gfb\",\n \"bdc\" => \"dbc\"\n )\n);\n</code></pre>\n\n<p>will output:</p>\n\n<pre><code>array(\n 0 => \"abc\",\n 1 => \"bdc\"\n)\n</code></pre>\n\n<p>So, it is not a good idea to compare it with a range of numbers as mentioned in top rated answer. It will always say that it is a hash array if you try to compare keys with a range.</p>\n"
},
{
"answer_id": 10614509,
"author": "KillEveryBody",
"author_id": 1211413,
"author_profile": "https://Stackoverflow.com/users/1211413",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n\nfunction is_list($array) {\n return array_keys($array) === range(0, count($array) - 1);\n}\n\nfunction is_assoc($array) {\n return count(array_filter(array_keys($array), 'is_string')) == count($array);\n}\n\n?>\n</code></pre>\n\n<p>Both of these examples, which scored the most points do not work correctly with arrays like <code>$array = array('foo' => 'bar', 1)</code></p>\n"
},
{
"answer_id": 11136956,
"author": "Gordon",
"author_id": 208809,
"author_profile": "https://Stackoverflow.com/users/208809",
"pm_score": 2,
"selected": false,
"text": "<p>This would work too (<a href=\"http://codepad.viper-7.com/AFSXXC\" rel=\"nofollow\">demo</a>):</p>\n\n<pre><code>function array_has_numeric_keys_only(array $array)\n{\n try {\n SplFixedArray::fromArray($array, true);\n } catch (InvalidArgumentException $e) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Please note that the main point of this answer is to inform you about the existence of <code>SplFixedArray</code> and not to encourage you to use Exceptions for these kinds of tests.</p>\n"
},
{
"answer_id": 11236087,
"author": "misterich",
"author_id": 293332,
"author_profile": "https://Stackoverflow.com/users/293332",
"pm_score": -1,
"selected": false,
"text": "<p>Actually, I found myself in a similar situation trying to take an array and parse it into XML. XML element names cannot begin with numbers -- and the code snippets I found did not correctly deal with arrays with numeric indexes.</p>\n\n<blockquote>\n <p><strong>Details on my particular situation are below</strong></p>\n</blockquote>\n\n<p>The answer provided above by @null ( http:// stackoverflow .com/a/173589/293332 ) was actually pretty darn close. I was dismayed that it got voted down tho: Those who do not understand regex lead very frustrating lives.</p>\n\n<p>Anyway, based upon his answer, here is what I ended up with:</p>\n\n<pre><code>/** \n * Checks if an array is associative by utilizing REGEX against the keys\n * @param $arr <array> Reference to the array to be checked\n * @return boolean\n */ \nprivate function isAssociativeArray( &$arr ) {\n return (bool)( preg_match( '/\\D/', implode( array_keys( $arr ) ) ) );\n}\n</code></pre>\n\n<p>See the <a href=\"http://www.php.net/manual/en/regexp.reference.escape.php\" rel=\"nofollow\" title=\"Yes _really_: PerlRegularExpression_match merely takes some practice\">PCRE Escape Sequences</a> and <a href=\"http://www.php.net/manual/en/reference.pcre.pattern.syntax.php\" rel=\"nofollow\">PCRE Syntax</a> pages for further details.</p>\n\n<h2>My Particular Situation</h2>\n\n<p>Here is an example array that I am dealing with:</p>\n\nCase A\n\n<pre><code>return array(\n \"GetInventorySummary\" => array(\n \"Filters\" => array( \n \"Filter\" => array(\n array(\n \"FilterType\" => \"Shape\",\n \"FilterValue\" => \"W\",\n ),\n array(\n \"FilterType\" => \"Dimensions\",\n \"FilterValue\" => \"8 x 10\",\n ),\n array(\n \"FilterType\" => \"Grade\",\n \"FilterValue\" => \"A992\",\n ),\n ),\n ),\n \"SummaryField\" => \"Length\",\n ),\n);\n</code></pre>\n\n<p>The catch is that the <code>filter</code> key is variable. For example:</p>\n\nCase B\n\n<pre><code>return array(\n \"GetInventorySummary\" => array(\n \"Filters\" => array( \n \"Filter\" => array(\n \"foo\" => \"bar\",\n \"bar\" => \"foo\",\n ),\n ),\n \"SummaryField\" => \"Length\",\n ),\n);\n</code></pre>\n\n<h3>Why I Need Assoc. Array Checker</h3>\n\n<p>If the array I am transforming is like <strong>Case A</strong>, what I want returned is:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<GetInventorySummary>\n <Filters>\n <Filter>\n <FilterType>Shape</FilterType>\n <FilterValue>W</FilterValue>\n </Filter>\n <Filter>\n <FilterType>Dimensions</FilterType>\n <FilterValue>8 x 10</FilterValue>\n </Filter>\n <Filter>\n <FilterType>Grade</FilterType>\n <FilterValue>A992</FilterValue>\n </Filter>\n </Filters>\n <SummaryField>Length</SummaryField>\n</GetInventorySummary>\n</code></pre>\n\n<p>... However, if the array I am transforming is like <strong>Case B</strong>, what I want returned is:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<GetInventorySummary>\n <Filters>\n <Filter>\n <foo>bar</foo>\n <bar>foo</bar>\n </Filter>\n </Filters>\n <SummaryField>Length</SummaryField>\n</GetInventorySummary>\n</code></pre>\n"
},
{
"answer_id": 11495941,
"author": "Niels Ockeloen",
"author_id": 1527516,
"author_profile": "https://Stackoverflow.com/users/1527516",
"pm_score": 4,
"selected": false,
"text": "<p>I think the following two functions are the best way to go for checking 'if an array is associative or numeric'. Since 'numeric' could mean only numeric keys or only sequential numeric keys, two functions are listed below that check either condition:</p>\n\n<pre><code>function is_indexed_array(&$arr) {\n for (reset($arr); is_int(key($arr)); next($arr));\n return is_null(key($arr));\n}\n\nfunction is_sequential_array(&$arr, $base = 0) {\n for (reset($arr), $base = (int) $base; key($arr) === $base++; next($arr));\n return is_null(key($arr));\n}\n</code></pre>\n\n<p>The first function checks if each key is an integer value. The second function checks if each key is an integer value and in addition checks if all keys are sequential starting at $base, which defaults to 0 and thus can be omitted if you do not need to specify another base value. key($my_array) returns null if the read pointer is moved past the end of the array, which is what ends the for loop and makes the statement after the for loop return true if all keys were integer. If not, the loop ends prematurely because a key is of type string, and the statement after the for loop will return false. The latter function in addition adds one to $base after each compare, to be able to check if the next key is of the correct value. The strict compare makes it also check if the key is of type integer. The $base = (int) $base part in the first section of the for loop can be left out when $base is omitted or if you make sure it is only called using an integer. But since I can't be sure for everybody, I left it in. The statement is executed only once, anyway. I think these are the most efficient solutions:</p>\n\n<ul>\n<li>Memory wise: No copying of data or key ranges. Doing an array_values or array_keys may seem shorter (less code) but keep in mind what goes on in the background once you make that call. Yes there are more (visible) statements than in some other solutions, but that is not what counts, is it?</li>\n<li>Time wise: Besides the fact that copying/extracting data and/or keys also takes time, this solution is more efficient than doing a foreach. Again a foreach may seem more efficient to some because it is shorter in notation, but in the background foreach also calls reset, key and next to do it's looping. But in addition it also calls valid to check the end condition, which is avoided here due to the combination with the integer check.</li>\n</ul>\n\n<p>Remember that an array key can only be an integer or a string, and a strictly numeric string such as \"1\" (but not \"01\") will be translated into an integer. Which is what makes checking for an integer key the only needed operation besides counting if you want the array to be sequential. Naturally, if is_indexed_array returns false the array can be seen as associative. I say 'seen', because in fact they all are.</p>\n"
},
{
"answer_id": 13522545,
"author": "Pang",
"author_id": 1402846,
"author_profile": "https://Stackoverflow.com/users/1402846",
"pm_score": 5,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/q/173400/1402846\">stated by the OP</a>:</p>\n\n<blockquote>\n <p>PHP treats all arrays as associative</p>\n</blockquote>\n\n<p>it is not quite sensible (IMHO) to write a function that checks if an array is <em>associative</em>. So first thing first: <a href=\"http://php.net/manual/en/language.types.array.php\" rel=\"noreferrer\">what is a key in a PHP array</a>?:</p>\n\n<blockquote>\n <p>The <em>key</em> can either be an <strong>integer</strong> or a <strong>string</strong>.</p>\n</blockquote>\n\n<p>That means there are 3 possible cases:</p>\n\n<ul>\n<li>Case 1. all keys are <strong>numeric</strong> / <strong>integers</strong>.</li>\n<li>Case 2. all keys are <strong>strings</strong>.</li>\n<li>Case 3. some keys are <strong>strings</strong>, some keys are <strong>numeric</strong> / <strong>integers</strong>.</li>\n</ul>\n\n<p>We can check each case with the following functions.</p>\n\n<h3>Case 1: all keys are <strong>numeric</strong> / <strong>integers</strong>.</h3>\n\n<p><strong>Note</strong>: <em>This function returns <strong>true</strong> for empty arrays too.</em></p>\n\n<pre><code>//! Check whether the input is an array whose keys are all integers.\n/*!\n \\param[in] $InputArray (array) Input array.\n \\return (bool) \\b true iff the input is an array whose keys are all integers.\n*/\nfunction IsArrayAllKeyInt($InputArray)\n{\n if(!is_array($InputArray))\n {\n return false;\n }\n\n if(count($InputArray) <= 0)\n {\n return true;\n }\n\n return array_unique(array_map(\"is_int\", array_keys($InputArray))) === array(true);\n}\n</code></pre>\n\n<h3>Case 2: all keys are <strong>strings</strong>.</h3>\n\n<p><strong>Note</strong>: <em>This function returns <strong>true</strong> for empty arrays too.</em></p>\n\n<pre><code>//! Check whether the input is an array whose keys are all strings.\n/*!\n \\param[in] $InputArray (array) Input array.\n \\return (bool) \\b true iff the input is an array whose keys are all strings.\n*/\nfunction IsArrayAllKeyString($InputArray)\n{\n if(!is_array($InputArray))\n {\n return false;\n }\n\n if(count($InputArray) <= 0)\n {\n return true;\n }\n\n return array_unique(array_map(\"is_string\", array_keys($InputArray))) === array(true);\n}\n</code></pre>\n\n<h3>Case 3. some keys are <strong>strings</strong>, some keys are <strong>numeric</strong> / <strong>integers</strong>.</h3>\n\n<p><strong>Note</strong>: <em>This function returns <strong>true</strong> for empty arrays too.</em></p>\n\n<pre><code>//! Check whether the input is an array with at least one key being an integer and at least one key being a string.\n/*!\n \\param[in] $InputArray (array) Input array.\n \\return (bool) \\b true iff the input is an array with at least one key being an integer and at least one key being a string.\n*/\nfunction IsArraySomeKeyIntAndSomeKeyString($InputArray)\n{\n if(!is_array($InputArray))\n {\n return false;\n }\n\n if(count($InputArray) <= 0)\n {\n return true;\n }\n\n return count(array_unique(array_map(\"is_string\", array_keys($InputArray)))) >= 2;\n}\n</code></pre>\n\n<p>It follows that:</p>\n\n<ul>\n<li>If the value is <strong>not an array</strong>, <strong>all 3</strong> functions return <strong>false</strong>.</li>\n<li>If the value is <strong>an empty array</strong>, <strong>all 3</strong> functions return <strong>true</strong><br>\n(which is by definition, as in \"<a href=\"http://en.wikipedia.org/wiki/Empty_set#Properties\" rel=\"noreferrer\">the empty set is a subset of any set <em>A</em> because all its elements belong to <em>A</em></a>\").</li>\n<li>If the value is <strong>a non-empty array</strong>, <strong>exactly 1</strong> function returns <strong>true</strong>.</li>\n</ul>\n\n<hr>\n\n<p>Now, for an array to be a <em>\"genuine\" array</em> that we are all accustomed to, meaning:</p>\n\n<ul>\n<li>Its keys are all <strong>numeric</strong> / <strong>integers</strong>.</li>\n<li>Its keys are <strong>sequential</strong> (i.e. increasing by step 1).</li>\n<li>Its keys <strong><a href=\"http://en.wikipedia.org/wiki/Array_data_type#Index_origin\" rel=\"noreferrer\">start from zero</a></strong>.</li>\n</ul>\n\n<p>We can check with the following function.</p>\n\n<h3>Case 3a. keys are <strong>numeric</strong> / <strong>integers</strong>, <strong>sequential</strong>, and <strong>zero-based</strong>.</h3>\n\n<p><strong>Note</strong>: <em>This function returns <strong>true</strong> for empty arrays too.</em></p>\n\n<pre><code>//! Check whether the input is an array whose keys are numeric, sequential, and zero-based.\n/*!\n \\param[in] $InputArray (array) Input array.\n \\return (bool) \\b true iff the input is an array whose keys are numeric, sequential, and zero-based.\n*/\nfunction IsArrayKeyNumericSequentialZeroBased($InputArray)\n{\n if(!is_array($InputArray))\n {\n return false;\n }\n\n if(count($InputArray) <= 0)\n {\n return true;\n }\n\n return array_keys($InputArray) === range(0, count($InputArray) - 1);\n}\n</code></pre>\n\n<h2>Caveats / Pitfalls (or, even more peculiar facts about array keys in PHP)</h2>\n\n<h3>Integer keys</h3>\n\n<p>The keys for these arrays are <strong><a href=\"http://php.net/manual/en/language.types.integer.php\" rel=\"noreferrer\">integers</a></strong>:</p>\n\n<pre><code>array(0 => \"b\");\narray(13 => \"b\");\narray(-13 => \"b\"); // Negative integers are also integers.\narray(0x1A => \"b\"); // Hexadecimal notation.\n</code></pre>\n\n<h3>String keys</h3>\n\n<p>The keys for these arrays are <strong><a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"noreferrer\">strings</a></strong>:</p>\n\n<pre><code>array(\"fish and chips\" => \"b\");\narray(\"\" => \"b\"); // An empty string is also a string.\narray(\"[email protected]\" => \"b\"); // Strings may contain non-alphanumeric characters.\narray(\"stack\\t\\\"over\\\"\\r\\nflow's cool\" => \"b\"); // Strings may contain special characters.\narray('$tα€k↔øv∈rflöw⛄' => \"b\"); // Strings may contain all kinds of symbols.\narray(\"functіon\" => \"b\"); // You think this looks fine? Think again! (see https://stackoverflow.com/q/9246051/1402846)\narray(\"ま말轉转ДŁ\" => \"b\"); // How about Japanese/Korean/Chinese/Russian/Polish?\narray(\"fi\\x0sh\" => \"b\"); // Strings may contain null characters.\narray(file_get_contents(\"https://www.google.com/images/nav_logo114.png\") => \"b\"); // Strings may even be binary!\n</code></pre>\n\n<h3>Integer keys that look like strings</h3>\n\n<p>If you think the key in <code>array(\"13\" => \"b\")</code> is a <em>string</em>, <strong>you are wrong</strong>. From the doc <a href=\"http://php.net/manual/en/language.types.array.php\" rel=\"noreferrer\">here</a>:</p>\n\n<blockquote>\n <p>Strings containing valid integers will be cast to the integer type. E.g. the key \"8\" will actually be stored under 8. On the other hand \"08\" will not be cast, as it isn't a valid decimal integer.</p>\n</blockquote>\n\n<p>For example, the key for these arrays are <strong>integers</strong>:</p>\n\n<pre><code>array(\"13\" => \"b\");\narray(\"-13\" => \"b\"); // Negative, ok.\n</code></pre>\n\n<p>But the key for these arrays are <strong>strings</strong>:</p>\n\n<pre><code>array(\"13.\" => \"b\");\narray(\"+13\" => \"b\"); // Positive, not ok.\narray(\"-013\" => \"b\");\narray(\"0x1A\" => \"b\"); // Not converted to integers even though it's a valid hexadecimal number.\narray(\"013\" => \"b\"); // Not converted to integers even though it's a valid octal number.\narray(\"18446744073709551616\" => \"b\"); // Not converted to integers as it can't fit into a 64-bit integer.\n</code></pre>\n\n<p>What's more, according to the <a href=\"http://www.php.net/manual/en/language.types.integer.php\" rel=\"noreferrer\">doc</a>,</p>\n\n<blockquote>\n <p>The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers.</p>\n</blockquote>\n\n<p>So the key for this array <strong>may or may not</strong> be an <em>integer</em> - it depends on your platform.</p>\n\n<pre><code>array(\"60000000000\" => \"b\"); // Array key could be integer or string, it can fit into a 64-bit (but not 32-bit) integer.\n</code></pre>\n\n<p>Even worse, PHP tends to be <strong>buggy</strong> if the integer is near the 2<sup>31</sup> = 2,147,483,648 boundary (see <a href=\"https://bugs.php.net/bug.php?id=51430\" rel=\"noreferrer\">bug 51430</a>, <a href=\"https://bugs.php.net/bug.php?id=52899\" rel=\"noreferrer\">bug 52899</a>). For example, on my local environment (PHP 5.3.8 on XAMPP 1.7.7 on Windows 7), <code>var_dump(array(\"2147483647\" => \"b\"))</code> gives</p>\n\n<pre><code>array(1) {\n [2147483647]=>\n string(1) \"b\"\n} \n</code></pre>\n\n<p>but on <a href=\"http://codepad.org/NK87Msp1\" rel=\"noreferrer\">this live demo on codepad</a> (PHP 5.2.5), the same expression gives</p>\n\n<pre><code>array(1) {\n [\"2147483647\"]=>\n string(1) \"b\"\n}\n</code></pre>\n\n<p>So the key is an <em>integer</em> in one environment but a <em>string</em> in another, even though <code>2147483647</code> is a valid signed 32-bit <em>integer</em>.</p>\n"
},
{
"answer_id": 14026836,
"author": "David Farrell",
"author_id": 1822537,
"author_profile": "https://Stackoverflow.com/users/1822537",
"pm_score": 2,
"selected": false,
"text": "<p>I think the definition of a scalar array will vary by application. That is, some applications will require a more strict sense of what qualifies as a scalar array, and some applications will require a more loose sense.</p>\n\n<p>Below I present 3 methods of varying strictness.</p>\n\n<pre><code><?php\n/**\n * Since PHP stores all arrays as associative internally, there is no proper\n * definition of a scalar array.\n * \n * As such, developers are likely to have varying definitions of scalar array,\n * based on their application needs.\n * \n * In this file, I present 3 increasingly strict methods of determining if an\n * array is scalar.\n * \n * @author David Farrell <[email protected]>\n */\n\n/**\n * isArrayWithOnlyIntKeys defines a scalar array as containing\n * only integer keys.\n * \n * If you are explicitly setting integer keys on an array, you\n * may need this function to determine scalar-ness.\n * \n * @param array $a\n * @return boolean\n */ \nfunction isArrayWithOnlyIntKeys(array $a)\n{\n if (!is_array($a))\n return false;\n foreach ($a as $k => $v)\n if (!is_int($k))\n return false;\n return true;\n}\n\n/**\n * isArrayWithOnlyAscendingIntKeys defines a scalar array as\n * containing only integer keys in ascending (but not necessarily\n * sequential) order.\n * \n * If you are performing pushes, pops, and unsets on your array,\n * you may need this function to determine scalar-ness.\n * \n * @param array $a\n * @return boolean\n */ \nfunction isArrayWithOnlyAscendingIntKeys(array $a)\n{\n if (!is_array($a))\n return false;\n $prev = null;\n foreach ($a as $k => $v)\n {\n if (!is_int($k) || (null !== $prev && $k <= $prev))\n return false;\n $prev = $k;\n }\n return true;\n}\n\n/**\n * isArrayWithOnlyZeroBasedSequentialIntKeys defines a scalar array\n * as containing only integer keys in sequential, ascending order,\n * starting from 0.\n * \n * If you are only performing operations on your array that are\n * guaranteed to either maintain consistent key values, or that\n * re-base the keys for consistency, then you can use this function.\n * \n * @param array $a\n * @return boolean\n */\nfunction isArrayWithOnlyZeroBasedSequentialIntKeys(array $a)\n{\n if (!is_array($a))\n return false;\n $i = 0;\n foreach ($a as $k => $v)\n if ($i++ !== $k)\n return false;\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 14977628,
"author": "Manu Manjunath",
"author_id": 495598,
"author_profile": "https://Stackoverflow.com/users/495598",
"pm_score": 3,
"selected": false,
"text": "<p>I noticed two popular approaches for this question: one using <code>array_values()</code> and other using <code>key()</code>. To find out which is faster, I wrote a small program:\n</p>\n\n<pre><code>$arrays = Array(\n 'Array #1' => Array(1, 2, 3, 54, 23, 212, 123, 1, 1),\n 'Array #2' => Array(\"Stack\", 1.5, 20, Array(3.4)),\n 'Array #3' => Array(1 => 4, 2 => 2),\n 'Array #4' => Array(3.0, \"2\", 3000, \"Stack\", 5 => \"4\"),\n 'Array #5' => Array(\"3\" => 4, \"2\" => 2),\n 'Array #6' => Array(\"0\" => \"One\", 1.0 => \"Two\", 2 => \"Three\"),\n 'Array #7' => Array(3 => \"asdf\", 4 => \"asdf\"),\n 'Array #8' => Array(\"apple\" => 1, \"orange\" => 2),\n);\n\nfunction is_indexed_array_1(Array &$arr) {\n return $arr === array_values($arr);\n}\n\nfunction is_indexed_array_2(Array &$arr) {\n for (reset($arr), $i = 0; key($arr) === $i++; next($arr))\n ;\n return is_null(key($arr));\n}\n\n// Method #1\n$start = microtime(true);\nfor ($i = 0; $i < 1000; $i++) {\n foreach ($arrays as $array) {\n $dummy = is_indexed_array_1($array);\n }\n}\n$end = microtime(true);\necho \"Time taken with method #1 = \".round(($end-$start)*1000.0,3).\"ms\\n\";\n\n// Method #2\n$start = microtime(true);\nfor ($i = 0; $i < 1000; $i++) {\n foreach ($arrays as $array) {\n $dummy = is_indexed_array_2($array);\n }\n}\n$end = microtime(true);\necho \"Time taken with method #1 = \".round(($end-$start)*1000.0,3).\"ms\\n\";\n</code></pre>\n\n<p>Output for the program on PHP 5.2 on CentOS is as follows:</p>\n\n<blockquote>\n <p>Time taken with method #1 = 10.745ms<br>\n Time taken with method #2 = 18.239ms</p>\n</blockquote>\n\n<p>Output on PHP 5.3 yielded similar results. Obviously using <code>array_values()</code> is much faster.</p>\n"
},
{
"answer_id": 17582663,
"author": "cloudfeet",
"author_id": 472388,
"author_profile": "https://Stackoverflow.com/users/472388",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's a bit pointless adding an answer to this huge queue, but here's a readable O(n) solution that doesn't require duplicating any values:</p>\n\n<pre><code>function isNumericArray($array) {\n $count = count($array);\n for ($i = 0; $i < $count; $i++) {\n if (!isset($array[$i])) {\n return FALSE;\n }\n }\n return TRUE;\n}\n</code></pre>\n\n<p>Rather than check the keys to see if they are all numeric, you iterate over the keys that <em>would</em> be there for a numeric array and make sure they exist.</p>\n"
},
{
"answer_id": 22396003,
"author": "macki",
"author_id": 1040357,
"author_profile": "https://Stackoverflow.com/users/1040357",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function is_array_assoc($foo) {\n if (is_array($foo)) {\n return (count(array_filter(array_keys($foo), 'is_string')) > 0);\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 24650366,
"author": "Byscripts",
"author_id": 1539115,
"author_profile": "https://Stackoverflow.com/users/1539115",
"pm_score": 2,
"selected": false,
"text": "<p>My solution:</p>\n\n<pre><code>function isAssociative(array $array)\n{\n return array_keys(array_merge($array)) !== range(0, count($array) - 1);\n}\n</code></pre>\n\n<p><code>array_merge</code> on a single array will reindex all <code>integer</code> keys, but not other. For example:</p>\n\n<pre><code>array_merge([1 => 'One', 3 => 'Three', 'two' => 'Two', 6 => 'Six']);\n\n// This will returns [0 => 'One', 1 => 'Three', 'two' => 'Two', 2 => 'Six']\n</code></pre>\n\n<p>So if a list (a non-associative array) is created <code>['a', 'b', 'c']</code> then a value is removed <code>unset($a[1])</code> then <code>array_merge</code> is called, the list is reindexed starting from 0.</p>\n"
},
{
"answer_id": 25206156,
"author": "lazycommit",
"author_id": 501831,
"author_profile": "https://Stackoverflow.com/users/501831",
"pm_score": 2,
"selected": false,
"text": "<p>One more fast from <a href=\"https://github.com/ephrin/structures/blob/master/Ephrin/Structures/ArrayStructure.php\" rel=\"nofollow\">source</a>.\nFit encoding of <code>json_encode</code> (and <code>bson_encode</code>). So has javascript Array compliance.</p>\n\n<pre><code>function isSequential($value){\n if(is_array($value) || ($value instanceof \\Countable && $value instanceof \\ArrayAccess)){\n for ($i = count($value) - 1; $i >= 0; $i--) {\n if (!isset($value[$i]) && !array_key_exists($i, $value)) {\n return false;\n }\n }\n return true;\n } else {\n throw new \\InvalidArgumentException(\n sprintf('Data type \"%s\" is not supported by method %s', gettype($value), __METHOD__)\n );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33163737,
"author": "c9s",
"author_id": 780629,
"author_profile": "https://Stackoverflow.com/users/780629",
"pm_score": 2,
"selected": false,
"text": "<p>By using <a href=\"https://github.com/c9s/xarray\" rel=\"nofollow\">xarray</a> PHP extension</p>\n\n<p>You can do this very fast (about 30+ times faster in PHP 5.6): </p>\n\n<pre><code>if (array_is_indexed($array)) { }\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>if (array_is_assoc($array)) { }\n</code></pre>\n"
},
{
"answer_id": 34908614,
"author": "Loading",
"author_id": 1263456,
"author_profile": "https://Stackoverflow.com/users/1263456",
"pm_score": 3,
"selected": false,
"text": "<p>One way to approach this is to piggyback on <code>json_encode</code>, which already has its own internal method of differentiating between an associative array and an indexed array in order to output the correct JSON.</p>\n\n<p>You can do this by checking to see if the first character returned after encoding is a <code>{</code> (associative array) or a <code>[</code> (indexed array).</p>\n\n<pre><code>// Too short :)\nfunction is_assoc($arr) {\n ksort($arr);\n return json_encode($arr)[0] === '{';\n}\n</code></pre>\n"
},
{
"answer_id": 35858728,
"author": "Jesse",
"author_id": 268083,
"author_profile": "https://Stackoverflow.com/users/268083",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function array_is_assoc(array $a) {\n $i = 0;\n foreach ($a as $k => $v) {\n if ($k !== $i++) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>Fast, concise, and memory efficient. No expensive comparisons, function calls or array copying.</p>\n"
},
{
"answer_id": 38183890,
"author": "nonsensei",
"author_id": 4805056,
"author_profile": "https://Stackoverflow.com/users/4805056",
"pm_score": 2,
"selected": false,
"text": "<p>answers are already given but there's too much disinformation about performance.\nI wrote this little benchmark script that shows that the foreach method is the fastest.</p>\n\n<p>Disclaimer: following methods were copy-pasted from the other answers</p>\n\n<pre><code><?php\n\nfunction method_1(Array &$arr) {\n return $arr === array_values($arr);\n}\n\nfunction method_2(Array &$arr) {\n for (reset($arr), $i = 0; key($arr) !== $i++; next($arr));\n return is_null(key($arr));\n}\n\nfunction method_3(Array &$arr) {\n return array_keys($arr) === range(0, count($arr) - 1);\n}\n\nfunction method_4(Array &$arr) {\n $idx = 0;\n foreach( $arr as $key => $val ){\n if( $key !== $idx )\n return FALSE;\n $idx++;\n }\n return TRUE;\n}\n\n\n\n\nfunction benchmark(Array $methods, Array &$target){ \n foreach($methods as $method){\n $start = microtime(true);\n for ($i = 0; $i < 1000; $i++)\n $dummy = call_user_func($method, $target);\n\n $end = microtime(true);\n echo \"Time taken with $method = \".round(($end-$start)*1000.0,3).\"ms\\n\";\n }\n}\n\n\n\n$targets = [\n 'Huge array' => range(0, 30000),\n 'Small array' => range(0, 1000),\n];\n$methods = [\n 'method_1',\n 'method_2',\n 'method_3',\n 'method_4',\n];\nforeach($targets as $targetName => $target){\n echo \"==== Benchmark using $targetName ====\\n\";\n benchmark($methods, $target);\n echo \"\\n\";\n}\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>==== Benchmark using Huge array ====\nTime taken with method_1 = 5504.632ms\nTime taken with method_2 = 4509.445ms\nTime taken with method_3 = 8614.883ms\nTime taken with method_4 = 2720.934ms\n\n==== Benchmark using Small array ====\nTime taken with method_1 = 77.159ms\nTime taken with method_2 = 130.03ms\nTime taken with method_3 = 160.866ms\nTime taken with method_4 = 69.946ms\n</code></pre>\n"
},
{
"answer_id": 38471132,
"author": "Justin Levene",
"author_id": 1938802,
"author_profile": "https://Stackoverflow.com/users/1938802",
"pm_score": -1,
"selected": false,
"text": "<p>Improvement from Mark Amery</p>\n\n<pre><code>function isAssoc($arr)\n{\n // Is it set, is an array, not empty and keys are not sequentialy numeric from 0\n return isset($arr) && is_array($arr) && count($arr)!=0 && array_keys($arr) !== range(0, count($arr) - 1);\n}\n</code></pre>\n\n<p>This tests if variable exists, if it is an array, if it is not an empty array and if the keys are not sequential from 0.</p>\n\n<p>To see if the array is associative</p>\n\n<pre><code>if (isAssoc($array)) ...\n</code></pre>\n\n<p>To see if it numeric</p>\n\n<pre><code>if (!isAssoc($array)) ...\n</code></pre>\n"
},
{
"answer_id": 39956857,
"author": "Haresh Vidja",
"author_id": 1793428,
"author_profile": "https://Stackoverflow.com/users/1793428",
"pm_score": -1,
"selected": false,
"text": "<p>In simple way you can check is array is associative or not by below steps</p>\n\n<ol>\n<li>convert all keys of array into one array by using <code>array_keys()</code></li>\n<li>filter out non numeric key from array using <code>array_filter()</code> and\n<code>is_numeric()</code></li>\n<li>compare number of elements in filtered array and actual array, If number of elements are not equals in both array then it is associative array.</li>\n</ol>\n\n<p>Function for above step is as below.</p>\n\n<pre><code> function isAssociative(array $array)\n {\n return count(array_filter(array_keys($array), function($v){return is_numeric($v);})) !== count($array));\n }\n</code></pre>\n"
},
{
"answer_id": 43237845,
"author": "Ben",
"author_id": 3150636,
"author_profile": "https://Stackoverflow.com/users/3150636",
"pm_score": 3,
"selected": false,
"text": "<p>There are many answers already, but here is the method that Laravel relies on within its Arr class: </p>\n\n<pre><code>/**\n * Determines if an array is associative.\n *\n * An array is \"associative\" if it doesn't have sequential numerical keys beginning with zero.\n *\n * @param array $array\n * @return bool\n */\npublic static function isAssoc(array $array)\n{\n $keys = array_keys($array);\n\n return array_keys($keys) !== $keys;\n}\n</code></pre>\n\n<p>Source: <a href=\"https://github.com/laravel/framework/blob/5.4/src/Illuminate/Support/Arr.php\" rel=\"nofollow noreferrer\">https://github.com/laravel/framework/blob/5.4/src/Illuminate/Support/Arr.php</a></p>\n"
},
{
"answer_id": 44793312,
"author": "voodoo417",
"author_id": 1397379,
"author_profile": "https://Stackoverflow.com/users/1397379",
"pm_score": -1,
"selected": false,
"text": "<p>Checking if array has all assoc-keys. With using <code>stdClass</code> & <a href=\"http://php.net/manual/en/function.get-object-vars.php\" rel=\"nofollow noreferrer\">get_object_vars</a> ^):</p>\n\n<pre><code>$assocArray = array('fruit1' => 'apple', \n 'fruit2' => 'orange', \n 'veg1' => 'tomato', \n 'veg2' => 'carrot');\n\n$assoc_object = (object) $assocArray;\n$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object))); \nvar_dump($isAssoc); // true\n</code></pre>\n\n<p>Why? Function <code>get_object_vars</code> returns only <strong>accessible</strong> properties (see more about what is occuring during converting <code>array</code> to <code>object</code> <a href=\"http://php.net/manual/en/function.get-object-vars.php\" rel=\"nofollow noreferrer\">here</a>). Then, just logically: if <strong>count of basic array's elements</strong> equals <strong>count of object's accessible properties</strong> - all keys are assoc.</p>\n\n<p><em>Few tests</em>: </p>\n\n<pre><code>$assocArray = array('apple', 'orange', 'tomato', 'carrot');\n$assoc_object = (object) $assocArray; \n$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));\nvar_dump($isAssoc); // false \n//...\n\n$assocArray = array( 0 => 'apple', 'orange', 'tomato', '4' => 'carrot');\n$assoc_object = (object) $assocArray; \n$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));\nvar_dump($isAssoc); // false \n\n//... \n$assocArray = array('fruit1' => 'apple', \n NULL => 'orange', \n 'veg1' => 'tomato', \n 'veg2' => 'carrot');\n\n$assoc_object = (object) $assocArray;\n$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object))); \nvar_dump($isAssoc); //false\n</code></pre>\n\n<p><em>Etc.</em></p>\n"
},
{
"answer_id": 48247922,
"author": "TylerY86",
"author_id": 2879498,
"author_profile": "https://Stackoverflow.com/users/2879498",
"pm_score": 2,
"selected": false,
"text": "<p>After some local benchmarking, debugging, compiler probing, profiling, and abusing 3v4l.org to benchmark across more versions (yes, I got a warning to stop) and\ncomparing against every variation I could find...</p>\n\n<p>I give you an organically derived <strong>best-average-worst-case scenario</strong> associative array test function that is at <em>worst</em> roughly as good as or better than all other average-case scenarios.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Tests if an array is an associative array.\n *\n * @param array $array An array to test.\n * @return boolean True if the array is associative, otherwise false.\n */\nfunction is_assoc(array &$arr) {\n // don't try to check non-arrays or empty arrays\n if (FALSE === is_array($arr) || 0 === ($l = count($arr))) {\n return false;\n }\n\n // shortcut by guessing at the beginning\n reset($arr);\n if (key($arr) !== 0) {\n return true;\n }\n\n // shortcut by guessing at the end\n end($arr);\n if (key($arr) !== $l-1) {\n return true;\n }\n\n // rely on php to optimize test by reference or fast compare\n return array_values($arr) !== $arr;\n}\n</code></pre>\n\n<p>From <a href=\"https://3v4l.org/rkieX\" rel=\"nofollow noreferrer\">https://3v4l.org/rkieX</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\n// array_values\nfunction method_1(Array &$arr) {\n return $arr === array_values($arr);\n}\n\n// method_2 was DQ; did not actually work\n\n// array_keys\nfunction method_3(Array &$arr) {\n return array_keys($arr) === range(0, count($arr) - 1);\n}\n\n// foreach\nfunction method_4(Array &$arr) {\n $idx = 0;\n foreach( $arr as $key => $val ){\n if( $key !== $idx )\n return FALSE;\n ++$idx;\n }\n return TRUE;\n}\n\n// guessing\nfunction method_5(Array &$arr) {\n global $METHOD_5_KEY;\n $i = 0;\n $l = count($arr)-1;\n\n end($arr);\n if ( key($arr) !== $l )\n return FALSE;\n\n reset($arr);\n do {\n if ( $i !== key($arr) )\n return FALSE;\n ++$i;\n next($arr);\n } while ($i < $l);\n return TRUE;\n}\n\n// naieve\nfunction method_6(Array &$arr) {\n $i = 0;\n $l = count($arr);\n do {\n if ( NULL === @$arr[$i] )\n return FALSE;\n ++$i;\n } while ($i < $l);\n return TRUE;\n}\n\n// deep reference reliance\nfunction method_7(Array &$arr) {\n return array_keys(array_values($arr)) === array_keys($arr);\n}\n\n\n// organic (guessing + array_values)\nfunction method_8(Array &$arr) {\n reset($arr);\n if ( key($arr) !== 0 )\n return FALSE;\n\n end($arr);\n if ( key($arr) !== count($arr)-1 )\n return FALSE;\n\n return array_values($arr) === $arr;\n}\n\nfunction benchmark(Array &$methods, Array &$target, $expected){ \n foreach($methods as $method){\n $start = microtime(true);\n for ($i = 0; $i < 2000; ++$i) {\n //$dummy = call_user_func($method, $target);\n if ( $method($target) !== $expected ) {\n echo \"Method $method is disqualified for returning an incorrect result.\\n\";\n unset($methods[array_search($method,$methods,true)]);\n $i = 0;\n break;\n }\n }\n if ( $i != 0 ) {\n $end = microtime(true);\n echo \"Time taken with $method = \".round(($end-$start)*1000.0,3).\"ms\\n\";\n }\n }\n}\n\n\n\n$true_targets = [\n 'Giant array' => range(0, 500),\n 'Tiny array' => range(0, 20),\n];\n\n\n$g = range(0,10);\nunset($g[0]);\n\n$false_targets = [\n 'Large array 1' => range(0, 100) + ['a'=>'a'] + range(101, 200),\n 'Large array 2' => ['a'=>'a'] + range(0, 200),\n 'Tiny array' => range(0, 10) + ['a'=>'a'] + range(11, 20),\n 'Gotcha array' => $g,\n];\n\n$methods = [\n 'method_1',\n 'method_3',\n 'method_4',\n 'method_5',\n 'method_6',\n 'method_7',\n 'method_8'\n];\n\n\nforeach($false_targets as $targetName => $target){\n echo \"==== Benchmark using $targetName expecing FALSE ====\\n\";\n benchmark($methods, $target, false);\n echo \"\\n\";\n}\nforeach($true_targets as $targetName => $target){\n echo \"==== Benchmark using $targetName expecting TRUE ====\\n\";\n benchmark($methods, $target, true);\n echo \"\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 50167674,
"author": "Prathamesh Datar",
"author_id": 1262204,
"author_profile": "https://Stackoverflow.com/users/1262204",
"pm_score": -1,
"selected": false,
"text": "<p>This is my function - </p>\n\n<pre><code>public function is_assoc_array($array){\n\n if(is_array($array) !== true){\n return false;\n }else{\n\n $check = json_decode(json_encode($array));\n\n if(is_object($check) === true){\n return true;\n }else{\n return false;\n }\n\n }\n\n}\n</code></pre>\n\n<p>Some examples</p>\n\n<pre><code> print_r((is_assoc_array(['one','two','three']))===true?'Yes':'No'); \\\\No\n print_r(is_assoc_array(['one'=>'one','two'=>'two','three'=>'three'])?'Yes':'No'); \\\\Yes\n print_r(is_assoc_array(['1'=>'one','2'=>'two','3'=>'three'])?'Yes':'No'); \\\\Yes\n print_r(is_assoc_array(['0'=>'one','1'=>'two','2'=>'three'])?'Yes':'No'); \\\\No\n</code></pre>\n\n<p>There was a similar solution by @devios1 in one of the answers but this was just another way using the inbuilt json related functions of PHP. I haven't checked how this solution fairs in terms of performance compared to other solutions that have been posted here. But it certainly has helped me solve this problem. Hope this helps.</p>\n"
},
{
"answer_id": 52194269,
"author": "Minwork",
"author_id": 10322539,
"author_profile": "https://Stackoverflow.com/users/10322539",
"pm_score": 1,
"selected": false,
"text": "<p>Or you can just use this:</p>\n\n<pre><code>Arr::isAssoc($array)\n</code></pre>\n\n<p>which will check if array contains <strong>any non-numeric key</strong> or:</p>\n\n<pre><code>Arr:isAssoc($array, true)\n</code></pre>\n\n<p>to check if array <strong>is strictly sequencial</strong> (contains auto generated int keys <em>0</em> to <em>n-1</em>)</p>\n\n<p>using <a href=\"https://github.com/minwork/array\" rel=\"nofollow noreferrer\">this</a> library.</p>\n"
},
{
"answer_id": 52275295,
"author": "Slayer Birden",
"author_id": 927404,
"author_profile": "https://Stackoverflow.com/users/927404",
"pm_score": 0,
"selected": false,
"text": "<p>I've come up with next method:</p>\n<pre><code>function isSequential(array $list): bool\n{\n $i = 0;\n $count = count($list);\n while (array_key_exists($i, $list)) {\n $i += 1;\n if ($i === $count) {\n return true;\n }\n }\n\n return false;\n}\n\n\nvar_dump(isSequential(array())); // false\nvar_dump(isSequential(array('a', 'b', 'c'))); // true\nvar_dump(isSequential(array("0" => 'a', "1" => 'b', "2" => 'c'))); // true\nvar_dump(isSequential(array("1" => 'a', "0" => 'b', "2" => 'c'))); // true\nvar_dump(isSequential(array("1a" => 'a', "0b" => 'b', "2c" => 'c'))); // false\nvar_dump(isSequential(array("a" => 'a', "b" => 'b', "c" => 'c'))); // false\n</code></pre>\n<p>*Note empty array is not considered a sequential array, but I think it's fine since empty arrays is like 0 - doesn't matter it's plus or minus, it's empty.</p>\n<p>Here are the advantages of this method compared to some listed above:</p>\n<ul>\n<li>It does not involve copying of arrays (someone mentioned in this gist <a href=\"https://gist.github.com/Thinkscape/1965669\" rel=\"nofollow noreferrer\">https://gist.github.com/Thinkscape/1965669</a> that <code>array_values</code> does not involve copying - what!?? <strong>It certainly does - as will be seen below</strong>)</li>\n<li>It's faster for bigger arrays and more memory friendly at the same time</li>\n</ul>\n<p>I've used benchmark kindly provided by <a href=\"https://stackoverflow.com/users/181664/\">Artur Bodera</a>, where I changed one of the arrays to 1M elements (<code>array_fill(0, 1000000, uniqid()), // big numeric array</code>).</p>\n<p>Here are the results for 100 iterations:</p>\n<pre><code>PHP 7.1.16 (cli) (built: Mar 31 2018 02:59:59) ( NTS )\n\nInitial memory: 32.42 MB\nTesting my_method (isset check) - 100 iterations\n Total time: 2.57942 s\n Total memory: 32.48 MB\n\nTesting method3 (array_filter of keys) - 100 iterations\n Total time: 5.10964 s\n Total memory: 64.42 MB\n\nTesting method1 (array_values check) - 100 iterations\n Total time: 3.07591 s\n Total memory: 64.42 MB\n\nTesting method2 (array_keys comparison) - 100 iterations\n Total time: 5.62937 s\n Total memory: 96.43 MB\n</code></pre>\n<p>*Methods are ordered based on their memory consumption</p>\n<p>**I used <code>echo " Total memory: " . number_format(memory_get_peak_usage()/1024/1024, 2) . " MB\\n";</code> to display memory usage</p>\n"
},
{
"answer_id": 52628664,
"author": "Rbgo Web",
"author_id": 3009380,
"author_profile": "https://Stackoverflow.com/users/3009380",
"pm_score": -1,
"selected": false,
"text": "<pre><code>/*\niszba - Is Zero Based Array\n\nDetects if an array is zero based or not.\n\nPARAMS:\n $chkvfnc\n Callback in the loop allows to check the values of each element.\n Signature:\n bool function chkvfnc($v);\n return:\n true continue looping\n false stop looping; iszba returns false too.\n\nNOTES:\n○ assert: $array is an array.\n○ May be memory efficient;\n it doesn't get extra arrays via array_keys() or ranges() into the function.\n○ Is pretty fast without a callback.\n○ With callback it's ~2.4 times slower.\n*/\nfunction iszba($array, $chkvfnc=null){\n\n $ncb = !$chkvfnc;\n $i = 0;\n\n foreach($array as $k => $v){\n if($k === $i++)\n if($ncb || $chkvfnc($v))\n continue;\n\n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>• Without callback it is ~30% faster than current leading answer,\nand possibly more memory efficient.</p>\n\n<p>• Just negate the answer to know if the array should be considered associative.</p>\n"
},
{
"answer_id": 56070491,
"author": "geilt",
"author_id": 849560,
"author_profile": "https://Stackoverflow.com/users/849560",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of the solutions here are elegant and pretty, but don't scale well, and are memory intensive or CPU intensive. Most are creating 2 new data points in memory with this solution from both sides of the comparison. The larger the array the harder and longer the process and memory used, and you lose the benefit of short circuit evaluation. I Did some testing with a few different ideas. Trying to avoid array_key_exists as it is costly, and also avoiding creating new large datasets to compare. I feel this is a simple way to tell if an array is sequential.</p>\n\n<pre><code>public function is_sequential( $arr = [] ){\n if( !is_array( $arr ) || empty( $arr ) ) return false;\n\n $i = 0;\n\n $total = count( $arr );\n\n foreach( $arr as $key => $value ) if( $key !== $i++ ) return false;\n\n return true;\n}\n</code></pre>\n\n<p>You run a single count on the main array and store a single integer. You then loop through the array and check for an exact match while iterating the counter. You should have from 1 to count. If it fails it will short circuit out which gives you performance boost when it is false. </p>\n\n<p>Originally I did this with a for loop and checking for isset( $arr[$i] ) but this will not detect null keys which requires array_key_exists, and as we know that is the worst function to use for speed.</p>\n\n<p>Constantly updating variables via foreach to check along with the iterator never growing past it's integer size let's PHP use it's built in memory optimization, caching and garbage collection to keep you at very low resource usage. </p>\n\n<p>Also, I will argue that using array_keys in a foreach is silly when you can simply run $key => $value and check the key. Why create the new data point? Once you abstract away the array keys you've consumed more memory immediately. </p>\n"
},
{
"answer_id": 58202788,
"author": "Aylian Craspa",
"author_id": 1640362,
"author_profile": "https://Stackoverflow.com/users/1640362",
"pm_score": 1,
"selected": false,
"text": "<p>This question is actually useless when it comes to array of php because with the nature of php an array should not have to be fully associative or indexing, it can be combination of both, the way user have define and assigned the value an array can be a combination of both. see the example below</p>\n\n<pre><code>$y= array(5);\n$y[\"0x\"]=\"n\";\n$y[\"vbg\"]=\"12132\";\n$y[1] = \"k\";\n\nvar_dump($y); //this will output 4 element array\n\necho \"</br>\" .$y[\"0x\"].\"</br>\".$y[0];\n\nfor($x=0;$x<sizeof($y);$x++){ // this will output all index elements & gives error after that\n echo \"</br> index elements \".$y[$x];\n}\n</code></pre>\n\n<p>so the correct question that has to ask is , is all the element in array are associative or index. if you really know that it will only be either associative or indexing not a combination of these two, you can just simply use this method to find wether it is an index or associative array.</p>\n\n<pre><code>function AssocTest(&$arr){\n if(is_array($arr)){\n\n reset($arr); // reset pointer to first element of array\n\n if(gettype(key($arr)) == \"string\"){ //get the type(nature) of first element key \n return true;\n }else{\n return false;\n }\n }else{\n return false;\n }\n}\n</code></pre>\n\n<p>you can use it as normal function</p>\n\n<pre><code>echo(AssocTest($y)? \"Associative array\": \"Not an Associative array/ Not an array at all\");\n</code></pre>\n\n<p>and important thing to remember evan you have initialize an array as associative but the names that you have gave the associative array is just numbers it will treat as an index array when it being read by php if you have not explicitly gave the string names. take a look at the example below.</p>\n\n<pre><code>$y[\"0\"]=\"n\";\n$y[\"1\"]=\"12132\";\n$y[\"22\"] = \"k\";\n\n//both will get the same output\necho \"<br/> s0 \".$y[\"22\"];\necho \"<br/> s0 \".$y[22];\n\nfor($x=0;$x<count($y);$x++){\n echo \"<br/> arr \".$y[$x]; // this will output up to 2nd element and give an error after\n\n}\n</code></pre>\n\n<p>so if you need to be sure all the elements of the array to be exactly indexed or either associative , there is no other way but go true all the elements and check each and every element key by generated index array as post by many people here.</p>\n\n<pre><code>function fullAssocTest(&$arr)\n{\n if(is_array($arr)){\n return (array_keys($arr) !== range(0, count($arr) - 1));\n }\n}\n</code></pre>\n\n<p>its less coding, but this thing is really process intensive and really un-necessary work.</p>\n"
},
{
"answer_id": 60720565,
"author": "pilat",
"author_id": 475615,
"author_profile": "https://Stackoverflow.com/users/475615",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes you can get away with only checking if the first array's Key is 0.</p>\n\n<p><code>$isSequential = array_keys($arr)[0] === 0</code></p>\n\n<p>, or, faster, but more verbose version:</p>\n\n<p><code>reset($arr); $isSequential = key($arr) === 0</code></p>\n"
},
{
"answer_id": 63685462,
"author": "Manu Manjunath",
"author_id": 495598,
"author_profile": "https://Stackoverflow.com/users/495598",
"pm_score": 3,
"selected": false,
"text": "<p>Most answers have sub-optimal time/space complexity or are changing semantics. So, here is another answer with the <strong>fastest</strong> and <strong>most functionally correct</strong> solution:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function is_sequential_array(Array &$a) {\n $n = count($a);\n for($i=0; $i<$n; $i++) {\n if(!array_key_exists($i, $a)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n<p>This answer has following advantages over other answers:</p>\n<ol>\n<li>Space complexity of <code>O(1)</code> (many answers here use <code>O(n)</code> space!)</li>\n<li>Does not apply equality on keys (which is an unwanted and expensive operation)</li>\n<li>Treats input array as immutable (many answers have implicitly created a copy by applying mutating functions)</li>\n<li>Uses function <code>array_key_exists</code> instead of <code>isset</code> (remember, <code>isset</code> additionally checks for 'is not null', thereby changing semantics)</li>\n<li>Worst-case time complexity is <code>O(n)</code> (many answers here have best-case time complexity of <code>O(n)</code>)</li>\n</ol>\n"
},
{
"answer_id": 63743929,
"author": "CSSBurner",
"author_id": 9858653,
"author_profile": "https://Stackoverflow.com/users/9858653",
"pm_score": -1,
"selected": false,
"text": "<p>I'm surprised no one has mentioned <code>array_key_first()</code></p>\n<p>For your test cases:</p>\n<pre><code>$sequentialArray = array('apple', 'orange', 'tomato', 'carrot');\n$isIndexedArray = is_int( array_key_first($sequentialArray) ); // true\n</code></pre>\n<p>whereas</p>\n<pre><code>$assocArray = array('fruit1' => 'apple', \n 'fruit2' => 'orange', \n 'veg1' => 'tomato', \n 'veg2' => 'carrot');\n\n$isIndexedArray = is_int( array_key_first($assocArray) ); // false\n</code></pre>\n<p>Read more about this function <a href=\"https://www.php.net/manual/en/function.array-key-first.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 63780789,
"author": "dipenparmar12",
"author_id": 8592918,
"author_profile": "https://Stackoverflow.com/users/8592918",
"pm_score": 4,
"selected": false,
"text": "<h3>Here is another simple but powerful logic ( which is also used by great Laravel framework in it's internal mechanism )</h3>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Determines if an array is associative.\n * @param array $array\n * @return bool\n */\nfunction isAssoc(array $array)\n{\n $keys = array_keys($array);\n\n return array_keys($keys) !== $keys;\n}\n</code></pre>\n"
},
{
"answer_id": 67898815,
"author": "Muhammad Dyas Yaskur",
"author_id": 2671470,
"author_profile": "https://Stackoverflow.com/users/2671470",
"pm_score": 5,
"selected": false,
"text": "<p>PHP 8.1 adds a built-in function to determine whether an array is a list with those semantics, or not. the function is <a href=\"https://wiki.php.net/rfc/is_list\" rel=\"noreferrer\"><code>array_is_list</code></a>:</p>\n<pre><code>$list = ["a", "b", "c"];\n\narray_is_list($list); // true\n\n$notAList = [1 => "a", 2 => "b", 3 => "c"];\n\narray_is_list($notAList); // false\n\n$alsoNotAList = ["a" => "a", "b" => "b", "c" => "c"];\n\narray_is_list($alsoNotAList); // false\n</code></pre>\n<p><a href=\"https://stitcher.io/blog/new-in-php-81\" rel=\"noreferrer\">reference</a></p>\n"
},
{
"answer_id": 68531238,
"author": "dılo sürücü",
"author_id": 5582655,
"author_profile": "https://Stackoverflow.com/users/5582655",
"pm_score": -1,
"selected": false,
"text": "<pre class=\"lang-php prettyprint-override\"><code>\nfunction is_assoc(array $array): bool\n{\n foreach ($array as $iValue) {\n if (is_array($iValue)) {\n return true;\n }\n }\n return false;\n\n}\n\n$d= is_assoc(["id",2,3]);\n\nvar_dump($d);\n</code></pre>\n"
},
{
"answer_id": 70613786,
"author": "PaulH",
"author_id": 4152976,
"author_profile": "https://Stackoverflow.com/users/4152976",
"pm_score": 2,
"selected": false,
"text": "<p>For those using Laravel:</p>\n<p><code>Arr::isAssoc</code> returns true if the given array is an associative array. An array is considered "associative" if it doesn't have sequential numerical keys beginning with zero:</p>\n<pre><code>use Illuminate\\Support\\Arr;\n\n$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);\n\n// true\n\n$isAssoc = Arr::isAssoc([1, 2, 3]);\n\n// false\n</code></pre>\n<p><a href=\"https://laravel.com/docs/8.x/helpers#method-array-isassoc\" rel=\"nofollow noreferrer\">https://laravel.com/docs/8.x/helpers#method-array-isassoc</a></p>\n"
},
{
"answer_id": 71267111,
"author": "godzillante",
"author_id": 1037567,
"author_profile": "https://Stackoverflow.com/users/1037567",
"pm_score": 1,
"selected": false,
"text": "<p>Just adding my two cents, and I think it should be pretty efficient based on @nonsensei 's benchmarks as well as being clearly legible:</p>\n<pre><code>function is_associative(array $array): bool\n{\n foreach ($array as $key => $value)\n {\n if (!is_string($key)) return false;\n }\n return true;\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array *"is a list"* (contains only numeric keys starting from 0)?
Basically, I want to be able to differentiate between this:
```
$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
```
and this:
```
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
```
|
You have asked two questions that are not quite equivalent:
* Firstly, how to determine whether an array has only numeric keys
* Secondly, how to determine whether an array has *sequential* numeric keys, starting from 0
Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)
The first question (simply checking that all keys are numeric) is [answered well by Captain kurO](https://stackoverflow.com/a/4254008/1709587).
For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:
```php
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
var_dump(isAssoc(['a', 'b', 'c'])); // false
var_dump(isAssoc(["0" => 'a', "1" => 'b', "2" => 'c'])); // false
var_dump(isAssoc(["1" => 'a', "0" => 'b', "2" => 'c'])); // true
var_dump(isAssoc(["a" => 'a', "b" => 'b', "c" => 'c'])); // true
```
|
173,433 |
<p>I have built a .dll under WinXP that claims it can't find DWMAPI.DLL when it's loaded. The problem is that this DLL is a Vista DLL, and this a known issue for XP users that have IE7 installed. The recommendation is to uninstall IE7 or repair the .NET Framework via Add/Remove programs. I did the repair, and nothing changed. I'm not about to uninstall IE7 since there must be a better solution that's not the equivalent of "reinstall windows".</p>
<p>I've read bad things about people who attempted to uninstall IE7, so I'm reluctant to go that route.</p>
<p>I am using C++ under Visual Studio 2003 (7.1). I don't see an option where I may have forced delay loading at application launch. I just used default settings when I created the DLL project. I did just now find an interesting option, Linker->Input->Delay Loaded DLLs, so I put DWMAPI.DLL in there to force it to be delay-loaded. However, I get this when linking:</p>
<pre><code>LINK : warning LNK4199: /DELAYLOAD:dwmapi.dll ignored; no imports found from dwmapi.dll
</code></pre>
<p>.. and it of course didn't change a thing when trying to load my DLL. For the heck of it, I added the whole tree of DLLs that lead to DWMAPI.DLL, and I get the same message. (For the record, it's foundation.dll->shell32.dll->shdocvw.dll->mshtml.dll->ieframe.dll->dwmapi.dll .)</p>
<p>To be more specific about what I'm doing, I am writing a Maya plugin and get the always-helpful text in the script editor:</p>
<pre><code>// Error: Unable to dynamically load : D:/blahblahblah/mydll.mll
The specified module could not be found.
//
// Error: The operation completed successfully.
//
// Error: The operation completed successfully.
(mydll) //
</code></pre>
<p>I used Dependency Walker to initially track down the problem, and that's what lead me to DWMAPI.DLL. These are the message depends gives me, and DWMAPI.DLL is the only thing that has a yellow question mark next to it:</p>
<pre><code>Warning: At least one delay-load dependency module was not found.
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
</code></pre>
<p>Gerald is right. Maya is, in fact, using a different PATH than the Dependency Walker. My plug-in loads another DLL (for image processing) that lives in the Maya plug-ins directory and depends found it with no problem, but Maya didn't. I had to add ";plug-ins" to the PATH in Maya.env.</p>
<p>Seeing as this problem wasn't related to DWMAPI.DLL after all, but DWMAPI is a common problem, I'll post the best link I found about the DWMAPI issue on Novell's website <a href="http://www.novell.com/communities/node/4372/handling-dwmapidll-dependency" rel="noreferrer">here</a>. Basically, most programs will have this warning in depends.exe, but if there is a delay-load icon next to it, and you are sure that the program won't directly or indirectly call DWMAPI, then it's fine. The problem is elsewhere. If the delay-load icon isn't present, then you have to look at the /DELAY and /DELAYLOAD options in Visual Studio. The fact that depends gave me a "warning" and not an "error" was a clue to the fact that DWMAPI is not being loaded automatically.</p>
|
[
{
"answer_id": 173505,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 2,
"selected": false,
"text": "<p>This is a tricky one. There's really 2 main ways you will get this error.</p>\n\n<p>1) You have your project set to force delay loaded DLLs to load at application launch. DWMAPI.dll is a delay-loaded DLL and thus normally will not be loaded unless one of it's functions is called. That won't happen on XP unless you're trying to do it in your DLL. But it's possible to set a compiler option to force your app to load the delay loaded DLLs anyway. If you're doing that, don't.</p>\n\n<p>2) It's often a false error that you will get from depends.exe when there is another problem. Run your DLL through dependency walker and see if there are any other dependency problems. If all else fails, try uninstalling IE7 and see if the problem persists. If it is a false error, after you install IE7 you will see the real error. You can install IE7 again afterwards.</p>\n"
},
{
"answer_id": 176312,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 4,
"selected": true,
"text": "<p>Based on your updated problem, DWMAPI.dll is probably not your problem. Dependency walker will always give you that error whenever you are linking to mshtml as it always checks delay loaded DLLs.</p>\n\n<p>At this point my best guess is that you have your project set to dynamically load the runtime libraries and the search path for DLLs is being changed by Maya. So it may be unable to find the MSVC runtime DLL(s). I haven't developed Maya plugins in a long time, but I've had that problem with other apps that have plugin DLLs recently. </p>\n\n<p>Try changing your setting in C/C++->Code Generation->Runtime Library to Multi-Threaded rather than Multi-Threaded DLL.</p>\n\n<p>Aside from that you can try fiddling with Dependency Walker to make it use the same search paths as Maya and see if you can come up with another dependency problem. </p>\n\n<p>As a last resort you can launch Maya in a debugger and set a breakpoint on LoadLibrary and find out which library is not being loaded that way.</p>\n"
},
{
"answer_id": 1327878,
"author": "ROAR",
"author_id": 90319,
"author_profile": "https://Stackoverflow.com/users/90319",
"pm_score": 2,
"selected": false,
"text": "<p>I had exactly this problem.</p>\n\n<p>Sneaky problem that took hours to solve.</p>\n\n<p>Anyway. I compiled my managed C++ application on the release machine. Got complaints from customers that could not run it, worked like a charm on all of our machines.</p>\n\n<p>It turned out that the release machine was automatically patched one night a month ago with the ATL vulnerability fix, and so was all other machines also, except one XP machine.</p>\n\n<p>That particulare XP machine could not run the application either. Installed the ATL fix (see link below), and voilá, every thing worked just like before.</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=766A6AF7-EC73-40FF-B072-9112BAB119C2&displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?familyid=766A6AF7-EC73-40FF-B072-9112BAB119C2&displaylang=en</a></p>\n\n<p>So lesson learned, always check your intermediate manifests (found the in debug or release directory), that will tell you what version of the DLL that the program have been linked against.</p>\n\n<p>Hope it helps anyone.</p>\n"
},
{
"answer_id": 3732887,
"author": "user450279",
"author_id": 450279,
"author_profile": "https://Stackoverflow.com/users/450279",
"pm_score": 2,
"selected": false,
"text": "<p>Try changing your setting in C/C++->Code Generation->Runtime Library to Multi-Threaded rather than Multi-Threaded DLL.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2666/"
] |
I have built a .dll under WinXP that claims it can't find DWMAPI.DLL when it's loaded. The problem is that this DLL is a Vista DLL, and this a known issue for XP users that have IE7 installed. The recommendation is to uninstall IE7 or repair the .NET Framework via Add/Remove programs. I did the repair, and nothing changed. I'm not about to uninstall IE7 since there must be a better solution that's not the equivalent of "reinstall windows".
I've read bad things about people who attempted to uninstall IE7, so I'm reluctant to go that route.
I am using C++ under Visual Studio 2003 (7.1). I don't see an option where I may have forced delay loading at application launch. I just used default settings when I created the DLL project. I did just now find an interesting option, Linker->Input->Delay Loaded DLLs, so I put DWMAPI.DLL in there to force it to be delay-loaded. However, I get this when linking:
```
LINK : warning LNK4199: /DELAYLOAD:dwmapi.dll ignored; no imports found from dwmapi.dll
```
.. and it of course didn't change a thing when trying to load my DLL. For the heck of it, I added the whole tree of DLLs that lead to DWMAPI.DLL, and I get the same message. (For the record, it's foundation.dll->shell32.dll->shdocvw.dll->mshtml.dll->ieframe.dll->dwmapi.dll .)
To be more specific about what I'm doing, I am writing a Maya plugin and get the always-helpful text in the script editor:
```
// Error: Unable to dynamically load : D:/blahblahblah/mydll.mll
The specified module could not be found.
//
// Error: The operation completed successfully.
//
// Error: The operation completed successfully.
(mydll) //
```
I used Dependency Walker to initially track down the problem, and that's what lead me to DWMAPI.DLL. These are the message depends gives me, and DWMAPI.DLL is the only thing that has a yellow question mark next to it:
```
Warning: At least one delay-load dependency module was not found.
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
```
Gerald is right. Maya is, in fact, using a different PATH than the Dependency Walker. My plug-in loads another DLL (for image processing) that lives in the Maya plug-ins directory and depends found it with no problem, but Maya didn't. I had to add ";plug-ins" to the PATH in Maya.env.
Seeing as this problem wasn't related to DWMAPI.DLL after all, but DWMAPI is a common problem, I'll post the best link I found about the DWMAPI issue on Novell's website [here](http://www.novell.com/communities/node/4372/handling-dwmapidll-dependency). Basically, most programs will have this warning in depends.exe, but if there is a delay-load icon next to it, and you are sure that the program won't directly or indirectly call DWMAPI, then it's fine. The problem is elsewhere. If the delay-load icon isn't present, then you have to look at the /DELAY and /DELAYLOAD options in Visual Studio. The fact that depends gave me a "warning" and not an "error" was a clue to the fact that DWMAPI is not being loaded automatically.
|
Based on your updated problem, DWMAPI.dll is probably not your problem. Dependency walker will always give you that error whenever you are linking to mshtml as it always checks delay loaded DLLs.
At this point my best guess is that you have your project set to dynamically load the runtime libraries and the search path for DLLs is being changed by Maya. So it may be unable to find the MSVC runtime DLL(s). I haven't developed Maya plugins in a long time, but I've had that problem with other apps that have plugin DLLs recently.
Try changing your setting in C/C++->Code Generation->Runtime Library to Multi-Threaded rather than Multi-Threaded DLL.
Aside from that you can try fiddling with Dependency Walker to make it use the same search paths as Maya and see if you can come up with another dependency problem.
As a last resort you can launch Maya in a debugger and set a breakpoint on LoadLibrary and find out which library is not being loaded that way.
|
173,473 |
<p>I have a generated HTML page with flash content in it. I am trying to reposition the flash content and make it "absolute". I have tried to wrap the object tags with a div tag, but to no avail. Can anyone tell me how to do this? Removing the generated positioning attributes does not work. </p>
<p>See relevant code below (it is not very neat, but this is how it is generated. I have removed most irrelevant code): </p>
<pre><code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>* welcome *</title>
<script language="javascript">AC_FL_RunContent = 0;</script>
<script src="AC_RunActiveContent.js" language="javascript"></script>
</head>
<body bgcolor="#000000">
<script language="javascript">
if (AC_FL_RunContent == 0) {
alert("This page requires AC_RunActiveContent.js.");
} else {
AC_FL_RunContent(
'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
'width', '430',
'height', '200',
'src', 'bar',
'quality', 'high',
'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
'align', 'right',
'play', 'true',
'loop', 'true',
'scale', 'showall',
'wmode', 'transparent',
'devicefont', 'false',
'id', 'bar',
'bgcolor', '#000000',
'name', 'bar',
'menu', 'true',
'allowFullScreen', 'false',
'allowScriptAccess','sameDomain',
'movie', 'bar',
'salign', ''
); //end AC code
}
</script>
<noscript>
<div style = "position: absolute">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="430" height="200" id="bar" align="right">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="false" />
<param name="movie" value="bar.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#000000" />
</object>
</div>
</noscript>
</code></pre>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 173507,
"author": "Fuzzy76",
"author_id": 15932,
"author_profile": "https://Stackoverflow.com/users/15932",
"pm_score": 2,
"selected": false,
"text": "<p>Since your div is wrapped in noscript it will only be shown if javascript is turned off, are you sure that is the behaviour you want?</p>\n"
},
{
"answer_id": 173514,
"author": "epeleg",
"author_id": 25412,
"author_profile": "https://Stackoverflow.com/users/25412",
"pm_score": 3,
"selected": true,
"text": "<p>you should place the JS script that actually creates you object inside your div not before it.</p>\n"
},
{
"answer_id": 173530,
"author": "Errico Malatesta",
"author_id": 24439,
"author_profile": "https://Stackoverflow.com/users/24439",
"pm_score": 1,
"selected": false,
"text": "<p>@Fuzzy76 & @epeleg.blogspot.com is right</p>\n\n<p>@pypmanetjies -> Your code must be like this (shortened):</p>\n\n<pre><code> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n <title>* welcome *</title>\n <script language=\"javascript\">AC_FL_RunContent = 0;</script>\n <script src=\"AC_RunActiveContent.js\" language=\"javascript\"></script>\n </head>\n <body bgcolor=\"#000000\">\n<div style = \"position: absolute\">\n <script language=\"javascript\">\n if (AC_FL_RunContent == 0) {\n alert(\"This page requires AC_RunActiveContent.js.\");\n } else {\n AC_FL_RunContent(\n...\n); //end AC code\n }\n </script>\n <noscript>\n <object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"430\" height=\"200\" id=\"bar\" align=\"right\">\n <param name=\"allowScriptAccess\" value=\"sameDomain\" />\n <param name=\"allowFullScreen\" value=\"false\" />\n <param name=\"movie\" value=\"bar.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"wmode\" value=\"transparent\" /><param name=\"bgcolor\" value=\"#000000\" />\n </object>\n\n </noscript> \n</div>\n</code></pre>\n"
},
{
"answer_id": 173799,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 1,
"selected": false,
"text": "<p>You might have to set a width and height on your as well.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25280/"
] |
I have a generated HTML page with flash content in it. I am trying to reposition the flash content and make it "absolute". I have tried to wrap the object tags with a div tag, but to no avail. Can anyone tell me how to do this? Removing the generated positioning attributes does not work.
See relevant code below (it is not very neat, but this is how it is generated. I have removed most irrelevant code):
```
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>* welcome *</title>
<script language="javascript">AC_FL_RunContent = 0;</script>
<script src="AC_RunActiveContent.js" language="javascript"></script>
</head>
<body bgcolor="#000000">
<script language="javascript">
if (AC_FL_RunContent == 0) {
alert("This page requires AC_RunActiveContent.js.");
} else {
AC_FL_RunContent(
'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
'width', '430',
'height', '200',
'src', 'bar',
'quality', 'high',
'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
'align', 'right',
'play', 'true',
'loop', 'true',
'scale', 'showall',
'wmode', 'transparent',
'devicefont', 'false',
'id', 'bar',
'bgcolor', '#000000',
'name', 'bar',
'menu', 'true',
'allowFullScreen', 'false',
'allowScriptAccess','sameDomain',
'movie', 'bar',
'salign', ''
); //end AC code
}
</script>
<noscript>
<div style = "position: absolute">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="430" height="200" id="bar" align="right">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="false" />
<param name="movie" value="bar.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#000000" />
</object>
</div>
</noscript>
```
Thanks in advance!
|
you should place the JS script that actually creates you object inside your div not before it.
|
173,487 |
<h1> 1st phase</h1>
<p>I have a problem shutting down my running JBoss instance under Eclipse since I changed
the JNDI port of JBoss. Of course I can shut it down from the console view but not with
the stop button (it still searches JNDI port at the default 1099 port). I'm looking
forward to any solutions. Thank you! </p>
<h2>Used environment:</h2>
<ul>
<li>JBoss 4.0.2 (using <em>default</em>)</li>
<li>Eclipse 3.4.0. (using JBoss Tools 2.1.1.GA)</li>
</ul>
<p>Default ports: 1098, 1099
Changed ports: 11098, 11099</p>
<p>I changed the following part in jbosspath/server/default/conf/jboss-service.xml:</p>
<pre><code> <!-- ==================================================================== -->
<!-- JNDI -->
<!-- ==================================================================== -->
<mbean code="org.jboss.naming.NamingService"
name="jboss:service=Naming"
xmbean-dd="resource:xmdesc/NamingService-xmbean.xml">
<!-- The call by value mode. true if all lookups are unmarshalled using
the caller's TCL, false if in VM lookups return the value by reference.
-->
<attribute name="CallByValue">false</attribute>
<!-- The listening port for the bootstrap JNP service. Set this to -1
to run the NamingService without the JNP invoker listening port.
-->
<attribute name="Port">11099</attribute>
<!-- The bootstrap JNP server bind address. This also sets the default
RMI service bind address. Empty == all addresses
-->
<attribute name="BindAddress">${jboss.bind.address}</attribute>
<!-- The port of the RMI naming service, 0 == anonymous -->
<attribute name="RmiPort">11098</attribute>
<!-- The RMI service bind address. Empty == all addresses
-->
<attribute name="RmiBindAddress">${jboss.bind.address}</attribute>
<!-- The thread pool service used to control the bootstrap lookups -->
<depends optional-attribute-name="LookupPool"
proxy-type="attribute">jboss.system:service=ThreadPool</depends>
</mbean>
<mbean code="org.jboss.naming.JNDIView"
name="jboss:service=JNDIView"
xmbean-dd="resource:xmdesc/JNDIView-xmbean.xml">
</mbean>
</code></pre>
<h2>Eclipse setup:</h2>
<p><img src="https://i.stack.imgur.com/nOlhy.png" width="500" title="jndi port to 11099" /></p>
<p><em>About my JBoss Tools preferences:</em>
I had a previous version, I got this problem, I read about some bugfix in JbossTools, so updated to 2.1.1.GA. Now the buttons changed, and I've got a new preferences view, but I cannot modify anything...seems to be abnormal as well:</p>
<p><img src="https://i.stack.imgur.com/Ocfcf.png" width="620" /></p>
<h2>Error dialog:</h2>
<p><img src="https://i.stack.imgur.com/uPPZ7.png" width="300" title="can't reach server" /></p>
<h2>The stacktrace:</h2>
<pre><code>javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]]
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1385)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:579)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:572)
at javax.naming.InitialContext.lookup(InitialContext.java:347)
at org.jboss.Shutdown.main(Shutdown.java:202)
Caused by: javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:254)
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1370)
... 4 more
Caused by: javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:228)
... 5 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
at java.net.Socket.connect(Socket.java:452)
at java.net.Socket.connect(Socket.java:402)
at java.net.Socket.<init>(Socket.java:309)
at java.net.Socket.<init>(Socket.java:211)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:69)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:62)
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:224)
... 5 more
Exception in thread "main"
</code></pre>
<h1> 2nd phase:</h1>
<p>After creating a new Server in File/new/other/server, it did appear in the preferences tab. Now the stop button is working (the server receives the shutdown messages without any additional modification of the jndi port -- there is no opportunity for it now) but it still throws an error message, though different, it's without exception stack trace: "Server JBoss 4.0 Server failed to stop."</p>
|
[
{
"answer_id": 173543,
"author": "huo73",
"author_id": 15657,
"author_profile": "https://Stackoverflow.com/users/15657",
"pm_score": 0,
"selected": false,
"text": "<p>In MyEclipse server configuration, you find the field \"Optional Shutdown Argument\", which is filled with the default value </p>\n\n<pre><code>--shutdown\n</code></pre>\n\n<p>Change it to </p>\n\n<pre><code>-s jnp://localhost:11099 --shutdown\n</code></pre>\n\n<p>Edited:</p>\n\n<p>Sorry, this answer is related to MyEclipse. However, there must be some place where you can specify the JBoss shutdown command in your environment as well.\nMaybe you take a look at the \"Run...\" configurations?</p>\n"
},
{
"answer_id": 173939,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": true,
"text": "<p>OK, what you have to do is File->New->Other->Server, and set up your JBoss server there. It will then appear in Preferences->JBossTools->Servers.</p>\n\n<p>Convoluted.</p>\n"
},
{
"answer_id": 783547,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>you should modify in the file \"/home/fmoisa/workspace/eclipse/plugins/org.eclipse.jst.server.generic.jboss_1.5.206.v20090115/servers/jboss42.serverdef\" this:</p>\n\n<p>\n org.jboss.Shutdown\n ${serverRootDirectory}/bin\n -S\n -Djboss.boot.loader.name=shutdown.bat\n jboss.shutdown\n </p>\n\n<p>to this:</p>\n\n<p>\n org.jboss.Shutdown\n ${serverRootDirectory}/bin\n -S -sjnp://localhost:11099\n -Djboss.boot.loader.name=shutdown.bat\n jboss.shutdown\n </p>\n\n<p>gl all ;)</p>\n"
},
{
"answer_id": 874281,
"author": "Max Rydahl Andersen",
"author_id": 71208,
"author_profile": "https://Stackoverflow.com/users/71208",
"pm_score": 0,
"selected": false,
"text": "<p>Use the server adapter provided by JBoss tools and not the one that comes default from Eclipse WTP.</p>\n\n<p>Then you can simply double click on the server and you can edit the JNDI port (which btw. is automatically picked up from the XML configuration if you don't do any thing). You can also do the trick about setting the JNDI port via command line arguments in the Launch Configuration but that is more trouble than just setting the port values.</p>\n"
},
{
"answer_id": 1512563,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a detailed fix for this problem:\nThe Eclipse WTP server connector won't shut down JBoss when the jndi port is remapped.</p>\n\n<p>This is because the default server connector profiles don't use their own alias for the jndiPort. This problem is also discussed at eclipse.org:\n<a href=\"http://www.eclipse.org/forums/index.php?t=msg&goto=489439&S=0db4920aab0a501c80a626edff84c17d#msg_489439\" rel=\"nofollow noreferrer\">http://www.eclipse.org/forums/index.php?t=msg&goto=489439&S=0db4920aab0a501c80a626edff84c17d#msg_489439</a></p>\n\n<p>The solution comes from the .serverdef files in eclipse:</p>\n\n<pre><code>\n<eclipse>\\plugins\\org.eclipse.jst.server.generic.jboss_1.5.105.v200709061325\\servers\\jboss*.serverdef\n</code></pre>\n\n<p>They declare an xml property for the jndi port: </p>\n\n<pre><code>\n<property id=\"jndiPort\"\n label=\"%jndiPort\"\n type=\"string\"\n context=\"server\"\n default=\"1099\" /> \n</code></pre>\n\n<p>This simply needs to be used where the serverdef has the STOP command coded:</p>\n\n<p>So this:</p>\n\n<pre><code>\n <stop>\n <mainClass>org.jboss.Shutdown</mainClass>\n <workingDirectory>${serverRootDirectory}/bin</workingDirectory>\n <programArguments>-S</programArguments>\n <vmParameters></vmParameters>\n <classpathReference>jboss</classpathReference>\n </stop>\n</code></pre>\n\n<p>becomes this:</p>\n\n<pre><code>\n <stop>\n <mainClass>org.jboss.Shutdown</mainClass>\n <workingDirectory>${serverRootDirectory}/bin</workingDirectory>\n <programArguments>-s jnp://${serverAddress}:${jndiPort}</programArguments>\n <vmParameters></vmParameters>\n <classpathReference>jboss</classpathReference>\n </stop>\n</code></pre>\n\n<p>The philosophy for this can be verified by comparison to the definition for the jndi connection:</p>\n\n<pre><code>\n <jndiConnection>\n <providerUrl>jnp://${serverAddress}:${jndiPort}</providerUrl>\n<initialContextFactory>org.jnp.interfaces.NamingContextFactory</initialContextFactory>\n <jndiProperty>\n <name></name>\n <value></value>\n </jndiProperty>\n </jndiConnection>\n</code></pre>\n\n<p>Credit for the inspiration for this general case fix goes to: Moisa Laurentiu Florin. It was their contribution that got me to look for a way of substituting in the ${jndiPort} instead of a hard coded value.</p>\n\n<p>This fix corrects both plain Eclipse WTP server connector. I'm still investigating the JBOss IDE connector</p>\n"
},
{
"answer_id": 3021497,
"author": "Wolfgang",
"author_id": 364379,
"author_profile": "https://Stackoverflow.com/users/364379",
"pm_score": 0,
"selected": false,
"text": "<p>This was changed in JBoss 6.0.0M3.</p>\n\n<p>The stop command is now:</p>\n\n<blockquote>\n <p>\"- s service:jmx:rmi:///jndi/rmi://localhost:1090/jmxrmi\"</p>\n</blockquote>\n\n<p>Note that the port also changed: <strong>It is no longer the JNDI port at 1099</strong>, but <strong>RMI/JMX port 1090</strong>. So, you will need another config parameter in the server definition.</p>\n\n<p>I don't know whether the \"JNDI port\" parameter is required at all for JBoss 6.0.0M3 servers.</p>\n\n<p>I have a modified eclipse plugin at <a href=\"http://www.cs.hs-rm.de/~knauf/public/\" rel=\"nofollow noreferrer\">http://www.cs.hs-rm.de/~knauf/public/</a> which contains a server definition for 6.0.0M3 including this change. This site also links to a JBoss forum thread with more details about this change.</p>\n\n<p>Best regards</p>\n\n<p>Wolfgang Knauf</p>\n"
},
{
"answer_id": 4783491,
"author": "Martín Sánchez",
"author_id": 587668,
"author_profile": "https://Stackoverflow.com/users/587668",
"pm_score": 2,
"selected": false,
"text": "<p>Open jboss-path\\bin\\shutdown.jar</p>\n\n<p>example: jboss-4.2.3.GA\\bin\\shutdown.jar</p>\n\n<p>and open jboss-path\\bin\\shutdown.jar\\jndi.properties</p>\n\n<p>and change</p>\n\n<p>java.naming.provider.url=jnp://localhost:1099 to java.naming.provider.url=jnp://localhost:11099</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19621/"
] |
1st phase
==========
I have a problem shutting down my running JBoss instance under Eclipse since I changed
the JNDI port of JBoss. Of course I can shut it down from the console view but not with
the stop button (it still searches JNDI port at the default 1099 port). I'm looking
forward to any solutions. Thank you!
Used environment:
-----------------
* JBoss 4.0.2 (using *default*)
* Eclipse 3.4.0. (using JBoss Tools 2.1.1.GA)
Default ports: 1098, 1099
Changed ports: 11098, 11099
I changed the following part in jbosspath/server/default/conf/jboss-service.xml:
```
<!-- ==================================================================== -->
<!-- JNDI -->
<!-- ==================================================================== -->
<mbean code="org.jboss.naming.NamingService"
name="jboss:service=Naming"
xmbean-dd="resource:xmdesc/NamingService-xmbean.xml">
<!-- The call by value mode. true if all lookups are unmarshalled using
the caller's TCL, false if in VM lookups return the value by reference.
-->
<attribute name="CallByValue">false</attribute>
<!-- The listening port for the bootstrap JNP service. Set this to -1
to run the NamingService without the JNP invoker listening port.
-->
<attribute name="Port">11099</attribute>
<!-- The bootstrap JNP server bind address. This also sets the default
RMI service bind address. Empty == all addresses
-->
<attribute name="BindAddress">${jboss.bind.address}</attribute>
<!-- The port of the RMI naming service, 0 == anonymous -->
<attribute name="RmiPort">11098</attribute>
<!-- The RMI service bind address. Empty == all addresses
-->
<attribute name="RmiBindAddress">${jboss.bind.address}</attribute>
<!-- The thread pool service used to control the bootstrap lookups -->
<depends optional-attribute-name="LookupPool"
proxy-type="attribute">jboss.system:service=ThreadPool</depends>
</mbean>
<mbean code="org.jboss.naming.JNDIView"
name="jboss:service=JNDIView"
xmbean-dd="resource:xmdesc/JNDIView-xmbean.xml">
</mbean>
```
Eclipse setup:
--------------

*About my JBoss Tools preferences:*
I had a previous version, I got this problem, I read about some bugfix in JbossTools, so updated to 2.1.1.GA. Now the buttons changed, and I've got a new preferences view, but I cannot modify anything...seems to be abnormal as well:

Error dialog:
-------------

The stacktrace:
---------------
```
javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]]
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1385)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:579)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:572)
at javax.naming.InitialContext.lookup(InitialContext.java:347)
at org.jboss.Shutdown.main(Shutdown.java:202)
Caused by: javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:254)
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1370)
... 4 more
Caused by: javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:228)
... 5 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
at java.net.Socket.connect(Socket.java:452)
at java.net.Socket.connect(Socket.java:402)
at java.net.Socket.<init>(Socket.java:309)
at java.net.Socket.<init>(Socket.java:211)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:69)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:62)
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:224)
... 5 more
Exception in thread "main"
```
2nd phase:
===========
After creating a new Server in File/new/other/server, it did appear in the preferences tab. Now the stop button is working (the server receives the shutdown messages without any additional modification of the jndi port -- there is no opportunity for it now) but it still throws an error message, though different, it's without exception stack trace: "Server JBoss 4.0 Server failed to stop."
|
OK, what you have to do is File->New->Other->Server, and set up your JBoss server there. It will then appear in Preferences->JBossTools->Servers.
Convoluted.
|
173,498 |
<p>I am trying to take a rather large CSV file and insert it into a MySQL database for referencing in a project. I would like to use the first line of the file to create the table using proper data types and not varchar for each column. The ultimate goal is to automate this process as I have several similar files but the each has different data and a different amount of "columns" in CSV files. The problem that I am having is gettype() is returning 'string' for each column instead of int, float and string as I would like it to.</p>
<p>Platform is PHP 5, OS is ubuntu 8.04</p>
<p>here is my code so far:</p>
<pre><code><?php
// GENERATE TABLE FROM FIRST LINE OF CSV FILE
$inputFile = 'file.csv';
$tableName = 'file_csv';
$fh = fopen($inputFile, 'r');
$contents = fread($fh, 5120); // 5KB
fclose($fh);
$fileLines = explode("\n", $contents); // explode to make sure we are only using the first line.
$fieldList = explode(',', $fileLines[0]); // separate columns, put into array
echo 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` ('."<br/>\n";
for($i = 0; $i <= count($fieldList); $i++)
{
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
echo ' PRIMARY KEY (`0`)'."<br/>\n";
echo ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;';
</code></pre>
<p>Example First line:
1,0,0,0,0,0,0,0,0,0,0,0,0.000000,0.000000,0,0,0,,0,0,1,0,50,'Word of Recall (OLD)',</p>
|
[
{
"answer_id": 173526,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 2,
"selected": false,
"text": "<p>Try casting the value and comparing it with the original one:</p>\n\n<pre><code>define('DECIMAL_SEPARATOR', '.');\n\nswitch ($fieldList[$i])\n{\n case (string)(int)$fieldList[$i]:\n $typeInfo = (strpos($fieldList[$i], DECIMAL_SEPARATOR) === false) ? 'int(11)' : 'float';\n break;\n case (string)(float)$fieldList[$i]:\n $typeInfo = 'float';\n break;\n default:\n $typeInfo = 'varchar(80)';\n break;\n}\n</code></pre>\n\n<p>Additionaly, check for the presence of decimal separator in the first case for numbers that are round, yet they have the decimal fraction part.</p>\n"
},
{
"answer_id": 173586,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 3,
"selected": true,
"text": "<p>Building on <a href=\"https://stackoverflow.com/questions/173498/using-php-to-take-the-first-line-of-a-csv-file-and-create-a-mysql-table-with-th#173526\">Nouveau</a>'s code you could do this</p>\n\n<pre><code>for($i = 0; $i <= count($fieldList); $i++)\n{\n if (is_numeric($fieldList[$i]))\n {\n if (strpos($fieldList[$i],'.') !== false){\n $fieldList[$i] = (int)$fieldList[$i];\n }else{\n $fieldList[$i] = (float)$fieldList[$i];\n }\n }\n\n switch(gettype($fieldList[$i])) {\n case 'integer':\n $typeInfo = 'int(11)';\n break;\n case 'float':\n case 'double':\n $typeInfo = 'float';\n break;\n\n case 'string':\n $typeInfo = 'varchar(80)';\n break;\n default:\n $typeInfo = 'varchar(80)';\n break;\n }\nif(gettype($fieldList[$i]) != NULL) echo \"\\t\".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i].\"<br/>\\n\";\n\n}\n</code></pre>\n\n<p>That works, note the addition of \"case 'double':\" in the switch, but there may be a better way to do the int/float check as they would only work with standard uk/us numbers.</p>\n"
},
{
"answer_id": 173597,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 1,
"selected": false,
"text": "<p>Using regular expressions will give you a flexible solution. If you need to detect date fields then this is the way to go.</p>\n"
},
{
"answer_id": 173601,
"author": "Jayrox",
"author_id": 24802,
"author_profile": "https://Stackoverflow.com/users/24802",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n\n// GENERATE TABLE FROM FIRST LINE OF CSV FILE\n\n$inputFile = 'file.csv';\n$tableName = 'file_csv';\n\n$fh = fopen($inputFile, 'r');\n $contents = fread($fh, 5120); // 5KB\nfclose($fh);\n\n$fileLines = explode(\"\\n\", $contents);\n\n$fieldList = explode(',', $fileLines[0]);\necho 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` ('.\"<br/>\\n\";\nfor($i = 0; $i <= count($fieldList); $i++)\n{\n\n if(strlen($fieldList[$i]) == 0) $typeInfo = 'varchar(80)';\n if(preg_match('/[0-9]/', $fieldList[$i])) $typeInfo = 'int(11)';\n if(preg_match('/[\\.]/', $fieldList[$i])) $typeInfo = 'float';\n if(preg_match('/[a-z\\\\\\']/i', $fieldList[$i])) $typeInfo = 'varchar(80)';\n\n echo \"\\t\".'`'.$i.'` '.$typeInfo.' NOT NULL, -- '.gettype($fieldList[$i]).' '.$fieldList[$i].\"<br/>\\n\";\n}\necho ' PRIMARY KEY (`0`)'.\"<br/>\\n\";\necho ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;';\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24802/"
] |
I am trying to take a rather large CSV file and insert it into a MySQL database for referencing in a project. I would like to use the first line of the file to create the table using proper data types and not varchar for each column. The ultimate goal is to automate this process as I have several similar files but the each has different data and a different amount of "columns" in CSV files. The problem that I am having is gettype() is returning 'string' for each column instead of int, float and string as I would like it to.
Platform is PHP 5, OS is ubuntu 8.04
here is my code so far:
```
<?php
// GENERATE TABLE FROM FIRST LINE OF CSV FILE
$inputFile = 'file.csv';
$tableName = 'file_csv';
$fh = fopen($inputFile, 'r');
$contents = fread($fh, 5120); // 5KB
fclose($fh);
$fileLines = explode("\n", $contents); // explode to make sure we are only using the first line.
$fieldList = explode(',', $fileLines[0]); // separate columns, put into array
echo 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` ('."<br/>\n";
for($i = 0; $i <= count($fieldList); $i++)
{
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
echo ' PRIMARY KEY (`0`)'."<br/>\n";
echo ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;';
```
Example First line:
1,0,0,0,0,0,0,0,0,0,0,0,0.000000,0.000000,0,0,0,,0,0,1,0,50,'Word of Recall (OLD)',
|
Building on [Nouveau](https://stackoverflow.com/questions/173498/using-php-to-take-the-first-line-of-a-csv-file-and-create-a-mysql-table-with-th#173526)'s code you could do this
```
for($i = 0; $i <= count($fieldList); $i++)
{
if (is_numeric($fieldList[$i]))
{
if (strpos($fieldList[$i],'.') !== false){
$fieldList[$i] = (int)$fieldList[$i];
}else{
$fieldList[$i] = (float)$fieldList[$i];
}
}
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
case 'double':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
```
That works, note the addition of "case 'double':" in the switch, but there may be a better way to do the int/float check as they would only work with standard uk/us numbers.
|
173,503 |
<p>I've got a "little" problem with Zend Framework Zend_Pdf class. Multibyte characters are stripped from generated pdf files. E.g. when I write aąbcčdeę it becomes abcd with lithuanian letters stripped.</p>
<p>I'm not sure if it's particularly Zend_Pdf problem or php in general. </p>
<p>Source text is encoded in utf-8, as well as the php source file which does the job.</p>
<p>Thank you in advance for your help ;)</p>
<p>P.S. I run Zend Framework v. 1.6 and I use FONT_TIMES_BOLD font. FONT_TIMES_ROMAN does work</p>
|
[
{
"answer_id": 173964,
"author": "leek",
"author_id": 3765,
"author_profile": "https://Stackoverflow.com/users/3765",
"pm_score": 1,
"selected": false,
"text": "<p>I believe Zend_Pdf got UTF-8 support in 1.5 - What version of Zend Framework are you running?</p>\n\n<p>Also - what font are you trying to render with? Have you tried alternate fonts?</p>\n"
},
{
"answer_id": 177445,
"author": "Sejanus",
"author_id": 25413,
"author_profile": "https://Stackoverflow.com/users/25413",
"pm_score": 0,
"selected": false,
"text": "<p>ZF v. 1.6, TIMES_BOLD (as I understand thats the only way to make text bold?)</p>\n"
},
{
"answer_id": 185651,
"author": "leek",
"author_id": 3765,
"author_profile": "https://Stackoverflow.com/users/3765",
"pm_score": 1,
"selected": false,
"text": "<p>Have you made sure that you are setting the character encoding as this example from the manual?</p>\n\n<pre><code>// Draw the string on the page\n$pdfPage->drawText($unicodeString, 72, 720, 'UTF-8');\n</code></pre>\n\n<p>If you're stuck into having to use a <strong>bold</strong> font, maybe try one of the other bold fonts?</p>\n\n<pre><code>Zend_Pdf_Font::FONT_COURIER_BOLD\nZend_Pdf_Font::FONT_TIMES_BOLD\nZend_Pdf_Font::FONT_HELVETICA_BOLD\n</code></pre>\n"
},
{
"answer_id": 240749,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "<p><code>Zend_Pdf</code> supports UTF-8 in version 1.5 of Zend Framework. However, the standard PDF fonts support only the Latin1 character set. This means you can't use <code>Zend_Pdf_Font::FONT_TIMES_BOLD</code> or any other \"built-in\" font. To use special characters you must load another TTF font that includes characters from other character sets. </p>\n\n<p>I use Mac OS X, so I tried the following code and it produces a PDF document with the correct characters.</p>\n\n<pre><code>$pdfDoc = new Zend_Pdf();\n$pdfPage = $pdfDoc->newPage(Zend_Pdf_Page::SIZE_LETTER);\n\n// load TTF font from Mac system library\n$font = Zend_Pdf_Font::fontWithPath('/Library/Fonts/Times New Roman Bold.ttf');\n$pdfPage->setFont($font, 36);\n\n$unicodeString = 'aąbcčdeę';\n$pdfPage->drawText($unicodeString, 72, 720, 'UTF-8');\n\n$pdfDoc->pages[] = $pdfPage;\n$pdfDoc->save('utf8.pdf');\n</code></pre>\n\n<p>See also this bug log: <a href=\"http://framework.zend.com/issues/browse/ZF-3649\" rel=\"noreferrer\">http://framework.zend.com/issues/browse/ZF-3649</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25413/"
] |
I've got a "little" problem with Zend Framework Zend\_Pdf class. Multibyte characters are stripped from generated pdf files. E.g. when I write aąbcčdeę it becomes abcd with lithuanian letters stripped.
I'm not sure if it's particularly Zend\_Pdf problem or php in general.
Source text is encoded in utf-8, as well as the php source file which does the job.
Thank you in advance for your help ;)
P.S. I run Zend Framework v. 1.6 and I use FONT\_TIMES\_BOLD font. FONT\_TIMES\_ROMAN does work
|
`Zend_Pdf` supports UTF-8 in version 1.5 of Zend Framework. However, the standard PDF fonts support only the Latin1 character set. This means you can't use `Zend_Pdf_Font::FONT_TIMES_BOLD` or any other "built-in" font. To use special characters you must load another TTF font that includes characters from other character sets.
I use Mac OS X, so I tried the following code and it produces a PDF document with the correct characters.
```
$pdfDoc = new Zend_Pdf();
$pdfPage = $pdfDoc->newPage(Zend_Pdf_Page::SIZE_LETTER);
// load TTF font from Mac system library
$font = Zend_Pdf_Font::fontWithPath('/Library/Fonts/Times New Roman Bold.ttf');
$pdfPage->setFont($font, 36);
$unicodeString = 'aąbcčdeę';
$pdfPage->drawText($unicodeString, 72, 720, 'UTF-8');
$pdfDoc->pages[] = $pdfPage;
$pdfDoc->save('utf8.pdf');
```
See also this bug log: <http://framework.zend.com/issues/browse/ZF-3649>
|
173,527 |
<p>I have some old rrdtool databases, for which the exact creation recipe has long been since lost. I need to create a new database with the same characteristics as the current ones. I've dumped a couple of old databases and pored over the contents but I'm not sure how to interpret the metadata. I think it appears in the following stanzas</p>
<pre><code><cf> AVERAGE </cf>
<pdp_per_row> 360 </pdp_per_row> <!-- 1800 seconds -->
<xff> 5.0000000000e-01 </xff>
</code></pre>
<p>There are four such stanzas, which correspond to the way I recall the round-robin cascading was set up. Has anyone already done this, or can give me pointers as to how to clone a new empty rrd database from an existing one? Or show me where I missed this in the documentation.</p>
|
[
{
"answer_id": 173547,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 3,
"selected": true,
"text": "<p>rrdtools' <a href=\"http://oss.oetiker.ch/rrdtool/doc/rrdinfo.en.html\" rel=\"nofollow noreferrer\">rrdinfo</a> is your friend!</p>\n\n<p>It will tell you how the rrd file's data source(s) and archive(s) were created. Example</p>\n\n<pre><code>$ rrdtool info random.rrd\nfilename = \"random.rrd\"\nrrd_version = \"0001\"\nstep = 300\nlast_update = 955892996\nds[a].type = \"GAUGE\"\nds[a].minimal_heartbeat = 600\nds[a].min = NaN\nds[a].max = NaN\nds[a].last_ds = \"UNKN\"\nds[a].value = 2.1824421548e+04\nds[a].unknown_sec = 0\nds[b].type = \"GAUGE\"\nds[b].minimal_heartbeat = 600\nds[b].min = NaN\nds[b].max = NaN\nds[b].last_ds = \"UNKN\"\nds[b].value = 3.9620838224e+03\nds[b].unknown_sec = 0\nrra[0].cf = \"AVERAGE\"\nrra[0].pdp_per_row = 1\nrra[0].cdp_prep[0].value = nan\nrra[0].cdp_prep[0].unknown_datapoints = 0\nrra[0].cdp_prep[1].value = nan\nrra[0].cdp_prep[1].unknown_datapoints = 0\n</code></pre>\n"
},
{
"answer_id": 5152325,
"author": "Lmwangi",
"author_id": 458878,
"author_profile": "https://Stackoverflow.com/users/458878",
"pm_score": 2,
"selected": false,
"text": "<p>You can try use the clone script described <a href=\"http://code.google.com/p/python-rrd-schema-parse/source/browse/rrdinfo-parser.py\" rel=\"nofollow\">here.</a> It's very basic but it works for simple rrd files. I used it to figure out a schema that was generated by munin. I needed to insert old data into munin so I reverse engineered the schema, set the --start to a date prior to the start of my old data and re-imported data into the rrd. </p>\n\n<pre><code>$ python rrdinfo-parser.py -f test.rrd\nrrdtool create test.rrd --start 920804400 --step 300 \\\nDS:speed:COUNTER:600:U:U \\\nRRA:AVERAGE:0.5:1:24 \\\nRRA:AVERAGE:0.5:6:10 \\\n</code></pre>\n"
},
{
"answer_id": 46308646,
"author": "Javier Op",
"author_id": 6126786,
"author_profile": "https://Stackoverflow.com/users/6126786",
"pm_score": 3,
"selected": false,
"text": "<p>I use the command <a href=\"https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html\" rel=\"noreferrer\">rrdcreate</a>. It can create a new rrd based in an existing one. The -t parameter indicate a existing rrd as template.</p>\n\n<p>rrdcreate new.rrd -t existing.rrd</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18625/"
] |
I have some old rrdtool databases, for which the exact creation recipe has long been since lost. I need to create a new database with the same characteristics as the current ones. I've dumped a couple of old databases and pored over the contents but I'm not sure how to interpret the metadata. I think it appears in the following stanzas
```
<cf> AVERAGE </cf>
<pdp_per_row> 360 </pdp_per_row> <!-- 1800 seconds -->
<xff> 5.0000000000e-01 </xff>
```
There are four such stanzas, which correspond to the way I recall the round-robin cascading was set up. Has anyone already done this, or can give me pointers as to how to clone a new empty rrd database from an existing one? Or show me where I missed this in the documentation.
|
rrdtools' [rrdinfo](http://oss.oetiker.ch/rrdtool/doc/rrdinfo.en.html) is your friend!
It will tell you how the rrd file's data source(s) and archive(s) were created. Example
```
$ rrdtool info random.rrd
filename = "random.rrd"
rrd_version = "0001"
step = 300
last_update = 955892996
ds[a].type = "GAUGE"
ds[a].minimal_heartbeat = 600
ds[a].min = NaN
ds[a].max = NaN
ds[a].last_ds = "UNKN"
ds[a].value = 2.1824421548e+04
ds[a].unknown_sec = 0
ds[b].type = "GAUGE"
ds[b].minimal_heartbeat = 600
ds[b].min = NaN
ds[b].max = NaN
ds[b].last_ds = "UNKN"
ds[b].value = 3.9620838224e+03
ds[b].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].pdp_per_row = 1
rra[0].cdp_prep[0].value = nan
rra[0].cdp_prep[0].unknown_datapoints = 0
rra[0].cdp_prep[1].value = nan
rra[0].cdp_prep[1].unknown_datapoints = 0
```
|
173,579 |
<p>I am writing a very specialized app in C# that floats as a mostly transparent window over the entire desktop. I want to be able to create and pass mouse events to applications behind mine, and have them appear to operate "normally", responding to those events. It would also be preferable if the window manager could respond.</p>
<p>I am not a Windows guru, and am unsure of how to best accomplish this.</p>
<p>From this page:
<a href="http://bytes.com/forum/thread270002.html" rel="noreferrer">http://bytes.com/forum/thread270002.html</a></p>
<p>it would appear that mouse_event would be good, except that since my app is floating over everything else, I'm guessing my generated events would never make it to the other apps underneath.</p>
<p>It seems the alternative is SendMessage, but that requires a fair amount of manual manipulation of windows, and the mouse events generated aren't "authentic."</p>
<p>Any thoughts on the best way to approach this?</p>
|
[
{
"answer_id": 173602,
"author": "Fionn",
"author_id": 21566,
"author_profile": "https://Stackoverflow.com/users/21566",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like you want to do something like filtering user input.</p>\n\n<p>Maybe you just need an keyboard/mouse hook.</p>\n\n<p>You maybe want to take a look at the windows API call SetWindowsHookEx.</p>\n\n<p>There should also be enough samples how to do that in C# available, the first thing i found was <a href=\"http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx\" rel=\"nofollow noreferrer\">this link</a> (maybe not the best article but should give you the idea).</p>\n"
},
{
"answer_id": 173800,
"author": "Garth",
"author_id": 23407,
"author_profile": "https://Stackoverflow.com/users/23407",
"pm_score": 3,
"selected": true,
"text": "<p>After looking at System hooks and other low level solutions I found a much simpler method.</p>\n\n<p>First, set the TransparencyKey and BackColor of the form to be the same. This didn't make any visual difference to me as my form was visually transparent already, but this will help in letting mouse events through.</p>\n\n<p>Second, the following code will let mouse events \"fall\" through your form.</p>\n\n<pre><code>protected override CreateParams CreateParams\n{\n get\n {\n CreateParams createParams = base.CreateParams;\n createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT\n\n return createParams;\n }\n}\n</code></pre>\n\n<p>Lastly, set TopMost to be true.</p>\n\n<p>Your form will now float on top of everything visually, but will give up focus to all other apps.</p>\n"
},
{
"answer_id": 7095082,
"author": "Kevin Parker",
"author_id": 568508,
"author_profile": "https://Stackoverflow.com/users/568508",
"pm_score": 1,
"selected": false,
"text": "<p>If you disable the control and return you're able to pass the MouseDown event to the parent.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23407/"
] |
I am writing a very specialized app in C# that floats as a mostly transparent window over the entire desktop. I want to be able to create and pass mouse events to applications behind mine, and have them appear to operate "normally", responding to those events. It would also be preferable if the window manager could respond.
I am not a Windows guru, and am unsure of how to best accomplish this.
From this page:
<http://bytes.com/forum/thread270002.html>
it would appear that mouse\_event would be good, except that since my app is floating over everything else, I'm guessing my generated events would never make it to the other apps underneath.
It seems the alternative is SendMessage, but that requires a fair amount of manual manipulation of windows, and the mouse events generated aren't "authentic."
Any thoughts on the best way to approach this?
|
After looking at System hooks and other low level solutions I found a much simpler method.
First, set the TransparencyKey and BackColor of the form to be the same. This didn't make any visual difference to me as my form was visually transparent already, but this will help in letting mouse events through.
Second, the following code will let mouse events "fall" through your form.
```
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return createParams;
}
}
```
Lastly, set TopMost to be true.
Your form will now float on top of everything visually, but will give up focus to all other apps.
|
173,593 |
<p>I've tried to override WndProc, but no message show up on paste event.</p>
<p>Then I tried to create custom filter and using method PreFilterMessage I was able to catch message with value 257 (KEYUP event), but that's not enough...</p>
|
[
{
"answer_id": 173610,
"author": "Goran",
"author_id": 23164,
"author_profile": "https://Stackoverflow.com/users/23164",
"pm_score": 4,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code> protected override void OnKeyDown(KeyEventArgs e)\n {\n if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)\n {\n MessageBox.Show(\"Hello world\");\n }\n base.OnKeyDown(e);\n }\n</code></pre>\n\n<p>Make sure your form KeyPreview = true.</p>\n"
},
{
"answer_id": 173654,
"author": "Dan Cristoloveanu",
"author_id": 24873,
"author_profile": "https://Stackoverflow.com/users/24873",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this by:</p>\n<ul>\n<li>Intercepting the <kbd>Ctrl</kbd>+<kbd>V</kbd> in KeyDown (or KeyUp) of your form</li>\n<li>Creating a menu in your form that contains a Paste option that has the <kbd>Ctrl</kbd>+<kbd>V</kbd> shortcut (this would maybe be better since you will have users looking for the options)</li>\n<li>Intercepting the KEYDOWN message like you described in the question and checking whether <kbd>Ctrl</kbd> is pressed at that time (I think this is the hardest of all 3).</li>\n</ul>\n<p>Personally I would go for using a menu option.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've tried to override WndProc, but no message show up on paste event.
Then I tried to create custom filter and using method PreFilterMessage I was able to catch message with value 257 (KEYUP event), but that's not enough...
|
Use:
```
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
MessageBox.Show("Hello world");
}
base.OnKeyDown(e);
}
```
Make sure your form KeyPreview = true.
|
173,617 |
<p>I read that you could call JavaScript code from a Java Applet by calling</p>
<pre><code>JApplet.getAppletContext().showDocument( "javascript:alert('Hello World');" );
</code></pre>
<p>However, when I do this i get the following error:</p>
<pre><code>java.net.MalformedURLException: unknown protocol: javascript
</code></pre>
<p>How do I work around this?</p>
|
[
{
"answer_id": 173743,
"author": "RuntimeException",
"author_id": 15789,
"author_profile": "https://Stackoverflow.com/users/15789",
"pm_score": 2,
"selected": false,
"text": "<pre><code> try {\n this.getAppletContext().showDocument(new URL(\"javascript:alert('hello world');\"));\n }catch(Exception e) {\n e.printStackTrace();\n }\n</code></pre>\n\n<p>Works !! </p>\n\n<p>Maybe the browser does not have javascript enabled.. just a guess</p>\n"
},
{
"answer_id": 204531,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>I get the same exception as you do because of that the URL class does not accept javascript: as a valid protocol.</p>\n\n<p>There is a workaround though; supply an URLStreamHandler to the URL constructor.</p>\n\n<p>Example:</p>\n\n<pre><code>final URLStreamHandler streamHandler = new URLStreamHandler() {\n\n @Override\n protected URLConnection openConnection(URL u)\n throws IOException {\n return null;\n }\n\n};\n\ntry {\n getAppletContext().showDocument(\n new URL(null, \"javascript:alert('It works!');\", streamHandler));\n} catch (MalformedURLException me) {\n //log or whatever\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20298/"
] |
I read that you could call JavaScript code from a Java Applet by calling
```
JApplet.getAppletContext().showDocument( "javascript:alert('Hello World');" );
```
However, when I do this i get the following error:
```
java.net.MalformedURLException: unknown protocol: javascript
```
How do I work around this?
|
I get the same exception as you do because of that the URL class does not accept javascript: as a valid protocol.
There is a workaround though; supply an URLStreamHandler to the URL constructor.
Example:
```
final URLStreamHandler streamHandler = new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u)
throws IOException {
return null;
}
};
try {
getAppletContext().showDocument(
new URL(null, "javascript:alert('It works!');", streamHandler));
} catch (MalformedURLException me) {
//log or whatever
}
```
|
173,618 |
<p>In MSVC, <a href="http://msdn.microsoft.com/en-us/library/ms679297.aspx" rel="noreferrer">DebugBreak()</a> or <a href="http://msdn.microsoft.com/fr-fr/library/f408b4et.aspx" rel="noreferrer">__debugbreak</a> cause a debugger to break. On x86 it is equivalent to writing "_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the <a href="https://stackoverflow.com/questions/37299/xcode-equivalent-of-asm-int-3-debugbreak-halt">XCode question</a> about that, but it doesn't seem portable enough.</p>
<p>Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG_BREAK or something into the code.</p>
|
[
{
"answer_id": 173630,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": true,
"text": "<p>What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.</p>\n\n<p>Something like:</p>\n\n<pre><code>#ifdef _MSC_VER\n#define DEBUG_BREAK __debugbreak()\n#else\n...\n#endif\n</code></pre>\n\n<p>This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use <code>DEBUG_BREAK</code> in your code.</p>\n"
},
{
"answer_id": 173656,
"author": "Hasturkun",
"author_id": 20270,
"author_profile": "https://Stackoverflow.com/users/20270",
"pm_score": 4,
"selected": false,
"text": "<p>GCC has a builtin function named <code>__builtin_trap</code> which you can see <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005ftrap-2760\" rel=\"noreferrer\">here</a>, however it is assumed that code execution halts once this is reached.</p>\n\n<p>you <em>should</em> ensure that the <code>__builtin_trap()</code> call is conditional, otherwise no code will be emitted after it.</p>\n\n<p>this post fueled by all of 5 minutes of testing, YMMV.</p>\n"
},
{
"answer_id": 173660,
"author": "QAZ",
"author_id": 14260,
"author_profile": "https://Stackoverflow.com/users/14260",
"pm_score": -1,
"selected": false,
"text": "<p>Instead of using 'normal' debug breaks, why not use one of the following, like a divide by zero:</p>\n\n<pre><code>int iCrash = 13 / 0;\n</code></pre>\n\n<p>or dereference a NULL pointer:</p>\n\n<pre><code>BYTE bCrash = *(BYTE *)(NULL);\n</code></pre>\n\n<p>At least this is portable accross many platforms/architectures.</p>\n\n<p>In many debuggers you can specify what action you want to perform on what exceptions so you can act accordingly when one of the above is hit (like pause execution, ala an \"int 3\" instruction) and an exception is generated.</p>\n"
},
{
"answer_id": 173925,
"author": "Suma",
"author_id": 16673,
"author_profile": "https://Stackoverflow.com/users/16673",
"pm_score": 2,
"selected": false,
"text": "<p>If you consider <code>assert(x)</code> portable enough, <code>assert(false)</code> seems to be the obvious portable solution to your problem.</p>\n"
},
{
"answer_id": 5561015,
"author": "caf",
"author_id": 134633,
"author_profile": "https://Stackoverflow.com/users/134633",
"pm_score": 6,
"selected": false,
"text": "<p>A method that is portable to most POSIX systems is:</p>\n\n<pre><code>raise(SIGTRAP);\n</code></pre>\n"
},
{
"answer_id": 19154316,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 4,
"selected": false,
"text": "<p>This looks like an appropriate compat library <a href=\"https://github.com/scottt/debugbreak\" rel=\"noreferrer\">https://github.com/scottt/debugbreak</a></p>\n"
},
{
"answer_id": 20792128,
"author": "johnwbyrd",
"author_id": 512923,
"author_profile": "https://Stackoverflow.com/users/512923",
"pm_score": -1,
"selected": false,
"text": "<p>If you are trying to debug a crash-related condition, good old fashioned abort() will give you a call stack on most platforms. Downside is that you can't continue from the current PC, which you probably don't want to do anyway.</p>\n\n<p><a href=\"http://www.cplusplus.com/reference/cstdlib/abort/\" rel=\"nofollow\">http://www.cplusplus.com/reference/cstdlib/abort/</a></p>\n"
},
{
"answer_id": 34074974,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>#define __debugbreak() \\\ndo \\\n{ static bool b; \\\n while (!b) \\\n sleep(1); \\\n b = false; \\\n} while (false)\n</code></pre>\n\n<p>When the process is sleeping, you can attach a debugger to the process, change the variable b to break the loop and do your thing. This code might not work in an optimized build!</p>\n"
},
{
"answer_id": 49079078,
"author": "nemequ",
"author_id": 501126,
"author_profile": "https://Stackoverflow.com/users/501126",
"pm_score": 5,
"selected": false,
"text": "<p>I just added <a href=\"https://github.com/nemequ/portable-snippets/tree/master/debug-trap\" rel=\"noreferrer\">a module</a> to <a href=\"https://github.com/nemequ/portable-snippets/\" rel=\"noreferrer\">portable-snippets</a> (a collection of public domain snippets of portable code) to do this. It's not 100% portable, but it should be pretty robust:</p>\n<ul>\n<li><code>__builtin_debugtrap</code> for some versions of clang (identified with <code>__has_builtin(__builtin_debugtrap)</code>)</li>\n<li>On MSVC and Intel C/C++ Compiler: <code>__debugbreak</code></li>\n<li>For ARM C/C++ Compiler: <code>__breakpoint(42)</code></li>\n<li>For x86/x86_64, assembly: <code>int3</code></li>\n<li>For ARM Thumb, assembly: <code>.inst 0xde01</code></li>\n<li>For ARM AArch64, assembly: <code>.inst 0xd4200000</code></li>\n<li>For other ARM, assembly: <code>.inst 0xe7f001f0</code></li>\n<li>For Alpha, assembly: <code>bpt</code></li>\n<li>For non-hosted C with GCC (or something which masquerades as it), <code>__builtin_trap</code></li>\n<li>Otherwise, include <code>signal.h</code> and\n<ul>\n<li>If <code>defined(SIGTRAP)</code> (i.e., POSIX), <code>raise(SIGTRAP)</code></li>\n<li>Otherwise, <code>raise(SIGABRT)</code></li>\n</ul>\n</li>\n</ul>\n<p>In the future the module in portable-snippets may expand to include other logic and I'll probably forget to update this answer, so you should look there for updates. It's public domain (CC0), so feel free to steal the code.</p>\n"
},
{
"answer_id": 57330958,
"author": "QwazyWabbit",
"author_id": 5538398,
"author_profile": "https://Stackoverflow.com/users/5538398",
"pm_score": 3,
"selected": false,
"text": "<p>This seems to be a very good, portable solution to this question:\n<a href=\"https://github.com/scottt/debugbreak\" rel=\"noreferrer\">https://github.com/scottt/debugbreak</a></p>\n\n<p>The header provided in the repository cited (debugbreak.h) encapsulates MSVC's</p>\n\n<pre><code> __debugbreak, \n</code></pre>\n\n<p>and </p>\n\n<pre><code> __asm__ volatile(\"int $0x03\");\n</code></pre>\n\n<p>on i386 and x86_64, and on ARM it implements</p>\n\n<pre><code> __asm__ volatile(\".inst 0xe7f001f0\");\n</code></pre>\n\n<p>as well as documenting some workarounds for problems noted in the header for single-stepping past the breakpoint in GDB plus a Python script for extending GDB on those platforms where <em>stepi</em> or <em>cont</em> get stuck. The script adds <strong>debugbreak-step</strong> and <strong>debugbreak-continue</strong> to GDB.</p>\n"
},
{
"answer_id": 67511652,
"author": "Heath Raftery",
"author_id": 3697870,
"author_profile": "https://Stackoverflow.com/users/3697870",
"pm_score": 0,
"selected": false,
"text": "<p>FWIW, none of these solutions worked on a nRF9160 using the NRF Connect SDK. That's a SEGGER Embedded Studio for ARM (Nordic Edition) environment, using the <code>arm-none-eabi-gcc</code> compiler.</p>\n<p>The <code>debug-trap.h</code>, <code>debugbreak.h</code> and <code>__builtin_trap()</code> mentioned in other answers all resulted in "undefined opcode" and a hard-fault (or a debug monitor fault, but the result is the same) and there no useful program counter, stack frame or other debuggable information.</p>\n<p>In the end, this alternate did work. I derived it from some other mysterious Nordic library, where it is referred to as <code>NRF_BREAKPOINT</code>:</p>\n<pre><code>#if defined(__GNUC__)\n __asm__("BKPT 0");\n#else\n __BKPT(0)\n#endif\n</code></pre>\n<p>At build time, it is the <code>__GNUC__</code> path which gets included, so <code>__asm__("BKPT 0")</code> is all that is required.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23740/"
] |
In MSVC, [DebugBreak()](http://msdn.microsoft.com/en-us/library/ms679297.aspx) or [\_\_debugbreak](http://msdn.microsoft.com/fr-fr/library/f408b4et.aspx) cause a debugger to break. On x86 it is equivalent to writing "\_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the [XCode question](https://stackoverflow.com/questions/37299/xcode-equivalent-of-asm-int-3-debugbreak-halt) about that, but it doesn't seem portable enough.
Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG\_BREAK or something into the code.
|
What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.
Something like:
```
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak()
#else
...
#endif
```
This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use `DEBUG_BREAK` in your code.
|
173,641 |
<p>I'm trying to use TestDriven.Net not only to test my code, but to call a function on my code whose purpose is to print out the internal state of the code to the Debug window.</p>
<p>Here's a very simplified example of what I'm trying to do..</p>
<pre><code><TestFixture()> _
Public Class UnitTest
<Test()> _
Public Sub TestDebug()
Dim oClass1 As New Class1
Assert.AreEqual(True, oClass1.IsTrue)
Debug.WriteLine("About to call .PrintDebug()")
oClass1.PrintToDebug()
End Sub
End Class
Public Class Class1
Private _IsTrue As Boolean = True
Public ReadOnly Property IsTrue() As Boolean
Get
Return _IsTrue
End Get
End Property
Public Sub PrintToDebug()
Debug.WriteLine("Internal state of Class1: " & _IsTrue)
End Sub
End Class
</code></pre>
<p>I'm trying to test the Public interface of Class1, and somehow view the output from the <code>Class1.PrintToDebug()</code> function.</p>
<p>I've looked through the <a href="http://www.testdriven.net/quickstart.aspx" rel="nofollow noreferrer">TestDriven.Net quickstart</a>, which shows examples of using the <code>Debug.WriteLine</code> in a unit test, but strangely this doesn't work for me either - i.e. the only Output in my 'Test' window is:</p>
<pre><code>------ Test started: Assembly: ClassLibrary1.dll ------
1 passed, 0 failed, 0 skipped, took 1.19 seconds.
</code></pre>
<p>I've tried looking in the other windows (Debug and Build), the Debug window has the 'Program Output' and 'Exception Messages' options enabled.</p>
<p>I've looked for options or preferences and can't find any!</p>
<p>Thanks for your help!</p>
<p><hr />
<strong>Edit:</strong> I'm using VB.Net 2.0, TestDriven.Net 2.14.2190 and NUnit 2.4.8.0</p>
|
[
{
"answer_id": 173651,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 5,
"selected": true,
"text": "<p>I found that while Debug.Writeline() doesn't work with unit tests, Console.WriteLine() does. </p>\n\n<p>The reason is that when you run tests, the debugger process isn't invoked, and Debug.WriteLine() is ignored. However, if you use \"Test with Debugger\", I think (haven't tried) Debug.WriteLine() will work.</p>\n"
},
{
"answer_id": 173693,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 2,
"selected": false,
"text": "<p><strong><code>Trace.WriteLine()</code></strong> appears to be the answer :o)</p>\n\n<p>Here's the output for the example from my question, using <code>Trace</code> instead of <code>Debug</code>:</p>\n\n<pre><code>------ Test started: Assembly: ClassLibrary1.dll ------\n\nInternal state of Class1: True\n\n1 passed, 0 failed, 0 skipped, took 0.61 seconds.\n</code></pre>\n\n<p>One thing I've found though.. execution is halted at the first failing unit test assertion, meaning that <code>Trace</code> statements aren't executed if an <code>Assert()</code> above them fails.</p>\n"
},
{
"answer_id": 173709,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>IIRC, this output is only shown in the output window when running an individual test. Try right-clicking in the test method to run just that test...?</p>\n"
},
{
"answer_id": 173953,
"author": "Christian.K",
"author_id": 21567,
"author_profile": "https://Stackoverflow.com/users/21567",
"pm_score": 0,
"selected": false,
"text": "<p>\"Run Tests...\" picks up whatever setting you currently have to build your solution/project.</p>\n\n<p>You have to make sure that the current build settings for your solution/project are set to \"Debug\" and not to \"Release\" (otherwise Debug.Write*() calls are <a href=\"http://msdn.microsoft.com/en-us/library/aa664622(VS.71).aspx\" rel=\"nofollow noreferrer\">conditionally</a> removed by the compiler).</p>\n"
},
{
"answer_id": 190742,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to know that 2.16 (the current beta version) includes:</p>\n\n<blockquote>\n <p>1587: Always display console\n output/error and test runner messages</p>\n \n <p>Test runner generated messages and\n console output will now be displayed\n when running all tests in a\n project/solution.</p>\n \n <p>1588: Optionally display trace/debug\n output when running all tests in\n project/solution</p>\n \n <p>By default trace/debug output isn't\n displayed when executing all tests in\n a project/solution. This behaviour can\n be modified via the TesDriven.Net\n options pane.</p>\n</blockquote>\n\n<p>So it seems that it will work in the next version.</p>\n"
},
{
"answer_id": 1839712,
"author": "jcansdale",
"author_id": 121348,
"author_profile": "https://Stackoverflow.com/users/121348",
"pm_score": 2,
"selected": false,
"text": "<p>Try using Trace.WriteLine(...) instead. The call to Debug.WriteLine(...) will only be made when DEBUG is defined. By default new Visual Studio projects no longer define DEBUG, but they do define TRACE.</p>\n\n<p>I should really change the quickstart example to use Trace instead.</p>\n\n<p>Regards,\nJamie.</p>\n"
},
{
"answer_id": 16285994,
"author": "Sergio",
"author_id": 2121580,
"author_profile": "https://Stackoverflow.com/users/2121580",
"pm_score": 0,
"selected": false,
"text": "<p>CTRL + ALT + I shows you the immediate window</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
] |
I'm trying to use TestDriven.Net not only to test my code, but to call a function on my code whose purpose is to print out the internal state of the code to the Debug window.
Here's a very simplified example of what I'm trying to do..
```
<TestFixture()> _
Public Class UnitTest
<Test()> _
Public Sub TestDebug()
Dim oClass1 As New Class1
Assert.AreEqual(True, oClass1.IsTrue)
Debug.WriteLine("About to call .PrintDebug()")
oClass1.PrintToDebug()
End Sub
End Class
Public Class Class1
Private _IsTrue As Boolean = True
Public ReadOnly Property IsTrue() As Boolean
Get
Return _IsTrue
End Get
End Property
Public Sub PrintToDebug()
Debug.WriteLine("Internal state of Class1: " & _IsTrue)
End Sub
End Class
```
I'm trying to test the Public interface of Class1, and somehow view the output from the `Class1.PrintToDebug()` function.
I've looked through the [TestDriven.Net quickstart](http://www.testdriven.net/quickstart.aspx), which shows examples of using the `Debug.WriteLine` in a unit test, but strangely this doesn't work for me either - i.e. the only Output in my 'Test' window is:
```
------ Test started: Assembly: ClassLibrary1.dll ------
1 passed, 0 failed, 0 skipped, took 1.19 seconds.
```
I've tried looking in the other windows (Debug and Build), the Debug window has the 'Program Output' and 'Exception Messages' options enabled.
I've looked for options or preferences and can't find any!
Thanks for your help!
---
**Edit:** I'm using VB.Net 2.0, TestDriven.Net 2.14.2190 and NUnit 2.4.8.0
|
I found that while Debug.Writeline() doesn't work with unit tests, Console.WriteLine() does.
The reason is that when you run tests, the debugger process isn't invoked, and Debug.WriteLine() is ignored. However, if you use "Test with Debugger", I think (haven't tried) Debug.WriteLine() will work.
|
173,642 |
<p>I only want a list of files that have been added (not ones that have been modified) since a certain date. Is there an easy way to do this?</p>
<p><strong>Answer</strong>: Here's what ended up working for me, thanks guys!</p>
<blockquote>
<p>svn log -v -r{2008-10-1}:HEAD svn://path.to.repo/ | grep "^ A" | grep ".java" | sort -u</p>
</blockquote>
|
[
{
"answer_id": 173665,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 4,
"selected": true,
"text": "<pre><code>svn log -v -r{2008-10-1}:HEAD | grep \"^ A\"\n</code></pre>\n"
},
{
"answer_id": 173669,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 1,
"selected": false,
"text": "<p>Something like</p>\n\n<p><code>svn log -v -r {\"2008-01-01\"}:HEAD . | grep ' A ' | sort -u</code></p>\n\n<p>should get you going...</p>\n"
},
{
"answer_id": 174080,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 2,
"selected": false,
"text": "<p>If you use 'svn log -v -q' you get the filename and no log messages. This is a little bit faster over http:// and svn:// as the log messages are not transferred to you.</p>\n\n<p>svn log --xml -v -q gives you the same information but in easy to parse xml. (This handles all corner cases on strange file names for you).</p>\n"
},
{
"answer_id": 18711027,
"author": "Harikrushna",
"author_id": 1587594,
"author_profile": "https://Stackoverflow.com/users/1587594",
"pm_score": 0,
"selected": false,
"text": "<p>you can try following command,</p>\n\n<pre><code>svn log -r '{2013-09-09}:HEAD'\n</code></pre>\n\n<p>Here you get all the revision details from date 9/9/2013</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
I only want a list of files that have been added (not ones that have been modified) since a certain date. Is there an easy way to do this?
**Answer**: Here's what ended up working for me, thanks guys!
>
> svn log -v -r{2008-10-1}:HEAD svn://path.to.repo/ | grep "^ A" | grep ".java" | sort -u
>
>
>
|
```
svn log -v -r{2008-10-1}:HEAD | grep "^ A"
```
|
173,646 |
<p>Most often the cleanup rules (Preferences > Java > Code Style > Clean Up) in Eclipse work perfectly and create nice-looking code.</p>
<p>But sometimes, especially with comments and concatenated string snippets (like inline SQL queries), the cleanup just messes things up, and destroys my formatting.</p>
<p>Is there a way to say to Eclipse <em>"Don't touch this block of text! I have formatted it just the way I like, and you would make it just less readable"</em>?</p>
|
[
{
"answer_id": 173984,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 0,
"selected": false,
"text": "<p>No. (To the best of my knowledge, and I have had the same problem and have looked many times hard and long...)</p>\n"
},
{
"answer_id": 175182,
"author": "srclontz",
"author_id": 4606,
"author_profile": "https://Stackoverflow.com/users/4606",
"pm_score": 2,
"selected": false,
"text": "<p>I have experienced the same problem, and while I don't have a solution, I can tell you how I work around the problem. </p>\n\n<p>Because of how formatting works, I deliberately avoid lines of code that are excessively long. In general, when I keep lines short, it makes better decisions as to how to format the code. This can even work with SQL statements, for example:</p>\n\n<pre><code>public static final String SELECT_SOMETHING = \"SELECT\"\n + \"OBJECTID, THIS, THAT, THEOTHER, THING\"\n + \" FROM DBNAME.DBSCHEMA.TABLE_T\"\n + \" WHERE ID = ?\";\n</code></pre>\n\n<p>This statement formats reasonably, because where possible items were split apart and concatenated together. When I don't do this, I get unpredictable results:</p>\n\n<pre><code>public static final String SELECT_SOMETHING = \"SELECT OBJECTID, SOMETHING FROM DBNAME.DBSCHEMA.TABLE_T WHERE ID = ?\";\n</code></pre>\n\n<p>For comments, I place them all on a single line when possible, and allow it to word wrap when it does the formatting.</p>\n\n<p>Also, it is possible to change the style using the code formatter to make things work better for your coding style. You may want everyone on the team to use the same format, just to avoid conflicts. Because it is easier to compare changes with other developers, or prior versions using your source control tool, even if it makes parts of your code less readable, using the formatter has still been to my advantage. </p>\n\n<p>Still, I understand your frustration when the formatter makes bad decisions!</p>\n"
},
{
"answer_id": 175350,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 1,
"selected": false,
"text": "<p>Feeling iffy about replying to my own question, but there's a workaround I currently do (<em>note: I have these cleanup rules as a save-action</em>): </p>\n\n<p>Save (with Ctrl/Cmd-S, don't know if it matters how you save) the code, and let Eclipse mess up your formatting. Then just press Ctrl/Cmd-Z to undo, and immediately re-save. The format reverts back to its original format and seems to be saved as intended.</p>\n"
},
{
"answer_id": 175992,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>(for Javadoc comments only)</p>\n\n<p>If I have a block of text that formatted just the way I like, I enclose them by the <pre></pre> tags.</p>\n"
},
{
"answer_id": 681623,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>if you don't want a field to become final (i.i: because you want to change it while debugging), you just assign it to itself on the constructor. This would get an eclipse warning, but your field will stay non-final.</p>\n"
},
{
"answer_id": 2932491,
"author": "MSzewczyk",
"author_id": 1082122,
"author_profile": "https://Stackoverflow.com/users/1082122",
"pm_score": 1,
"selected": false,
"text": "<p>For SQL statements in code, you can put a single-line comment character at the end of each line. Then the formatter can't reformat it. It's uglier than not having to do it, but it's prettier than if Eclipse formats it.</p>\n\n<pre><code>StringBuffer sql = new StringBuffer() //\n .append(\"SELECT whatever \\n\") //\n .append(\"FROM some_table\");\n</code></pre>\n"
},
{
"answer_id": 7096358,
"author": "Michael Piefel",
"author_id": 2621917,
"author_profile": "https://Stackoverflow.com/users/2621917",
"pm_score": 4,
"selected": true,
"text": "<p>I assume you do not really mean ‘Clean Up’, but the ‘Format source code’ option hidden within. It is configured in Preferences > Java > Code Style > Formatter. And, indeed, there is an option called ‘On/Off Tags’. Sadly, it’s off by default. You would now write it like so:</p>\n\n<pre><code>// @formatter:off\nStringBuilder sql = new StringBuilder()\n .append(\"SELECT whatever \\n\")\n .append(\"FROM some_table\");\n// @formatter:on\n</code></pre>\n\n<p>It may well be possible that the accepted answer was correct at the time of writing, however, this was introduced in Eclipse 3.5, if I’m not mistaken.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
Most often the cleanup rules (Preferences > Java > Code Style > Clean Up) in Eclipse work perfectly and create nice-looking code.
But sometimes, especially with comments and concatenated string snippets (like inline SQL queries), the cleanup just messes things up, and destroys my formatting.
Is there a way to say to Eclipse *"Don't touch this block of text! I have formatted it just the way I like, and you would make it just less readable"*?
|
I assume you do not really mean ‘Clean Up’, but the ‘Format source code’ option hidden within. It is configured in Preferences > Java > Code Style > Formatter. And, indeed, there is an option called ‘On/Off Tags’. Sadly, it’s off by default. You would now write it like so:
```
// @formatter:off
StringBuilder sql = new StringBuilder()
.append("SELECT whatever \n")
.append("FROM some_table");
// @formatter:on
```
It may well be possible that the accepted answer was correct at the time of writing, however, this was introduced in Eclipse 3.5, if I’m not mistaken.
|
173,652 |
<p>I have a WPF Window which has a among other controls hosts a Frame. In that frame I display different pages. Is there way to make a dialog modal to only a page? When I'm showing the dialog it should not be possible to click on any control on the page but it should be possible to click on a control on the same window that is not on the page.</p>
|
[
{
"answer_id": 173702,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 1,
"selected": false,
"text": "<p>You are not looking for a modal dialog here. You need a function that will disable the \"page\" control, show a dialog, and re-enable it when the dialog closes.</p>\n\n<p>I'm not too sure whether you understand what a modal dialog is meant to do though?</p>\n"
},
{
"answer_id": 173769,
"author": "Brad Leach",
"author_id": 708,
"author_profile": "https://Stackoverflow.com/users/708",
"pm_score": 6,
"selected": true,
"text": "<p>If I am correct in interpreting your message, you want something that works similar to what \n<a href=\"http://www.dnrtv.com/default.aspx?showNum=115\" rel=\"noreferrer\">Billy Hollis demonstrates in his StaffLynx application</a>.</p>\n\n<p>I recently built a similar control and it turns out that this sort of idea is relatively simple to implement in WPF. I created a custom control called DialogPresenter. In the control template for the custom control, I added markup similar to the following:</p>\n\n<pre><code><ControlTemplate TargetType=\"{x:Type local=DialogPresenter}\">\n <Grid>\n <ContentControl>\n <ContentPresenter />\n </ContentControl>\n <!-- The Rectangle is what simulates the modality -->\n <Rectangle x:Name=\"Overlay\" Visibility=\"Collapsed\" Opacity=\"0.4\" Fill=\"LightGrey\" />\n <Grid x:Name=\"Dialog\" Visibility=\"Collapsed\">\n <!-- The template for the dialog goes here (borders and such...) -->\n <ContentPresenter x:Name=\"PART_DialogView\" />\n </Grid>\n </Grid>\n <ControlTemplate.Triggers>\n <!-- Triggers to change the visibility of the PART_DialogView and Overlay -->\n </ControlTemplate.Triggers>\n</ControlTemplate>\n</code></pre>\n\n<p>I also added a <code>Show(Control view)</code> method, which finds the the 'PART_DialogView', and adds the passed in view to the <code>Content</code> property.</p>\n\n<p>This then allows me to use the <code>DialogPresenter</code> as follows:</p>\n\n<pre><code><controls:DialogPresenter x:Name=\"DialogPresenter\">\n <!-- Normal parent view content here -->\n <TextBlock>Hello World</TextBlock>\n <Button>Click Me!</Button>\n</controls:DialogPresenter>\n</code></pre>\n\n<p>To the buttons event handler (or bound command), I simply call the Show() method of the <code>DialogPresenter</code>.</p>\n\n<p>You can also easily add ScaleTransform markup to the DialogPresenter template to get scaling effects shown in the video. This solution has neat and tidy custom control code, and a very simple interface for your UI programming team.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 4163802,
"author": "Dean Chalk",
"author_id": 328848,
"author_profile": "https://Stackoverflow.com/users/328848",
"pm_score": 2,
"selected": false,
"text": "<p>Why not just use nested message pumps to create modal controls</p>\n\n<p><a href=\"http://deanchalk.com/wpf-modal-controls-via-dispatcherframe-nested-message-pumps/\" rel=\"nofollow\">http://deanchalk.com/wpf-modal-controls-via-dispatcherframe-nested-message-pumps/</a></p>\n"
},
{
"answer_id": 11277444,
"author": "Benjamin Gale",
"author_id": 577417,
"author_profile": "https://Stackoverflow.com/users/577417",
"pm_score": 2,
"selected": false,
"text": "<p>I have a project on <a href=\"https://github.com/BenjaminGale/ModalContentPresenter\" rel=\"nofollow noreferrer\">github</a> which is a custom <code>FrameworkElement</code> that allows you to display modal content over the primary content.</p>\n\n<p>The control can be used like this:</p>\n\n<pre><code><c:ModalContentPresenter IsModal=\"{Binding DialogIsVisible}\">\n <TabControl Margin=\"5\">\n <Button Margin=\"55\"\n Padding=\"10\"\n Command=\"{Binding ShowModalContentCommand}\">\n This is the primary Content\n </Button>\n </TabItem>\n </TabControl>\n\n <c:ModalContentPresenter.ModalContent>\n <Button Margin=\"75\"\n Padding=\"50\"\n Command=\"{Binding HideModalContentCommand}\">\n This is the modal content\n </Button>\n </c:ModalContentPresenter.ModalContent>\n\n</c:ModalContentPresenter>\n</code></pre>\n\n<p>Features:</p>\n\n<ul>\n<li>Displays arbitrary content.</li>\n<li>Does not disable the primary content whilst the modal content is being displayed.</li>\n<li>Disables mouse and keyboard access to the primary content whilst the modal content is displayed.</li>\n<li>Is only modal to the content it is covering, not the entire application.</li>\n<li>can be used in an MVVM friendly way by binding to the <code>IsModal</code> property. </li>\n</ul>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] |
I have a WPF Window which has a among other controls hosts a Frame. In that frame I display different pages. Is there way to make a dialog modal to only a page? When I'm showing the dialog it should not be possible to click on any control on the page but it should be possible to click on a control on the same window that is not on the page.
|
If I am correct in interpreting your message, you want something that works similar to what
[Billy Hollis demonstrates in his StaffLynx application](http://www.dnrtv.com/default.aspx?showNum=115).
I recently built a similar control and it turns out that this sort of idea is relatively simple to implement in WPF. I created a custom control called DialogPresenter. In the control template for the custom control, I added markup similar to the following:
```
<ControlTemplate TargetType="{x:Type local=DialogPresenter}">
<Grid>
<ContentControl>
<ContentPresenter />
</ContentControl>
<!-- The Rectangle is what simulates the modality -->
<Rectangle x:Name="Overlay" Visibility="Collapsed" Opacity="0.4" Fill="LightGrey" />
<Grid x:Name="Dialog" Visibility="Collapsed">
<!-- The template for the dialog goes here (borders and such...) -->
<ContentPresenter x:Name="PART_DialogView" />
</Grid>
</Grid>
<ControlTemplate.Triggers>
<!-- Triggers to change the visibility of the PART_DialogView and Overlay -->
</ControlTemplate.Triggers>
</ControlTemplate>
```
I also added a `Show(Control view)` method, which finds the the 'PART\_DialogView', and adds the passed in view to the `Content` property.
This then allows me to use the `DialogPresenter` as follows:
```
<controls:DialogPresenter x:Name="DialogPresenter">
<!-- Normal parent view content here -->
<TextBlock>Hello World</TextBlock>
<Button>Click Me!</Button>
</controls:DialogPresenter>
```
To the buttons event handler (or bound command), I simply call the Show() method of the `DialogPresenter`.
You can also easily add ScaleTransform markup to the DialogPresenter template to get scaling effects shown in the video. This solution has neat and tidy custom control code, and a very simple interface for your UI programming team.
Hope this helps!
|
173,670 |
<p>Being primarily a C++ developer the absence of <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization" rel="noreferrer">RAII (Resource Acquisition Is Initialization)</a> in Java and .NET has always bothered me. The fact that the onus of cleaning up is moved from the class writer to its consumer (by means of <code>try finally</code> or .NET's <a href="http://blogs.msdn.com/cyrusn/archive/2005/05/10/415956.aspx" rel="noreferrer"><code>using</code> construct</a>) seems to be markedly inferior.</p>
<p>I see why in Java there is no support for RAII since all objects are located on the heap and the garbage collector inherently doesn't support deterministic destruction, but in .NET with the introduction of value-types (<code>struct</code>) we have the (seemingly) perfect candidate for RAII. A value type that's created on the stack has a well defined scope and C++ destructor semantics can be used. However the CLR does not permit a value-type to have a destructor.</p>
<p>My random searches found one argument that if a value-type is <a href="http://www.csharphelp.com/archives/archive100.html" rel="noreferrer">boxed</a> it falls under the jurisdiction of the garbage collector and therefore its destruction becomes non-deterministic.
I feel that this argument isn't strong enough, the benefits of RAII are big enough to say that a value-type with a destructor cannot be boxed (or used as a class member).</p>
<p><strong>To cut a long story short my question is</strong>: are there any other reasons value types can not be used in order to introduce RAII to .NET? (or do you think my argument about RAII's obvious advantages are flawed?)</p>
<p><strong>Edit:</strong> I must have not phrased the question clearly since the first four answers have missed the point. I <em>know</em> about <code>Finalize</code> and its non-deterministic characteristics, I know about the <code>using</code> construct and I feel these two options are inferior to RAII. <code>using</code> is one more thing the consumer of a class must remember (how many people forgot to put a <code>StreamReader</code> in a <code>using</code> block?). My question is a philosophical one about the language design, why is it the way it is and can it be improved?</p>
<p>For instance with a generic deterministically destructible value-type I can make the <code>using</code> and <code>lock</code> keywords redundant (achievable by library classes):</p>
<pre><code> public struct Disposer<T> where T : IDisposable
{
T val;
public Disposer(T t) { val = t; }
public T Value { get { return val; } }
~Disposer() // Currently illegal
{
if (val != default(T))
val.Dispose();
}
}
</code></pre>
<hr>
<p>I can't help but end with a apropos quotation which I once saw but can't currently find its origin.</p>
<blockquote>
<p>You can take my deterministic destruction when my cold dead hand goes out of scope. --<em>Anon</em></p>
</blockquote>
|
[
{
"answer_id": 173677,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "<p>The closest you get to that is the very limited stackalloc operator.</p>\n"
},
{
"answer_id": 173689,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": -1,
"selected": false,
"text": "<p>You can do a form of RAII in .net and java using finalize() methods. A finalize() overload is called before the class is cleaned up by the GC and so can be used to clean up any resources that absolutely shouldn't be kept by the class (mutexes, sockets, file handles, etc). It still isn't deterministic though. </p>\n\n<p>With .NET you can do some of this deterministically with the IDisposable interface and the using keyword, but this does have limitations (using construct when used required for deterministic behaviour, still no deterministic memory deallocation, not automatically used in classes, etc). </p>\n\n<p>And yes, I feel there is a place for RAII ideas to be introduced into .NET and other managed languages, although the exact mechanism could be debated endlessly. The only other alternative I could see would be to introduce a GC that could handle arbitrary resource cleanup (not just memory) but then you have issues when said resources absolutely have to be released deterministically.</p>\n"
},
{
"answer_id": 173690,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 1,
"selected": false,
"text": "<p>There's some similar threads if you search for them but basicly what it boils down to is that if you want to RAII on .NET simply implement an IDisposable type and use the \"using\" statement to get deterministic Disposal. That way many of the same ideoms can be implemented and used in only a slightly more wordy manner.</p>\n"
},
{
"answer_id": 173705,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>Excellent question and one that has bothered me greatly. It appears that the benefits of RAII are perceived very differently. In my experience with .NET, the lack of deterministic (or at least reliable) resource collection is one of the major drawbacks. In fact, .NET has forced me several times to employ whole architectures to deal with unmanaged resources that <em>might</em> (but might not) require explicit collecting. Which, of course, is a huge drawback because it makes the overall architecture more difficult and directs the client's attention away from the more central aspects.</p>\n"
},
{
"answer_id": 173740,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 4,
"selected": false,
"text": "<p>Brian Harry has a nice post about the rationales <a href=\"http://blogs.msdn.com/brada/articles/371015.aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Here is an excerpt:</p>\n\n<blockquote>\n <h2>What about deterministic finalization and value types (structs)?</h2>\n \n <p>-------------- I've seen a lot of questions about structs having\n destructors, etc. This is worth\n comment. There are a variety of\n issues for why some languages don't\n have them.</p>\n \n <p>(1) composition - They don't give you\n deterministic lifetime in the general\n case for the same kinds of composition\n reasons described above. Any\n non-deterministic class containing one\n would not call the destructor until it\n was finalized by the GC anyway.</p>\n \n <p>(2) copy constructors - The one place\n where it would really be nice is in\n stack allocated locals. They would be\n scoped to the method and all would be\n great. Unfortunately, in order to get\n this to really work, you also have to\n add copy constructors and call them\n every time an instance is copied. \n This is one of the ugliest and most\n complex things about C++. You end up\n getting code executing all over the\n place where you don't expect it. It\n causes bunches of language problems. \n Some language designers have chosen to\n stay away from this.</p>\n \n <p>Let's say we created structs with\n destructors but added a bunch of\n restrictions to make their behavior\n sensible in the face of the issues\n above. The restrictions would be\n something like:</p>\n \n <p>(1) You can only declare them as local\n variables. </p>\n \n <p>(2) You can only pass them\n by-ref</p>\n \n <p>(3) You can't assign them, you\n can only access fields and call\n methods on them. </p>\n \n <p>(4) You can't box\n them. </p>\n \n <p>(5) Problems using them through\n Reflection (late binding) because that\n usually involves boxing. </p>\n \n <p>maybe more,\n but that's a good start.</p>\n \n <p>What use would these things be? Would\n you actually create a file or a\n database connection class that can\n ONLY be used as a local variable? I\n don't believe anybody really would. \n What you would do instead is create a\n general purpose connection and then\n create an auto destructed wrapper for\n use as a scoped local variable. The\n caller would then pick what they\n wanted to use. Note the caller made a\n decision and it is not entirely\n encapsulated in the object itself. \n Given that you could use something\n like the suggestions coming up in a\n couple of sections.</p>\n</blockquote>\n\n<p>The replacement for RAII in .NET is the using-pattern, which works almost as well once you get used to it.</p>\n"
},
{
"answer_id": 173845,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 5,
"selected": true,
"text": "<p>A better title would be \"Why is there no RAII in C#/VB\". C++/CLI (The evolution of the abortion that was Managed C++) has RAII in the exact same sense as C++. It's all just syntax sugar for the same finalisation pattern that the rest of the CLI languages use (Destructors in managed objects for C++/CLI are effectively finalisers), but it is there.</p>\n\n<p>You might like <a href=\"http://blogs.msdn.com/hsutter/archive/2004/07/31/203137.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/hsutter/archive/2004/07/31/203137.aspx</a></p>\n"
},
{
"answer_id": 4435814,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "<p>IMHO, the big things that VB.net and C# need are:</p>\n\n<ol><li>a \"using\" declaration for fields, which would cause the compiler to generate code to dispose of all fields thus tagged. The default behavior should be for the compiler to make a class implement IDisposable if it does not, or insert disposal logic before the start of the main disposal routine for any of a number of common IDisposal implementation patterns, or else use an attribute to specify that the disposal stuff should go in a routine with a particular name.\n<li>a means of deterministically disposing of objects whose constructors and/or field initializers throw an exception, either by a default behavior (calling the default disposal method) or a custom behavior (calling a method with a particular name).\n<li>For vb.net, an auto-generated method to null out all WithEvent fields.\n</ol>\n\n<p>All of those can be kludged pretty well in vb.net, and somewhat less well in C#, but first-class support for them would improve both languages.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
Being primarily a C++ developer the absence of [RAII (Resource Acquisition Is Initialization)](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) in Java and .NET has always bothered me. The fact that the onus of cleaning up is moved from the class writer to its consumer (by means of `try finally` or .NET's [`using` construct](http://blogs.msdn.com/cyrusn/archive/2005/05/10/415956.aspx)) seems to be markedly inferior.
I see why in Java there is no support for RAII since all objects are located on the heap and the garbage collector inherently doesn't support deterministic destruction, but in .NET with the introduction of value-types (`struct`) we have the (seemingly) perfect candidate for RAII. A value type that's created on the stack has a well defined scope and C++ destructor semantics can be used. However the CLR does not permit a value-type to have a destructor.
My random searches found one argument that if a value-type is [boxed](http://www.csharphelp.com/archives/archive100.html) it falls under the jurisdiction of the garbage collector and therefore its destruction becomes non-deterministic.
I feel that this argument isn't strong enough, the benefits of RAII are big enough to say that a value-type with a destructor cannot be boxed (or used as a class member).
**To cut a long story short my question is**: are there any other reasons value types can not be used in order to introduce RAII to .NET? (or do you think my argument about RAII's obvious advantages are flawed?)
**Edit:** I must have not phrased the question clearly since the first four answers have missed the point. I *know* about `Finalize` and its non-deterministic characteristics, I know about the `using` construct and I feel these two options are inferior to RAII. `using` is one more thing the consumer of a class must remember (how many people forgot to put a `StreamReader` in a `using` block?). My question is a philosophical one about the language design, why is it the way it is and can it be improved?
For instance with a generic deterministically destructible value-type I can make the `using` and `lock` keywords redundant (achievable by library classes):
```
public struct Disposer<T> where T : IDisposable
{
T val;
public Disposer(T t) { val = t; }
public T Value { get { return val; } }
~Disposer() // Currently illegal
{
if (val != default(T))
val.Dispose();
}
}
```
---
I can't help but end with a apropos quotation which I once saw but can't currently find its origin.
>
> You can take my deterministic destruction when my cold dead hand goes out of scope. --*Anon*
>
>
>
|
A better title would be "Why is there no RAII in C#/VB". C++/CLI (The evolution of the abortion that was Managed C++) has RAII in the exact same sense as C++. It's all just syntax sugar for the same finalisation pattern that the rest of the CLI languages use (Destructors in managed objects for C++/CLI are effectively finalisers), but it is there.
You might like <http://blogs.msdn.com/hsutter/archive/2004/07/31/203137.aspx>
|
173,681 |
<p>Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually?</p>
<p>I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and using it (marked as TWO). Am I assigning a variable in the stack to a field in ONE? Can the code be referencing to a dangling pointer which in this case worked because the program was small enough?</p>
<p>I've compiled and ran it, it worked fine but I'm having a strange crash in my actual program where I'm assigning string literals to fields of the class like this and I suspect the case I mentioned above.</p>
<pre><code>#include <iostream>
using namespace std;
class MemoryLeak
{
private:
char *s;
public:
MemoryLeak() {}
void store()
{
s = "Storing a string"; // ONE
}
char *retrieve()
{
return s;
}
};
int main()
{
MemoryLeak *obj = new MemoryLeak();
obj->store();
cout << obj->retrieve() << endl; // TWO
delete obj;
return 0;
}
</code></pre>
<p>Should I be declaring the variable "s" as a char array instead of a pointer? I'm planning to use std::string, but I'm just curious about this.</p>
<p>Any pointers or help is, as always, much appreciated :) Thanks.</p>
|
[
{
"answer_id": 173686,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 4,
"selected": true,
"text": "<p>String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you're going to be referencing the string literal that the compiler has already produced for you. Note that modifying this (which would require changing memory protection typically) will change all uses of this literal.</p>\n"
},
{
"answer_id": 173714,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe the cause of the crash is that you did not 0-terminate the string?</p>\n"
},
{
"answer_id": 173719,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 3,
"selected": false,
"text": "<p>It is undefined behaviour to modify a string literal, and is most likely the cause of the crash in your program (ISO C++: 2.13.4/2). The standard allows for a conversion from a string literal to <code>char*</code> for backwards compatibility to C and you should only have that conversion in your code if you absolutely need it.</p>\n\n<p>If you wish to treat the string literal as a constant, then you can change the type of your member to a <code>const char *</code>.</p>\n\n<p>If your design requires that <code>s</code> can be modified, then I would recommend changing its type to <code>std::string</code>.</p>\n"
},
{
"answer_id": 173816,
"author": "Srikanth",
"author_id": 7205,
"author_profile": "https://Stackoverflow.com/users/7205",
"pm_score": 1,
"selected": false,
"text": "<p>Thank you Cody and Richard.</p>\n\n<p>I found the cause of the bug. It was because I was doing a delete on an object which was already delete'd. I was doing:</p>\n\n<pre><code>if (obj != NULL) delete obj;\n</code></pre>\n\n<p>I changed it to:</p>\n\n<pre><code>if (obj != NULL)\n{\n delete obj;\n obj = NULL;\n}\n</code></pre>\n\n<p>Learning C++ is definitely fun :)</p>\n"
},
{
"answer_id": 175010,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "<p>Lets have a look at your options.<br>\nThere are also a couple of things you should do:</p>\n\n<pre><code> /*\n * Should initialize s to NULL or a valid string in constructor */\n MemoryLeak()\n {\n store();\n }\n\n void store()\n {\n // This does not need to be freed because it is a string literal\n // generated by the compiler.\n s = \"Storing a string\"; // ONE\n\n // Note this is allowed for backward compatibility but the string is\n // really stored as a const char* and thus unmodifiable. If somebody\n // retrieves this C-String and tries to change any of the contents the\n // code could potentially crash as this is UNDEFINED Behavior.\n\n // The following does need to be free'd.\n // But given the type of s is char* this is more correct.\n s = strdup(\"Storing a string\");\n\n // This makes a copy of the string on the heap.\n // Because you allocated the memory it is modifiable by anybody\n // retrieving it but you also need to explicitly de-allocate it\n // with free()\n }\n</code></pre>\n\n<p>What you are doing is using C-Strings. These should not be confused with C++ std::string. The C++ std::string is auto-initialized to the empty string. Any memory allocated is de-allocated correctly. It can easily be returned as both a modifiable and non modifiable version. It is also easy to manipulate (<b>i.e.</b> grow shrink change). If you grow a C-String you need to re-allocate memory and copy the string to the new memory etc (it is very time consuming an error prone).</p>\n\n<p>To cope with dynamically allocating your object I would learn about smart pointers.<br>\nSee this article for more details on smart pointers.<br>\n<a href=\"https://stackoverflow.com/questions/94227/smart-pointers-or-who-owns-you-baby\">Smart Pointers or who owns you Baby</a></p>\n\n<pre><code>std::auto_ptr<MemoryLeak> obj(new MemoryLeak());\n\nobj->store();\nstd::cout << obj->retrieve() << std::endl; // TWO\n\n// No need to delete When object goes out of scope it auto deletes the memory.\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7205/"
] |
Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually?
I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and using it (marked as TWO). Am I assigning a variable in the stack to a field in ONE? Can the code be referencing to a dangling pointer which in this case worked because the program was small enough?
I've compiled and ran it, it worked fine but I'm having a strange crash in my actual program where I'm assigning string literals to fields of the class like this and I suspect the case I mentioned above.
```
#include <iostream>
using namespace std;
class MemoryLeak
{
private:
char *s;
public:
MemoryLeak() {}
void store()
{
s = "Storing a string"; // ONE
}
char *retrieve()
{
return s;
}
};
int main()
{
MemoryLeak *obj = new MemoryLeak();
obj->store();
cout << obj->retrieve() << endl; // TWO
delete obj;
return 0;
}
```
Should I be declaring the variable "s" as a char array instead of a pointer? I'm planning to use std::string, but I'm just curious about this.
Any pointers or help is, as always, much appreciated :) Thanks.
|
String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you're going to be referencing the string literal that the compiler has already produced for you. Note that modifying this (which would require changing memory protection typically) will change all uses of this literal.
|
173,687 |
<p>I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.</p>
<p>When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:</p>
<pre><code>b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
self.log.write("Click! (%d)\n" % event.GetId())
</code></pre>
<p>But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value? </p>
<p>It would greatly reduce copy & pasting the same code but with different callers.</p>
|
[
{
"answer_id": 173694,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 6,
"selected": false,
"text": "<p>You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.</p>\n\n<pre><code>b = wx.Button(self, 10, \"Default Button\", (20, 20))\n self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)\ndef OnClick(self, event, somearg):\n self.log.write(\"Click! (%d)\\n\" % event.GetId())\n</code></pre>\n\n<p>If you're out to reduce the amount of code to type, you might also try a little automatism like:</p>\n\n<pre><code>class foo(whateverwxobject):\n def better_bind(self, type, instance, handler, *args, **kwargs):\n self.Bind(type, lambda event: handler(event, *args, **kwargs), instance)\n\n def __init__(self):\n self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')\n</code></pre>\n"
},
{
"answer_id": 173826,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 4,
"selected": false,
"text": "<p>The nicest way would be to make a generator of event handlers, e.g.:</p>\n\n<pre><code>def getOnClick(self, additionalArgument):\n def OnClick(event):\n self.log.write(\"Click! (%d), arg: %s\\n\" \n % (event.GetId(), additionalArgument))\n return OnClick\n</code></pre>\n\n<p>Now you bind it with:</p>\n\n<pre><code>b = wx.Button(self, 10, \"Default Button\", (20, 20))\nb.Bind(wx.EVT_BUTTON, self.getOnClick('my additional data'))\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.
When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:
```
b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
self.log.write("Click! (%d)\n" % event.GetId())
```
But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value?
It would greatly reduce copy & pasting the same code but with different callers.
|
You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.
```
b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)
def OnClick(self, event, somearg):
self.log.write("Click! (%d)\n" % event.GetId())
```
If you're out to reduce the amount of code to type, you might also try a little automatism like:
```
class foo(whateverwxobject):
def better_bind(self, type, instance, handler, *args, **kwargs):
self.Bind(type, lambda event: handler(event, *args, **kwargs), instance)
def __init__(self):
self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')
```
|
173,706 |
<p>I am having the problem that I cannot select a specific XML node which needs to be deleted. I have already tried to select the node by using the XPath which works fine for some XML files but I cannot figure out the correct XPath for a node in a more complex file.</p>
<p>Does anybody know a freeware tool which can load a XML file so that the user can select a specific node and receives the accurate XPath without having an enumeration in the path?</p>
<p><code>/root/anything[2]</code> <-- unfortunatly I cannot use such a statement because the number of the element might change. I need an expression that is based on an attribute.</p>
<p>In case that there is no freeware tool for this operation, does anybody know another way how I can select the needed node?</p>
<p><strong>XML Sample:</strong></p>
<p><strong>Root Node:</strong> SmsFormData </p>
<p><strong>Attributes:</strong> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" FormatVersion="1.0" xmlns="http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework"</p>
<p><strong>Child node:</strong> Form</p>
<p><strong>Attributes:</strong> Id="some GUID" CustomData="Some data" FormType="some type" ForceRefresh="false"</p>
<p><strong>Child/Child node:</strong> Pages</p>
<p><strong>Child/Child/Child node:</strong> Page</p>
<p><strong>Attributes:</strong> VendorId="VendorName" Id="some GUID" Assembly="dll File name" Namespace="some Namespace" Type="some Type" HelpID=""></p>
<p>My xPath expression to select this specific page would now be:</p>
<p><strong>xPath =</strong> <code>/SmsFormData/Form/Pages/Page[@Id="some Guid"]</code></p>
<p>To do the selection I am using the following vbscript code:</p>
<pre><code>Set objDOM = CreateObject("Msxml2.DOMDocument.4.0")
objDOM.async = false
objDOM.load(file)
set objNode = objDOM.selectSingleNode(xPath)
</code></pre>
<p>The problem is now that the <code>objNode</code> object is empty. The node is not selected, but why?</p>
|
[
{
"answer_id": 173748,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 0,
"selected": false,
"text": "<p>Given the following XML:</p>\n\n<pre><code><root>\n <anything foo=\"bar\">value1</anything>\n <anything foo=\"qux\">value2</anything>\n</root>\n</code></pre>\n\n<p>...you can obtain the value of the second anything node using the XPath expression:</p>\n\n<pre><code>/root/anything[@foo=\"qux\"]\n</code></pre>\n\n<p>(so, instead of the numbered index, you use @property=\"value\" as the selector).</p>\n\n<p>As for a tool to generate queries like this automagically, the aptly named <a href=\"http://weblogs.asp.net/nleghari/articles/visualxpath.aspx\" rel=\"nofollow noreferrer\">Visual XPath</a> should do the trick, and it's free (it even comes with C# source code).</p>\n\n<p>Edit, after followup by poster: this form of XPath selection works as well for 'simple cases' as it does for the most complicated documents. You <i>do</i> have to make sure your XPath expression is correct, of course, and although Visual XPath will indeed use numeric indexes, it at least gives you the rest of the expression, and you can easily substitute the @property=\"value\" selector for the number, and test the result.</p>\n\n<p>Given the example XML above, this VBscript:</p>\n\n<pre><code>objDOM.selectSingleNode(\"/root/anything[@foo=\"\"qux\"\"]/text()\").nodeValue\n</code></pre>\n\n<p>...returns the string \"value2\": depending on your needs, you may need to tweak things a little bit (again, tools like Visual XPath, or any good <a href=\"http://www.w3schools.com/Xpath/xpath_functions.asp\" rel=\"nofollow noreferrer\">XPath reference</a> will help you with that).</p>\n"
},
{
"answer_id": 173812,
"author": "Marcus",
"author_id": 25428,
"author_profile": "https://Stackoverflow.com/users/25428",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your fast reply! This surely works in simple cases but this does not work in my specific case :(</p>\n\n<p>So therefore lets go into the details:</p>\n\n<p><strong>Root Node:</strong> SmsFormData </p>\n\n<p><strong>Attributes:</strong> xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" FormatVersion=\"1.0\" xmlns=\"http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework\"</p>\n\n<p><strong>Child node:</strong> Form</p>\n\n<p><strong>Attributes:</strong> Id=\"some GUID\" CustomData=\"Some data\" FormType=\"some type\" ForceRefresh=\"false\"</p>\n\n<p><strong>Child/Child node:</strong>\nPages</p>\n\n<p><strong>Child/Child/Child node:</strong> Page</p>\n\n<p><strong>Attributes:</strong> VendorId=\"VendorName\" Id=\"some GUID\" Assembly=\"dll File name\" Namespace=\"some Namespace\" Type=\"some Type\" HelpID=\"\"></p>\n\n<p>My xPath expression to select this specific page would now be:</p>\n\n<p><strong>xPath =</strong> \"/SmsFormData/Form/Pages/Page[@Id=\"some Guid\"]\"</p>\n\n<p>To do the selection I am using the following vbscript code:</p>\n\n<pre><code>Set objDOM = CreateObject(\"Msxml2.DOMDocument.4.0\") \n\nobjDOM.async = false \nobjDOM.load(file) \n\nset objNode = objDOM.selectSingleNode(xPath) \n</code></pre>\n\n<p>The problem is now that the objNode object is empty. The node is not selected, but why?</p>\n\n<p>Oh and by the way: Thanks for the Visual XPath tip! I have tried using it but unfortunately it does the enumeration way :/</p>\n"
},
{
"answer_id": 173822,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 0,
"selected": false,
"text": "<p>You need to set the Selection Language to XPath using</p>\n\n<p>objDOM.SetProperty \"SelectionLanguage\", \"XPath\"</p>\n\n<p>Once you have set this property you can then use full XPath to access any elements you want</p>\n"
},
{
"answer_id": 173825,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 0,
"selected": false,
"text": "<p>If you have the Firefox browser, you can simply install the DOM Inspector (required only for Firefox 3.0), and the XPather extensions. Then, you can traverse to the node you want in the DOM Inspector window, and the corresponding XPath will be displayed in the XPather toolbar in the same window. </p>\n\n<p>DOM Inspector: <a href=\"https://addons.mozilla.org/en-US/firefox/addon/6622\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/en-US/firefox/addon/6622</a></p>\n\n<p>XPather: <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1192?id=1192\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/en-US/firefox/addon/1192?id=1192</a></p>\n\n<p>The XPather seems to use attributes (and not enumeration) whenever possible to identify nodes (atleast that's what I found in my little experimentation...). \nHope that helps... </p>\n"
},
{
"answer_id": 173896,
"author": "Marcus",
"author_id": 25428,
"author_profile": "https://Stackoverflow.com/users/25428",
"pm_score": 0,
"selected": false,
"text": "<p>Hm,... I get the impression that the problem must be file based.\nEven if I set the property for the SelectionLanguage and if I use an enumerated XPath (which I got by using the FireFox XPather) the node Object still remains empty.</p>\n\n<p>Does anybody has an idea what could be wrong? The xml file comes with an Microsoft application and therefore should be valid. At least I don't have any problems while opening the file or using it within the application so the syntax should be ok.</p>\n\n<p>Or does maybe somebody have a vbscript function that iterates through the whole xml file to find the needed node in order to delete it?</p>\n"
},
{
"answer_id": 173922,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 0,
"selected": false,
"text": "<p>You problem is that you have a default namespace. XPaths default name space is always the 'no name' name space.</p>\n\n<p>You need:-</p>\n\n<pre><code>sNamespaces = \"xmlns:cf='http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework'\"\nobjDOM.setProperty \"SelectionNamespaces\", sNamespaces\n</code></pre>\n\n<p>Now you can use in your XPath:-</p>\n\n<pre><code>xPath = \"/cf:SmsFormData/cf:Form/cf:Pages/cf:Page[@Id=\"\"some Guid\"\"]\"\n</code></pre>\n"
},
{
"answer_id": 173923,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": true,
"text": "<p>This is a default namespace issue. Try including the following code after you load in the XML:</p>\n\n<pre><code>objDom.SetProperty \"SelectionNamespaces\", \"xmlns:cf=\"\"http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework\"\"\"\n</code></pre>\n\n<p>You then use this <code>cf</code> prefix in your XPath eg:</p>\n\n<pre><code>objDom.SelectSingleNode(\"/cf:SmsFormData/cf:Form/cf:Pages/cf:Page[@Id='Some Guid']\")\n</code></pre>\n\n<p>Whilst this may seem a bit quirky, it is intentional behaviour. Take a look at <a href=\"http://support.microsoft.com/kb/288147\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/288147</a> for more information, and you may find <a href=\"http://msdn.microsoft.com/en-us/library/ms950779.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms950779.aspx</a> useful as well.</p>\n"
},
{
"answer_id": 459465,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if it is any use to you, but I had a similar problem.</p>\n\n<p>I had an app generated XML file that I needed to manage. It was of the format:\n<code><LoginData>\n <GeneralData>\n <LoginMask>65537</LoginMask>\n </GeneralData>\n <UserData>\n <User>\n <Username>TEST0</Username>\n ...\n </User>\n <User>\n <Username>TEST1</Username>\n ...\n </User>\n </UserData>\n</LoginData></code></p>\n\n<p>I needed to match on a Username and remove the other User tags. </p>\n\n<p>Took me (being a complete XML noob) ages to work it out, but in the end I hit on matching on a node, and deleting the child of the parent node:</p>\n\n<p>for each x in oXmlDoc.documentElement.selectSingleNode(\"UserData\").childNodes\n if x.getElementsByTagName(\"Username\").item(0).text = \"TEST1\" then\n set exx = x.getElementsByTagName(\"Username\").item(0)\n wscript.echo(x.getElementsByTagName(\"Username\").item(0).text)\n wScript.echo(x.nodename & \": \" & x.text)\n x.parentNode.removeChild(x)\n end if\nnext</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25428/"
] |
I am having the problem that I cannot select a specific XML node which needs to be deleted. I have already tried to select the node by using the XPath which works fine for some XML files but I cannot figure out the correct XPath for a node in a more complex file.
Does anybody know a freeware tool which can load a XML file so that the user can select a specific node and receives the accurate XPath without having an enumeration in the path?
`/root/anything[2]` <-- unfortunatly I cannot use such a statement because the number of the element might change. I need an expression that is based on an attribute.
In case that there is no freeware tool for this operation, does anybody know another way how I can select the needed node?
**XML Sample:**
**Root Node:** SmsFormData
**Attributes:** xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" FormatVersion="1.0" xmlns="http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework"
**Child node:** Form
**Attributes:** Id="some GUID" CustomData="Some data" FormType="some type" ForceRefresh="false"
**Child/Child node:** Pages
**Child/Child/Child node:** Page
**Attributes:** VendorId="VendorName" Id="some GUID" Assembly="dll File name" Namespace="some Namespace" Type="some Type" HelpID="">
My xPath expression to select this specific page would now be:
**xPath =** `/SmsFormData/Form/Pages/Page[@Id="some Guid"]`
To do the selection I am using the following vbscript code:
```
Set objDOM = CreateObject("Msxml2.DOMDocument.4.0")
objDOM.async = false
objDOM.load(file)
set objNode = objDOM.selectSingleNode(xPath)
```
The problem is now that the `objNode` object is empty. The node is not selected, but why?
|
This is a default namespace issue. Try including the following code after you load in the XML:
```
objDom.SetProperty "SelectionNamespaces", "xmlns:cf=""http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework"""
```
You then use this `cf` prefix in your XPath eg:
```
objDom.SelectSingleNode("/cf:SmsFormData/cf:Form/cf:Pages/cf:Page[@Id='Some Guid']")
```
Whilst this may seem a bit quirky, it is intentional behaviour. Take a look at <http://support.microsoft.com/kb/288147> for more information, and you may find <http://msdn.microsoft.com/en-us/library/ms950779.aspx> useful as well.
|
173,717 |
<p>What is the easiest way to copy the all the values from a column in a table to another column in the same table?</p>
|
[
{
"answer_id": 173720,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 4,
"selected": false,
"text": "<p>This script will update ALL values in the field1 with the values from the field2 in the corresponding row</p>\n\n<pre><code>UPDATE table SET field1 = field2\n</code></pre>\n"
},
{
"answer_id": 173722,
"author": "Panagiotis Korros",
"author_id": 19331,
"author_profile": "https://Stackoverflow.com/users/19331",
"pm_score": 7,
"selected": true,
"text": "<p>With a single statement (if the columns have the same datatype)</p>\n\n<pre><code>UPDATE <tablename>\nSET <destination column name> = <source column name>\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25438/"
] |
What is the easiest way to copy the all the values from a column in a table to another column in the same table?
|
With a single statement (if the columns have the same datatype)
```
UPDATE <tablename>
SET <destination column name> = <source column name>
```
|
173,727 |
<p>I would like to save data in cookies (user name, email address, etc...) but I don't the user to easily read it or modify it. I need to be able able to read the data back. How can I do that with php 5.2+?</p>
<p>It would be used for "welcome back bob" kind of feature. It is not a replacement for persistence or session storage.</p>
|
[
{
"answer_id": 173731,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't want your users to read it don't put it in a cookie;\nIn stead use Session's with a cookie that stays for a longer time. This way the data stays on the server and not at the computer of the user.</p>\n\n<p><a href=\"http://www.paulsrichards.com/2008/07/29/persistent-sessions-with-php/\" rel=\"nofollow noreferrer\">See this article about persistant sessions</a></p>\n"
},
{
"answer_id": 173746,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 3,
"selected": false,
"text": "<p>I suggest you not only encrypt but also sign the data. If you don't sign the data, you won't be able to tell reliably whether the user modified the data. Also, to avoid replay you may want to add some timestamp/validity period information into the data.</p>\n"
},
{
"answer_id": 173750,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<p>If you absolutely must do this then you can use the symmetric encryption functionality in <code>mcrypt</code>.</p>\n\n<p><a href=\"http://php.net/mcrypt\" rel=\"nofollow noreferrer\">http://php.net/mcrypt</a></p>\n"
},
{
"answer_id": 173754,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 2,
"selected": false,
"text": "<p>For encryption example see \"symmetric encryption\" section in <a href=\"http://www.osix.net/modules/article/?id=606\" rel=\"nofollow noreferrer\">http://www.osix.net/modules/article/?id=606</a>.</p>\n\n<p>To prevent unauthorized modification, use HMAC: <a href=\"http://php.net/hash-hmac\" rel=\"nofollow noreferrer\">http://php.net/hash-hmac</a>, and about hmac in general: <a href=\"http://en.wikipedia.org/wiki/HMAC\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/HMAC</a>, <a href=\"http://en.wikipedia.org/wiki/Message_authentication_code\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Message_authentication_code</a></p>\n\n<p>And if you don't have to, don't store sensitive data in a cookie, even encrypted. You may want to read more about \"data indirection\".</p>\n"
},
{
"answer_id": 173764,
"author": "Shoan",
"author_id": 17404,
"author_profile": "https://Stackoverflow.com/users/17404",
"pm_score": 4,
"selected": true,
"text": "<p>We use mcrypt in our projects to achieve encryption. Below is a code sample based on content found on the internet:</p>\n\n<pre><code><?php\nclass MyProjCrypt {\n\n private $td;\n private $iv;\n private $ks;\n private $salt;\n private $encStr;\n private $decStr;\n\n\n /**\n * The constructor initializes the cryptography library\n * @param $salt string The encryption key\n * @return void\n */\n function __construct($salt) {\n $this->td = mcrypt_module_open('rijndael-256', '', 'ofb', ''); // algorithm\n $this->ks = mcrypt_enc_get_key_size($this->td); // key size needed for the algorithm\n $this->salt = substr(md5($salt), 0, $this->ks);\n }\n\n /**\n * Generates a hex string of $src\n * @param $src string String to be encrypted\n * @return void\n */\n function encrypt($src) {\n srand(( double) microtime() * 1000000); //for sake of MCRYPT_RAND\n $this->iv = mcrypt_create_iv($this->ks, MCRYPT_RAND); \n mcrypt_generic_init($this->td, $this->salt, $this->iv);\n $tmpStr = mcrypt_generic($this->td, $src);\n mcrypt_generic_deinit($this->td);\n mcrypt_module_close($this->td);\n\n //convert the encrypted binary string to hex\n //$this->iv is needed to decrypt the string later. It has a fixed length and can easily \n //be seperated out from the encrypted String\n $this->encStr = bin2hex($this->iv.$tmpStr);\n\n }\n\n /**\n * Decrypts a hex string \n * @param $src string String to be decrypted\n * @return void\n */\n function decrypt($src) {\n //convert the hex string to binary\n $corrected = preg_replace(\"[^0-9a-fA-F]\", \"\", $src);\n $binenc = pack(\"H\".strlen($corrected), $corrected);\n\n //retrieve the iv from the encrypted string\n $this->iv = substr($binenc, 0, $this->ks);\n\n //retrieve the encrypted string alone(minus iv)\n $binstr = substr($binenc, $this->ks);\n\n /* Initialize encryption module for decryption */\n mcrypt_generic_init($this->td, $this->salt, $this->iv);\n /* Decrypt encrypted string */\n $decrypted = mdecrypt_generic($this->td, $binstr);\n\n /* Terminate decryption handle and close module */\n mcrypt_generic_deinit($this->td);\n mcrypt_module_close($this->td);\n $this->decStr = trim($decrypted);\n\n }\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1771/"
] |
I would like to save data in cookies (user name, email address, etc...) but I don't the user to easily read it or modify it. I need to be able able to read the data back. How can I do that with php 5.2+?
It would be used for "welcome back bob" kind of feature. It is not a replacement for persistence or session storage.
|
We use mcrypt in our projects to achieve encryption. Below is a code sample based on content found on the internet:
```
<?php
class MyProjCrypt {
private $td;
private $iv;
private $ks;
private $salt;
private $encStr;
private $decStr;
/**
* The constructor initializes the cryptography library
* @param $salt string The encryption key
* @return void
*/
function __construct($salt) {
$this->td = mcrypt_module_open('rijndael-256', '', 'ofb', ''); // algorithm
$this->ks = mcrypt_enc_get_key_size($this->td); // key size needed for the algorithm
$this->salt = substr(md5($salt), 0, $this->ks);
}
/**
* Generates a hex string of $src
* @param $src string String to be encrypted
* @return void
*/
function encrypt($src) {
srand(( double) microtime() * 1000000); //for sake of MCRYPT_RAND
$this->iv = mcrypt_create_iv($this->ks, MCRYPT_RAND);
mcrypt_generic_init($this->td, $this->salt, $this->iv);
$tmpStr = mcrypt_generic($this->td, $src);
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
//convert the encrypted binary string to hex
//$this->iv is needed to decrypt the string later. It has a fixed length and can easily
//be seperated out from the encrypted String
$this->encStr = bin2hex($this->iv.$tmpStr);
}
/**
* Decrypts a hex string
* @param $src string String to be decrypted
* @return void
*/
function decrypt($src) {
//convert the hex string to binary
$corrected = preg_replace("[^0-9a-fA-F]", "", $src);
$binenc = pack("H".strlen($corrected), $corrected);
//retrieve the iv from the encrypted string
$this->iv = substr($binenc, 0, $this->ks);
//retrieve the encrypted string alone(minus iv)
$binstr = substr($binenc, $this->ks);
/* Initialize encryption module for decryption */
mcrypt_generic_init($this->td, $this->salt, $this->iv);
/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($this->td, $binstr);
/* Terminate decryption handle and close module */
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
$this->decStr = trim($decrypted);
}
}
```
|
173,745 |
<p>I'm looking for a query which will return me an extra column at the end of my current query which is the count of all columns within the return set which contain a null column. For example:</p>
<pre><code>Col 1 - Col 2 - Col 3
A B 0
A NULL 1
NULL NULL 2
</code></pre>
<p>Is there a simple way to get this return set based on the row values rather than having to requery all the criteria which fetches the original rows?</p>
|
[
{
"answer_id": 173794,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 0,
"selected": false,
"text": "<p>If there isnt a very good reason you need to do this in the SQL, you should just do a for loop through the result set and count the NULL vlues then. </p>\n\n<p>The cost goes from n^n to n..</p>\n"
},
{
"answer_id": 173805,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p>Ugly solution:</p>\n\n<pre><code>select Col1, Col2,\n case when Col1 is null then 1 else 0 end\n + case when Col2 is null then 1 else 0 end\n as Col3\nfrom (\n\nselect 'A' as Col1, 'B' as Col2\nunion select 'A', NULL\nunion select NULL, NULL\n\n) z\n</code></pre>\n\n<p>This returns</p>\n\n<pre><code>Col1 Col2 Col3\nNULL NULL 2\nA NULL 1\nA B 0\n</code></pre>\n"
},
{
"answer_id": 173831,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 0,
"selected": false,
"text": "<p>You can use computed column:</p>\n\n<pre><code>CREATE TABLE testTable(\n col1 nchar(10) NULL,\n col2 nchar(10) NULL,\n col3 AS (case when col1 IS NULL then (1) else (0) end+case when col2 IS NULL then (1) else (0) end)\n)\n</code></pre>\n\n<p>It is not a pretty solution, but should work.</p>\n\n<p>If you are dealing with a big number of columns and many of them you expect to be NULL then you could use <a href=\"http://msdn.microsoft.com/en-us/library/cc280604.aspx\" rel=\"nofollow noreferrer\">sparse columns</a> (available in SQL Server 2008). It will be optimised for NULL and it can automatically generate XML representation for each row of data in the table.</p>\n"
},
{
"answer_id": 174048,
"author": "Mladen",
"author_id": 21404,
"author_profile": "https://Stackoverflow.com/users/21404",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select count(*) - count(ColumnName) as NumberOfNulls from yourTable\n</code></pre>\n\n<p>returns number of nulls in specific column. if you do this for every column you can get that data.</p>\n"
},
{
"answer_id": 174062,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 2,
"selected": false,
"text": "<p>Oracle has a function NVL2() which makes this easy.</p>\n\n<pre><code>select col1,\n col2,\n col3,\n ...\n NVL2(col1,0,1)\n +NVL2(col2,0,1)\n +NVL2(col3,0,1) coln\nfrom whatever\n</code></pre>\n"
},
{
"answer_id": 178674,
"author": "Thorsten",
"author_id": 25320,
"author_profile": "https://Stackoverflow.com/users/25320",
"pm_score": 1,
"selected": false,
"text": "<p>As in a similar post, SQL is not very suited to work across different columns within a row, but muach better on working across rows.</p>\n\n<p>I'd suggest to turn the table into 'individual' facts about a row, e.g.</p>\n\n<pre><code>select <key>, col1 as value From aTable\nUNION\nselect <key>, col2 as value From aTable\nUNION\n... and so on for the other columns to be summed.\n</code></pre>\n\n<p>This can be turned into a view i.e.</p>\n\n<pre><code>create view aView as (select as above).\n</code></pre>\n\n<p>Then the correct answer is just</p>\n\n<pre><code>select key, count(*)\nfrom aView\nwhere value is null\nGroup By key\n</code></pre>\n"
},
{
"answer_id": 7539174,
"author": "Jasper Austin Alexander",
"author_id": 962633,
"author_profile": "https://Stackoverflow.com/users/962633",
"pm_score": 1,
"selected": false,
"text": "<pre><code>create table TEST\n(\n a VARCHAR2(10),\n b VARCHAR2(10),\n c VARCHAR2(10)\n);\n\ninsert into TEST (a, b, c)\nvalues ('jas', 'abhi', 'shail');\ninsert into TEST (a, b, c)\nvalues (null, 'abhi', 'shail');\ninsert into TEST (a, b, c)\nvalues ('jas', null, 'shail');\ninsert into TEST (a, b, c)\nvalues ('jas', 'abhi', null);\ninsert into TEST (a, b, c)\nvalues ('jas', 'abhi', 'abc|xyz');\ninsert into TEST (a, b, c)\nvalues ('jas', 'abhi', 'abc|xyz');\ninsert into TEST (a, b, c)\nvalues ('jas', 'abhi', 'abc|xyz');\ninsert into TEST (a, b, c)\nvalues (null, 'abhi', 'abc|xyz');\ncommit;\n\nselect sum(nvl2(a,null,1)),sum(nvl2(b,null,1)),sum(nvl2(c,null,1)) from test \nwhere a is null \nor b is null\nor c is null\norder by 1,2,3 \n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm looking for a query which will return me an extra column at the end of my current query which is the count of all columns within the return set which contain a null column. For example:
```
Col 1 - Col 2 - Col 3
A B 0
A NULL 1
NULL NULL 2
```
Is there a simple way to get this return set based on the row values rather than having to requery all the criteria which fetches the original rows?
|
Ugly solution:
```
select Col1, Col2,
case when Col1 is null then 1 else 0 end
+ case when Col2 is null then 1 else 0 end
as Col3
from (
select 'A' as Col1, 'B' as Col2
union select 'A', NULL
union select NULL, NULL
) z
```
This returns
```
Col1 Col2 Col3
NULL NULL 2
A NULL 1
A B 0
```
|
173,757 |
<p>We run a medium-size site that gets a few hundred thousand pageviews a day. Up until last weekend we ran with a load usually below 0.2 on a virtual machine. The OS is Ubuntu.</p>
<p>When deploying the latest version of our application, we also did an apt-get dist-upgrade before deploying. After we had deployed we noticed that the load on the CPU had spiked dramatically (sometimes reaching 10 and stopping to respond to page requests). </p>
<p>We tried dumping a full minute of Xdebug profiling data from PHP, but looking through it revealed only a few somewhat slow parts, but nothing to explain the huge jump.</p>
<p>We are now pretty sure that nothing in the new version of our website is triggering the problem, but we have no way to be sure. We have rolled back a lot of the changes, but the problem still persists.</p>
<p>When look at processes, we see that single Apache processes use quite a bit of CPU over a longer period of time than strictly necessary. However, when using strace on the affected process, we never see anything but</p>
<pre><code>accept(3,
</code></pre>
<p>and it hangs for a while before receiving a new connection, so we can't actually see what is causing the problem.</p>
<p>The stack is PHP 5, Apache 2 (prefork), MySQL 5.1. Most things run through Memcached. We've tried APC and eAccelerator.</p>
<p>So, what should be our next step? Are there any profiling methods we overlooked/don't know about?</p>
|
[
{
"answer_id": 173788,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps you where using worker MPM before and now you are not?</p>\n\n<p>I know PHP5 does not work with the Worker MPM. On my Ubuntu server, PHP5 can only be installed with the Prefork MPM. It seems that PHP5 module is not compatible with multithreading version of Apache. </p>\n\n<p>I found a link here that will show you how to get better performance with <a href=\"http://ivan.gudangbaca.com/installing_apache2_and_php5_using_mod_fcgid\" rel=\"nofollow noreferrer\">mod_fcgid</a></p>\n\n<p>To see what worker MPM is see <a href=\"http://httpd.apache.org/docs/2.0/mod/worker.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 173833,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 1,
"selected": false,
"text": "<p>I'd use dTrace to solve this mystery... if it was running on Solaris or Mac... but since Linux doesn't have it you might want to try their <a href=\"http://sourceware.org/systemtap/\" rel=\"nofollow noreferrer\">Systemtap</a>, however I can't say anything about its usability since I haven't used it.</p>\n\n<p>With dTrace you could easily sniff out the culprits within a day, and would hope with Systemtap it would be similiar</p>\n"
},
{
"answer_id": 173942,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 0,
"selected": false,
"text": "<p>Another option that I can't assure you will do any good, but it's more than worth the effort. Is to read the detailed changelog for the new version, and review what might have changed that could remotely affect you. </p>\n\n<p>Going through the changelogs has saved me more than once. Especially when some config options have changed and when something got deprecated. Worst case is it'll give you some clues as to where to look next</p>\n"
},
{
"answer_id": 174994,
"author": "Jon Topper",
"author_id": 6945,
"author_profile": "https://Stackoverflow.com/users/6945",
"pm_score": 3,
"selected": false,
"text": "<p>Seeing an accept() call from your Apache process isn't at all unusual - that's the webserver waiting for a new request.</p>\n\n<p>First of all, you want to establish what the parameters of the load are. Something like</p>\n\n<pre><code>vmstat 1\n</code></pre>\n\n<p>will show you what your system is up to. Look in the 'swap' and 'io' columns. If you see anything other than '0' in the 'si' and 'so' columns, your system is swapping because of a low memory condition. Consider reducing the number of running Apache children, or throwing more RAM in your server.</p>\n\n<p>If RAM isn't an issue, look at the 'cpu' columns. You're interested in the 'us' and 'sy' columns. These show you the percentage of CPU time spent in either user processes or system. A high 'us' number points the finger at Apache or your scripts - or potentially something else on the server.</p>\n\n<p>Running</p>\n\n<pre><code>top\n</code></pre>\n\n<p>will show you which processes are the most active.</p>\n\n<p>Have you ruled out your database? The most common cause of unexpectedly high load I've seen on production LAMP stacks come down to database queries. You may have deployed new code with an expensive query in it; or got to the point where there are enough rows in your dataset to cause previously cheap queries to become expensive.</p>\n\n<p>During periods of high load, do</p>\n\n<pre><code>echo \"show full processlist\" | mysql | grep -v Sleep\n</code></pre>\n\n<p>to see if there are either long-running queries, or huge numbers of the same query operating at once. Other mysql tools will help you optimise these.</p>\n\n<p>You may find it useful to configure and use mod_status for Apache, which will allow you to see what request each Apache child is serving and for how long it has been doing so.</p>\n\n<p>Finally, get some long-term statistical monitoring set up. Something like zabbix is straightforward to configure, and will let you monitor resource usage over time, such that if things get slow, you have historical baselines to compare against, and a better ieda of when problems started.</p>\n"
},
{
"answer_id": 218509,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 5,
"selected": true,
"text": "<p>The answer ended up being not-Apache related. As mentioned, we were on a virtual machine. Our user sessions are pretty big (think 500kB per active user), so we had a lot of disk IO. The disk was nearly full, meaning that Ubuntu spent a lot of time moving things around (or so we think). There was no easy way to extend the disk (because it was not set up properly for VMWare). This completely killed performance, and Apache and MySQL would occasionally use 100% CPU (for a very short time), and the system would be so slow to update the CPU usage meters that it seemed to be stuck there.</p>\n\n<p>We ended up setting up a new VM (which also gave us the opportunity to thoroughly document everything on the server). On the new VM we allocated plenty of disk space, and moved sessions into memory (using memcached). Our load dropped to 0.2 on off-peak use and around 1 near peak use (on a 2-CPU VM). Moving the sessions into memcached took a lot of disk IO away (we were constantly using about 2MB/s of disk IO, which is very bad).</p>\n\n<p>Conclusion; sometimes you just have to start over... :)</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606/"
] |
We run a medium-size site that gets a few hundred thousand pageviews a day. Up until last weekend we ran with a load usually below 0.2 on a virtual machine. The OS is Ubuntu.
When deploying the latest version of our application, we also did an apt-get dist-upgrade before deploying. After we had deployed we noticed that the load on the CPU had spiked dramatically (sometimes reaching 10 and stopping to respond to page requests).
We tried dumping a full minute of Xdebug profiling data from PHP, but looking through it revealed only a few somewhat slow parts, but nothing to explain the huge jump.
We are now pretty sure that nothing in the new version of our website is triggering the problem, but we have no way to be sure. We have rolled back a lot of the changes, but the problem still persists.
When look at processes, we see that single Apache processes use quite a bit of CPU over a longer period of time than strictly necessary. However, when using strace on the affected process, we never see anything but
```
accept(3,
```
and it hangs for a while before receiving a new connection, so we can't actually see what is causing the problem.
The stack is PHP 5, Apache 2 (prefork), MySQL 5.1. Most things run through Memcached. We've tried APC and eAccelerator.
So, what should be our next step? Are there any profiling methods we overlooked/don't know about?
|
The answer ended up being not-Apache related. As mentioned, we were on a virtual machine. Our user sessions are pretty big (think 500kB per active user), so we had a lot of disk IO. The disk was nearly full, meaning that Ubuntu spent a lot of time moving things around (or so we think). There was no easy way to extend the disk (because it was not set up properly for VMWare). This completely killed performance, and Apache and MySQL would occasionally use 100% CPU (for a very short time), and the system would be so slow to update the CPU usage meters that it seemed to be stuck there.
We ended up setting up a new VM (which also gave us the opportunity to thoroughly document everything on the server). On the new VM we allocated plenty of disk space, and moved sessions into memory (using memcached). Our load dropped to 0.2 on off-peak use and around 1 near peak use (on a 2-CPU VM). Moving the sessions into memcached took a lot of disk IO away (we were constantly using about 2MB/s of disk IO, which is very bad).
Conclusion; sometimes you just have to start over... :)
|
173,786 |
<p>I have a UIScrollView that shows vertical data, but where the horizontal component is no wider than the screen of the iPhone. The problem is that the user is still able to drag horizontally, and basically expose blank sections of the UI. I have tried setting:</p>
<pre><code>scrollView.alwaysBounceHorizontal = NO;
scrollView.directionalLockEnabled = YES;
</code></pre>
<p>Which helps a little, but still doesn't stop the user from being able to drag horizontally. Surely there is a way to fix this easily?</p>
|
[
{
"answer_id": 173852,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": 3,
"selected": false,
"text": "<p>Try setting scrollView.bounces to NO and scrollView.alwaysBounceVertical to YES.</p>\n"
},
{
"answer_id": 174920,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 5,
"selected": true,
"text": "<p>That's strange, because whenever I create a scroll view with frame and content size within the bounds of the screen on either dimension, the scroll view does not scroll (or bounce) in that direction.</p>\n\n<pre><code>// Should scroll vertically but not horizontally\nUIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];\nscrollView.contentSize = CGSizeMake(320, 1000);\n</code></pre>\n\n<p>Are you sure the frame fits completely within the screen and contentSize's width is not greater than the scroll view's width?</p>\n"
},
{
"answer_id": 176203,
"author": "benzado",
"author_id": 10947,
"author_profile": "https://Stackoverflow.com/users/10947",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure the UIScrollView's contentSize is not wider than the UIScrollView itself. In my own apps this was enough to avoid horizontal scrolling, except in cases where I got really crazy swiping in random directions (e.g., starting a scroll while the view was still decelerating).</p>\n"
},
{
"answer_id": 178761,
"author": "spotcatbug",
"author_id": 4756,
"author_profile": "https://Stackoverflow.com/users/4756",
"pm_score": 0,
"selected": false,
"text": "<p>Something to keep in mind: <em>You</em> know there's nothing extra to see horizontally, but will your users know that? You may want a little horizontal bounce, even if there's no extra content to show horizontally. This let's the user know that their attempts to scroll horizontally are not being ignored, there's just nothing there for them to see. But, yeah, often you really don't want the bounce.</p>\n"
},
{
"answer_id": 10949232,
"author": "Denis Kutlubaev",
"author_id": 751641,
"author_profile": "https://Stackoverflow.com/users/751641",
"pm_score": 0,
"selected": false,
"text": "<p>My version for webViews, a common solution: </p>\n\n<pre><code>- (void)webViewDidFinishLoad:(UIWebView *)webView {\n\n[webView.scrollView setContentSize: CGSizeMake(webView.frame.size.width, webView.scrollView.contentSize.height)];\n\n}\n</code></pre>\n"
},
{
"answer_id": 14412762,
"author": "n13",
"author_id": 129213,
"author_profile": "https://Stackoverflow.com/users/129213",
"pm_score": 2,
"selected": false,
"text": "<p>Whether or not a view scrolls (and bounces) horizontally depends on three things:</p>\n\n<ul>\n<li>The content size</li>\n<li>The left and right content insets</li>\n<li>The width of the scroll view - </li>\n</ul>\n\n<p>If the scroll view can fit the content size plus the insets then it doesn't scroll or bounce.</p>\n\n<p>Avoid horizontal bouncing like so:</p>\n\n<pre><code>scrollView.contentSize = CGSizeMake(scrollView.frame.size.width - scrollView.contentInset.left - scrollView.contentInset.right, height);\n</code></pre>\n\n<p>I am adding this answer because the previous ones did not take contentInset into account.</p>\n"
},
{
"answer_id": 14413653,
"author": "Jaldip Katre",
"author_id": 1421502,
"author_profile": "https://Stackoverflow.com/users/1421502",
"pm_score": 3,
"selected": false,
"text": "<p>The checkbox for bounce vertically in storyboard-scrollview can simply help...</p>\n\n<p><img src=\"https://i.stack.imgur.com/oqtYU.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 22750291,
"author": "Asnis Apps",
"author_id": 2926546,
"author_profile": "https://Stackoverflow.com/users/2926546",
"pm_score": 5,
"selected": false,
"text": "<pre><code>scrollView.bounces = NO;\n</code></pre>\n\n<p>Worked for me.</p>\n"
},
{
"answer_id": 38840638,
"author": "Addison",
"author_id": 1525759,
"author_profile": "https://Stackoverflow.com/users/1525759",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone developing for OS X is looking here, as of OS X 10.7, the solution is to set the <a href=\"https://developer.apple.com/reference/appkit/nsscrollview/1403540-horizontalscrollelasticity\" rel=\"nofollow\">horizontalScrollElasticity</a> property to <code>false</code>/<code>NO</code> on the scroll view, like this:</p>\n\n<p>Swift:</p>\n\n<pre><code>scrollView.horizontalScrollElasticity = false\n</code></pre>\n\n<p>Objective-C:</p>\n\n<pre><code>scrollView.horizontalScrollElasticity = NO\n</code></pre>\n"
},
{
"answer_id": 40536760,
"author": "Michael Katkov",
"author_id": 955321,
"author_profile": "https://Stackoverflow.com/users/955321",
"pm_score": 3,
"selected": false,
"text": "<p>That works for me in Swift:</p>\n\n<pre><code>scrollView.alwaysBounceHorizontal = false\nscrollView.bounces = false\n</code></pre>\n"
},
{
"answer_id": 54071842,
"author": "Luan Si Ho",
"author_id": 7895927,
"author_profile": "https://Stackoverflow.com/users/7895927",
"pm_score": -1,
"selected": false,
"text": "<p>In my case, i just need to set this line:</p>\n\n<p><code>collectionView.bounces = false</code></p>\n"
},
{
"answer_id": 69990134,
"author": "xyzgentoo",
"author_id": 602024,
"author_profile": "https://Stackoverflow.com/users/602024",
"pm_score": 0,
"selected": false,
"text": "<p>You can disable horizontal bounces like this:</p>\n<pre><code>- (void)scrollViewDidScroll:(UIScrollView *)scrollView {\n if (scrollView.contentOffset.x < 0) {\n scrollView.contentOffset = CGPointMake(0, scrollView.contentOffset.y);\n } else if (scrollView.contentOffset.x > scrollView.contentSize.width) {\n scrollView.contentOffset = CGPointMake(scrollView.contentSize.width, scrollView.contentOffset.y);\n }\n}\n</code></pre>\n<p>It resets the contentOffset.x manually and won't affect the vertical bounces. It works...</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] |
I have a UIScrollView that shows vertical data, but where the horizontal component is no wider than the screen of the iPhone. The problem is that the user is still able to drag horizontally, and basically expose blank sections of the UI. I have tried setting:
```
scrollView.alwaysBounceHorizontal = NO;
scrollView.directionalLockEnabled = YES;
```
Which helps a little, but still doesn't stop the user from being able to drag horizontally. Surely there is a way to fix this easily?
|
That's strange, because whenever I create a scroll view with frame and content size within the bounds of the screen on either dimension, the scroll view does not scroll (or bounce) in that direction.
```
// Should scroll vertically but not horizontally
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
scrollView.contentSize = CGSizeMake(320, 1000);
```
Are you sure the frame fits completely within the screen and contentSize's width is not greater than the scroll view's width?
|
173,814 |
<p>How can ALTER be used to drop a column in a MySQL table if that column exists? </p>
<p>I know I can use <code>ALTER TABLE my_table DROP COLUMN my_column</code>, but that will throw an error if <code>my_column</code> does not exist. Is there alternative syntax for dropping the column conditionally?</p>
<p>I'm using MySQL version 4.0.18.</p>
|
[
{
"answer_id": 173820,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 7,
"selected": true,
"text": "<p><strong>For MySQL, there is none:</strong> <a href=\"http://bugs.mysql.com/bug.php?id=10789\" rel=\"noreferrer\">MySQL Feature Request</a>. </p>\n\n<p>Allowing this is arguably a really bad idea, anyway: <code>IF EXISTS</code> indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.</p>\n\n<p>But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.</p>\n\n<p>MariaDB also supports the following starting with 10.0.2:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DROP [COLUMN] [IF EXISTS] col_name \n</code></pre>\n\n<p>i. e.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>ALTER TABLE my_table DROP IF EXISTS my_column;\n</code></pre>\n\n<p>But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL. </p>\n"
},
{
"answer_id": 2120452,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 6,
"selected": false,
"text": "<p>There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.</p>\n\n<pre><code>drop procedure if exists schema_change;\n\ndelimiter ';;'\ncreate procedure schema_change() begin\n\n /* delete columns if they exist */\n if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column1') then\n alter table table1 drop column `column1`;\n end if;\n if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column2') then\n alter table table1 drop column `column2`;\n end if;\n\n /* add columns */\n alter table table1 add column `column1` varchar(255) NULL;\n alter table table1 add column `column2` varchar(255) NULL;\n\nend;;\n\ndelimiter ';'\ncall schema_change();\n\ndrop procedure if exists schema_change;\n</code></pre>\n\n<p>I wrote some more detailed information in a <a href=\"http://bitkickers.blogspot.com/2010/01/mysql-drop-column-if-exists.html\" rel=\"noreferrer\">blog post</a>.</p>\n"
},
{
"answer_id": 2155890,
"author": "DrHyde",
"author_id": 261131,
"author_profile": "https://Stackoverflow.com/users/261131",
"pm_score": 3,
"selected": false,
"text": "<p>Chase Seibert's answer works, but I'd add that if you have several schemata you want to alter the SELECT thus:</p>\n\n<pre><code>select * from information_schema.columns where table_schema in (select schema()) and table_name=...\n</code></pre>\n"
},
{
"answer_id": 6453654,
"author": "ajp",
"author_id": 22045,
"author_profile": "https://Stackoverflow.com/users/22045",
"pm_score": -1,
"selected": false,
"text": "<p>I realise this thread is quite old now, but I was having the same problem.\nThis was my very basic solution using the MySQL Workbench, but it worked fine...</p>\n\n<ol>\n<li>get a new sql editor and execute SHOW TABLES to get a list of your tables</li>\n<li>select all of the rows, and choose copy to clipboard (unquoted) from the context menu</li>\n<li>paste the list of names into another editor tab</li>\n<li>write your query, ie ALTER TABLE <code>x</code> DROP <code>a</code>;</li>\n<li>do some copying and pasting, so you end up with separate query for each table</li>\n<li>Toggle whether the workbench should stop when an error occurs</li>\n<li>Hit execute and look through the output log</li>\n</ol>\n\n<p>any tables which had the table now haven't\nany tables which didn't will have shown an error in the logs</p>\n\n<p>then you can find/replace 'drop <code>a</code>' change it to 'ADD COLUMN <code>b</code> INT NULL' etc and run the whole thing again....</p>\n\n<p>a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.</p>\n"
},
{
"answer_id": 45505899,
"author": "Pradeep Puranik",
"author_id": 340131,
"author_profile": "https://Stackoverflow.com/users/340131",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is an old thread, but there is a simple way to handle this requirement without using stored procedures. This may help someone.</p>\n\n<pre><code>set @exist_Check := (\n select count(*) from information_schema.columns \n where TABLE_NAME='YOUR_TABLE' \n and COLUMN_NAME='YOUR_COLUMN' \n and TABLE_SCHEMA=database()\n) ;\nset @sqlstmt := if(@exist_Check>0,'alter table YOUR_TABLE drop column YOUR_COLUMN', 'select ''''') ;\nprepare stmt from @sqlstmt ;\nexecute stmt ;\n</code></pre>\n\n<p>Hope this helps someone, as it did me (after a lot of trial and error).</p>\n"
},
{
"answer_id": 49676339,
"author": "sp00m",
"author_id": 1225328,
"author_profile": "https://Stackoverflow.com/users/1225328",
"pm_score": 4,
"selected": false,
"text": "<p>I just built a reusable procedure that can help making <code>DROP COLUMN</code> idempotent:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>-- column_exists:\n\nDROP FUNCTION IF EXISTS column_exists;\n\nDELIMITER $$\nCREATE FUNCTION column_exists(\n tname VARCHAR(64),\n cname VARCHAR(64)\n)\n RETURNS BOOLEAN\n READS SQL DATA\n BEGIN\n RETURN 0 < (SELECT COUNT(*)\n FROM `INFORMATION_SCHEMA`.`COLUMNS`\n WHERE `TABLE_SCHEMA` = SCHEMA()\n AND `TABLE_NAME` = tname\n AND `COLUMN_NAME` = cname);\n END $$\nDELIMITER ;\n\n-- drop_column_if_exists:\n\nDROP PROCEDURE IF EXISTS drop_column_if_exists;\n\nDELIMITER $$\nCREATE PROCEDURE drop_column_if_exists(\n tname VARCHAR(64),\n cname VARCHAR(64)\n)\n BEGIN\n IF column_exists(tname, cname)\n THEN\n SET @drop_column_if_exists = CONCAT('ALTER TABLE `', tname, '` DROP COLUMN `', cname, '`');\n PREPARE drop_query FROM @drop_column_if_exists;\n EXECUTE drop_query;\n END IF;\n END $$\nDELIMITER ;\n</code></pre>\n\n<p>Usage:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CALL drop_column_if_exists('my_table', 'my_column');\n</code></pre>\n\n<p>Example:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT column_exists('my_table', 'my_column'); -- 1\nCALL drop_column_if_exists('my_table', 'my_column'); -- success\nSELECT column_exists('my_table', 'my_column'); -- 0\nCALL drop_column_if_exists('my_table', 'my_column'); -- success\nSELECT column_exists('my_table', 'my_column'); -- 0\n</code></pre>\n"
},
{
"answer_id": 57681721,
"author": "Frank Flynn",
"author_id": 52549,
"author_profile": "https://Stackoverflow.com/users/52549",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps the simplest way to solve this (that will work) is:</p>\n\n<ul>\n<li><p>CREATE new_table AS SELECT id, col1, col2, ... (only the columns you actually want in the final table)\nFROM my_table;</p></li>\n<li><p>RENAME my_table TO old_table, new_table TO my_table;</p></li>\n<li><p>DROP old_table;</p></li>\n</ul>\n\n<p>Or keep old_table for a rollback if needed.</p>\n\n<p>This will work but foreign keys will not be moved. You would have to re-add them to my_table later; also foreign keys in other tables that reference my_table will have to be fixed (pointed to the new my_table).</p>\n\n<p>Good Luck...</p>\n"
},
{
"answer_id": 59574226,
"author": "Shah Zain",
"author_id": 5196973,
"author_profile": "https://Stackoverflow.com/users/5196973",
"pm_score": 2,
"selected": false,
"text": "<h2>You can use this script, use your column, schema and table name</h2>\n<pre><code> IF EXISTS (SELECT *\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName' \n AND TABLE_SCHEMA = SchemaName)\n BEGIN\n ALTER TABLE TableName DROP COLUMN ColumnName;\n END;\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7362/"
] |
How can ALTER be used to drop a column in a MySQL table if that column exists?
I know I can use `ALTER TABLE my_table DROP COLUMN my_column`, but that will throw an error if `my_column` does not exist. Is there alternative syntax for dropping the column conditionally?
I'm using MySQL version 4.0.18.
|
**For MySQL, there is none:** [MySQL Feature Request](http://bugs.mysql.com/bug.php?id=10789).
Allowing this is arguably a really bad idea, anyway: `IF EXISTS` indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.
But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.
MariaDB also supports the following starting with 10.0.2:
```sql
DROP [COLUMN] [IF EXISTS] col_name
```
i. e.
```sql
ALTER TABLE my_table DROP IF EXISTS my_column;
```
But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.
|
173,821 |
<p>I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?</p>
<p>At the moment I am doing:</p>
<pre><code>SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug("lynxThreeFile::readSlideInfoHeader");
}
</code></pre>
<p>but what I want is something generic:</p>
<pre><code>SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug(this.className() + "::" + this.functionName());
}
</code></pre>
|
[
{
"answer_id": 173828,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 6,
"selected": true,
"text": "<p>\"<code>__FUNCTION__</code>\" is supported by both MSVC and GCC and should give you the information you need. </p>\n"
},
{
"answer_id": 174369,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "<p>If you check out boost there is a macro BOOST_CURRENT_FUNCTION that is portable across platforms. In the C99 standard there is a compiler variable <code>__func__</code> that has the desired effect. I believe has been accepted into the C++0x standard. A reasonable number of compilers will already support this.</p>\n"
},
{
"answer_id": 175047,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 4,
"selected": false,
"text": "<p>I see from your example that you are using <a href=\"http://qt.nokia.com/\" rel=\"noreferrer\">Qt</a>. In which case your best bet is to use <code>Q_FUNC_INFO</code> found in <code><QGlobal></code>. Here's the description:</p>\n\n<blockquote>\n <p>Expands to a string that describe the\n function the macro resides in. How\n this string looks more specifically is\n compiler dependent. With GNU GCC it is\n typically the function signature,\n while with other compilers it might be\n the line and column number.</p>\n</blockquote>\n"
},
{
"answer_id": 175311,
"author": "Mark Kegel",
"author_id": 14788,
"author_profile": "https://Stackoverflow.com/users/14788",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using gcc you may find <code>__PRETTY_FUNCTION__</code> more to your liking.</p>\n"
},
{
"answer_id": 217808,
"author": "Ronny Brendel",
"author_id": 14114,
"author_profile": "https://Stackoverflow.com/users/14114",
"pm_score": 3,
"selected": false,
"text": "<p><strong><code>__func__</code></strong> is c99 ( which does in turn mean it might not work with visual studio - but hey it's standard :o) )</p>\n\n<p><strong><code>__FUNCTION__</code></strong> works pretty much everywhere</p>\n\n<p><strong><code>__PRETTY_FUNCTION__</code></strong> is gnu specific and returns the full qualified name with (namespaces?), classname, returntype, functionname, parameterslist</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24459/"
] |
I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?
At the moment I am doing:
```
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug("lynxThreeFile::readSlideInfoHeader");
}
```
but what I want is something generic:
```
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug(this.className() + "::" + this.functionName());
}
```
|
"`__FUNCTION__`" is supported by both MSVC and GCC and should give you the information you need.
|
173,834 |
<p>Given an SQLConnection object how can you get a schema for a single table?</p>
<p>I seemed to be able to get the schema from a <code>DataSet</code> which I'd gotten from running a query, but all the schema info I could get from the connection seemed to be related to what tables were available and not the actual details on the tables.</p>
|
[
{
"answer_id": 173863,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>I think accessing the schema from the query (via GetSchemaTable) is the only way to do it. \nYou can run a query which returns no rows (select * from table where 1=2) if the schema is all you're interested in.</p>\n\n<p>You should use the KeyInfo CommandBehaviour to execute the source query, as otherwise not all the information returned is guaranteed to be accurate</p>\n\n<pre><code>Command.ExecuteReader(CommandBehavior.KeyInfo)\n</code></pre>\n"
},
{
"answer_id": 173871,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": false,
"text": "<p>This code will do what you want (obviously change the table name, server name etc):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\n\nnamespace ConsoleApp\n{\n class Program\n {\n static void Main(string[] args)\n {\n string query = \"SELECT * FROM t where 1=0\";\n string connectionString = \"initial catalog=test;data source=localhost;Trusted_Connection=Yes\";\n\n DataTable tblSchema;\n\n using (SqlConnection cnn = new SqlConnection(connectionString))\n {\n using (SqlCommand cmd = cnn.CreateCommand())\n {\n cmd.CommandText = query;\n cmd.CommandType = CommandType.Text;\n cnn.Open();\n using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.KeyInfo))\n {\n tblSchema = rdr.GetSchemaTable();\n }\n cnn.Close();\n }\n }\n int numColumns = tblSchema.Columns.Count;\n foreach (DataRow dr in tblSchema.Rows)\n {\n Console.WriteLine(\"{0}: {1}\", dr[\"ColumnName\"], dr[\"DataType\"]);\n }\n\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 173881,
"author": "KristoferA",
"author_id": 11241,
"author_profile": "https://Stackoverflow.com/users/11241",
"pm_score": 0,
"selected": false,
"text": "<p>SQL Server - query the catalog views... sysobjects, syscolumns etc if SQL 2000 or earlier... sys.objects, sys.columns etc if SQL 2005 or higher. (although the older views are still available it is advisable to use the newer ones)</p>\n\n<p>Complete reference here:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms189783.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms189783.aspx</a></p>\n\n<p>Example:</p>\n\n<pre><code>select so.name, sc.*\nfrom sys.objects as so\ninner join sys.columns as sc on sc.object_id = so.object_id\nwhere so.name='some_table'\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
Given an SQLConnection object how can you get a schema for a single table?
I seemed to be able to get the schema from a `DataSet` which I'd gotten from running a query, but all the schema info I could get from the connection seemed to be related to what tables were available and not the actual details on the tables.
|
I think accessing the schema from the query (via GetSchemaTable) is the only way to do it.
You can run a query which returns no rows (select \* from table where 1=2) if the schema is all you're interested in.
You should use the KeyInfo CommandBehaviour to execute the source query, as otherwise not all the information returned is guaranteed to be accurate
```
Command.ExecuteReader(CommandBehavior.KeyInfo)
```
|
173,835 |
<p>I am using Spry (<code>SpryData.js,xpath.js</code>)</p>
<pre><code> var ds1 = new Spry.Data.XMLDataSet("_db/db.xml", "bildiriler/bildiri",{useCache:false});
// load the xml tree
</code></pre>
<p>....</p>
<pre><code><!-- use it in a loop -
Sometimes the page use "ds1.loadData();" to refresh the data -->
<div spry:region="ds1" spry:repeatchildren="ds1">
<a href="#">{author}</a></div>
</code></pre>
<p>So how can I show a loader animation or "Loading text" while XML data is loading </p>
<p>(It takes a long time -about 2 sec from a slow CD-. My XML file is big 100KB )</p>
|
[
{
"answer_id": 173859,
"author": "Alex Gyoshev",
"author_id": 25427,
"author_profile": "https://Stackoverflow.com/users/25427",
"pm_score": 1,
"selected": false,
"text": "<p>I am not quite good at Spry, but can't you add a css background to the div placeholder (<div spry:region=\"ds1\" ...) which will be shown at all time (and probably can be replaced through an observer that sets the background-image of the placeholder when the rows are loaded)...</p>\n"
},
{
"answer_id": 174320,
"author": "Errico Malatesta",
"author_id": 24439,
"author_profile": "https://Stackoverflow.com/users/24439",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. I found it (strangely, not from the docs of Spry on <a href=\"http://labs.adobe.com/technologies/spry\" rel=\"nofollow noreferrer\">http://labs.adobe.com/technologies/spry</a>)\nI found it from this example -> <a href=\"http://www.infoaccelerator.net/blog/archives.cfm/date/2006/7\" rel=\"nofollow noreferrer\">http://www.infoaccelerator.net/blog/archives.cfm/date/2006/7</a></p>\n\n<p>i put this line into the div tag (spry:region) :</p>\n\n<pre><code><p spry:state =\"loading\"> Loading ( text or an image ) </p>\n</code></pre>\n"
},
{
"answer_id": 3351158,
"author": "loali",
"author_id": 404265,
"author_profile": "https://Stackoverflow.com/users/404265",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div align=\"center\" spry:region=\"dsmain\" spry:state=\"loading\" >\n<img src=\"../icon/Loader/1.gif\" />\n<br />please wait ...\n</div> \n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24439/"
] |
I am using Spry (`SpryData.js,xpath.js`)
```
var ds1 = new Spry.Data.XMLDataSet("_db/db.xml", "bildiriler/bildiri",{useCache:false});
// load the xml tree
```
....
```
<!-- use it in a loop -
Sometimes the page use "ds1.loadData();" to refresh the data -->
<div spry:region="ds1" spry:repeatchildren="ds1">
<a href="#">{author}</a></div>
```
So how can I show a loader animation or "Loading text" while XML data is loading
(It takes a long time -about 2 sec from a slow CD-. My XML file is big 100KB )
|
I am not quite good at Spry, but can't you add a css background to the div placeholder (<div spry:region="ds1" ...) which will be shown at all time (and probably can be replaced through an observer that sets the background-image of the placeholder when the rows are loaded)...
|
173,846 |
<p>I'm trying to have my Struts2 app redirect to a generated URL. In this case, I want the URL to use the current date, or a date I looked up in a database. So <code>/section/document</code> becomes <code>/section/document/2008-10-06</code></p>
<p>What's the best way to do this?</p>
|
[
{
"answer_id": 174100,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 2,
"selected": false,
"text": "<p>I ended up subclassing Struts' <code>ServletRedirectResult</code> and overriding it's <code>doExecute()</code> method to do my logic before calling <code>super.doExecute()</code>. it looks like this:</p>\n\n<pre><code>public class AppendRedirectionResult extends ServletRedirectResult {\n private DateFormat df = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n @Override\n protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {\n String date = df.format(new Date());\n String loc = \"/section/document/\"+date;\n super.doExecute(loc, invocation);\n }\n}\n</code></pre>\n\n<p>I'm not sure if this is the best way to do it, but it works.</p>\n"
},
{
"answer_id": 179251,
"author": "Johnny Wey",
"author_id": 25855,
"author_profile": "https://Stackoverflow.com/users/25855",
"pm_score": 7,
"selected": true,
"text": "<p>Here's how we do it:</p>\n\n<p>In Struts.xml, have a dynamic result such as:</p>\n\n<pre><code><result name=\"redirect\" type=\"redirect\">${url}</result>\n</code></pre>\n\n<p>In the action:</p>\n\n<pre><code>private String url;\n\npublic String getUrl()\n{\n return url;\n}\n\npublic String execute()\n{\n [other stuff to setup your date]\n url = \"/section/document\" + date;\n return \"redirect\";\n}\n</code></pre>\n\n<p>You can actually use this same technology to set dynamic values for any variable in your struts.xml using OGNL. We've created all sorts of dynamic results including stuff like RESTful links. Cool stuff.</p>\n"
},
{
"answer_id": 696804,
"author": "Ivan Morales",
"author_id": 84573,
"author_profile": "https://Stackoverflow.com/users/84573",
"pm_score": 4,
"selected": false,
"text": "<p>One can also use <code>annotations</code> and the Convention plug-in to avoid repetitive configuration in struts.xml:</p>\n\n<pre><code>@Result(location=\"${url}\", type=\"redirect\")\n</code></pre>\n\n<p>The ${url} means \"use the value of the getUrl method\"</p>\n"
},
{
"answer_id": 23708112,
"author": "hari",
"author_id": 3547935,
"author_profile": "https://Stackoverflow.com/users/3547935",
"pm_score": 2,
"selected": false,
"text": "<p>If anyone wants to redirect directly in <code>ActionClass</code>:</p>\n\n<pre><code>public class RedirecActionExample extends ActionSupport {\nHttpServletResponse response=(HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);\n\n url=\"http://localhost:8080/SpRoom-1.0-SNAPSHOT/\"+date;\n response.sendRedirect(url);\n return super.execute(); \n}\n</code></pre>\n\n<p>Edit: Added a missing quote.</p>\n"
},
{
"answer_id": 24891251,
"author": "tiwari.vikash",
"author_id": 1449506,
"author_profile": "https://Stackoverflow.com/users/1449506",
"pm_score": 1,
"selected": false,
"text": "<p>You can redirect to another action using annotation - </p>\n\n<pre><code>@Result(\n name = \"resultName\",\n type = \"redirectAction\",\n params = { \"actionName\", \"XYZAction\" }\n)\n</code></pre>\n"
},
{
"answer_id": 40402314,
"author": "Aaron",
"author_id": 7659,
"author_profile": "https://Stackoverflow.com/users/7659",
"pm_score": 1,
"selected": false,
"text": "<p>One can redirect directly from an interceptor without regard to which action is involved.</p>\n\n<p><strong>In struts.xml</strong></p>\n\n<pre><code> <global-results>\n <result name=\"redir\" type=\"redirect\">${#request.redirUrl}</result>\n </global-results>\n</code></pre>\n\n<p><strong>In Interceptor</strong></p>\n\n<pre><code>@Override\npublic String intercept(ActionInvocation ai) throws Exception\n{\n final ActionContext context = ai.getInvocationContext(); \n HttpServletRequest request = (HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);\n request.setAttribute(\"redirUrl\", \"http://the.new.target.org\");\n return \"redir\";\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6400/"
] |
I'm trying to have my Struts2 app redirect to a generated URL. In this case, I want the URL to use the current date, or a date I looked up in a database. So `/section/document` becomes `/section/document/2008-10-06`
What's the best way to do this?
|
Here's how we do it:
In Struts.xml, have a dynamic result such as:
```
<result name="redirect" type="redirect">${url}</result>
```
In the action:
```
private String url;
public String getUrl()
{
return url;
}
public String execute()
{
[other stuff to setup your date]
url = "/section/document" + date;
return "redirect";
}
```
You can actually use this same technology to set dynamic values for any variable in your struts.xml using OGNL. We've created all sorts of dynamic results including stuff like RESTful links. Cool stuff.
|
173,851 |
<p>I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect <code>SERVER['argc']</code>, but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.</p>
|
[
{
"answer_id": 173856,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>I think</p>\n\n<pre><code>$_SERVER['REMOTE_ADDR']\n</code></pre>\n\n<p>will not be populated from the CLI.</p>\n\n<p>Also, all the HTTP_* keys in the $_SERVER superglobal won't be populated from the CLI, or do it the right way hop just mentioned :-)</p>\n"
},
{
"answer_id": 173887,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "<p>Use the <a href=\"http://php.net/php_sapi_name\" rel=\"noreferrer\"><code>php_sapi_name()</code></a> function.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if (php_sapi_name() == \"cli\") {\n // In cli-mode\n} else {\n // Not in cli-mode\n}\n</code></pre>\n\n<p>Here are some relevant notes from the docs:</p>\n\n<blockquote>\n <p><strong>php_sapi_name</strong> — Returns the type of interface between web server and PHP</p>\n \n <p>Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.</p>\n</blockquote>\n\n<p>In PHP >= 4.2.0, there is also a predefined constant, <code>PHP_SAPI</code>, that has the same value as <code>php_sapi_name()</code>.</p>\n"
},
{
"answer_id": 1235061,
"author": "Steve",
"author_id": 151283,
"author_profile": "https://Stackoverflow.com/users/151283",
"pm_score": 3,
"selected": false,
"text": "<p>The documentation page for <code>php_sapi</code>_name clearly states how it works:</p>\n<blockquote>\n<p>Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using....</p>\n<p>Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.</p>\n</blockquote>\n<p>I'm not sure why hop doesn't think that PHP is for serious programmers (I'm a serious programmer, and I use PHP daily), but if he wants to help clarify the documentation then perhaps he can audit all possible web servers that PHP can run on and determine the names of all possible interface types for each server. Just make sure to keep that list updated as new web servers and interfaces are added.</p>\n<p>Also, Bobby said:</p>\n<blockquote>\n<p>I'm intrigued as to why the doc. example inspects the first 3 characters, whilst the description states the string should be exactly "CGI"</p>\n</blockquote>\n<p>The description for the example states:</p>\n<blockquote>\n<p>This example checks for the substring cgi because it may also be cgi-fcgi.</p>\n</blockquote>\n"
},
{
"answer_id": 4392867,
"author": "Xeoncross",
"author_id": 99923,
"author_profile": "https://Stackoverflow.com/users/99923",
"pm_score": 5,
"selected": false,
"text": "<p>This will always work. (If the PHP version is 4.2.0 or higher)</p>\n\n<pre><code>define('CLI', PHP_SAPI === 'cli');\n</code></pre>\n\n<p>Which makes it easy to use at the top of your scripts:</p>\n\n<pre><code><?php PHP_SAPI === 'cli' or die('not allowed');\n</code></pre>\n"
},
{
"answer_id": 12654906,
"author": "ya.teck",
"author_id": 272927,
"author_profile": "https://Stackoverflow.com/users/272927",
"pm_score": 4,
"selected": false,
"text": "<p>Here is Drupal 7 implementation: <a href=\"http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_is_cli/7\" rel=\"noreferrer\">drupal_is_cli()</a>:</p>\n\n<pre><code>function drupal_is_cli() {\n return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));\n}\n</code></pre>\n\n<p>However Drupal 8 <a href=\"https://www.drupal.org/node/2295037\" rel=\"noreferrer\">recommends</a> using <code>PHP_SAPI === 'cli'</code></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] |
I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect `SERVER['argc']`, but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.
|
Use the [`php_sapi_name()`](http://php.net/php_sapi_name) function.
```php
if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}
```
Here are some relevant notes from the docs:
>
> **php\_sapi\_name** — Returns the type of interface between web server and PHP
>
>
> Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
>
>
>
In PHP >= 4.2.0, there is also a predefined constant, `PHP_SAPI`, that has the same value as `php_sapi_name()`.
|
173,866 |
<p>I have a web page which contains a select box. When I open a jQuery Dialog it is displayed partly behind the select box.</p>
<p>How should I approach this problem? Should I hide the select box or does jQuery offer some kind of 'shim' solution. (I have Googled but didn't find anything)</p>
<p>Here is some code:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>testJQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
<link rel="stylesheet" href="theme/smooth/theme.css" type="text/css" media="screen" />
</head>
<body>
<a class="pop" href="nix">Click me</a>
<p/>
<select size="20">
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
</select>
<div id="xyz" class="flora hiddenAsset">
<div id="dialog" title="Edit Link">
<p>Enter the link details:</p>
<table width="80%" border="1">
<tr><td>URL</td><td><input id="url" style="width:100%" maxlength="200" value="{url}"/></td></tr>
<tr><td>Title</td><td><input id="title" style="width:100%" maxlength="200" value="{title}"/></td></tr>
<tr><td>Target</td><td><input id="target" size="20" maxlength="200" value="{target}"/></td></tr>
</table>
</div>
</div>
<script type="text/javascript" src="../script/firebug/firebug.js"></script>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript" src="jquery-ui-1.5.2.js"></script>
<script type="text/javascript" src="jqSOAPClient.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(){
console.debug('ready');
$('.hiddenAsset').hide();
$('a.pop').bind('click', showDialog);
console.debug('ready - done');
});
var showDialog = function(){
console.debug('show');
$('#dialog').dialog({
modal: true,
overlay: {
backgroundColor: '#666',
opacity: '.3',
filter: 'alpha(opacity=30)'
},
width: '400px',
height: '300px',
buttons: {
Ok: function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
console.debug('show-done');
return false;
};
})(jQuery);
</script>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 173856,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>I think</p>\n\n<pre><code>$_SERVER['REMOTE_ADDR']\n</code></pre>\n\n<p>will not be populated from the CLI.</p>\n\n<p>Also, all the HTTP_* keys in the $_SERVER superglobal won't be populated from the CLI, or do it the right way hop just mentioned :-)</p>\n"
},
{
"answer_id": 173887,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "<p>Use the <a href=\"http://php.net/php_sapi_name\" rel=\"noreferrer\"><code>php_sapi_name()</code></a> function.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if (php_sapi_name() == \"cli\") {\n // In cli-mode\n} else {\n // Not in cli-mode\n}\n</code></pre>\n\n<p>Here are some relevant notes from the docs:</p>\n\n<blockquote>\n <p><strong>php_sapi_name</strong> — Returns the type of interface between web server and PHP</p>\n \n <p>Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.</p>\n</blockquote>\n\n<p>In PHP >= 4.2.0, there is also a predefined constant, <code>PHP_SAPI</code>, that has the same value as <code>php_sapi_name()</code>.</p>\n"
},
{
"answer_id": 1235061,
"author": "Steve",
"author_id": 151283,
"author_profile": "https://Stackoverflow.com/users/151283",
"pm_score": 3,
"selected": false,
"text": "<p>The documentation page for <code>php_sapi</code>_name clearly states how it works:</p>\n<blockquote>\n<p>Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using....</p>\n<p>Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.</p>\n</blockquote>\n<p>I'm not sure why hop doesn't think that PHP is for serious programmers (I'm a serious programmer, and I use PHP daily), but if he wants to help clarify the documentation then perhaps he can audit all possible web servers that PHP can run on and determine the names of all possible interface types for each server. Just make sure to keep that list updated as new web servers and interfaces are added.</p>\n<p>Also, Bobby said:</p>\n<blockquote>\n<p>I'm intrigued as to why the doc. example inspects the first 3 characters, whilst the description states the string should be exactly "CGI"</p>\n</blockquote>\n<p>The description for the example states:</p>\n<blockquote>\n<p>This example checks for the substring cgi because it may also be cgi-fcgi.</p>\n</blockquote>\n"
},
{
"answer_id": 4392867,
"author": "Xeoncross",
"author_id": 99923,
"author_profile": "https://Stackoverflow.com/users/99923",
"pm_score": 5,
"selected": false,
"text": "<p>This will always work. (If the PHP version is 4.2.0 or higher)</p>\n\n<pre><code>define('CLI', PHP_SAPI === 'cli');\n</code></pre>\n\n<p>Which makes it easy to use at the top of your scripts:</p>\n\n<pre><code><?php PHP_SAPI === 'cli' or die('not allowed');\n</code></pre>\n"
},
{
"answer_id": 12654906,
"author": "ya.teck",
"author_id": 272927,
"author_profile": "https://Stackoverflow.com/users/272927",
"pm_score": 4,
"selected": false,
"text": "<p>Here is Drupal 7 implementation: <a href=\"http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_is_cli/7\" rel=\"noreferrer\">drupal_is_cli()</a>:</p>\n\n<pre><code>function drupal_is_cli() {\n return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));\n}\n</code></pre>\n\n<p>However Drupal 8 <a href=\"https://www.drupal.org/node/2295037\" rel=\"noreferrer\">recommends</a> using <code>PHP_SAPI === 'cli'</code></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11249/"
] |
I have a web page which contains a select box. When I open a jQuery Dialog it is displayed partly behind the select box.
How should I approach this problem? Should I hide the select box or does jQuery offer some kind of 'shim' solution. (I have Googled but didn't find anything)
Here is some code:
```
<!DOCTYPE html>
<html lang="en">
<head>
<title>testJQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
<link rel="stylesheet" href="theme/smooth/theme.css" type="text/css" media="screen" />
</head>
<body>
<a class="pop" href="nix">Click me</a>
<p/>
<select size="20">
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
</select>
<div id="xyz" class="flora hiddenAsset">
<div id="dialog" title="Edit Link">
<p>Enter the link details:</p>
<table width="80%" border="1">
<tr><td>URL</td><td><input id="url" style="width:100%" maxlength="200" value="{url}"/></td></tr>
<tr><td>Title</td><td><input id="title" style="width:100%" maxlength="200" value="{title}"/></td></tr>
<tr><td>Target</td><td><input id="target" size="20" maxlength="200" value="{target}"/></td></tr>
</table>
</div>
</div>
<script type="text/javascript" src="../script/firebug/firebug.js"></script>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript" src="jquery-ui-1.5.2.js"></script>
<script type="text/javascript" src="jqSOAPClient.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(){
console.debug('ready');
$('.hiddenAsset').hide();
$('a.pop').bind('click', showDialog);
console.debug('ready - done');
});
var showDialog = function(){
console.debug('show');
$('#dialog').dialog({
modal: true,
overlay: {
backgroundColor: '#666',
opacity: '.3',
filter: 'alpha(opacity=30)'
},
width: '400px',
height: '300px',
buttons: {
Ok: function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
console.debug('show-done');
return false;
};
})(jQuery);
</script>
</body>
</html>
```
|
Use the [`php_sapi_name()`](http://php.net/php_sapi_name) function.
```php
if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}
```
Here are some relevant notes from the docs:
>
> **php\_sapi\_name** — Returns the type of interface between web server and PHP
>
>
> Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
>
>
>
In PHP >= 4.2.0, there is also a predefined constant, `PHP_SAPI`, that has the same value as `php_sapi_name()`.
|
173,868 |
<p>This is a question you can read everywhere on the web with various answers:</p>
<pre><code>$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
</code></pre>
<p>etc.</p>
<p>However, there is always "the best way" and it should be on Stack Overflow.</p>
|
[
{
"answer_id": 173872,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://uk.php.net/manual/en/function.pathinfo.php\" rel=\"noreferrer\"><code>pathinfo()</code></a></p>\n\n<pre><code>$path_info = pathinfo('/foo/bar/baz.bill');\n\necho $path_info['extension']; // \"bill\"\n</code></pre>\n"
},
{
"answer_id": 173876,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 12,
"selected": true,
"text": "<p>People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).</p>\n\n<p>In fact, it does exist, but few people know it. Meet <a href=\"http://php.net/manual/en/function.pathinfo.php\" rel=\"noreferrer\"><code>pathinfo()</code></a>:</p>\n\n<pre><code>$ext = pathinfo($filename, PATHINFO_EXTENSION);\n</code></pre>\n\n<p>This is fast and built-in. <code>pathinfo()</code> can give you other information, such as canonical path, depending on the constant you pass to it.</p>\n\n<p>Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:</p>\n\n<pre><code>setlocale(LC_ALL,'en_US.UTF-8');\n</code></pre>\n\n<p>Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.</p>\n\n<p>Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.</p>\n\n<p>Enjoy</p>\n"
},
{
"answer_id": 174473,
"author": "Toxygene",
"author_id": 8428,
"author_profile": "https://Stackoverflow.com/users/8428",
"pm_score": 5,
"selected": false,
"text": "<p>E-satis's response is the correct way to determine the file extension.</p>\n\n<p>Alternatively, instead of relying on a files extension, you could use the <a href=\"http://us2.php.net/fileinfo\" rel=\"nofollow noreferrer\">fileinfo</a> to determine the files MIME type.</p>\n\n<p>Here's a simplified example of processing an image uploaded by a user:</p>\n\n<pre><code>// Code assumes necessary extensions are installed and a successful file upload has already occurred\n\n// Create a FileInfo object\n$finfo = new FileInfo(null, '/path/to/magic/file');\n\n// Determine the MIME type of the uploaded file\nswitch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) { \n case 'image/jpg':\n $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);\n break;\n\n case 'image/png':\n $im = imagecreatefrompng($_FILES['image']['tmp_name']);\n break;\n\n case 'image/gif':\n $im = imagecreatefromgif($_FILES['image']['tmp_name']);\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 11914810,
"author": "Anonymous",
"author_id": 1125062,
"author_profile": "https://Stackoverflow.com/users/1125062",
"pm_score": 5,
"selected": false,
"text": "<p>As long as it does not contain a path you can also use:</p>\n\n<pre><code>array_pop(explode('.', $fname))\n</code></pre>\n\n<p>Where <code>$fname</code> is a name of the file, for example: <code>my_picture.jpg</code>.\nAnd the outcome would be: <code>jpg</code></p>\n"
},
{
"answer_id": 12932338,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 6,
"selected": false,
"text": "<p>There is also <a href=\"http://php.net/SplFileInfo\" rel=\"noreferrer\"><code>SplFileInfo</code></a>:</p>\n\n<pre><code>$file = new SplFileInfo($path);\n$ext = $file->getExtension();\n</code></pre>\n\n<p>Often you can write better code if you pass such an object around instead of a string. Your code is more speaking then. Since PHP 5.4 this is a one-liner:</p>\n\n<pre><code>$ext = (new SplFileInfo($path))->getExtension();\n</code></pre>\n"
},
{
"answer_id": 13183055,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 4,
"selected": false,
"text": "<p>Sometimes it's useful to not to use <code>pathinfo($path, PATHINFO_EXTENSION)</code>. For example:</p>\n\n<pre><code>$path = '/path/to/file.tar.gz';\n\necho ltrim(strstr($path, '.'), '.'); // tar.gz\necho pathinfo($path, PATHINFO_EXTENSION); // gz\n</code></pre>\n\n<p>Also note that <code>pathinfo</code> fails to handle some non-ASCII characters (usually it just suppresses them from the output). In extensions that usually isn't a problem, but it doesn't hurt to be aware of that caveat.</p>\n"
},
{
"answer_id": 13604680,
"author": "AlexB",
"author_id": 1139150,
"author_profile": "https://Stackoverflow.com/users/1139150",
"pm_score": -1,
"selected": false,
"text": "<p>Use </p>\n\n<pre><code>str_replace('.', '', strrchr($file_name, '.'))\n</code></pre>\n\n<p>for a quick extension retrieval (if you know for sure your file name has one).</p>\n"
},
{
"answer_id": 20398498,
"author": "Kurt Zhong",
"author_id": 480120,
"author_profile": "https://Stackoverflow.com/users/480120",
"pm_score": 3,
"selected": false,
"text": "<pre><code>substr($path, strrpos($path, '.') + 1);\n</code></pre>\n"
},
{
"answer_id": 25092925,
"author": "Subodh Ghulaxe",
"author_id": 1868660,
"author_profile": "https://Stackoverflow.com/users/1868660",
"pm_score": 4,
"selected": false,
"text": "<p><strong>1)</strong> If you are using <strong>(PHP 5 >= 5.3.6)</strong>\nyou can use <strong><a href=\"http://php.net/manual/en/splfileinfo.getextension.php\">SplFileInfo::getExtension</a> — Gets the file extension</strong></p>\n\n<p>Example code</p>\n\n<pre><code><?php\n\n$info = new SplFileInfo('test.png');\nvar_dump($info->getExtension());\n\n$info = new SplFileInfo('test.tar.gz');\nvar_dump($info->getExtension());\n\n?>\n</code></pre>\n\n<p>This will output</p>\n\n<pre><code>string(3) \"png\"\nstring(2) \"gz\"\n</code></pre>\n\n<p><strong>2)</strong> Another way of getting the extension if you are using <strong>(PHP 4 >= 4.0.3, PHP 5)</strong> is <a href=\"http://php.net/manual/en/function.pathinfo.php\"><strong>pathinfo</strong></a></p>\n\n<p>Example code</p>\n\n<pre><code><?php\n\n$ext = pathinfo('test.png', PATHINFO_EXTENSION);\nvar_dump($ext);\n\n$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);\nvar_dump($ext);\n\n?>\n</code></pre>\n\n<p>This will output</p>\n\n<pre><code>string(3) \"png\"\nstring(2) \"gz\"\n</code></pre>\n\n<p>// EDIT: removed a bracket</p>\n"
},
{
"answer_id": 27961090,
"author": "Deepika Patel",
"author_id": 2756364,
"author_profile": "https://Stackoverflow.com/users/2756364",
"pm_score": 2,
"selected": false,
"text": "<p>This will work</p>\n\n<pre><code>$ext = pathinfo($filename, PATHINFO_EXTENSION);\n</code></pre>\n"
},
{
"answer_id": 28054743,
"author": "Jonathan Ellis",
"author_id": 555485,
"author_profile": "https://Stackoverflow.com/users/555485",
"pm_score": 2,
"selected": false,
"text": "<p>I found that the <code>pathinfo()</code> and <code>SplFileInfo</code> solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a <code>#</code> (fragment identifiers) and/or <code>?</code> (query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.</p>\n\n<p>I found this was a reliable way to use <code>pathinfo()</code> on a URL after first parsing it to strip out the unnecessary clutter after the file extension:</p>\n\n<pre><code>$url_components = parse_url($url); // First parse the URL\n$url_path = $url_components['path']; // Then get the path component\n$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()\n</code></pre>\n"
},
{
"answer_id": 28731667,
"author": "G. I. Joe",
"author_id": 2986881,
"author_profile": "https://Stackoverflow.com/users/2986881",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an example. Suppose $filename is \"example.txt\",</p>\n\n<pre><code>$ext = substr($filename, strrpos($filename, '.', -1), strlen($filename));\n</code></pre>\n\n<p>So $ext will be \".txt\".</p>\n"
},
{
"answer_id": 30207481,
"author": "Shahbaz",
"author_id": 1869193,
"author_profile": "https://Stackoverflow.com/users/1869193",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest way to get file extension in PHP is to use PHP's built-in function <a href=\"http://php.net/manual/en/function.pathinfo.php\" rel=\"nofollow noreferrer\">pathinfo</a>.</p>\n\n<pre><code>$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);\necho ($file_ext); // The output should be the extension of the file e.g., png, gif, or html\n</code></pre>\n"
},
{
"answer_id": 30454683,
"author": "version 2",
"author_id": 4152420,
"author_profile": "https://Stackoverflow.com/users/4152420",
"pm_score": 3,
"selected": false,
"text": "<p>A quick fix would be something like this.</p>\n\n<pre><code>// Exploding the file based on the . operator\n$file_ext = explode('.', $filename);\n\n// Count taken (if more than one . exist; files like abc.fff.2013.pdf\n$file_ext_count = count($file_ext);\n\n// Minus 1 to make the offset correct\n$cnt = $file_ext_count - 1;\n\n// The variable will have a value pdf as per the sample file name mentioned above.\n$file_extension = $file_ext[$cnt];\n</code></pre>\n"
},
{
"answer_id": 31476046,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 7,
"selected": false,
"text": "<p>Example URL: <strong><code>http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ</code></strong></p>\n<p>A) <em>Don't use suggested unsafe <a href=\"http://php.net/manual/en/function.pathinfo.php#example-2610\" rel=\"noreferrer\"><strong><code>PATHINFO</code></strong></a></em>:</p>\n<pre><code>pathinfo($url)['dirname'] 'http://example.com/myfolder'\npathinfo($url)['basename'] 'sympony.mp3?a=1&b=2#XYZ' // <------- BAD !!\npathinfo($url)['extension'] 'mp3?a=1&b=2#XYZ' // <------- BAD !!\npathinfo($url)['filename'] 'sympony'\n</code></pre>\n<p>B) Use <a href=\"http://php.net/manual/en/function.parse-url.php#refsect1-function.parse-url-examples\" rel=\"noreferrer\">PARSE_URL</a>:</p>\n<pre><code>parse_url($url)['scheme'] 'http'\nparse_url($url)['host'] 'example.com'\nparse_url($url)['path'] '/myfolder/sympony.mp3'\nparse_url($url)['query'] 'aa=1&bb=2'\nparse_url($url)['fragment'] 'XYZ'\n</code></pre>\n<p>BONUS: View <a href=\"https://stackoverflow.com/questions/6768793/get-the-full-url-in-php/26944636#26944636\">all native PHP examples</a></p>\n"
},
{
"answer_id": 37019281,
"author": "Samir Karmacharya",
"author_id": 5387175,
"author_profile": "https://Stackoverflow.com/users/5387175",
"pm_score": 2,
"selected": false,
"text": "<p>You can get all file extensions in a particular folder and do operations with a specific file extension:</p>\n\n<pre><code><?php\n $files = glob(\"abc/*.*\"); // abc is the folder all files inside folder\n //print_r($files);\n //echo count($files);\n for($i=0; $i<count($files); $i++):\n $extension = pathinfo($files[$i], PATHINFO_EXTENSION);\n $ext[] = $extension;\n // Do operation for particular extension type\n if($extension=='html'){\n // Do operation\n }\n endfor;\n print_r($ext);\n?>\n</code></pre>\n"
},
{
"answer_id": 37410143,
"author": "smile 22121",
"author_id": 5790794,
"author_profile": "https://Stackoverflow.com/users/5790794",
"pm_score": 2,
"selected": false,
"text": "<p>You can try also this:</p>\n\n<pre><code> pathinfo(basename($_FILES[\"fileToUpload\"][\"name\"]), PATHINFO_EXTENSION)\n</code></pre>\n"
},
{
"answer_id": 37606085,
"author": "Arshid KV",
"author_id": 2513873,
"author_profile": "https://Stackoverflow.com/users/2513873",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://php.net/manual/en/function.pathinfo.php\" rel=\"nofollow noreferrer\">pathinfo</a> is an array. We can check <strong>directory name, file name, extension</strong>, etc.:</p>\n\n<pre><code>$path_parts = pathinfo('test.png');\n\necho $path_parts['extension'], \"\\n\";\necho $path_parts['dirname'], \"\\n\";\necho $path_parts['basename'], \"\\n\";\necho $path_parts['filename'], \"\\n\";\n</code></pre>\n"
},
{
"answer_id": 39413224,
"author": "Ray Foss",
"author_id": 370238,
"author_profile": "https://Stackoverflow.com/users/370238",
"pm_score": 1,
"selected": false,
"text": "<p>If you are looking for speed (such as in a router), you probably don't want to tokenize everything. Many other answers will fail with <code>/root/my.folder/my.css</code> </p>\n\n<pre><code>ltrim(strrchr($PATH, '.'),'.');\n</code></pre>\n"
},
{
"answer_id": 40078863,
"author": "Abbas",
"author_id": 2763330,
"author_profile": "https://Stackoverflow.com/users/2763330",
"pm_score": 2,
"selected": false,
"text": "<p>Use <code>substr($path, strrpos($path,'.')+1);</code>. It is the fastest method of all compares.</p>\n\n<p>@Kurt Zhong already answered.</p>\n\n<p>Let's check the comparative result here: <a href=\"https://eval.in/661574\" rel=\"nofollow noreferrer\">https://eval.in/661574</a></p>\n"
},
{
"answer_id": 42184574,
"author": "pooya_sabramooz",
"author_id": 3619526,
"author_profile": "https://Stackoverflow.com/users/3619526",
"pm_score": 3,
"selected": false,
"text": "<p>You can try also this (it works on PHP 5.* and 7):</p>\n\n<pre><code>$info = new SplFileInfo('test.zip');\necho $info->getExtension(); // ----- Output -----> zip\n</code></pre>\n\n<p>Tip: it returns an empty string if the file doesn't have an extension</p>\n"
},
{
"answer_id": 51695722,
"author": "Dan Bray",
"author_id": 2452680,
"author_profile": "https://Stackoverflow.com/users/2452680",
"pm_score": 1,
"selected": false,
"text": "<p>Although the \"best way\" is debatable, I believe this is the best way for a few reasons:</p>\n\n<pre><code>function getExt($path)\n{\n $basename = basename($path);\n return substr($basename, strlen(explode('.', $basename)[0]) + 1);\n}\n</code></pre>\n\n<ol>\n<li>It works with multiple parts to an extension, eg <code>tar.gz</code></li>\n<li>Short and efficient code</li>\n<li>It works with both a filename and a complete path</li>\n</ol>\n"
},
{
"answer_id": 55399890,
"author": "Fred",
"author_id": 2421121,
"author_profile": "https://Stackoverflow.com/users/2421121",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I was looking for that.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\n$url = 'http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ';\n$tmp = @parse_url($url)['path'];\n$ext = pathinfo($tmp, PATHINFO_EXTENSION);\n\nvar_dump($ext);\n</code></pre>\n"
},
{
"answer_id": 55539659,
"author": "Tommy89",
"author_id": 5815685,
"author_profile": "https://Stackoverflow.com/users/5815685",
"pm_score": 2,
"selected": false,
"text": "<p>IMO, this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens):</p>\n<pre><code>$ext = explode('.', $filename); // Explode the string\n$my_ext = end($ext); // Get the last entry of the array\n\necho $my_ext;\n</code></pre>\n"
},
{
"answer_id": 57066213,
"author": "Anjani Barnwal",
"author_id": 7156889,
"author_profile": "https://Stackoverflow.com/users/7156889",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ltrim(strstr($file_url, '.'), '.')\n</code></pre>\n\n<blockquote>\n <p>this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens</p>\n</blockquote>\n"
},
{
"answer_id": 57126293,
"author": "Ali Han",
"author_id": 585626,
"author_profile": "https://Stackoverflow.com/users/585626",
"pm_score": 3,
"selected": false,
"text": "<h2>Sorry... \"Short Question; But NOT Short Answer\"</h2>\n\n<p><strong>Example 1 for PATH</strong></p>\n\n<pre><code>$path = \"/home/ali/public_html/wp-content/themes/chicken/css/base.min.css\";\n$name = pathinfo($path, PATHINFO_FILENAME);\n$ext = pathinfo($path, PATHINFO_EXTENSION);\nprintf('<hr> Name: %s <br> Extension: %s', $name, $ext);\n</code></pre>\n\n<p><strong>Example 2 for URL</strong></p>\n\n<pre><code>$url = \"//www.example.com/dir/file.bak.php?Something+is+wrong=hello\";\n$url = parse_url($url);\n$name = pathinfo($url['path'], PATHINFO_FILENAME);\n$ext = pathinfo($url['path'], PATHINFO_EXTENSION);\nprintf('<hr> Name: %s <br> Extension: %s', $name, $ext);\n</code></pre>\n\n<p>Output of example 1:</p>\n\n<pre><code>Name: base.min\nExtension: css\n</code></pre>\n\n<p>Output of example 2:</p>\n\n<pre><code>Name: file.bak\nExtension: php\n</code></pre>\n\n<h2>References</h2>\n\n<ol>\n<li><p><a href=\"https://www.php.net/manual/en/function.pathinfo.php\" rel=\"noreferrer\">https://www.php.net/manual/en/function.pathinfo.php</a></p></li>\n<li><p><a href=\"https://www.php.net/manual/en/function.realpath.php\" rel=\"noreferrer\">https://www.php.net/manual/en/function.realpath.php</a></p></li>\n<li><p><a href=\"https://www.php.net/manual/en/function.parse-url.php\" rel=\"noreferrer\">https://www.php.net/manual/en/function.parse-url.php</a></p></li>\n</ol>\n"
},
{
"answer_id": 57937519,
"author": "Sai Kiran Sangam",
"author_id": 12024442,
"author_profile": "https://Stackoverflow.com/users/12024442",
"pm_score": 2,
"selected": false,
"text": "<p><code>$ext = preg_replace('/^.*\\.([^.]+)$/D', '$1', $fileName);</code></p>\n\n<p>preg_replace approach we using regular expression search and replace. In preg_replace function first parameter is pattern to the search, second parameter $1 is a reference to whatever is matched by the first (.*) and third parameter is file name.</p>\n\n<p>Another way, we can also use strrpos to find the position of the last occurrence of a ‘.’ in a file name and increment that position by 1 so that it will explode string from (.)</p>\n\n<p><code>$ext = substr($fileName, strrpos($fileName, '.') + 1);</code></p>\n"
},
{
"answer_id": 61079134,
"author": "dkellner",
"author_id": 1892607,
"author_profile": "https://Stackoverflow.com/users/1892607",
"pm_score": 5,
"selected": false,
"text": "<h2>Do it faster!</h2>\n<p>In other words, if you only work with a filename, please stop using pathinfo.<br></p>\n<p>I mean, sure if you have a <em>full pathname</em>, pathinfo makes sense because it's smarter than just finding dots: the path can contain dots and filename itself may have none. So in this case, considering an input string like <code>d:/some.thing/myfile</code>, pathinfo and other fully equipped methods are a good choice.</p>\n<p>But if all you have is a <em>filename</em>, with no path, it's simply pointless to make the system work a lot more than it needs to. And this can give you <strong>a 10x speed boost</strong>.</p>\n<p>Here's a quick speed test:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/* 387 ns */ function method1($s) {return preg_replace("/.*\\./","",$s);} // edge case problem\n/* 769 ns */ function method2($s) {preg_match("/\\.([^\\.]+)$/",$s,$a);return $a[1];}\n/* 67 ns */ function method3($s) {$n = strrpos($s,"."); if($n===false) return "";return substr($s,$n+1);}\n/* 175 ns */ function method4($s) {$a = explode(".",$s);$n = count($a); if($n==1) return "";return $a[$n-1];}\n/* 731 ns */ function method5($s) {return pathinfo($s, PATHINFO_EXTENSION);}\n/* 732 ns */ function method6($s) {return (new SplFileInfo($s))->getExtension();}\n\n// All measured on Linux; it will be vastly different on Windows\n</code></pre>\n<p>Those nanosecond values will obviously differ on each system, but they give a clear picture about proportions. <code>SplFileInfo</code> and <code>pathinfo</code> are great fellas, but for this kind of job it's simply not worth it to wake them up. For the same reason, <code>explode()</code> is considerably faster than regex. Very simple tools tend to beat more sophisticated ones.</p>\n<h3>Conclusion</h3>\n<p>This seems to be the Way of the Samurai:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function fileExtension($name) {\n $n = strrpos($name, '.');\n return ($n === false) ? '' : substr($name, $n+1);\n}\n</code></pre>\n<p><em>Remember this is for simple filenames only. If you have paths involved, stick to pathinfo or deal with the dirname separately.</em></p>\n"
},
{
"answer_id": 65613057,
"author": "Ashok Chandrapal",
"author_id": 1642072,
"author_profile": "https://Stackoverflow.com/users/1642072",
"pm_score": 0,
"selected": false,
"text": "<p>I tried one simple solution it might help to someone else to get just filename from the URL which having get parameters</p>\n<pre><code><?php\n\n$path = "URL will be here";\necho basename(parse_url($path)['path']);\n\n?>\n</code></pre>\n<p>Thanks</p>\n"
},
{
"answer_id": 71884623,
"author": "RafaSashi",
"author_id": 2456038,
"author_profile": "https://Stackoverflow.com/users/2456038",
"pm_score": 2,
"selected": false,
"text": "<p>In one line:</p>\n<pre><code>pathinfo(parse_url($url,PHP_URL_PATH),PATHINFO_EXTENSION);\n</code></pre>\n"
},
{
"answer_id": 73551735,
"author": "Brad",
"author_id": 4753391,
"author_profile": "https://Stackoverflow.com/users/4753391",
"pm_score": 3,
"selected": false,
"text": "<p><strong>The "best" way depends on the context and what you are doing with that file extension.</strong>\nHowever,</p>\n<p> <a href=\"https://www.php.net/manual/en/function.pathinfo.php\" rel=\"noreferrer\">pathinfo</a> in general is the best when you consider all the angles.</p>\n<pre><code>pathinfo($file, PATHINFO_EXTENSION)\n</code></pre>\n<p>It is not the fastest, but it is fast enough. It is easy to read, easy to remember and reuse everywhere. Anyone can understand it at a glance and remove PATHINFO_EXT flag if they need more info about the file.</p>\n<p>❌ <a href=\"https://www.php.net/manual/en/function.strrpos.php\" rel=\"noreferrer\">strrpos</a> method. described in several answers is faster yes but requires additional safety checks which, in turn, requires you to wrap it inside a function, to make it easily reusable.\nThen you must take the function with you from project to project or look it up.\nWrapping it in a function call with extra checks also makes it slower and if you need any other info about the file you now have other methods to call and at that point, you lose the speed advantage anyway whilst having a solution that's harder to read.\nThe potential for speed is there but is not worth it unless you need to address such a bottleneck.</p>\n<p>❌ I'd also rule out any ideas using <a href=\"https://www.php.net/manual/en/function.substr\" rel=\"noreferrer\">substr</a>, <a href=\"https://www.php.net/manual/en/function.explode\" rel=\"noreferrer\">explode</a>, and most other manual manipulations for the same reasons mentioned above.</p>\n<p>❌<a href=\"https://www.php.net/manual/en/class.splfileinfo.php\" rel=\"noreferrer\">SplFileInfo</a> is very cool but takes up much more brain space with a lot of interfaces that you no doubt waste time learning only to look them up again next time. I'd only use it in specific cases where you will find the extra interfaces worth someone learning Spl when they come back to add/edit your code later.</p>\n<p>❌ I would not consider <a href=\"https://www.php.net/manual/en/function.preg-replace\" rel=\"noreferrer\">preg_replace</a> at all as any regex function in PHP is on average 3 times slower than any other function, is harder to read, and is in most cases can easily be done with something simpler. Regex is powerful and it has its place in those specific situations where it can replace several method calls and condition checks in one line.\nGetting a file extension this way is like using an anvil to hammer in a nail.</p>\n<hr />\n<p>While of course "the best" would come down to public opinion, I'd argue that other methods are only "the best" in specialized cases.</p>\n<p>For example, if you just want to check for a specific type then I wouldn't use any of the suggested methods as <a href=\"https://www.php.net/manual/en/function.stripos.php\" rel=\"noreferrer\">stripos</a> would be the fastest case insensitive comparison to use.</p>\n<pre><code>if (stripos('/here/is/sOme.fiLe.PdF', '.pdf', -4) !== false )\n{\n //its a pdf file\n}\n</code></pre>\n<p>But again pathinfo would still be nicer to read and probably worth the performance cost.</p>\n<p><strong>But what about https://ome.Com.///lica.ted?URLS ?</strong></p>\n<p>Extracting paths from URLs is a separate concern that is outside the scope of the question and will require an extra step in any case where a simple one-time string comparison won't do.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
This is a question you can read everywhere on the web with various answers:
```
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
```
etc.
However, there is always "the best way" and it should be on Stack Overflow.
|
People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).
In fact, it does exist, but few people know it. Meet [`pathinfo()`](http://php.net/manual/en/function.pathinfo.php):
```
$ext = pathinfo($filename, PATHINFO_EXTENSION);
```
This is fast and built-in. `pathinfo()` can give you other information, such as canonical path, depending on the constant you pass to it.
Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:
```
setlocale(LC_ALL,'en_US.UTF-8');
```
Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.
Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE\_URL.
Enjoy
|
173,870 |
<p>I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone <em>really</em> find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE*s and plain old file descriptors: ifstreams cannot read from a device. Can anyone think of a reason why?</p>
<pre><code>const char* path = "/dev/disk3";
char b;
// this works
FILE* f= fopen(path, "rb");
int i = fread(&b, 1, 1, f); // returns 1, success!
// this does not work
ifstream cf(path, ios::binary);
cf.read(&b, 1);
bool good = cf.good(); // returns false, failure.
</code></pre>
|
[
{
"answer_id": 174095,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>I have found random issues like this in C++ I/O for years. It has always seemed like a backwards step to me.</p>\n\n<p>I haven't tried it, but you might want to look at what Boost has to offer:</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/index.html\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/index.html</a></p>\n"
},
{
"answer_id": 174268,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "<p>Works fine for me, its not a problem inherent to c++ stream file I/O as you seem to think.</p>\n\n<p>Maybe try adding <code>ios::in</code> to the openmode flags. According to 27.8.1.6 of the standard, it is required to or with ios::in so this probably won't do anything.</p>\n\n<p>Try checking which bit is actually set - instead of calling good(), try checking bad(), eof(), and fail() individually. This might give a clue as to what the error was.</p>\n"
},
{
"answer_id": 176879,
"author": "Rhythmic Fistman",
"author_id": 22147,
"author_profile": "https://Stackoverflow.com/users/22147",
"pm_score": 3,
"selected": true,
"text": "<p>The device is unbuffered and must be read from in 512 byte multiples. ifstream does it's own buffering and strangely decided to read <em>1023</em> bytes ahead, which fails with \"Invalid argument\". Interestingly, this ifstream is implemented on top of a FILE*. However, FILE* left to its own devices was reading ahead using a nicer, rounder number of bytes. </p>\n\n<p>Thanks to dtrace for vital clues. I guess we'll never know if the folk who thought they knew answer but didn't want to say were right. </p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22147/"
] |
I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone *really* find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE\*s and plain old file descriptors: ifstreams cannot read from a device. Can anyone think of a reason why?
```
const char* path = "/dev/disk3";
char b;
// this works
FILE* f= fopen(path, "rb");
int i = fread(&b, 1, 1, f); // returns 1, success!
// this does not work
ifstream cf(path, ios::binary);
cf.read(&b, 1);
bool good = cf.good(); // returns false, failure.
```
|
The device is unbuffered and must be read from in 512 byte multiples. ifstream does it's own buffering and strangely decided to read *1023* bytes ahead, which fails with "Invalid argument". Interestingly, this ifstream is implemented on top of a FILE\*. However, FILE\* left to its own devices was reading ahead using a nicer, rounder number of bytes.
Thanks to dtrace for vital clues. I guess we'll never know if the folk who thought they knew answer but didn't want to say were right.
|
173,886 |
<p>Please consider this example class:</p>
<pre><code>[Serializable]
public class SomeClass
{
private DateTime _SomeDateTime;
public DateTime SomeDateTime
{
get { return _SomeDateTime; }
set { _SomeDateTime = value; }
}
}
</code></pre>
<p>I would like to alter the serialization of any DateTime declared in the class according to my own rules. The members of this class will change frequently and I don't want to maintain a custom serializer for every change. Also I would like this behaviour to be inherited by subclasses and not code a custom serializer for every one. The serialization is being output by a web service. Thanks for any help!</p>
|
[
{
"answer_id": 173894,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 2,
"selected": false,
"text": "<p>Have you thought about simply using a Nullable date time</p>\n\n<pre><code>public DateTime? SomeDateTime {get; set;}\n</code></pre>\n\n<p>This way you can actually have a null value as a legitimate value in your class. Typically you want to avoid custom serialization whenever possible. Once you do custom serialization such as implementing <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx\" rel=\"nofollow noreferrer\">ISerializable</a></strong>, then you are stuck with it, and all other derived classes are stuck with it.</p>\n\n<p>Remember what a pain in the butt it is to have to always override the ISerializable members for custom exceptions? This is because System.Exception implements ISerializable and therefore all derived exceptions (that means everything) must implement those members if you ever expect them to cross AppDomains.</p>\n"
},
{
"answer_id": 173913,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you can use a \"bool ShouldSerializeSomeDateTime()\" method to enable/disable serialization of individual members, but I don't think that is quite what you need. Another common option is to add a member that does the format itself:</p>\n\n<p>public string SomeDateTimeFormatted {\n get { return theField == DateTime.MinValue ? \"\" : theField.ToString(\"R\");} // or whatever format\n set { ... opposite ...}\n }</p>\n\n<p>It is nicer to stick with the inbuilt serialization if you can, though - in part to reduce the amount of code you need to write. Josh's suggestion for a nullable DateTime (DateTime?) is a good one, although it might still not be quite empty-string vs formatted-string - I expect it would use the xsi:nil markup.</p>\n"
},
{
"answer_id": 174436,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 3,
"selected": true,
"text": "<p>look at the OnSerializing and OnDeserializing attributes to call custom methods when your objects are serialized. you can impelment some custom logic in there and decouple the serializing process from the actual datatypes.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] |
Please consider this example class:
```
[Serializable]
public class SomeClass
{
private DateTime _SomeDateTime;
public DateTime SomeDateTime
{
get { return _SomeDateTime; }
set { _SomeDateTime = value; }
}
}
```
I would like to alter the serialization of any DateTime declared in the class according to my own rules. The members of this class will change frequently and I don't want to maintain a custom serializer for every change. Also I would like this behaviour to be inherited by subclasses and not code a custom serializer for every one. The serialization is being output by a web service. Thanks for any help!
|
look at the OnSerializing and OnDeserializing attributes to call custom methods when your objects are serialized. you can impelment some custom logic in there and decouple the serializing process from the actual datatypes.
|
173,919 |
<p>When merging topic branch "B" into "A" using <code>git merge</code>, I get some conflicts. I know all the conflicts can be solved using the version in "B".</p>
<p>I am aware of <code>git merge -s ours</code>. But what I want is something like <code>git merge -s theirs</code>.</p>
<p>Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing <code>git</code> commands? (<code>git checkout</code> every unmerged file from B)</p>
<p>The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.</p>
|
[
{
"answer_id": 173954,
"author": "elmarco",
"author_id": 1277510,
"author_profile": "https://Stackoverflow.com/users/1277510",
"pm_score": 4,
"selected": false,
"text": "<p>I solved my problem using</p>\n\n<pre><code>git checkout -m old\ngit checkout -b new B\ngit merge -s ours old\n</code></pre>\n"
},
{
"answer_id": 174283,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 7,
"selected": false,
"text": "<p>Older versions of git allowed you to use the \"theirs\" merge strategy:</p>\n\n<pre><code>git pull --strategy=theirs remote_branch\n</code></pre>\n\n<p>But this has since been removed, as explained in this message by <a href=\"http://marc.info/?l=git&m=121637513604413&w=2\" rel=\"noreferrer\">Junio Hamano</a> (the Git maintainer). As noted in the link, instead you would do this:</p>\n\n<pre><code>git fetch origin\ngit reset --hard origin\n</code></pre>\n\n<p>Beware, though, that this is different than an actual merge. Your solution is probably the option you're really looking for.</p>\n"
},
{
"answer_id": 3364506,
"author": "Alan W. Smith",
"author_id": 102401,
"author_profile": "https://Stackoverflow.com/users/102401",
"pm_score": 11,
"selected": true,
"text": "<p>A similar alternative is the <code>--strategy-option</code> (short form <code>-X</code>) option, which accepts <code>theirs</code>. For example:</p>\n<pre><code>git checkout branchA\ngit merge -X theirs branchB\n</code></pre>\n<p>However, this is more equivalent to <code>-X ours</code> than <code>-s ours</code>. The key difference being that <code>-X</code> performs a regular recursive merge, resolving any conflicts using the chosen side, whereas <code>-s ours</code> changes the merge to just completely ignore the other side.</p>\n<p>In some cases, the main problem using <code>-X theirs</code> instead of the hypothetical <code>-s theirs</code> is deleted files. In this case, just run <code>git rm</code> with the name of any files that were deleted:</p>\n<pre><code>git rm {DELETED-FILE-NAME}\n</code></pre>\n<p>After that, the <code>-X theirs</code> may work as expected.</p>\n<p>Of course, doing the actual removal with the <code>git rm</code> command will prevent the conflict from happening in the first place.</p>\n"
},
{
"answer_id": 4969679,
"author": "Paul Pladijs",
"author_id": 613109,
"author_profile": "https://Stackoverflow.com/users/613109",
"pm_score": 8,
"selected": false,
"text": "<p>A possible and tested solution for merging branchB into our checked-out branchA:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code># in case branchA is not our current branch\ngit checkout branchA\n\n# make merge commit but without conflicts!!\n# the contents of 'ours' will be discarded later\ngit merge -s ours branchB \n\n# make temporary branch to merged commit\ngit branch branchTEMP \n\n# get contents of working tree and index to the one of branchB\ngit reset --hard branchB\n\n# reset to our merged commit but \n# keep contents of working tree and index\ngit reset --soft branchTEMP\n\n# change the contents of the merged commit\n# with the contents of branchB\ngit commit --amend\n\n# get rid off our temporary branch\ngit branch -D branchTEMP\n\n# verify that the merge commit contains only contents of branchB\ngit diff HEAD branchB\n</code></pre>\n\n<p>To automate it you can wrap it into a script using branchA and branchB as arguments.</p>\n\n<p>This solution preserves the first and second parent of the merge commit, just as you would expect of <code>git merge -s theirs branchB</code>.</p>\n"
},
{
"answer_id": 10130264,
"author": "rafalmag",
"author_id": 252363,
"author_profile": "https://Stackoverflow.com/users/252363",
"pm_score": 4,
"selected": false,
"text": "<p>If you are on branch A do:</p>\n\n<pre><code>git merge -s recursive -X theirs B\n</code></pre>\n\n<p>Tested on git version 1.7.8</p>\n"
},
{
"answer_id": 13209363,
"author": "musicmatze",
"author_id": 1391026,
"author_profile": "https://Stackoverflow.com/users/1391026",
"pm_score": 6,
"selected": false,
"text": "<p>I used the answer from Paul Pladijs since now. I found out, you can do a \"normal\" merge, conflicts occur, so you do </p>\n\n<pre><code>git checkout --theirs <file>\n</code></pre>\n\n<p>to resolve the conflict by using the revision from the other branch. If you do this for each file, you have the same behaviour as you would expect from </p>\n\n<pre><code>git merge <branch> -s theirs\n</code></pre>\n\n<p>Anyway, the effort is more than it would be with the merge-strategy! (This was tested with git version 1.8.0)</p>\n"
},
{
"answer_id": 14562169,
"author": "Pawan Maheshwari",
"author_id": 648030,
"author_profile": "https://Stackoverflow.com/users/648030",
"pm_score": 0,
"selected": false,
"text": "<p>This will merge your newBranch in existing baseBranch</p>\n\n<pre><code>git checkout <baseBranch> // this will checkout baseBranch\ngit merge -s ours <newBranch> // this will simple merge newBranch in baseBranch\ngit rm -rf . // this will remove all non references files from baseBranch (deleted in newBranch)\ngit checkout newBranch -- . //this will replace all conflicted files in baseBranch\n</code></pre>\n"
},
{
"answer_id": 16526138,
"author": "jthill",
"author_id": 1290731,
"author_profile": "https://Stackoverflow.com/users/1290731",
"pm_score": 3,
"selected": false,
"text": "<p>See <a href=\"http://marc.info/?l=git&m=121637513604413&w=2\" rel=\"noreferrer\">Junio Hamano's widely cited answer</a>: if you're going to discard committed content, just discard the commits, or at any rate keep it out of the main history. Why bother everyone in the future reading commit messages from commits that have nothing to offer?</p>\n\n<p>But sometimes there are administrative requirements, or perhaps some other reason. For those situations where you really have to record commits that contribute nothing, you want:</p>\n\n<p>(edit: wow, did I manage to get this wrong before. This one works.)</p>\n\n<pre><code>git update-ref HEAD $(\n git commit-tree -m 'completely superseding with branchB content' \\\n -p HEAD -p branchB branchB:\n)\ngit reset --hard\n</code></pre>\n"
},
{
"answer_id": 18682314,
"author": "Gandalf458",
"author_id": 1894055,
"author_profile": "https://Stackoverflow.com/users/1894055",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n<p>When merging topic branch "B" in "A" using git merge, I get some conflicts. I >know all the conflicts can be solved using the version in "B".</p>\n<p>I am aware of git merge -s ours. But what I want is something like git merge >-s their.</p>\n</blockquote>\n<p>I'm assuming that you created a branch off of master and now want to merge back into master, overriding any of the old stuff in master. That's exactly what I wanted to do when I came across this post.</p>\n<p>Do exactly what it is you want to do, Except merge the one branch into the other first. I just did this, and it worked great.</p>\n<pre><code>git checkout Branch\ngit merge master -s ours\n</code></pre>\n<p>Then, checkout master and merge your branch in it (it will go smoothly now):</p>\n<pre><code>git checkout master\ngit merge Branch\n</code></pre>\n"
},
{
"answer_id": 19686137,
"author": "thoutbeckers",
"author_id": 2338613,
"author_profile": "https://Stackoverflow.com/users/2338613",
"pm_score": 3,
"selected": false,
"text": "<p>To really properly do a merge which takes <em>only</em> input from the branch you are merging you can do</p>\n\n<p><code>git merge --strategy=ours ref-to-be-merged</code></p>\n\n<p><code>git diff --binary ref-to-be-merged | git apply --reverse --index</code></p>\n\n<p><code>git commit --amend</code></p>\n\n<p>There will be no conflicts in any scenario I know of, you don't have to make additional branches, and it acts like a normal merge commit.</p>\n\n<p>This doesn't play nice with submodules however.</p>\n"
},
{
"answer_id": 27338013,
"author": "siegi",
"author_id": 1347968,
"author_profile": "https://Stackoverflow.com/users/1347968",
"pm_score": 7,
"selected": false,
"text": "<p>It is not entirely clear what your desired outcome is, so there is some confusion about the "correct" way of doing it in the answers and their comments. I try to give an overview and see the following three options:</p>\n<p><strong>Try merge and use B for conflicts</strong></p>\n<p>This is <em>not</em> the "theirs version for <code>git merge -s ours</code>" but the "theirs version for <code>git merge -X ours</code>" (which is short for <code>git merge -s recursive -X ours</code>):</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git checkout branchA\n# also uses -s recursive implicitly\ngit merge -X theirs branchB\n</code></pre>\n<p>This is what e.g. <a href=\"https://stackoverflow.com/a/3364506/1347968\">Alan W. Smith's answer</a> does.</p>\n<p><strong>Use content from B only</strong></p>\n<p>This creates a merge commit for both branches but discards all changes from <code>branchA</code> and only keeps the contents from <code>branchB</code>.</p>\n<pre class=\"lang-bash prettyprint-override\"><code># Get the content you want to keep.\n# If you want to keep branchB at the current commit, you can add --detached,\n# else it will be advanced to the merge commit in the next step.\ngit checkout branchB\n\n# Do the merge an keep current (our) content from branchB we just checked out.\ngit merge -s ours branchA\n\n# Set branchA to current commit and check it out.\ngit checkout -B branchA\n</code></pre>\n<p>Note that the merge commits first parent now is that from <code>branchB</code> and only the second is from <code>branchA</code>. This is what e.g. <a href=\"https://stackoverflow.com/a/18682314/1347968\">Gandalf458's answer</a> does.</p>\n<p><strong>Use content from B only and keep correct parent order</strong></p>\n<p>This is the real "theirs version for <code>git merge -s ours</code>". It has the same content as in the option before (i.e. only that from <code>branchB</code>) but the order of parents is correct, i.e. the first parent comes from <code>branchA</code> and the second from <code>branchB</code>.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git checkout branchA\n\n# Do a merge commit. The content of this commit does not matter,\n# so use a strategy that never fails.\n# Note: This advances branchA.\ngit merge -s ours branchB\n\n# Change working tree and index to desired content.\n# --detach ensures branchB will not move when doing the reset in the next step.\ngit checkout --detach branchB\n\n# Move HEAD to branchA without changing contents of working tree and index.\ngit reset --soft branchA\n\n# 'attach' HEAD to branchA.\n# This ensures branchA will move when doing 'commit --amend'.\ngit checkout branchA\n\n# Change content of merge commit to current index (i.e. content of branchB).\ngit commit --amend -C HEAD\n</code></pre>\n<p>This is what <a href=\"https://stackoverflow.com/a/4969679/1347968\">Paul Pladijs's answer</a> does (without requiring a temporary branch).</p>\n<p><strong>Special cases</strong></p>\n<p>If the commit of <code>branchB</code> is an ancestor of <code>branchA</code>, <code>git merge</code> does not work (it just exits with a message like "<em>Already up to date.</em>").</p>\n<p>In this or other similar/advanced cases the low-level command <a href=\"https://git-scm.com/docs/git-commit-tree\" rel=\"nofollow noreferrer\"><code>git commit-tree</code></a> can be used.</p>\n"
},
{
"answer_id": 29806926,
"author": "Michael R",
"author_id": 428628,
"author_profile": "https://Stackoverflow.com/users/428628",
"pm_score": 2,
"selected": false,
"text": "<p>This one uses a git plumbing command read-tree, but makes for a shorter overall workflow.</p>\n\n<pre><code>git checkout <base-branch>\n\ngit merge --no-commit -s ours <their-branch>\ngit read-tree -u --reset <their-branch>\ngit commit\n\n# Check your work!\ngit diff <their-branch>\n</code></pre>\n"
},
{
"answer_id": 39251301,
"author": "briemers",
"author_id": 6148805,
"author_profile": "https://Stackoverflow.com/users/6148805",
"pm_score": 1,
"selected": false,
"text": "<p>I think what you actually want is:</p>\n\n<pre><code>git checkout -B mergeBranch branchB\ngit merge -s ours branchA\ngit checkout branchA\ngit merge mergeBranch\ngit branch -D mergeBranch\n</code></pre>\n\n<p>This seems clumsy, but it should work. The only think I really dislike about this solution is the git history will be confusing... But at least the history will be completely preserved and you won't need to do something special for deleted files.</p>\n"
},
{
"answer_id": 43049246,
"author": "Trann",
"author_id": 613748,
"author_profile": "https://Stackoverflow.com/users/613748",
"pm_score": -1,
"selected": false,
"text": "<p>I just recently needed to do this for two separate repositories that share a common history. I started with:</p>\n\n<ul>\n<li><code>Org/repository1 master</code></li>\n<li><code>Org/repository2 master</code></li>\n</ul>\n\n<p>I wanted all the changes from <code>repository2 master</code> to be applied to <code>repository1 master</code>, accepting all changes that repository2 would make. In git's terms, this <em>should</em> be a strategy called <code>-s theirs</code> BUT it does not exist. Be careful because <code>-X theirs</code> is named like it would be what you want, but it is <em>NOT</em> the same (it even says so in the man page).</p>\n\n<p>The way I solved this was to go to <code>repository2</code> and make a new branch <code>repo1-merge</code>. In that branch, I ran <code>git pull [email protected]:Org/repository1 -s ours</code> and it merges fine with no issues. I then push it to the remote.</p>\n\n<p>Then I go back to <code>repository1</code> and make a new branch <code>repo2-merge</code>. In that branch, I run <code>git pull [email protected]:Org/repository2 repo1-merge</code> which will complete with issues.</p>\n\n<p>Finally, you would either need to issue a merge request in <code>repository1</code> to make it the new master, or just keep it as a branch.</p>\n"
},
{
"answer_id": 46741538,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Why doesn't it exist?</p>\n</blockquote>\n\n<p>While I mention in \"<a href=\"https://stackoverflow.com/a/4912267/6309\">git command for making one branch like another</a>\" how to simulate <code>git merge -s theirs</code>, note that Git 2.15 (Q4 2017) is now clearer:</p>\n\n<blockquote>\n <p>The documentation for '<code>-X<option></code>' for merges was misleadingly\n written to suggest that \"<code>-s theirs</code>\" exists, which is not the case.</p>\n</blockquote>\n\n<p>See <a href=\"https://github.com/git/git/commit/c25d98b2a730cbc63033ba3360df2519d43a40cd\" rel=\"noreferrer\">commit c25d98b</a> (25 Sep 2017) by <a href=\"https://github.com/gitster\" rel=\"noreferrer\">Junio C Hamano (<code>gitster</code>)</a>.<br>\n<sup>(Merged by <a href=\"https://github.com/gitster\" rel=\"noreferrer\">Junio C Hamano -- <code>gitster</code> --</a> in <a href=\"https://github.com/git/git/commit/4da3e234f5a3989328c4dc8368cf5906f8679b30\" rel=\"noreferrer\">commit 4da3e23</a>, 28 Sep 2017)</sup> </p>\n\n<blockquote>\n <h2>merge-strategies: avoid implying that \"<code>-s theirs</code>\" exists</h2>\n \n <p>The description of <code>-Xours</code> merge option has a parenthetical note\n that tells the readers that it is very different from <code>-s ours</code>,\n which is correct, but the description of <code>-Xtheirs</code> that follows it\n carelessly says \"this is the opposite of <code>ours</code>\", giving a false\n impression that the readers also need to be warned that it is very\n different from <code>-s theirs</code>, which in reality does not even exist.</p>\n</blockquote>\n\n<p><code>-Xtheirs</code> is a <em>strategy option</em> applied to recursive strategy. This means that recursive strategy will still merge anything it can, and will only fall back to \"<code>theirs</code>\" logic in case of conflicts.</p>\n\n<p>That debate for the pertinence or not of a <code>theirs</code> merge strategy was brought back recently <a href=\"https://marc.info/?l=git&m=150635053217381&w=2\" rel=\"noreferrer\">in this Sept. 2017 thread</a>.<br>\nIt acknowledges <a href=\"https://public-inbox.org/git/alpine.DEB.1.00.0807290123300.2725@eeepc-johanness/\" rel=\"noreferrer\">older (2008) threads</a> </p>\n\n<blockquote>\n <p>In short, the previous discussion can be summarized to \"we don't want '<code>-s theirs</code>' as it encourages the wrong workflow\". </p>\n</blockquote>\n\n<p>It mentions the alias:</p>\n\n<pre><code>mtheirs = !sh -c 'git merge -s ours --no-commit $1 && git read-tree -m -u $1' -\n</code></pre>\n\n<p>Yaroslav Halchenko tries to advocate once more for that strategy, <a href=\"https://marc.info/?l=git&m=150639760028942&w=2\" rel=\"noreferrer\">but Junio C. Hamano adds</a>:</p>\n\n<blockquote>\n <p>The reason why ours and theirs are not symmetric is because you are you and not them---the control and ownership of our history and their history is not symmetric.</p>\n \n <p>Once you decide that their history is the mainline, you'd rather want to treat your line of development as a side branch and make a merge in that direction, i.e. the first parent of the resulting merge is a commit on their history and the second parent is the last bad one of your history. So you would end up using \"<code>checkout their-history && merge -s ours your-history</code>\" to\n keep the first-parenthood sensible.</p>\n \n <p>And at that point, use of \"<code>-s ours</code>\" is no longer a workaround for lack of \"<code>-s theirs</code>\".<br>\n <strong>It is a proper part of the desired semantics, i.e. from the point of view of the surviving canonical history line, you want to preserve what it did, nullifying what the other line of history did</strong>.</p>\n</blockquote>\n\n<p>Junio adds, as commented by <a href=\"https://stackoverflow.com/users/795690/mike-beaton\">Mike Beaton</a>:</p>\n\n<blockquote>\n <p><code>git merge -s ours <their-ref></code> effectively says 'mark commits made up to <code><their-ref></code> on their branch as commits to be permanently ignored';<br>\n <strong>and this matters because, if you subsequently merge from later states of their branch, their later changes will be brought in without the ignored changes ever being brought in</strong>.</p>\n</blockquote>\n"
},
{
"answer_id": 50334247,
"author": "Boaz Nahum",
"author_id": 1173533,
"author_profile": "https://Stackoverflow.com/users/1173533",
"pm_score": 2,
"selected": false,
"text": "<p>The equivalent(which keep parent order) to 'git merge -s theirs branchB'</p>\n\n<p>Before merge:<a href=\"https://i.stack.imgur.com/6AFQ5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6AFQ5.png\" alt=\"enter image description here\"></a></p>\n\n<p>!!! Make sure you are in clean state !!!</p>\n\n<p>Do the merge:</p>\n\n<pre><code>git commit-tree -m \"take theirs\" -p HEAD -p branchB 'branchB^{tree}'\ngit reset --hard 36daf519952 # is the output of the prev command\n</code></pre>\n\n<p>What we did ?\n We created a new commit which two parents ours and theirs and the contnet of the commit is branchB - theirs</p>\n\n<p>After merge:<a href=\"https://i.stack.imgur.com/XlMV5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XlMV5.png\" alt=\"enter image description here\"></a></p>\n\n<p>More precisely:</p>\n\n<pre><code>git commit-tree -m \"take theirs\" -p HEAD -p 'SOURCE^{commit}' 'SOURCE^{tree}'\n</code></pre>\n"
},
{
"answer_id": 52659754,
"author": "rubund",
"author_id": 5744809,
"author_profile": "https://Stackoverflow.com/users/5744809",
"pm_score": -1,
"selected": false,
"text": "<p>A simple and intuitive (in my opinion) two-step way of doing it is</p>\n\n<pre><code>git checkout branchB .\ngit commit -m \"Picked up the content from branchB\"\n</code></pre>\n\n<p>followed by</p>\n\n<pre><code>git merge -s ours branchB\n</code></pre>\n\n<p>(which marks the two branches as merged)</p>\n\n<p>The only disadvantage is that it does not remove files which have been deleted in branchB from your current branch. A simple diff between the two branches afterwards will show if there are any such files.</p>\n\n<p>This approach also makes it clear from the revision log afterwards what was done - and what was intended.</p>\n"
},
{
"answer_id": 56368650,
"author": "Brain2000",
"author_id": 231839,
"author_profile": "https://Stackoverflow.com/users/231839",
"pm_score": 2,
"selected": false,
"text": "<p>This answer was given by Paul Pladijs. I just took his commands and made a git alias for convenience.</p>\n\n<p>Edit your .gitconfig and add the following:</p>\n\n<pre><code>[alias]\n mergetheirs = \"!git merge -s ours \\\"$1\\\" && git branch temp_THEIRS && git reset --hard \\\"$1\\\" && git reset --soft temp_THEIRS && git commit --amend && git branch -D temp_THEIRS\"\n</code></pre>\n\n<p>Then you can \"git merge -s theirs A\" by running:</p>\n\n<pre><code>git checkout B (optional, just making sure we're on branch B)\ngit mergetheirs A\n</code></pre>\n"
},
{
"answer_id": 74070090,
"author": "Edgar Bonet",
"author_id": 463687,
"author_profile": "https://Stackoverflow.com/users/463687",
"pm_score": 0,
"selected": false,
"text": "<p>Revisiting this old question, as I just found a solution that is both\nshort and – since it uses only porcelain commands – easy to understand.\nTo be clear, I want to answer the problem stated in the title of the\nquestion (implement <code>git merge -s theirs</code>), not the question body. In\nother words, I want to create a merge commit with a tree identical to\nthe tree of its second parent:</p>\n<pre class=\"lang-bash prettyprint-override\"><code># Start from the branch that is going to receive the merge.\ngit switch our_branch\n\n# Create the merge commit, albeit with the wrong tree.\ngit merge -s ours their_branch\n\n# Replace our working tree and our index with their tree.\ngit restore --source=their_branch --worktree --staged :/\n\n# Put their tree in the merge commit.\ngit commit --amend\n</code></pre>\n<p><strong>Caveat</strong>: <code>git restore</code> is a fairly new command, introduced in git\n2.23. <code>git help restore</code> warns that</p>\n<blockquote>\n<p>THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.</p>\n</blockquote>\n<p>I did test this method with multiple versions of git (2.25.1, 2.30.2,\n2.31.1, 2.34.1 and 2.35.1), and it worked as expected.</p>\n"
},
{
"answer_id": 74643586,
"author": "tobylaroni",
"author_id": 3298457,
"author_profile": "https://Stackoverflow.com/users/3298457",
"pm_score": 0,
"selected": false,
"text": "<p>This doesn't necessarily answer the original poster's question, but I landed here in a situation where I had already attempted a merge but ended up with conflicts. Usually I manage conflicts in an IDE, but when I don't have access to that, the following REGEX can be used to find and replace differences with the "theirs" content:</p>\n<p>Replce <code><<<<<<< HEAD\\n[^•>]+\\n=======\\n([^•>]+)>>>>>>> .+\\n</code> with <code>\\1</code></p>\n<p>(Just in case anyone else lands on this page for the same reason I did).</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277510/"
] |
When merging topic branch "B" into "A" using `git merge`, I get some conflicts. I know all the conflicts can be solved using the version in "B".
I am aware of `git merge -s ours`. But what I want is something like `git merge -s theirs`.
Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing `git` commands? (`git checkout` every unmerged file from B)
The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.
|
A similar alternative is the `--strategy-option` (short form `-X`) option, which accepts `theirs`. For example:
```
git checkout branchA
git merge -X theirs branchB
```
However, this is more equivalent to `-X ours` than `-s ours`. The key difference being that `-X` performs a regular recursive merge, resolving any conflicts using the chosen side, whereas `-s ours` changes the merge to just completely ignore the other side.
In some cases, the main problem using `-X theirs` instead of the hypothetical `-s theirs` is deleted files. In this case, just run `git rm` with the name of any files that were deleted:
```
git rm {DELETED-FILE-NAME}
```
After that, the `-X theirs` may work as expected.
Of course, doing the actual removal with the `git rm` command will prevent the conflict from happening in the first place.
|
173,980 |
<p>There are numerous times you have an interface that accepts similar type arguments that have a separate domain logic meaning:</p>
<pre><code>public static class Database
{
public static bool HasAccess(string userId, string documentId) { return true; }
}
</code></pre>
<p>Now it's quite easy to have someone key documentId instead of userId and vice versa. One could prevent that by abstracting the data type of the arguments:</p>
<pre><code>public class UserId
{
public string Value { get; internal set; }
public static implicit operator string(UserId id) { return id.Value; }
}
public class DocumentId
{
public string Value { get; internal set; }
public static implicit operator string(DocumentId id) { return id.Value; }
}
public static class Database
{
public static bool HasAccess(UserId userId, DocumentId documentId) { return true; }
}
</code></pre>
<p>This way you get a nice compiler warning if you type in arguments out of order:</p>
<pre><code>UserId e = new UserId() { Value = "a" };
DocumentId d = new DocumentId() { Value = "b" };
Database.HasAccess(d, e);
</code></pre>
<p>You also get the ability to change abstracted type in without affecting the rest of the system but that's not very likely. Would abstracting type be a good idea to get more type safety?</p>
<p>The question relates to C# solutions but short descriptions in other languages is welcome.</p>
<p>EDIT: Removed the implicit cast from string and pointing finger at the C# tag.</p>
|
[
{
"answer_id": 173985,
"author": "Johan Bresler",
"author_id": 3535708,
"author_profile": "https://Stackoverflow.com/users/3535708",
"pm_score": 2,
"selected": false,
"text": "<p>I think you answered your own question - better data integrity and validation, better system</p>\n"
},
{
"answer_id": 173989,
"author": "Nick Fortescue",
"author_id": 5346,
"author_profile": "https://Stackoverflow.com/users/5346",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it is sometimes a good idea. But if you get too obsessed with this you become an architecture astronaut.</p>\n\n<p>As regards the type safety argument - it does increase type safety but lots of languages manage fine without it.</p>\n\n<p>In my opinion the best way to go is leave it as a String to start with, and then when you find yourself reusing the interface, make the refactoring to a more abstract type at that point.</p>\n\n<p>Predicting the future is too hard to waste time trying. </p>\n"
},
{
"answer_id": 173990,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>Seems to be a lot of overhead for something your unit tests ought to prevent anyway, at least in this case.</p>\n"
},
{
"answer_id": 173994,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "<p>Interesting, but I suspect that in many cases (particularly seialization / RPC APIs) this will only add confustion/overhead. Also - a minor implementation detail, but given this approach I'd make the wrappers fully immutable, not just \"internal set\" immutable.</p>\n\n<p>TBH - I'd probably rather use unit tests for most of this... sometimes simple is beautiful. The other problem is that since you have implicit operators, it won't stop you doing the much more likely:</p>\n\n<pre><code>string user = \"fred\";\nSomeMethodThatWantsADocument(user);\n</code></pre>\n\n<p>That should compile; the implicit operator undoes all your good work...</p>\n"
},
{
"answer_id": 173997,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 1,
"selected": false,
"text": "<p>This is where typedef becomes useful in C++. You can have UserID and DocumentID as typedeffed types and thus are not interchangable without a cast, but don't require anything more than a quick note to the compiler saying 'this should be a separate type distinct from other types even though it is really just type X'.</p>\n"
},
{
"answer_id": 174023,
"author": "interstar",
"author_id": 8482,
"author_profile": "https://Stackoverflow.com/users/8482",
"pm_score": 1,
"selected": false,
"text": "<p>In this case, it doesn't look worth it to me.</p>\n\n<p>You've added 12 lines, spread across two extra-classes. In some languages you're looking at having to manage two new files for that. (Not sure in C#). You've introduced a lot of extra cognitive load. Those classes appear whenever you navigate your class-list; they appear in your automatically generated documentation; they're there as something that newcomers to your codebase see whenever they're trying to learn their way around, they're in the dependency graph of the compiler etc. Programmers have to know the types and create two new objects whenever they call HasAccess.</p>\n\n<p>And for what? To prevent you accidentally mixing up the username and document id when checking if someone has a right to access the database. That check should probably be written two, maybe three times in a normal system. (If you're writing it a lot you probably haven't got enough reuse in your database access code)</p>\n\n<p>So, I'd say that this is excess astronautics. My rule of thumb is that classes or types should encapsulate variant <em>behaviour</em>, not variant use of passive data.</p>\n"
},
{
"answer_id": 174098,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "<p>What you don't ask and don't answer are the questions that best determine if the new types are important:</p>\n\n<ol>\n<li><p>What is the projected, realistic lifetime of this system? If the answer is 2+ years, you should have at least one level of abstraction for the database and for the user id. In other words, your database should be abstract and your user and credentials should be abstract. Then you implement your database and userid in terms of the abstract definition. That way, if the needs should change your changes will be local to the places that need it most.</p></li>\n<li><p>What are the gains and losses from having a userid data type? This question should be answered in terms of usability, expressiveness, and type safety. The number of created classes or extra lines are largely immaterial if there are clear gains in usability and expressiveness - hooray, you win. Let me give you an example of a clear loss - I worked with a class hierarchy that contained an abstract base class with several concrete children types. Rather than provide constructors for the child classes and appropriate accessors, they made a factory method that took an XML string or stream as an argument and constructed the appropriate concrete class from that. It was such a loss in usability that it made this library painful - even their sample code reeked of lose. While I could construct everything they offered, it felt heinous and generated runtime instead of compile time errors for typical issues.</p></li>\n</ol>\n"
},
{
"answer_id": 174145,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>While at the end of the day, you may not care, the more abstraction the harder the maintenance (especially for other people). If in six months you have to start digging through this code to find or fix a bug, or even add a new feature, it will take you that much longer to remember what you did and why. If someone else is doing it, multiply that time. Elegant code is always nice when you're writing new code, but I always like to weigh that with the needs of maintainers down the road.</p>\n"
},
{
"answer_id": 174618,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 0,
"selected": false,
"text": "<p>This feels like a YAGNI issue to me. If you're just doing it because it MIGHT be useful, that's usually not a good enough reason for the extra complexity. Also, as others have noted, this is the sort of thing that unit tests should catch.</p>\n\n<p>Another thing I try to keep in mind is whether an abstraction is meant to protect programmers from themselves. Yes, it is theoretically easy to flip-flop two string arguments. But in all seriousness, paying attention to argument ordering has been a fundamental aspect of programming in most languages for decades. It's not something that should happen often, and it's certainly something that tests should be catching. If this type of thing is a common problem in your organization, I'd say you have bigger problems to worry about.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23164/"
] |
There are numerous times you have an interface that accepts similar type arguments that have a separate domain logic meaning:
```
public static class Database
{
public static bool HasAccess(string userId, string documentId) { return true; }
}
```
Now it's quite easy to have someone key documentId instead of userId and vice versa. One could prevent that by abstracting the data type of the arguments:
```
public class UserId
{
public string Value { get; internal set; }
public static implicit operator string(UserId id) { return id.Value; }
}
public class DocumentId
{
public string Value { get; internal set; }
public static implicit operator string(DocumentId id) { return id.Value; }
}
public static class Database
{
public static bool HasAccess(UserId userId, DocumentId documentId) { return true; }
}
```
This way you get a nice compiler warning if you type in arguments out of order:
```
UserId e = new UserId() { Value = "a" };
DocumentId d = new DocumentId() { Value = "b" };
Database.HasAccess(d, e);
```
You also get the ability to change abstracted type in without affecting the rest of the system but that's not very likely. Would abstracting type be a good idea to get more type safety?
The question relates to C# solutions but short descriptions in other languages is welcome.
EDIT: Removed the implicit cast from string and pointing finger at the C# tag.
|
Interesting, but I suspect that in many cases (particularly seialization / RPC APIs) this will only add confustion/overhead. Also - a minor implementation detail, but given this approach I'd make the wrappers fully immutable, not just "internal set" immutable.
TBH - I'd probably rather use unit tests for most of this... sometimes simple is beautiful. The other problem is that since you have implicit operators, it won't stop you doing the much more likely:
```
string user = "fred";
SomeMethodThatWantsADocument(user);
```
That should compile; the implicit operator undoes all your good work...
|
173,995 |
<p>As a function argument I get a <code>vector<double>& vec</code> (an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes.</p>
<p>This will work </p>
<pre><code>vec.clear();
vec.resize( n, 0.0 );
</code></pre>
<p>And this will work as well:</p>
<pre><code>vec.resize( n );
vec.assign( n, 0.0 );
</code></pre>
<p>Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this? </p>
|
[
{
"answer_id": 173998,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<pre><code>std::vector<double>(n).swap(vec);\n</code></pre>\n\n<p>This has the advantage of actually compacting your vector too. (In your first example, <code>clear()</code> does not guarantee to compact your vector.)</p>\n"
},
{
"answer_id": 174571,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 5,
"selected": true,
"text": "<pre><code>std::vector<double>(n).swap(vec);\n</code></pre>\n\n<p>After this, vec is guaranteed to have size and capacity n, with all values 0.0.</p>\n\n<p>Perhaps the more idiomatic way since C++11 is</p>\n\n<pre><code>vec.assign(n, 0.);\nvec.shrink_to_fit();\n</code></pre>\n\n<p>with the second line optional. In the case where <code>vec</code> starts off with more than <code>n</code> elements, whether to call <code>shrink_to_fit</code> is a trade-off between holding onto more memory than is required vs performing a re-allocation.</p>\n"
},
{
"answer_id": 176247,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 2,
"selected": false,
"text": "<p>Well let's round out the ways to do this :)</p>\n\n<pre><code>vec.swap(std::vector<double>(n));\nstd::vector<double>(n).swap(vec);\nstd::swap(vector<double>(n), vec);\nstd::swap(vec, vector<double>(n));\n</code></pre>\n"
},
{
"answer_id": 177313,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "<p>Neither of the code snippets that you posted do any memory deallocation, so they are roughly equal.</p>\n\n<p>The swap trick that everyone else keeps posting will take longer to execute, because it will deallocate the memory originally used by the vector. This may or may not be desirable.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/173995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
] |
As a function argument I get a `vector<double>& vec` (an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes.
This will work
```
vec.clear();
vec.resize( n, 0.0 );
```
And this will work as well:
```
vec.resize( n );
vec.assign( n, 0.0 );
```
Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this?
|
```
std::vector<double>(n).swap(vec);
```
After this, vec is guaranteed to have size and capacity n, with all values 0.0.
Perhaps the more idiomatic way since C++11 is
```
vec.assign(n, 0.);
vec.shrink_to_fit();
```
with the second line optional. In the case where `vec` starts off with more than `n` elements, whether to call `shrink_to_fit` is a trade-off between holding onto more memory than is required vs performing a re-allocation.
|
174,005 |
<p>I have an xml file providing data for a datagrid in Flex 2 that includes an unformatted Price field (ie: it is just a number).
Can anyone tell me how I take that datafield and format it - add a currency symbol, put in thousand separators etc.
Thanks.
S.</p>
|
[
{
"answer_id": 174057,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "<p>How about the CurrencyFormatter class</p>\n\n<p>See <a href=\"http://livedocs.adobe.com/flex/2/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001087.html\" rel=\"nofollow noreferrer\">here</a> for docs from Flex 2. It's pretty easy to use.</p>\n\n<p>You can use one of these in a labelFunction on a DataGrid Column to format your numbers.</p>\n"
},
{
"answer_id": 174608,
"author": "JustLogic",
"author_id": 21664,
"author_profile": "https://Stackoverflow.com/users/21664",
"pm_score": 2,
"selected": true,
"text": "<p>As stated above an easy way to do this would be to add a labelFunction to the specified column and format the data within there.</p>\n\n<p>Frequently I find that its much easier to work with objects then straight XML so normally if I am receiving XML from a function I would create an object and parser for that XML and you can format the data inside the parser also if you like.</p>\n\n<p>Another way to handle this would be inside an itemRenderer. Example:</p>\n\n<pre><code><mx:DataGridColumn id=\"dgc\" headerText=\"Money\" editable=\"false\">\n <mx:itemRenderer>\n <mx:Component>\n <mx:HBox horizontalAlign=\"right\">\n <mx:CurrencyFormatter id=\"cFormat\" precision=\"2\" currencySymbol=\"$\" useThousandsSeparator=\"true\"/>\n <mx:Label id=\"lbl\" text=\"{cFormat.format(data)}\" />\n </mx:HBox>\n </mx:Component>\n </mx:itemRenderer>\n</mx:DataGridColumn>\n</code></pre>\n"
},
{
"answer_id": 176415,
"author": "user25463",
"author_id": 25463,
"author_profile": "https://Stackoverflow.com/users/25463",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks alot for your answers...they helped a great deal.</p>\n\n<p>In the end I went for a solution that involved the following three elements:</p>\n\n<pre><code><mx:DataGridColumn headerText=\"Price\" textAlign=\"right\" labelFunction=\"formatCcy\" width=\"60\"/>\n\npublic function formatCcy(item:Object, column:DataGridColumn):String\n {\n return euroPrice.format(item.price);\n }\n\n<mx:CurrencyFormatter id=\"euroPrice\" precision=\"0\" \n rounding=\"none\"\n decimalSeparatorTo=\".\"\n thousandsSeparatorTo=\",\"\n useThousandsSeparator=\"true\"\n useNegativeSign=\"true\"\n currencySymbol=\"€\"\n alignSymbol=\"left\"/>\n</code></pre>\n\n<p>I dont know whether this is the correct solution, but it seems to work (at the moment),\nThanks again,\nS...</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25463/"
] |
I have an xml file providing data for a datagrid in Flex 2 that includes an unformatted Price field (ie: it is just a number).
Can anyone tell me how I take that datafield and format it - add a currency symbol, put in thousand separators etc.
Thanks.
S.
|
As stated above an easy way to do this would be to add a labelFunction to the specified column and format the data within there.
Frequently I find that its much easier to work with objects then straight XML so normally if I am receiving XML from a function I would create an object and parser for that XML and you can format the data inside the parser also if you like.
Another way to handle this would be inside an itemRenderer. Example:
```
<mx:DataGridColumn id="dgc" headerText="Money" editable="false">
<mx:itemRenderer>
<mx:Component>
<mx:HBox horizontalAlign="right">
<mx:CurrencyFormatter id="cFormat" precision="2" currencySymbol="$" useThousandsSeparator="true"/>
<mx:Label id="lbl" text="{cFormat.format(data)}" />
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
```
|
174,024 |
<p>Consider the following method signatures:</p>
<pre><code>public fooMethod (Foo[] foos) { /*...*/ }
</code></pre>
<p>and</p>
<pre><code>public fooMethod (Foo... foos) { /*...*/ }
</code></pre>
<p><em>Explanation: The former takes an array of Foo-objects as an argument - <code>fooMethod(new Foo[]{..})</code> - while the latter takes an arbitrary amount of arguments of type Foo, and presents them as an array of Foo:s within the method - <code>fooMethod(fooObject1, fooObject2, etc...</code>).</em></p>
<p>Java throws a fit if both are defined, claiming that they are duplicate methods. I did some detective work, and found out that the first declaration really requires an explicit array of Foo objects, and that's the only way to call that method. The second way actually accepts both an arbitrary amount of Foo arguments AND also accepts an array of Foo objects.</p>
<p>So, the question is, since the latter method seems more flexible, are there any reasons to use the first example, or have I missed anything vital?</p>
|
[
{
"answer_id": 174032,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 1,
"selected": false,
"text": "<p>The latter was introduced in Java 5 and existing libraries are gradually being reworked to support it. You might still use the former to stress that the method requires 2+ inputs, plus there are restrictions on where the ... can be used.</p>\n"
},
{
"answer_id": 174036,
"author": "Shimi Bandiel",
"author_id": 15100,
"author_profile": "https://Stackoverflow.com/users/15100",
"pm_score": 5,
"selected": true,
"text": "<p>These methods are actually the same.</p>\n\n<p>This feature is called varargs and it is a compiler feature. Behind the scenes is is translates to the former version.</p>\n\n<p>There is a pitfall if you define a method that accepts Object... and you sent one parameter of type Object[]!</p>\n"
},
{
"answer_id": 174060,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 0,
"selected": false,
"text": "<p>There are certainly no performance issues or things like that to consider, so it comes down to semantics.</p>\n\n<p>Do you expect the caller of your method to have an array of Foo's ready at hand? Then use the Foo[] version. Use the varargs variant to emphasize the possibility of having a \"bunch\" of Foo's instead of an array.</p>\n\n<p>A classical example for varargs ist the string-format (in C#, dunno how its called in Java):</p>\n\n<pre><code>string Format(string formatString, object... args)\n</code></pre>\n\n<p>Here you expect the args to be of different types, so having an array of arguments would be quite unusal, hence the varargs variant.</p>\n\n<p>On the other hand in something like</p>\n\n<pre><code>string Join(string[] substrings, char concatenationCharacter)\n</code></pre>\n\n<p>using an Array is perfectly reasonable.</p>\n\n<p>Also note that you can have multiple array-parameters and only one vararg parameter at the end of the paramater-list.</p>\n"
},
{
"answer_id": 174067,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": false,
"text": "<p>I'd like to add to Shimi's explanation to add that another restriction of the varargs syntax is that the vararg must be the last declared parameter. So you can't do this:</p>\n\n<pre><code>void myMethod(String... values, int num);\n</code></pre>\n\n<p>This means that any given method can only have a single vararg parameter. In cases where you want to pass multiple arrays, you can use varargs for only one of them.</p>\n\n<p>In practice, varargs are at their best when you are treating the args as an arbitrary number of distinct values, rather than as an array. Java5 maps them to an array simply because that was the most convenient thing to do.</p>\n\n<p>A good example is String.format(). Here, the varargs are matched against the format placeholders in the first argument.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
Consider the following method signatures:
```
public fooMethod (Foo[] foos) { /*...*/ }
```
and
```
public fooMethod (Foo... foos) { /*...*/ }
```
*Explanation: The former takes an array of Foo-objects as an argument - `fooMethod(new Foo[]{..})` - while the latter takes an arbitrary amount of arguments of type Foo, and presents them as an array of Foo:s within the method - `fooMethod(fooObject1, fooObject2, etc...`).*
Java throws a fit if both are defined, claiming that they are duplicate methods. I did some detective work, and found out that the first declaration really requires an explicit array of Foo objects, and that's the only way to call that method. The second way actually accepts both an arbitrary amount of Foo arguments AND also accepts an array of Foo objects.
So, the question is, since the latter method seems more flexible, are there any reasons to use the first example, or have I missed anything vital?
|
These methods are actually the same.
This feature is called varargs and it is a compiler feature. Behind the scenes is is translates to the former version.
There is a pitfall if you define a method that accepts Object... and you sent one parameter of type Object[]!
|
174,025 |
<p>How do you trigger a javascript function using actionscript in flash?</p>
<p>The goal is to trigger jQuery functionality from a flash movie</p>
|
[
{
"answer_id": 174034,
"author": "jochil",
"author_id": 23794,
"author_profile": "https://Stackoverflow.com/users/23794",
"pm_score": 5,
"selected": true,
"text": "<p>Take a look at the <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html\" rel=\"noreferrer\">ExternalInterface</a>-Class. <br>\nFrom the AS3-Language Reference:</p>\n\n<blockquote>\n <p>The ExternalInterface class is the\n External API, an application\n programming interface that enables\n straightforward communication between\n ActionScript and the Flash Player\n container– for example, an HTML page\n with JavaScript. Adobe recommends\n using ExternalInterface for all\n JavaScript-ActionScript communication.</p>\n</blockquote>\n\n<p>And it's work like this:</p>\n\n<pre><code>ExternalInterface.addCallback(\"sendToActionScript\", receivedFromJavaScript);\nExternalInterface.call(\"sendToJavaScript\", input.text);\n</code></pre>\n\n<p>You can submit parameters and recieve callbacks...pretty cool, right? ;)</p>\n\n<p>As I know it will also work on AS2...</p>\n"
},
{
"answer_id": 174075,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 2,
"selected": false,
"text": "<p>As Jochen said ExternalInterface is the way to go and I can confirm that it works with AS2.</p>\n\n<p>If you plan to trigger navigation or anything that affects the area where the flash sits don't do it directly from the function you call from flash. Flash expects a return value from the function it calls and if the flash object does not exist when the function is completed the flash plugin will crash. </p>\n\n<p>If you need to do navigation or alter the content you can add a setTimeout call (into your js function). That will create a new thread and give flash the return value it expects.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
] |
How do you trigger a javascript function using actionscript in flash?
The goal is to trigger jQuery functionality from a flash movie
|
Take a look at the [ExternalInterface](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html)-Class.
From the AS3-Language Reference:
>
> The ExternalInterface class is the
> External API, an application
> programming interface that enables
> straightforward communication between
> ActionScript and the Flash Player
> container– for example, an HTML page
> with JavaScript. Adobe recommends
> using ExternalInterface for all
> JavaScript-ActionScript communication.
>
>
>
And it's work like this:
```
ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);
ExternalInterface.call("sendToJavaScript", input.text);
```
You can submit parameters and recieve callbacks...pretty cool, right? ;)
As I know it will also work on AS2...
|
174,069 |
<p>How can I, in Java or using some other programming language, add a new program group in the applications menu in both KDE and Gnome? </p>
<p>I am testing with Ubuntu and Kubuntu 8. Putting a simple .menu file in ~/.config/menus/applications-merged worked in Kubuntu, but the same procedure does nothing in Ubuntu.</p>
<p>The content of my file is as follows:</p>
<pre><code><!DOCTYPE Menu PUBLIC "-//freedesktop//DTD Menu 1.0//EN" "http://www.freedesktop.org/standards/menu-spec/1.0/menu.dtd">
<Menu>
<Menu>
<Name>My Program Group</Name>
<Include>
<Filename>shortcut.desktop</Filename>
</Include>
</Menu>
</Menu>
</code></pre>
<p>Note that the .desktop file is correctly placed in ~/.local/share/applications.</p>
<p>Ps: The original question did not specify I wanted a solution in a programmatic way.</p>
|
[
{
"answer_id": 174082,
"author": "fly.floh",
"author_id": 25442,
"author_profile": "https://Stackoverflow.com/users/25442",
"pm_score": 0,
"selected": false,
"text": "<p>In Gnome use System -> Settings -> Menu then just choose New Menu or New Entry.</p>\n"
},
{
"answer_id": 174087,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 2,
"selected": true,
"text": "<p>Maybe xdg-desktop-menu does that? See <code>man xdg-desktop-menu</code> or <a href=\"http://manpages.ubuntu.com/manpages/hardy/en/man1/xdg-desktop-menu.html\" rel=\"nofollow noreferrer\">http://manpages.ubuntu.com/manpages/hardy/en/man1/xdg-desktop-menu.html</a> .</p>\n"
},
{
"answer_id": 175169,
"author": "Thiago Chaves",
"author_id": 16873,
"author_profile": "https://Stackoverflow.com/users/16873",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks, oliver. I used xdg-desktop-menu and then analyzed its output. The correct menu file needs to explicitly name the outer menu (Applications), as follows:</p>\n\n<pre><code><!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\" \n \"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n<Menu>\n <Name>Applications</Name>\n<Menu>\n <Name>My Program Group</Name>\n <Include>\n <Filename>shortcut.desktop</Filename>\n </Include>\n</Menu>\n</Menu>\n</code></pre>\n\n<p>This worked fine in Kubuntu, Ubuntu and Fedora Core 9. Couldn't make it work on openSUSE, though.</p>\n"
},
{
"answer_id": 176155,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": false,
"text": "<p>I recommend you look into freedesktop.org standards that cover this. Up to date list is available here:</p>\n\n<p><a href=\"http://www.freedesktop.org/wiki/Specifications/menu-spec\" rel=\"nofollow noreferrer\"><a href=\"http://www.freedesktop.org/wiki/Specifications/menu-spec\" rel=\"nofollow noreferrer\">http://www.freedesktop.org/wiki/Specifications/menu-spec</a></a></p>\n\n<p>The latest one is currently 1.0:</p>\n\n<p><a href=\"http://standards.freedesktop.org/menu-spec/1.0/\" rel=\"nofollow noreferrer\"><a href=\"http://standards.freedesktop.org/menu-spec/1.0/\" rel=\"nofollow noreferrer\">http://standards.freedesktop.org/menu-spec/1.0/</a></a></p>\n\n<p>FreeDesktop.org standards are followed by Gnome, KDE and XFCE, so it should work on any distribution.</p>\n"
},
{
"answer_id": 183763,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure what you meant exactly with \"in openSUSE the .directory file is mandatory or else the program group does not shows up\"; generally I suppose you have to call xdg-desktop-menu twice (once for the program group and once for the program itself), and so you have to supply two different .directory files as well. If the program group is empty, it makes sense that the desktop hides it.</p>\n\n<p>(But maybe I completely misunderstood you here :-) and I've never used xdg-desktop-menu myself anyway).</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16873/"
] |
How can I, in Java or using some other programming language, add a new program group in the applications menu in both KDE and Gnome?
I am testing with Ubuntu and Kubuntu 8. Putting a simple .menu file in ~/.config/menus/applications-merged worked in Kubuntu, but the same procedure does nothing in Ubuntu.
The content of my file is as follows:
```
<!DOCTYPE Menu PUBLIC "-//freedesktop//DTD Menu 1.0//EN" "http://www.freedesktop.org/standards/menu-spec/1.0/menu.dtd">
<Menu>
<Menu>
<Name>My Program Group</Name>
<Include>
<Filename>shortcut.desktop</Filename>
</Include>
</Menu>
</Menu>
```
Note that the .desktop file is correctly placed in ~/.local/share/applications.
Ps: The original question did not specify I wanted a solution in a programmatic way.
|
Maybe xdg-desktop-menu does that? See `man xdg-desktop-menu` or <http://manpages.ubuntu.com/manpages/hardy/en/man1/xdg-desktop-menu.html> .
|
174,093 |
<p>Assuming I have an ArrayList</p>
<pre><code>ArrayList<MyClass> myList;
</code></pre>
<p>And I want to call toArray, is there a performance reason to use</p>
<pre><code>MyClass[] arr = myList.toArray(new MyClass[myList.size()]);
</code></pre>
<p>over</p>
<pre><code>MyClass[] arr = myList.toArray(new MyClass[0]);
</code></pre>
<p>?</p>
<p>I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.</p>
<p>Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...</p>
|
[
{
"answer_id": 174105,
"author": "Matthew Murdoch",
"author_id": 4023,
"author_profile": "https://Stackoverflow.com/users/4023",
"pm_score": -1,
"selected": false,
"text": "<p>Using 'toArray' with the array of the correct size will perform better as the alternative will create first the zero sized array then the array of the correct size. However, as you say the difference is likely to be negligible.</p>\n\n<p>Also, note that the javac compiler does not perform any optimization. These days all optimizations are performed by the JIT/HotSpot compilers at runtime. I am not aware of any optimizations around 'toArray' in any JVMs.</p>\n\n<p>The answer to your question, then, is largely a matter of style but for consistency's sake should form part of any coding standards you adhere to (whether documented or otherwise).</p>\n"
},
{
"answer_id": 174108,
"author": "Panagiotis Korros",
"author_id": 19331,
"author_profile": "https://Stackoverflow.com/users/19331",
"pm_score": 2,
"selected": false,
"text": "<p>The first case is more efficient.</p>\n\n<p>That is because in the second case:</p>\n\n<pre><code>MyClass[] arr = myList.toArray(new MyClass[0]);\n</code></pre>\n\n<p>the runtime actually creates an empty array (with zero size) and then inside the toArray method creates another array to fit the actual data. This creation is done using reflection using the following code (taken from jdk1.5.0_10):</p>\n\n<pre><code>public <T> T[] toArray(T[] a) {\n if (a.length < size)\n a = (T[])java.lang.reflect.Array.\n newInstance(a.getClass().getComponentType(), size);\nSystem.arraycopy(elementData, 0, a, 0, size);\n if (a.length > size)\n a[size] = null;\n return a;\n}\n</code></pre>\n\n<p>By using the first form, you avoid the creation of a second array and also avoid the reflection code.</p>\n"
},
{
"answer_id": 174110,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 2,
"selected": false,
"text": "<p>toArray checks that the array passed is of the right size (that is, large enough to fit the elements from your list) and if so, uses that. Consequently if the size of the array provided it smaller than required, a new array will be reflexively created.</p>\n\n<p>In your case, an array of size zero, is immutable, so could safely be elevated to a static final variable, which might make your code a little cleaner, which avoids creating the array on each invocation. A new array will be created inside the method anyway, so it's a readability optimisation.</p>\n\n<p>Arguably the faster version is to pass the array of a correct size, but unless you can <em>prove</em> this code is a performance bottleneck, prefer readability to runtime performance until proven otherwise.</p>\n"
},
{
"answer_id": 174146,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 7,
"selected": false,
"text": "<p>As of <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html#toArray(T[])\" rel=\"noreferrer\">ArrayList in Java 5</a>, the array will be filled already if it has the right size (or is bigger). Consequently</p>\n\n<pre><code>MyClass[] arr = myList.toArray(new MyClass[myList.size()]);\n</code></pre>\n\n<p>will create one array object, fill it and return it to \"arr\". On the other hand</p>\n\n<pre><code>MyClass[] arr = myList.toArray(new MyClass[0]);\n</code></pre>\n\n<p>will create two arrays. The second one is an array of MyClass with length 0. So there is an object creation for an object that will be thrown away immediately. As far as the source code suggests the compiler / JIT cannot optimize this one so that it is not created. Additionally, using the zero-length object results in casting(s) within the toArray() - method.</p>\n\n<p>See the source of ArrayList.toArray():</p>\n\n<pre><code>public <T> T[] toArray(T[] a) {\n if (a.length < size)\n // Make a new array of a's runtime type, but my contents:\n return (T[]) Arrays.copyOf(elementData, size, a.getClass());\n System.arraycopy(elementData, 0, a, 0, size);\n if (a.length > size)\n a[size] = null;\n return a;\n}\n</code></pre>\n\n<p>Use the first method so that only one object is created and avoid (implicit but nevertheless expensive) castings.</p>\n"
},
{
"answer_id": 174244,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "<p>Modern JVMs optimise reflective array construction in this case, so the performance difference is tiny. Naming the collection twice in such boilerplate code is not a great idea, so I'd avoid the first method. Another advantage of the second is that it works with synchronised and concurrent collections. If you want to make optimisation, reuse the empty array (empty arrays are immutable and can be shared), or use a profiler(!).</p>\n"
},
{
"answer_id": 18325193,
"author": "MiguelMunoz",
"author_id": 2028066,
"author_profile": "https://Stackoverflow.com/users/2028066",
"pm_score": -1,
"selected": false,
"text": "<p>The second one is marginally mor readable, but there so little improvement that it's not worth it. The first method is faster, with no disadvantages at runtime, so that's what I use. But I write it the second way, because it's faster to type. Then my IDE flags it as a warning and offers to fix it. With a single keystroke, it converts the code from the second type to the first one.</p>\n"
},
{
"answer_id": 29444594,
"author": "assylias",
"author_id": 829571,
"author_profile": "https://Stackoverflow.com/users/829571",
"pm_score": 8,
"selected": true,
"text": "<p>Counterintuitively, the fastest version, on Hotspot 8, is:</p>\n\n<pre><code>MyClass[] arr = myList.toArray(new MyClass[0]);\n</code></pre>\n\n<p>I have run a micro benchmark using jmh the results and code are below, showing that the version with an empty array consistently outperforms the version with a presized array. Note that if you can reuse an existing array of the correct size, the result may be different.</p>\n\n<p>Benchmark results (score in microseconds, smaller = better):</p>\n\n<pre><code>Benchmark (n) Mode Samples Score Error Units\nc.a.p.SO29378922.preSize 1 avgt 30 0.025 ▒ 0.001 us/op\nc.a.p.SO29378922.preSize 100 avgt 30 0.155 ▒ 0.004 us/op\nc.a.p.SO29378922.preSize 1000 avgt 30 1.512 ▒ 0.031 us/op\nc.a.p.SO29378922.preSize 5000 avgt 30 6.884 ▒ 0.130 us/op\nc.a.p.SO29378922.preSize 10000 avgt 30 13.147 ▒ 0.199 us/op\nc.a.p.SO29378922.preSize 100000 avgt 30 159.977 ▒ 5.292 us/op\nc.a.p.SO29378922.resize 1 avgt 30 0.019 ▒ 0.000 us/op\nc.a.p.SO29378922.resize 100 avgt 30 0.133 ▒ 0.003 us/op\nc.a.p.SO29378922.resize 1000 avgt 30 1.075 ▒ 0.022 us/op\nc.a.p.SO29378922.resize 5000 avgt 30 5.318 ▒ 0.121 us/op\nc.a.p.SO29378922.resize 10000 avgt 30 10.652 ▒ 0.227 us/op\nc.a.p.SO29378922.resize 100000 avgt 30 139.692 ▒ 8.957 us/op\n</code></pre>\n\n\n\n<hr>\n\n<p>For reference, the code:</p>\n\n<pre><code>@State(Scope.Thread)\n@BenchmarkMode(Mode.AverageTime)\npublic class SO29378922 {\n @Param({\"1\", \"100\", \"1000\", \"5000\", \"10000\", \"100000\"}) int n;\n private final List<Integer> list = new ArrayList<>();\n @Setup public void populateList() {\n for (int i = 0; i < n; i++) list.add(0);\n }\n @Benchmark public Integer[] preSize() {\n return list.toArray(new Integer[n]);\n }\n @Benchmark public Integer[] resize() {\n return list.toArray(new Integer[0]);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You can find similar results, full analysis, and discussion in the blog post <a href=\"https://shipilev.net/blog/2016/arrays-wisdom-ancients/\" rel=\"noreferrer\"><em>Arrays of Wisdom of the Ancients</em></a>. To summarize: the JVM and JIT compiler contains several optimizations that enable it to cheaply create and initialize a new correctly sized array, and those optimizations can not be used if you create the array yourself.</p>\n"
},
{
"answer_id": 50738003,
"author": "Антон Антонов",
"author_id": 1231300,
"author_profile": "https://Stackoverflow.com/users/1231300",
"pm_score": 5,
"selected": false,
"text": "<p><em>From JetBrains Intellij Idea inspection:</em></p>\n\n<blockquote>\n <p>There are two styles to convert a collection to an array: either using\n a pre-sized array (like <b>c.toArray(new String[c.size()])</b>) or\n using an empty array (like <b>c.toArray(new String[0])</b>. <p> In\n older Java versions using pre-sized array was recommended, as the\n reflection call which is necessary to create an array of proper size\n was quite slow. However since late updates of OpenJDK 6 this call\n was intrinsified, making the performance of the empty array version\n the same and sometimes even better, compared to the pre-sized\n version. Also passing pre-sized array is dangerous for a concurrent or\n synchronized collection as a data race is possible between the\n <b>size</b> and <b>toArray</b> call which may result in extra nulls\n at the end of the array, if the collection was concurrently shrunk\n during the operation. </p> <p> This inspection allows to follow the\n uniform style: either using an empty array (which is recommended in\n modern Java) or using a pre-sized array (which might be faster in\n older Java versions or non-HotSpot based JVMs). </p></p>\n</blockquote>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581/"
] |
Assuming I have an ArrayList
```
ArrayList<MyClass> myList;
```
And I want to call toArray, is there a performance reason to use
```
MyClass[] arr = myList.toArray(new MyClass[myList.size()]);
```
over
```
MyClass[] arr = myList.toArray(new MyClass[0]);
```
?
I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.
Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...
|
Counterintuitively, the fastest version, on Hotspot 8, is:
```
MyClass[] arr = myList.toArray(new MyClass[0]);
```
I have run a micro benchmark using jmh the results and code are below, showing that the version with an empty array consistently outperforms the version with a presized array. Note that if you can reuse an existing array of the correct size, the result may be different.
Benchmark results (score in microseconds, smaller = better):
```
Benchmark (n) Mode Samples Score Error Units
c.a.p.SO29378922.preSize 1 avgt 30 0.025 ▒ 0.001 us/op
c.a.p.SO29378922.preSize 100 avgt 30 0.155 ▒ 0.004 us/op
c.a.p.SO29378922.preSize 1000 avgt 30 1.512 ▒ 0.031 us/op
c.a.p.SO29378922.preSize 5000 avgt 30 6.884 ▒ 0.130 us/op
c.a.p.SO29378922.preSize 10000 avgt 30 13.147 ▒ 0.199 us/op
c.a.p.SO29378922.preSize 100000 avgt 30 159.977 ▒ 5.292 us/op
c.a.p.SO29378922.resize 1 avgt 30 0.019 ▒ 0.000 us/op
c.a.p.SO29378922.resize 100 avgt 30 0.133 ▒ 0.003 us/op
c.a.p.SO29378922.resize 1000 avgt 30 1.075 ▒ 0.022 us/op
c.a.p.SO29378922.resize 5000 avgt 30 5.318 ▒ 0.121 us/op
c.a.p.SO29378922.resize 10000 avgt 30 10.652 ▒ 0.227 us/op
c.a.p.SO29378922.resize 100000 avgt 30 139.692 ▒ 8.957 us/op
```
---
For reference, the code:
```
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
public class SO29378922 {
@Param({"1", "100", "1000", "5000", "10000", "100000"}) int n;
private final List<Integer> list = new ArrayList<>();
@Setup public void populateList() {
for (int i = 0; i < n; i++) list.add(0);
}
@Benchmark public Integer[] preSize() {
return list.toArray(new Integer[n]);
}
@Benchmark public Integer[] resize() {
return list.toArray(new Integer[0]);
}
}
```
---
You can find similar results, full analysis, and discussion in the blog post [*Arrays of Wisdom of the Ancients*](https://shipilev.net/blog/2016/arrays-wisdom-ancients/). To summarize: the JVM and JIT compiler contains several optimizations that enable it to cheaply create and initialize a new correctly sized array, and those optimizations can not be used if you create the array yourself.
|
174,119 |
<p>I see this often in the build scripts of projects that use autotools (autoconf, automake). When somebody wants to check the value of a shell variable, they frequently use this idiom:</p>
<pre><code>if test "x$SHELL_VAR" = "xyes"; then
...
</code></pre>
<p>What is the advantage to this over simply checking the value like this:</p>
<pre><code>if test $SHELL_VAR = "yes"; then
...
</code></pre>
<p>I figure there must be some reason that I see this so often, but I can't figure out what it is.</p>
|
[
{
"answer_id": 174125,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": -1,
"selected": false,
"text": "<p>I used to do that in DOS when the SHELL_VAR might be undefined.</p>\n"
},
{
"answer_id": 174156,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "<p>I believe its due to </p>\n\n<pre><code>SHELLVAR=$(true)\nif test $SHELLVAR = \"yes\" ; then echo \"yep\" ; fi \n\n# bash: test: =: unary operator expected\n</code></pre>\n\n<p>as well as </p>\n\n<pre><code>if test $UNDEFINEDED = \"yes\" ; then echo \"yep\" ; fi\n# bash: test: =: unary operator expected\n</code></pre>\n\n<p>and </p>\n\n<pre><code>SHELLVAR=\" hello\" \nif test $SHELLVAR = \"hello\" ; then echo \"yep\" ; fi\n# yep \n</code></pre>\n\n<p>however, this should usually work </p>\n\n<pre><code>SHELLVAR=\" hello\"\nif test \"$SHELLVAR\" = \"hello\" ; then echo \"yep\" ; fi \n#<no output>\n</code></pre>\n\n<p>but when it complains in output somewhere else, its hard to tell what its complaining about I guess, so </p>\n\n<pre><code>SHELLVAR=\" hello\"\nif test \"x$SHELLVAR\" = \"xhello\" ; then echo \"yep\" ; fi \n</code></pre>\n\n<p>works just as well, but would be easier to debug. </p>\n"
},
{
"answer_id": 174162,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": -1,
"selected": false,
"text": "<p>If you don't do the \"x$SHELL_VAR\" thing, then if $SHELL_VAR is undefined, you get an error about \"=\" not being a monadic operator or something like that.</p>\n"
},
{
"answer_id": 174288,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": true,
"text": "<p>If you're using a shell that does <em>simple</em> substitution and the <code>SHELL_VAR</code> variable does not exist (or is blank), then you need to watch out for the edge cases. The following translations will happen:</p>\n\n<pre><code>if test $SHELL_VAR = yes; then --> if test = yes; then\nif test x$SHELL_VAR = xyes; then --> if test x = xyes; then\n</code></pre>\n\n<p>The first of these will generate an error since the fist argument to <code>test</code> has gone missing. The second does not have that problem.</p>\n\n<p>Your case translates as follows:</p>\n\n<pre><code>if test \"x$SHELL_VAR\" = \"xyes\"; then --> if test \"x\" = \"xyes\"; then\n</code></pre>\n\n<p>The <code>x</code>, at least for POSIX-compliant shells, is actually redundant since the quotes ensue that both an empty argument and one containing spaces are interpreted as a single object.</p>\n"
},
{
"answer_id": 174331,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 4,
"selected": false,
"text": "<p>There's two reasons that I know of for this convention: </p>\n\n<p><a href=\"http://tldp.org/LDP/abs/html/comparison-ops.html\" rel=\"noreferrer\">http://tldp.org/LDP/abs/html/comparison-ops.html</a></p>\n\n<blockquote>\n <p>In a compound test, even quoting the string variable might not suffice. \n [ -n \"$string\" -o \"$a\" = \"$b\" ] may cause an error with some versions of \n Bash if $string is empty. The safe way is to append an extra character to \n possibly empty variables, [ \"x$string\" != x -o \"x$a\" = \"x$b\" ] (the \"x's\" cancel out).</p>\n</blockquote>\n\n<p>Second, in other shells than Bash, especially older ones, the test conditions like '-z' to test for an empty variable did not exist, so while this: </p>\n\n<pre><code>if [ -z \"$SOME_VAR\" ]; then\n echo \"this variable is not defined\"\nfi\n</code></pre>\n\n<p>will work fine in BASH, if you're aiming for portability across various UNIX environments where you can't be sure that the default shell will be Bash and whether it supports the -z test condition, it's safer to use the form if [ \"x$SOME_VAR\" = \"x\" ] since that will always have the intended effect. Essentially this is an old shell scripting trick for finding an empty variable, and it's still used today for backwards compatibility despite there being cleaner methods available.</p>\n"
},
{
"answer_id": 180630,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "<p>The other reason that no-one else has yet mentioned is in relation to option processing. If you write:</p>\n\n<pre><code>if [ \"$1\" = \"abc\" ]; then ...\n</code></pre>\n\n<p>and $1 has the value '-n', the syntax of the test command is ambiguous; it is not clear what you were testing. The 'x' at the front prevents a leading dash from causing trouble.</p>\n\n<p>You have to be looking at really ancient shells to find one where the test command does not have support for <code>-n</code> or <code>-z</code>; the Version 7 (1978) <code>test</code> command included them. It isn't quite irrelevant - some Version 6 UNIX stuff escaped into BSD, but these days, you'd be extremely hard pressed to find anything that ancient in current use.</p>\n\n<p>Not using double quotes around values is dangerous, as a number of other people pointed out. Indeed, if there's a chance that file names might contain spaces (MacOS X and Windows both encourage that to some extent, and Unix has always supported it, though tools like <code>xargs</code> make it harder), then you should enclose file names in double quotes every time you use them too. Unless you are in charge of the value (e.g. during option handling, and you set the variable to 'no' at startup and 'yes' when a flag is included in the command line) then it is not safe to use unquoted forms of variables until you've proved them safe -- and you may as well do it all the time for many purposes. Or document that your scripts will fail horribly if users attempt to process files with blanks in the names. (And there are other characters to worry about too -- backticks could be rather nasty too, for instance.)</p>\n"
},
{
"answer_id": 38114348,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "<p>I recommend instead:</p>\n\n<pre><code>if test \"yes\" = \"$SHELL_VAR\"; then\n</code></pre>\n\n<p>since it does away with the ugly <code>x</code>, and still solves the problem mentioned by <a href=\"https://stackoverflow.com/a/174288/895245\">https://stackoverflow.com/a/174288/895245</a> that <code>$SHELL_VAR</code> may start with <code>-</code> and be read as an option. </p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78437/"
] |
I see this often in the build scripts of projects that use autotools (autoconf, automake). When somebody wants to check the value of a shell variable, they frequently use this idiom:
```
if test "x$SHELL_VAR" = "xyes"; then
...
```
What is the advantage to this over simply checking the value like this:
```
if test $SHELL_VAR = "yes"; then
...
```
I figure there must be some reason that I see this so often, but I can't figure out what it is.
|
If you're using a shell that does *simple* substitution and the `SHELL_VAR` variable does not exist (or is blank), then you need to watch out for the edge cases. The following translations will happen:
```
if test $SHELL_VAR = yes; then --> if test = yes; then
if test x$SHELL_VAR = xyes; then --> if test x = xyes; then
```
The first of these will generate an error since the fist argument to `test` has gone missing. The second does not have that problem.
Your case translates as follows:
```
if test "x$SHELL_VAR" = "xyes"; then --> if test "x" = "xyes"; then
```
The `x`, at least for POSIX-compliant shells, is actually redundant since the quotes ensue that both an empty argument and one containing spaces are interpreted as a single object.
|
174,143 |
<p>In SQL Server 2005, is there a way of deleting rows and being told how many were <strong>actually</strong> deleted? </p>
<p>I could do a <code>select count(*)</code> with the same conditions, but I need this to be utterly trustworthy. </p>
<p>My first guess was to use the <code>@@ROWCOUNT</code> variables - but that isn't set, e.g. </p>
<pre><code>delete
from mytable
where datefield = '5-Oct-2008'
select @@ROWCOUNT
</code></pre>
<p>always returns a 0. </p>
<p>MSDN suggests the <a href="http://msdn.microsoft.com/en-us/library/ms189835.aspx" rel="noreferrer"><code>OUTPUT</code></a> construction, e.g. </p>
<pre><code>delete from mytable
where datefield = '5-Oct-2008'
output datefield into #doomed
select count(*)
from #doomed
</code></pre>
<p>this actually fails with a syntax error. </p>
<p>Any ideas? </p>
|
[
{
"answer_id": 174157,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": -1,
"selected": false,
"text": "<p>Create temp table with one column, id.</p>\n\n<p>Insert into temp table selecting the ids you want to delete. That gives you your count.</p>\n\n<p>Delete from your table where id in (select id from temp table)</p>\n"
},
{
"answer_id": 174158,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 7,
"selected": true,
"text": "<p>Have you tried <code>SET NOCOUNT OFF</code>?</p>\n"
},
{
"answer_id": 174178,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 3,
"selected": false,
"text": "<p>In your example <code>@@ROWCOUNT</code> should work - it's a proper way to find out a number of deleted rows. If you're trying to delete something from your application then you'll need to use <code>SET NOCOUNT ON</code></p>\n\n<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/ms189837.aspx\" rel=\"noreferrer\">MSDN</a> @@ROWCOUNT function is updated even when SET NOCOUNT is ON as <code>SET NOCOUNT</code> only affects the message you get after the the execution.</p>\n\n<p>So if you're trying to work with the results of <code>@@ROWCOUNT</code> from, for example, ADO.NET then <code>SET NOCOUNT ON</code> should definitely help.</p>\n"
},
{
"answer_id": 174212,
"author": "Simon",
"author_id": 20048,
"author_profile": "https://Stackoverflow.com/users/20048",
"pm_score": 4,
"selected": false,
"text": "<p>I use @@ROWCOUNT for this exact purpose in SQL2000 with no issues. Make sure that you're not inadvertantly resetting this count before checking it though (BOL: 'This variable is set to 0 by any statement that does not return rows, such as an IF statement').</p>\n"
},
{
"answer_id": 183339,
"author": "Howard Pinsley",
"author_id": 7961,
"author_profile": "https://Stackoverflow.com/users/7961",
"pm_score": 0,
"selected": false,
"text": "<p>Out of curiosity, how are you calling the procedure? (I'm assuming it is a stored procedure?). The reason I ask is that there is a difference between a stored procedure's return value (which would be 0 in this case), and a rowset result -- which in this case would be a single row with a single column. In ADO.Net, the former would be accessed by a parameter and the latter with a SqlDataReader. Are you, perhaps, mistaking the procedure's return value as the rowcount?</p>\n"
},
{
"answer_id": 21060985,
"author": "Adly",
"author_id": 1205392,
"author_profile": "https://Stackoverflow.com/users/1205392",
"pm_score": 3,
"selected": false,
"text": "<p>Just do this: </p>\n\n<pre><code>SET NOCOUNT off ;\nSELECT @p1 = @@ROWCOUNT\n</code></pre>\n\n<p>where p1 is the output parameter you set in the stored procedure.\nHope it helps.</p>\n"
},
{
"answer_id": 28995439,
"author": "James L.",
"author_id": 822072,
"author_profile": "https://Stackoverflow.com/users/822072",
"pm_score": 1,
"selected": false,
"text": "<p>I found a case where you can't use <code>@@rowcount</code>, like when you want to know the distinct count of the values that were deleted instead of the total count. In this case you would have to do the following:</p>\n\n<pre><code>delete from mytable \nwhere datefield = '5-Oct-2008' \noutput deleted.datefield into #doomed\n\nselect count(distinct datefield)\nfrom #doomed\n</code></pre>\n\n<p>The syntax error in the OP was because <code>output</code> did not include <code>deleted</code> before the <code>datefield</code> field name.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2902/"
] |
In SQL Server 2005, is there a way of deleting rows and being told how many were **actually** deleted?
I could do a `select count(*)` with the same conditions, but I need this to be utterly trustworthy.
My first guess was to use the `@@ROWCOUNT` variables - but that isn't set, e.g.
```
delete
from mytable
where datefield = '5-Oct-2008'
select @@ROWCOUNT
```
always returns a 0.
MSDN suggests the [`OUTPUT`](http://msdn.microsoft.com/en-us/library/ms189835.aspx) construction, e.g.
```
delete from mytable
where datefield = '5-Oct-2008'
output datefield into #doomed
select count(*)
from #doomed
```
this actually fails with a syntax error.
Any ideas?
|
Have you tried `SET NOCOUNT OFF`?
|
174,153 |
<p>In C#, does anybody know why the following will compile:</p>
<pre><code>int i = 1;
++i;
i++;
</code></pre>
<p>but this will not compile?</p>
<pre><code>int i = 1;
++i++;
</code></pre>
<p>(Compiler error: The operand of an increment or decrement operator must be a variable, property or indexer.)</p>
|
[
{
"answer_id": 174160,
"author": "steffenj",
"author_id": 15328,
"author_profile": "https://Stackoverflow.com/users/15328",
"pm_score": -1,
"selected": false,
"text": "<p>My guess: to avoid such ugly and unnecessary constructs. Also it would use 2 operations (2x INC) instead of one (1x ADD 2).</p>\n\n<p>Yes, i know ... \"but i want to increase by two and i'm a l33t g33k!\"</p>\n\n<p>Well, don't be a geek and write something that doesn't look like an inadvertent mistake, like this:</p>\n\n<pre><code>i += 2;\n</code></pre>\n"
},
{
"answer_id": 174175,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 5,
"selected": true,
"text": "<p>you are running one of the operands on the result of the other, the result of a increment/decrement is a value - and you can not use increment/decrement on a value it has to be a variable that can be set.</p>\n"
},
{
"answer_id": 174182,
"author": "fluffels",
"author_id": 12828,
"author_profile": "https://Stackoverflow.com/users/12828",
"pm_score": 2,
"selected": false,
"text": "<p>My guess would be that ++i returns an integer value type, to which you then try to apply the ++ operator. Seeing as you can't write to a value type (think about 0++ and if that would make sense), the compiler will issue an error.</p>\n\n<p>In other words, those statements are parsed as this sequence:</p>\n\n<pre><code>++i (i = 2, returns 2)\n2++ (nothing can happen here, because you can't write a value back into '2')\n</code></pre>\n"
},
{
"answer_id": 174222,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>For the same reason you can't say</p>\n\n<pre><code>5++;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>f(i)++;\n</code></pre>\n\n<p>A function returns a <em>value</em>, not a variable. The increment operators also return values, but cannot be applied to values.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
In C#, does anybody know why the following will compile:
```
int i = 1;
++i;
i++;
```
but this will not compile?
```
int i = 1;
++i++;
```
(Compiler error: The operand of an increment or decrement operator must be a variable, property or indexer.)
|
you are running one of the operands on the result of the other, the result of a increment/decrement is a value - and you can not use increment/decrement on a value it has to be a variable that can be set.
|
174,155 |
<p>Switch statement fallthrough is one of my personal major reasons for loving <code>switch</code> vs. <code>if/else if</code> constructs. An example is in order here:</p>
<pre><code>static string NumberToWords(int number)
{
string[] numbers = new string[]
{ "", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };
string[] tens = new string[]
{ "", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
string[] teens = new string[]
{ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen" };
string ans = "";
switch (number.ToString().Length)
{
case 3:
ans += string.Format("{0} hundred and ", numbers[number / 100]);
case 2:
int t = (number / 10) % 10;
if (t == 1)
{
ans += teens[number % 10];
break;
}
else if (t > 1)
ans += string.Format("{0}-", tens[t]);
case 1:
int o = number % 10;
ans += numbers[o];
break;
default:
throw new ArgumentException("number");
}
return ans;
}
</code></pre>
<p>The smart people are cringing because the <code>string[]</code>s should be declared outside the function: well, they are, this is just an example.</p>
<p>The compiler fails with the following error:</p>
<pre>
Control cannot fall through from one case label ('case 3:') to another
Control cannot fall through from one case label ('case 2:') to another
</pre>
<p>Why? And is there any way to get this sort of behaviour without having three <code>if</code>s?</p>
|
[
{
"answer_id": 174176,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 2,
"selected": false,
"text": "<p>They changed the switch statement (from C/Java/C++) behavior for c#. I guess the reasoning was that people forgot about the fall through and errors were caused. One book I read said to use goto to simulate, but this doesn't sound like a good solution to me.</p>\n"
},
{
"answer_id": 174177,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>A jump statement such as a break is\n required after each case block,\n including the last block whether it is\n a case statement or a default\n statement. With one exception, (unlike\n the C++ switch statement), C# does not\n support an implicit fall through from\n one case label to another. The one\n exception is if a case statement has\n no code.</p>\n</blockquote>\n\n<p>-- <a href=\"http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx\" rel=\"nofollow noreferrer\">C# switch() documentation</a></p>\n"
},
{
"answer_id": 174183,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "<p>They left out this behaviour by design to avoid when it was not used by will but caused problems.</p>\n\n<p>It can be used only if there is no statement in the case part, like:</p>\n\n<pre><code>switch (whatever)\n{\n case 1:\n case 2:\n case 3: boo; break;\n}\n</code></pre>\n"
},
{
"answer_id": 174191,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 5,
"selected": false,
"text": "<p>Switch fallthrough is historically one of the major source of bugs in modern softwares. The language designer decided to make it mandatory to jump at the end of the case, unless you are defaulting to the next case directly without processing.</p>\n\n<pre><code>switch(value)\n{\n case 1:// this is still legal\n case 2:\n}\n</code></pre>\n"
},
{
"answer_id": 174200,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 4,
"selected": false,
"text": "<p>You can 'goto case label'\n<a href=\"http://www.blackwasp.co.uk/CSharpGoto.aspx\" rel=\"nofollow noreferrer\">http://www.blackwasp.co.uk/CSharpGoto.aspx</a></p>\n\n<blockquote>\n <p>The goto statement is a simple command that unconditionally transfers the control of the program to another statement. The command is often criticised with some developers advocating its removal from all high-level programming languages because it can lead to <a href=\"http://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"nofollow noreferrer\"><em>spaghetti code</em></a>. This occurs when there are so many goto statements or similar jump statements that the code becomes difficult to read and maintain. However, there are programmers who point out that the goto statement, when used carefully, provides an elegant solution to some problems...</p>\n</blockquote>\n"
},
{
"answer_id": 174210,
"author": "Marcus",
"author_id": 25428,
"author_profile": "https://Stackoverflow.com/users/25428",
"pm_score": -1,
"selected": false,
"text": "<p>You forgot to add the \"break;\" statement into case 3. In case 2 you wrote it into the if block.\nTherefore try this:</p>\n\n<pre><code>case 3: \n{\n ans += string.Format(\"{0} hundred and \", numbers[number / 100]);\n break;\n}\n\n\ncase 2: \n{\n int t = (number / 10) % 10; \n if (t == 1) \n { \n ans += teens[number % 10]; \n } \n else if (t > 1) \n {\n ans += string.Format(\"{0}-\", tens[t]); \n }\n break;\n}\n\ncase 1: \n{\n int o = number % 10; \n ans += numbers[o]; \n break; \n}\n\ndefault: \n{\n throw new ArgumentException(\"number\");\n}\n</code></pre>\n"
},
{
"answer_id": 174223,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 10,
"selected": true,
"text": "<p>(Copy/paste of an <a href=\"https://stackoverflow.com/questions/9033/hidden-features-of-c?answer=90432#90432\">answer I provided elsewhere</a>)</p>\n\n<p>Falling through <code>switch</code>-<code>case</code>s can be achieved by having no code in a <code>case</code> (see <code>case 0</code>), or using the special <code>goto case</code> (see <code>case 1</code>) or <code>goto default</code> (see <code>case 2</code>) forms:</p>\n\n<pre><code>switch (/*...*/) {\n case 0: // shares the exact same code as case 1\n case 1:\n // do something\n goto case 2;\n case 2:\n // do something else\n goto default;\n default:\n // do something entirely different\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 174228,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>The \"why\" is to avoid accidental fall-through, for which I'm grateful. This is a not uncommon source of bugs in C and Java.</p>\n\n<p>The workaround is to use goto, e.g.</p>\n\n<pre><code>switch (number.ToString().Length)\n{\n case 3:\n ans += string.Format(\"{0} hundred and \", numbers[number / 100]);\n goto case 2;\n case 2:\n // Etc\n}\n</code></pre>\n\n<p>The general design of switch/case is a little bit unfortunate in my view. It stuck too close to C - there are some useful changes which could be made in terms of scoping etc. Arguably a smarter switch which could do pattern matching etc would be helpful, but that's really changing from switch to \"check a sequence of conditions\" - at which point a different name would perhaps be called for.</p>\n"
},
{
"answer_id": 2972718,
"author": "Shilpa gulati",
"author_id": 358271,
"author_profile": "https://Stackoverflow.com/users/358271",
"pm_score": 0,
"selected": false,
"text": "<p>After each case statement require <strong>break</strong> or <strong>goto</strong> statement even if it is a default case.</p>\n"
},
{
"answer_id": 3357232,
"author": "Dai Tran",
"author_id": 405000,
"author_profile": "https://Stackoverflow.com/users/405000",
"pm_score": 0,
"selected": false,
"text": "<p>You can achieve fall through like c++ by the goto keyword.</p>\n\n<p>EX:</p>\n\n<pre><code>switch(num)\n{\n case 1:\n goto case 3;\n case 2:\n goto case 3;\n case 3:\n //do something\n break;\n case 4:\n //do something else\n break;\n case default:\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 20470441,
"author": "Jon Hanna",
"author_id": 400547,
"author_profile": "https://Stackoverflow.com/users/400547",
"pm_score": 5,
"selected": false,
"text": "<p>To add to the answers here, I think it's worth considering the opposite question in conjunction with this, viz. why did C allow fall-through in the first place?</p>\n<p>Any programming language of course serves two goals:</p>\n<ol>\n<li>Provide instructions to the computer.</li>\n<li>Leave a record of the intentions of the programmer.</li>\n</ol>\n<p>The creation of any programming language is therefore a balance between how to best serve these two goals. On the one hand, the easier it is to turn into computer instructions (whether those are machine code, bytecode like IL, or the instructions are interpreted on execution) then more able that process of compilation or interpretation will be to be efficient, reliable and compact in output. Taken to its extreme, this goal results in our just writing in assembly, IL, or even raw op-codes, because the easiest compilation is where there is no compilation at all.</p>\n<p>Conversely, the more the language expresses the intention of the programmer, rather than the means taken to that end, the more understandable the program both when writing and during maintenance.</p>\n<p>Now, <code>switch</code> could always have been compiled by converting it into the equivalent chain of <code>if-else</code> blocks or similar, but it was designed as allowing compilation into a particular common assembly pattern where one takes a value, computes an offset from it (whether by looking up a table indexed by a perfect hash of the value, or by actual arithmetic on the value*). It's worth noting at this point that today, C# compilation will sometimes turn <code>switch</code> into the equivalent <code>if-else</code>, and sometimes use a hash-based jump approach (and likewise with C, C++, and other languages with comparable syntax).</p>\n<p>In this case there are two good reasons for allowing fall-through:</p>\n<ol>\n<li><p>It just happens naturally anyway: if you build a jump table into a set of instructions, and one of the earlier batches of instructions doesn't contain some sort of jump or return, then execution will just naturally progress into the next batch. Allowing fall-through was what would "just happen" if you turned the <code>switch</code>-using C into jump-table–using machine code.</p>\n</li>\n<li><p>Coders who wrote in assembly were already used to the equivalent: when writing a jump table by hand in assembly, they would have to consider whether a given block of code would end with a return, a jump outside of the table, or just continue on to the next block. As such, having the coder add an explicit <code>break</code> when necessary was "natural" for the coder too.</p>\n</li>\n</ol>\n<p>At the time therefore, it was a reasonable attempt to balance the two goals of a computer language as it relates to both the produced machine code, and the expressiveness of the source code.</p>\n<p>Four decades later though, things are not quite the same, for a few reasons:</p>\n<ol>\n<li>Coders in C today may have little or no assembly experience. Coders in many other C-style languages are even less likely to (especially Javascript!). Any concept of "what people are used to from assembly" is no longer relevant.</li>\n<li>Improvements in optimisations mean that the likelihood of <code>switch</code> either being turned into <code>if-else</code> because it was deemed the approach likely to be most efficient, or else turned into a particularly esoteric variant of the jump-table approach are higher. The mapping between the higher- and lower-level approaches is not as strong as it once was.</li>\n<li>Experience has shown that fall-through tends to be the minority case rather than the norm (a study of Sun's compiler found 3% of <code>switch</code> blocks used a fall-through other than multiple labels on the same block, and it was thought that the use-case here meant that this 3% was in fact much higher than normal). So the language as studied make the unusual more readily catered-to than the common.</li>\n<li>Experience has shown that fall-through tends to be the source of problems both in cases where it is accidentally done, and also in cases where correct fall-through is missed by someone maintaining the code. This latter is a subtle addition to the bugs associated with fall-through, because even if your code is perfectly bug-free, your fall-through can still cause problems.</li>\n</ol>\n<p>Related to those last two points, consider the following quote from the current edition of K&R:</p>\n<blockquote>\n<p>Falling through from one case to another is not robust, being prone to disintegration when the program is modified. With the exception of multiple labels for a single computation, fall-throughs should be used sparingly, and commented.</p>\n<p>As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.</p>\n</blockquote>\n<p>So, from the horse's mouth, fall-through in C is problematic. It's considered good practice to always document fall-throughs with comments, which is an application of the general principle that one should document where one does something unusual, because that's what will trip later examination of the code and/or make your code look like it has a novice's bug in it when it is in fact correct.</p>\n<p>And when you think about it, code like this:</p>\n<pre><code>switch(x)\n{\n case 1:\n foo();\n /* FALLTHRU */\n case 2:\n bar();\n break;\n}\n</code></pre>\n<p><strong>Is</strong> adding something to make the fall-through explicit in the code, it's just not something that can be detected (or whose absence can be detected) by the compiler.</p>\n<p>As such, the fact that on has to be explicit with fall-through in C# doesn't add any penalty to people who wrote well in other C-style languages anyway, since they would already be explicit in their fall-throughs.†</p>\n<p>Finally, the use of <code>goto</code> here is already a norm from C and other such languages:</p>\n<pre><code>switch(x)\n{\n case 0:\n case 1:\n case 2:\n foo();\n goto below_six;\n case 3:\n bar();\n goto below_six;\n case 4:\n baz();\n /* FALLTHRU */\n case 5:\n below_six:\n qux();\n break;\n default:\n quux();\n}\n</code></pre>\n<p>In this sort of case where we want a block to be included in the code executed for a value other than just that which brings one to the preceding block, then we're already having to use <code>goto</code>. (Of course, there are means and ways of avoiding this with different conditionals but that's true of just about everything relating to this question). As such C# built on the already normal way to deal with one situation where we want to hit more than one block of code in a <code>switch</code>, and just generalised it to cover fall-through as well. It also made both cases more convenient and self-documenting, since we have to add a new label in C but can use the <code>case</code> as a label in C#. In C# we can get rid of the <code>below_six</code> label and use <code>goto case 5</code> which is clearer as to what we are doing. (We'd also have to add <code>break</code> for the <code>default</code>, which I left out just to make the above C code clearly not C# code).</p>\n<p>In summary therefore:</p>\n<ol>\n<li>C# no longer relates to unoptimised compiler output as directly as C code did 40 years ago (nor does C these days), which makes one of the inspirations of fall-through irrelevant.</li>\n<li>C# remains compatible with C in not just having implicit <code>break</code>, for easier learning of the language by those familiar with similar languages, and easier porting.</li>\n<li>C# removes a possible source of bugs or misunderstood code that has been well-documented as causing problems for the last four decades.</li>\n<li>C# makes existing best-practice with C (document fall through) enforceable by the compiler.</li>\n<li>C# makes the unusual case the one with more explicit code, the usual case the one with the code one just writes automatically.</li>\n<li>C# uses the same <code>goto</code>-based approach for hitting the same block from different <code>case</code> labels as is used in C. It just generalises it to some other cases.</li>\n<li>C# makes that <code>goto</code>-based approach more convenient, and clearer, than it is in C, by allowing <code>case</code> statements to act as labels.</li>\n</ol>\n<p>All in all, a pretty reasonable design decision</p>\n<hr />\n<p>*Some forms of BASIC would allow one to do the likes of <code>GOTO (x AND 7) * 50 + 240</code> which while brittle and hence a particularly persuasive case for banning <code>goto</code>, does serve to show a higher-language equivalent of the sort of way that lower-level code can make a jump based on arithmetic upon a value, which is much more reasonable when it's the result of compilation rather than something that has to be maintained manually. Implementations of Duff's Device in particular lend themselves well to the equivalent machine code or IL because each block of instructions will often be the same length without needing the addition of <code>nop</code> fillers.</p>\n<p>†Duff's Device comes up here again, as a reasonable exception. The fact that with that and similar patterns there's a repetition of operations serves to make the use of fall-through relatively clear even without an explicit comment to that effect.</p>\n"
},
{
"answer_id": 21790515,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Just a quick note to add that the compiler for Xamarin actually got this wrong and it allows fallthrough. It has supposedly been fixed, but has not been released. Discovered this in some code that actually was falling through and the compiler did not complain.</p>\n"
},
{
"answer_id": 26232895,
"author": "gm2008",
"author_id": 2197555,
"author_profile": "https://Stackoverflow.com/users/2197555",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/06tc147t.aspx\" rel=\"nofollow\">switch (C# Reference) says</a></p>\n\n<blockquote>\n <p>C# requires the end of switch sections, including the final one, </p>\n</blockquote>\n\n<p>So you also need to add a <code>break;</code> to your <code>default</code> section, otherwise there will still will be a compiler error.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
Switch statement fallthrough is one of my personal major reasons for loving `switch` vs. `if/else if` constructs. An example is in order here:
```
static string NumberToWords(int number)
{
string[] numbers = new string[]
{ "", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };
string[] tens = new string[]
{ "", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
string[] teens = new string[]
{ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen" };
string ans = "";
switch (number.ToString().Length)
{
case 3:
ans += string.Format("{0} hundred and ", numbers[number / 100]);
case 2:
int t = (number / 10) % 10;
if (t == 1)
{
ans += teens[number % 10];
break;
}
else if (t > 1)
ans += string.Format("{0}-", tens[t]);
case 1:
int o = number % 10;
ans += numbers[o];
break;
default:
throw new ArgumentException("number");
}
return ans;
}
```
The smart people are cringing because the `string[]`s should be declared outside the function: well, they are, this is just an example.
The compiler fails with the following error:
```
Control cannot fall through from one case label ('case 3:') to another
Control cannot fall through from one case label ('case 2:') to another
```
Why? And is there any way to get this sort of behaviour without having three `if`s?
|
(Copy/paste of an [answer I provided elsewhere](https://stackoverflow.com/questions/9033/hidden-features-of-c?answer=90432#90432))
Falling through `switch`-`case`s can be achieved by having no code in a `case` (see `case 0`), or using the special `goto case` (see `case 1`) or `goto default` (see `case 2`) forms:
```
switch (/*...*/) {
case 0: // shares the exact same code as case 1
case 1:
// do something
goto case 2;
case 2:
// do something else
goto default;
default:
// do something entirely different
break;
}
```
|
174,163 |
<p>Is entity framework just a fancy name for another CRUD code generator?</p>
<p>Or is there more to it?</p>
|
[
{
"answer_id": 174176,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 2,
"selected": false,
"text": "<p>They changed the switch statement (from C/Java/C++) behavior for c#. I guess the reasoning was that people forgot about the fall through and errors were caused. One book I read said to use goto to simulate, but this doesn't sound like a good solution to me.</p>\n"
},
{
"answer_id": 174177,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>A jump statement such as a break is\n required after each case block,\n including the last block whether it is\n a case statement or a default\n statement. With one exception, (unlike\n the C++ switch statement), C# does not\n support an implicit fall through from\n one case label to another. The one\n exception is if a case statement has\n no code.</p>\n</blockquote>\n\n<p>-- <a href=\"http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx\" rel=\"nofollow noreferrer\">C# switch() documentation</a></p>\n"
},
{
"answer_id": 174183,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "<p>They left out this behaviour by design to avoid when it was not used by will but caused problems.</p>\n\n<p>It can be used only if there is no statement in the case part, like:</p>\n\n<pre><code>switch (whatever)\n{\n case 1:\n case 2:\n case 3: boo; break;\n}\n</code></pre>\n"
},
{
"answer_id": 174191,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 5,
"selected": false,
"text": "<p>Switch fallthrough is historically one of the major source of bugs in modern softwares. The language designer decided to make it mandatory to jump at the end of the case, unless you are defaulting to the next case directly without processing.</p>\n\n<pre><code>switch(value)\n{\n case 1:// this is still legal\n case 2:\n}\n</code></pre>\n"
},
{
"answer_id": 174200,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 4,
"selected": false,
"text": "<p>You can 'goto case label'\n<a href=\"http://www.blackwasp.co.uk/CSharpGoto.aspx\" rel=\"nofollow noreferrer\">http://www.blackwasp.co.uk/CSharpGoto.aspx</a></p>\n\n<blockquote>\n <p>The goto statement is a simple command that unconditionally transfers the control of the program to another statement. The command is often criticised with some developers advocating its removal from all high-level programming languages because it can lead to <a href=\"http://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"nofollow noreferrer\"><em>spaghetti code</em></a>. This occurs when there are so many goto statements or similar jump statements that the code becomes difficult to read and maintain. However, there are programmers who point out that the goto statement, when used carefully, provides an elegant solution to some problems...</p>\n</blockquote>\n"
},
{
"answer_id": 174210,
"author": "Marcus",
"author_id": 25428,
"author_profile": "https://Stackoverflow.com/users/25428",
"pm_score": -1,
"selected": false,
"text": "<p>You forgot to add the \"break;\" statement into case 3. In case 2 you wrote it into the if block.\nTherefore try this:</p>\n\n<pre><code>case 3: \n{\n ans += string.Format(\"{0} hundred and \", numbers[number / 100]);\n break;\n}\n\n\ncase 2: \n{\n int t = (number / 10) % 10; \n if (t == 1) \n { \n ans += teens[number % 10]; \n } \n else if (t > 1) \n {\n ans += string.Format(\"{0}-\", tens[t]); \n }\n break;\n}\n\ncase 1: \n{\n int o = number % 10; \n ans += numbers[o]; \n break; \n}\n\ndefault: \n{\n throw new ArgumentException(\"number\");\n}\n</code></pre>\n"
},
{
"answer_id": 174223,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 10,
"selected": true,
"text": "<p>(Copy/paste of an <a href=\"https://stackoverflow.com/questions/9033/hidden-features-of-c?answer=90432#90432\">answer I provided elsewhere</a>)</p>\n\n<p>Falling through <code>switch</code>-<code>case</code>s can be achieved by having no code in a <code>case</code> (see <code>case 0</code>), or using the special <code>goto case</code> (see <code>case 1</code>) or <code>goto default</code> (see <code>case 2</code>) forms:</p>\n\n<pre><code>switch (/*...*/) {\n case 0: // shares the exact same code as case 1\n case 1:\n // do something\n goto case 2;\n case 2:\n // do something else\n goto default;\n default:\n // do something entirely different\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 174228,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>The \"why\" is to avoid accidental fall-through, for which I'm grateful. This is a not uncommon source of bugs in C and Java.</p>\n\n<p>The workaround is to use goto, e.g.</p>\n\n<pre><code>switch (number.ToString().Length)\n{\n case 3:\n ans += string.Format(\"{0} hundred and \", numbers[number / 100]);\n goto case 2;\n case 2:\n // Etc\n}\n</code></pre>\n\n<p>The general design of switch/case is a little bit unfortunate in my view. It stuck too close to C - there are some useful changes which could be made in terms of scoping etc. Arguably a smarter switch which could do pattern matching etc would be helpful, but that's really changing from switch to \"check a sequence of conditions\" - at which point a different name would perhaps be called for.</p>\n"
},
{
"answer_id": 2972718,
"author": "Shilpa gulati",
"author_id": 358271,
"author_profile": "https://Stackoverflow.com/users/358271",
"pm_score": 0,
"selected": false,
"text": "<p>After each case statement require <strong>break</strong> or <strong>goto</strong> statement even if it is a default case.</p>\n"
},
{
"answer_id": 3357232,
"author": "Dai Tran",
"author_id": 405000,
"author_profile": "https://Stackoverflow.com/users/405000",
"pm_score": 0,
"selected": false,
"text": "<p>You can achieve fall through like c++ by the goto keyword.</p>\n\n<p>EX:</p>\n\n<pre><code>switch(num)\n{\n case 1:\n goto case 3;\n case 2:\n goto case 3;\n case 3:\n //do something\n break;\n case 4:\n //do something else\n break;\n case default:\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 20470441,
"author": "Jon Hanna",
"author_id": 400547,
"author_profile": "https://Stackoverflow.com/users/400547",
"pm_score": 5,
"selected": false,
"text": "<p>To add to the answers here, I think it's worth considering the opposite question in conjunction with this, viz. why did C allow fall-through in the first place?</p>\n<p>Any programming language of course serves two goals:</p>\n<ol>\n<li>Provide instructions to the computer.</li>\n<li>Leave a record of the intentions of the programmer.</li>\n</ol>\n<p>The creation of any programming language is therefore a balance between how to best serve these two goals. On the one hand, the easier it is to turn into computer instructions (whether those are machine code, bytecode like IL, or the instructions are interpreted on execution) then more able that process of compilation or interpretation will be to be efficient, reliable and compact in output. Taken to its extreme, this goal results in our just writing in assembly, IL, or even raw op-codes, because the easiest compilation is where there is no compilation at all.</p>\n<p>Conversely, the more the language expresses the intention of the programmer, rather than the means taken to that end, the more understandable the program both when writing and during maintenance.</p>\n<p>Now, <code>switch</code> could always have been compiled by converting it into the equivalent chain of <code>if-else</code> blocks or similar, but it was designed as allowing compilation into a particular common assembly pattern where one takes a value, computes an offset from it (whether by looking up a table indexed by a perfect hash of the value, or by actual arithmetic on the value*). It's worth noting at this point that today, C# compilation will sometimes turn <code>switch</code> into the equivalent <code>if-else</code>, and sometimes use a hash-based jump approach (and likewise with C, C++, and other languages with comparable syntax).</p>\n<p>In this case there are two good reasons for allowing fall-through:</p>\n<ol>\n<li><p>It just happens naturally anyway: if you build a jump table into a set of instructions, and one of the earlier batches of instructions doesn't contain some sort of jump or return, then execution will just naturally progress into the next batch. Allowing fall-through was what would "just happen" if you turned the <code>switch</code>-using C into jump-table–using machine code.</p>\n</li>\n<li><p>Coders who wrote in assembly were already used to the equivalent: when writing a jump table by hand in assembly, they would have to consider whether a given block of code would end with a return, a jump outside of the table, or just continue on to the next block. As such, having the coder add an explicit <code>break</code> when necessary was "natural" for the coder too.</p>\n</li>\n</ol>\n<p>At the time therefore, it was a reasonable attempt to balance the two goals of a computer language as it relates to both the produced machine code, and the expressiveness of the source code.</p>\n<p>Four decades later though, things are not quite the same, for a few reasons:</p>\n<ol>\n<li>Coders in C today may have little or no assembly experience. Coders in many other C-style languages are even less likely to (especially Javascript!). Any concept of "what people are used to from assembly" is no longer relevant.</li>\n<li>Improvements in optimisations mean that the likelihood of <code>switch</code> either being turned into <code>if-else</code> because it was deemed the approach likely to be most efficient, or else turned into a particularly esoteric variant of the jump-table approach are higher. The mapping between the higher- and lower-level approaches is not as strong as it once was.</li>\n<li>Experience has shown that fall-through tends to be the minority case rather than the norm (a study of Sun's compiler found 3% of <code>switch</code> blocks used a fall-through other than multiple labels on the same block, and it was thought that the use-case here meant that this 3% was in fact much higher than normal). So the language as studied make the unusual more readily catered-to than the common.</li>\n<li>Experience has shown that fall-through tends to be the source of problems both in cases where it is accidentally done, and also in cases where correct fall-through is missed by someone maintaining the code. This latter is a subtle addition to the bugs associated with fall-through, because even if your code is perfectly bug-free, your fall-through can still cause problems.</li>\n</ol>\n<p>Related to those last two points, consider the following quote from the current edition of K&R:</p>\n<blockquote>\n<p>Falling through from one case to another is not robust, being prone to disintegration when the program is modified. With the exception of multiple labels for a single computation, fall-throughs should be used sparingly, and commented.</p>\n<p>As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.</p>\n</blockquote>\n<p>So, from the horse's mouth, fall-through in C is problematic. It's considered good practice to always document fall-throughs with comments, which is an application of the general principle that one should document where one does something unusual, because that's what will trip later examination of the code and/or make your code look like it has a novice's bug in it when it is in fact correct.</p>\n<p>And when you think about it, code like this:</p>\n<pre><code>switch(x)\n{\n case 1:\n foo();\n /* FALLTHRU */\n case 2:\n bar();\n break;\n}\n</code></pre>\n<p><strong>Is</strong> adding something to make the fall-through explicit in the code, it's just not something that can be detected (or whose absence can be detected) by the compiler.</p>\n<p>As such, the fact that on has to be explicit with fall-through in C# doesn't add any penalty to people who wrote well in other C-style languages anyway, since they would already be explicit in their fall-throughs.†</p>\n<p>Finally, the use of <code>goto</code> here is already a norm from C and other such languages:</p>\n<pre><code>switch(x)\n{\n case 0:\n case 1:\n case 2:\n foo();\n goto below_six;\n case 3:\n bar();\n goto below_six;\n case 4:\n baz();\n /* FALLTHRU */\n case 5:\n below_six:\n qux();\n break;\n default:\n quux();\n}\n</code></pre>\n<p>In this sort of case where we want a block to be included in the code executed for a value other than just that which brings one to the preceding block, then we're already having to use <code>goto</code>. (Of course, there are means and ways of avoiding this with different conditionals but that's true of just about everything relating to this question). As such C# built on the already normal way to deal with one situation where we want to hit more than one block of code in a <code>switch</code>, and just generalised it to cover fall-through as well. It also made both cases more convenient and self-documenting, since we have to add a new label in C but can use the <code>case</code> as a label in C#. In C# we can get rid of the <code>below_six</code> label and use <code>goto case 5</code> which is clearer as to what we are doing. (We'd also have to add <code>break</code> for the <code>default</code>, which I left out just to make the above C code clearly not C# code).</p>\n<p>In summary therefore:</p>\n<ol>\n<li>C# no longer relates to unoptimised compiler output as directly as C code did 40 years ago (nor does C these days), which makes one of the inspirations of fall-through irrelevant.</li>\n<li>C# remains compatible with C in not just having implicit <code>break</code>, for easier learning of the language by those familiar with similar languages, and easier porting.</li>\n<li>C# removes a possible source of bugs or misunderstood code that has been well-documented as causing problems for the last four decades.</li>\n<li>C# makes existing best-practice with C (document fall through) enforceable by the compiler.</li>\n<li>C# makes the unusual case the one with more explicit code, the usual case the one with the code one just writes automatically.</li>\n<li>C# uses the same <code>goto</code>-based approach for hitting the same block from different <code>case</code> labels as is used in C. It just generalises it to some other cases.</li>\n<li>C# makes that <code>goto</code>-based approach more convenient, and clearer, than it is in C, by allowing <code>case</code> statements to act as labels.</li>\n</ol>\n<p>All in all, a pretty reasonable design decision</p>\n<hr />\n<p>*Some forms of BASIC would allow one to do the likes of <code>GOTO (x AND 7) * 50 + 240</code> which while brittle and hence a particularly persuasive case for banning <code>goto</code>, does serve to show a higher-language equivalent of the sort of way that lower-level code can make a jump based on arithmetic upon a value, which is much more reasonable when it's the result of compilation rather than something that has to be maintained manually. Implementations of Duff's Device in particular lend themselves well to the equivalent machine code or IL because each block of instructions will often be the same length without needing the addition of <code>nop</code> fillers.</p>\n<p>†Duff's Device comes up here again, as a reasonable exception. The fact that with that and similar patterns there's a repetition of operations serves to make the use of fall-through relatively clear even without an explicit comment to that effect.</p>\n"
},
{
"answer_id": 21790515,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Just a quick note to add that the compiler for Xamarin actually got this wrong and it allows fallthrough. It has supposedly been fixed, but has not been released. Discovered this in some code that actually was falling through and the compiler did not complain.</p>\n"
},
{
"answer_id": 26232895,
"author": "gm2008",
"author_id": 2197555,
"author_profile": "https://Stackoverflow.com/users/2197555",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/06tc147t.aspx\" rel=\"nofollow\">switch (C# Reference) says</a></p>\n\n<blockquote>\n <p>C# requires the end of switch sections, including the final one, </p>\n</blockquote>\n\n<p>So you also need to add a <code>break;</code> to your <code>default</code> section, otherwise there will still will be a compiler error.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is entity framework just a fancy name for another CRUD code generator?
Or is there more to it?
|
(Copy/paste of an [answer I provided elsewhere](https://stackoverflow.com/questions/9033/hidden-features-of-c?answer=90432#90432))
Falling through `switch`-`case`s can be achieved by having no code in a `case` (see `case 0`), or using the special `goto case` (see `case 1`) or `goto default` (see `case 2`) forms:
```
switch (/*...*/) {
case 0: // shares the exact same code as case 1
case 1:
// do something
goto case 2;
case 2:
// do something else
goto default;
default:
// do something entirely different
break;
}
```
|
174,190 |
<p>I have a Rails application for project management where there are Project and Task models. A project can have many tasks, but a task can also have many tasks, ad infinitum.</p>
<p>Using nested resources, we can have /projects/1/tasks, /projects/1/tasks/new, /projects/1/tasks/3/edit etc.</p>
<p>However, how do you represent the recursive nature of tasks RESTfully? I don't want go another level deep, so perhaps the following would do:</p>
<pre><code>map.resources :tasks do |t|
t.resources :tasks
end
</code></pre>
<p>That would give me the following urls:</p>
<pre><code>/tasks/3/tasks/new
/tasks/3/tasks/45/edit
</code></pre>
<p>Or perhaps when it comes to an individual task I can just use /tasks/45/edit</p>
<p>Is this a reasonable design?</p>
<p>Cam</p>
|
[
{
"answer_id": 174227,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "<p>there's no reason they should have decendant URLS. </p>\n\n<p>logically:</p>\n\n<pre>\n/projects/1 --> project 1 \n/projects/1/edit ( etc )\n/tasks/1 --> task 1 \n/project/1/tasks --> task list for project 1 \n/project/1/tasks/new \n/project/1/tasks/1/edit -> /tasks/5/edit ( redundancy ) \n/project/1/tasks/1 -> redirect to /tasks/1 \n/tasks/1/project -> redirect to /projects/1 \n/tasks/3/tasks --> list of tasks that are children tasks of task 3\n/tasks/3/tasks/5 -> redirect /tasks/5/ ( because you don't really need to have a recursive URL )\n/tasks/5/parents -> list of tasks that are parents of tasks 3\n/tasks/5/parents/3 -> redirect /tasks/3/ \n</pre>\n\n<p>there's no reason IMHO to require the URLs be associative, you're not going to need to know that task 5 is a child of task 3 to edit task 5. </p>\n"
},
{
"answer_id": 174287,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 3,
"selected": false,
"text": "<p>Going anywhere beyond a single nested route is generally considered a bad idea.</p>\n\n<p>From page 108 of <strong>The Rails Way</strong>:</p>\n\n<p><a href=\"http://weblog.jamisbuck.org/2007/2/5/nesting-resources\" rel=\"noreferrer\">\"<em>Jamis Busk a very influential figure in the Rails community, almost as much as David himself. In February 2007, vis his blog, he basically told us that deep nesting was a _bad_ thing, and proposed the following rule of thumb: Resources <strong>should never</strong> be nested more than one level deep.</em>\"</a></p>\n\n<p>Now some would argue with this (which is discussed on page 109) but when you're talking about nesting tasks with tasks it just doesn't seem to make much sense.</p>\n\n<p>I would approach your solution a different way and like it was mentioned above, a project should have many tasks but for a task to have many tasks doesn't seem correct and maybe those should be re-named as sub-tasks or something along those lines.</p>\n"
},
{
"answer_id": 175449,
"author": "Steropes",
"author_id": 21872,
"author_profile": "https://Stackoverflow.com/users/21872",
"pm_score": 2,
"selected": false,
"text": "<p>I'm currently on a project that does something similar. The answer I used that was very elegant was I added a parent_id column that pointed to another task. When doing your model, make sure to do the following:</p>\n\n<pre><code>belongs_to :project\nbelongs_to :parent, :class_name => \"Task\"\nhas_many :children, :class_name => \"Task\", :foreign_key => \"parent_id\"\n</code></pre>\n\n<p>...and then you can do recursion by:</p>\n\n<pre><code>def do_something(task)\n task.children.each do |child|\n puts \"Something!\"\n do_something(child)\n end\nend \n</code></pre>\n\n<p>This way, you can reference your tasks by its parent or by its children. When doing your routes, you'll access a single task always by</p>\n\n<pre><code>/project/:project_id/task/:task_id\n</code></pre>\n\n<p>even though it may have a parent or children.</p>\n\n<p>Just make sure that you don't have a task that has its parent the same as its child or else you'll go into an infinite loop when you do your recursion to find all the children. You can add the condition to your validation scripts to make sure it doesn't.</p>\n\n<p>See also: <a href=\"http://api.rubyonrails.com/classes/ActiveRecord/Acts/Tree/ClassMethods.html\" rel=\"nofollow noreferrer\">acts_as_tree</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25484/"
] |
I have a Rails application for project management where there are Project and Task models. A project can have many tasks, but a task can also have many tasks, ad infinitum.
Using nested resources, we can have /projects/1/tasks, /projects/1/tasks/new, /projects/1/tasks/3/edit etc.
However, how do you represent the recursive nature of tasks RESTfully? I don't want go another level deep, so perhaps the following would do:
```
map.resources :tasks do |t|
t.resources :tasks
end
```
That would give me the following urls:
```
/tasks/3/tasks/new
/tasks/3/tasks/45/edit
```
Or perhaps when it comes to an individual task I can just use /tasks/45/edit
Is this a reasonable design?
Cam
|
Going anywhere beyond a single nested route is generally considered a bad idea.
From page 108 of **The Rails Way**:
["*Jamis Busk a very influential figure in the Rails community, almost as much as David himself. In February 2007, vis his blog, he basically told us that deep nesting was a \_bad\_ thing, and proposed the following rule of thumb: Resources **should never** be nested more than one level deep.*"](http://weblog.jamisbuck.org/2007/2/5/nesting-resources)
Now some would argue with this (which is discussed on page 109) but when you're talking about nesting tasks with tasks it just doesn't seem to make much sense.
I would approach your solution a different way and like it was mentioned above, a project should have many tasks but for a task to have many tasks doesn't seem correct and maybe those should be re-named as sub-tasks or something along those lines.
|
174,198 |
<p>With the new approach of having the get/set within the attribut of the class like that :</p>
<pre><code>public string FirstName {
get; set;
}
</code></pre>
<p>Why simply not simply put the attribute FirstName public without accessor?</p>
|
[
{
"answer_id": 174201,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 4,
"selected": false,
"text": "<p>Because, in the future, if you change the implementation, code using the current interface won't break.</p>\n\n<p>For instance, you implement a simple class with a public field and start using your class in some external modules. A month later you discover you need to implement lazy loading in that class. You would then need to transform the field to a property. From the external module point of ciew, it might look the same syntaxicaly, but it is not. A property is a set of functions, while a field is an offset in a class instance.</p>\n\n<p>By using a property, you effectively reduce the risk the interface will change.</p>\n"
},
{
"answer_id": 174202,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 6,
"selected": true,
"text": "<p>Two of the big problems with direct access to variable inside class (field/attribute) are: </p>\n\n<p>1) You can't easily databind against fields.</p>\n\n<p>2) If you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters)</p>\n"
},
{
"answer_id": 174206,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>This mostly comes down to it having become a common coding convention. It makes it easy to then add custom processing code if you desire. But you are correct, there is technically no real need for this. Though, if you do add custom processing later, this will help you to not break the interface.</p>\n"
},
{
"answer_id": 174221,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 0,
"selected": false,
"text": "<p>I think the questioner is asking why not do the following...</p>\n\n<pre><code>public string FirstName { }\n</code></pre>\n\n<p>Why bother with the accessors when you could shorten it to the above. I think the answer is that by requiring the accessors makes it obvious to the person reading the code that it is a standard get/set. Without them you can see above it is hard to spot this is automatically being implemented.</p>\n"
},
{
"answer_id": 174326,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>The key is that the compiler translates the property 'under the hood' into a function pair, and when you have code that looks like it's using the property it's actually calling functions when compiled down to IL. </p>\n\n<p>So let's say you build this as a field and have code in a separate assembly that uses this field. If later on the implementation changes and you decide to make it a property to hide the changes from the rest of your code, you still need to re-compile and re-deploy the other assembly. If it's a property from the get-go then things will just work.</p>\n"
},
{
"answer_id": 205567,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "<p>For 99% of cases, exposing a public field is fine.</p>\n\n<p>The common advice is to use fields: \"If you expose public fields from your classes you can't later change them to properties \". I know that we all want our code to be future-proof, but there are some problems with this thinking:</p>\n\n<ul>\n<li><p>The consumers of your class can probably recompile when you change your interface.</p></li>\n<li><p>99% of your data members will never need to become non-trivial properties. It's <a href=\"http://c2.com/cgi/wiki?SpeculativeGenerality\" rel=\"nofollow noreferrer\">speculative generality</a>. You're writing a lot of code that will probaby never be useful.</p></li>\n<li><p>If you need binary compatability across versions, making data members in to properties probably isn't enough. At the very least, you should only expose interfacess and hide all constructors, and expose factories (see code below).</p></li>\n</ul>\n\n<hr>\n\n<pre><code>public class MyClass : IMyClass\n{\n public static IMyClass New(...)\n {\n return new MyClass(...);\n }\n}\n</code></pre>\n\n<p>It's a hard problem, trying to make code that will work in an uncertain future. Really hard.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/205568/have-trivial-properties-ever-saved-your-bacon\">Does anyone have an example of a time when using trivial properties saved their bacon?</a> </p>\n"
},
{
"answer_id": 205612,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 0,
"selected": false,
"text": "<p>When you get a bug and you need to find out which methods are modifying your fields and when, you'll care a lot more. Putting light weight property accessors in up front saves a phenomenal amount of heartache should a bug arise involving the field you wrapped. I've been in that situation a couple of times and it isn't pleasant, especially when it turns out to be re-entrancy related.</p>\n\n<p>Doing this work upfront and sticking a breakpoint on an accessor is a lot easier than the alternatives.</p>\n"
},
{
"answer_id": 208577,
"author": "Mister Dev",
"author_id": 14441,
"author_profile": "https://Stackoverflow.com/users/14441",
"pm_score": -1,
"selected": false,
"text": "<p>It preserve the encapsulation of the object and reduce the code to be more simple to read.</p>\n"
},
{
"answer_id": 208601,
"author": "Mathieu Garstecki",
"author_id": 22078,
"author_profile": "https://Stackoverflow.com/users/22078",
"pm_score": 2,
"selected": false,
"text": "<p>This style of notation is more useful when you mix acessibility for the getter and setter. For example, you can write:</p>\n\n<pre><code>public int Foo { get; private set; }\n</code></pre>\n\n<p>You could also put an internal setter, or even make the getter private and the setter public.</p>\n\n<p>This notation avoids the need to explicitly write a private variable just to handle the classic problem of the internally writable/externally readable value.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] |
With the new approach of having the get/set within the attribut of the class like that :
```
public string FirstName {
get; set;
}
```
Why simply not simply put the attribute FirstName public without accessor?
|
Two of the big problems with direct access to variable inside class (field/attribute) are:
1) You can't easily databind against fields.
2) If you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters)
|
174,232 |
<p>Basically I'm trying to accomplish the same thing that "mailto:[email protected]" does in Internet Explorer Mobile.</p>
<p>But I want to be able to do it from a managed Windows Mobile application. I don't want to send an email pro grammatically in the background.</p>
<p>I want to be able to create the email in Pocket Outlook and then let the user do the rest.</p>
<p>Hopefully that helps you hopefully help me!</p>
|
[
{
"answer_id": 174312,
"author": "Petros",
"author_id": 2812,
"author_profile": "https://Stackoverflow.com/users/2812",
"pm_score": 4,
"selected": true,
"text": "<p>I assume you use C#. You add a reference to System.Diagnostics and then write the following code:</p>\n\n<pre><code>ProcessStartInfo psi = \n new ProcessStartInfo(\"mailto:[email protected]?subject=MySubject\", \"\");\nProcess.Start(psi);\n</code></pre>\n\n<p>This will start the default email client on your mobile device.</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/aa767737(VS.85).aspx\" rel=\"nofollow noreferrer\">mailto protocol definition</a> might come handy too.</p>\n"
},
{
"answer_id": 302078,
"author": "Jake Stevenson",
"author_id": 22383,
"author_profile": "https://Stackoverflow.com/users/22383",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use Microsoft.WindowsMobile.PocketOutlook.MessagingApplication.DisplayComposeForm like so:</p>\n\n<pre><code>OutlookSession sess = new OutlookSession();\nEmailAccountCollection accounts = sess.EmailAccounts;\n//Contains all accounts on the device \n//I'll just choose the first one -- you might want to ask them\nMessagingApplication.DisplayComposeForm(accounts[0], \n \"[email protected]\", \"The Subject\", \"The Body\");\n</code></pre>\n\n<p>The DisplayComposeForm method has a lot of overloads with options for attachments and more.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23294/"
] |
Basically I'm trying to accomplish the same thing that "mailto:[email protected]" does in Internet Explorer Mobile.
But I want to be able to do it from a managed Windows Mobile application. I don't want to send an email pro grammatically in the background.
I want to be able to create the email in Pocket Outlook and then let the user do the rest.
Hopefully that helps you hopefully help me!
|
I assume you use C#. You add a reference to System.Diagnostics and then write the following code:
```
ProcessStartInfo psi =
new ProcessStartInfo("mailto:[email protected]?subject=MySubject", "");
Process.Start(psi);
```
This will start the default email client on your mobile device.
The [mailto protocol definition](http://msdn.microsoft.com/en-us/library/aa767737(VS.85).aspx) might come handy too.
|
174,239 |
<p>I have inherited a c# class 'Button' (which I can't change) which clashes with the BCL class 'Windows.Forms.Button'. Normally, Id be very happy to go:</p>
<pre><code>MyPackage.MyClass.Button;
</code></pre>
<p>But there are a large number or references to this class which is a pain to have to re-type.</p>
<p>Is there any way to get the compiler (linker?) to default to using the customised version of Button over the BCL version?</p>
|
[
{
"answer_id": 174252,
"author": "Vincent McNabb",
"author_id": 16299,
"author_profile": "https://Stackoverflow.com/users/16299",
"pm_score": 2,
"selected": false,
"text": "<p>You could remove <code>using Windows.Forms;</code> from the top of the code. That would of course mean that you would have to reference all Windows.Forms items specifically.</p>\n"
},
{
"answer_id": 174257,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>Add this to the top of the file:</p>\n\n<pre><code>using MyButton = MyPackage.MyClass.Button;\n</code></pre>\n\n<p>Now you can reference your custom button using a distinct name. You may need to do something similar for the stock button if you use that anywhere in the same file.</p>\n"
},
{
"answer_id": 174265,
"author": "Mr. Mark",
"author_id": 19274,
"author_profile": "https://Stackoverflow.com/users/19274",
"pm_score": 0,
"selected": false,
"text": "<p>You can at least make it a small bit less painful/wordy with \"using\":</p>\n\n<pre><code>using MPMC = MyPackage.MyClass;\n</code></pre>\n\n<p>then you can say: </p>\n\n<pre><code>MPMC.Button\n</code></pre>\n"
},
{
"answer_id": 174273,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 2,
"selected": false,
"text": "<p>if you want to use it by default, replace </p>\n\n<pre><code>using Windows.Forms;\n</code></pre>\n\n<p>with </p>\n\n<pre><code>using MyPackage.MyClass;\n</code></pre>\n\n<p>If you do that, you'll need to fully qualify all the buttons from Windows.Forms.</p>\n\n<p>Or, if you want to, you can alias the namespace</p>\n\n<pre><code>using My = MyPackage.MyClass;\n//... then\nMy.Button b = ...\n</code></pre>\n\n<p>Or alias the button</p>\n\n<pre><code>using MyButton = MyPackage.MyClass.Button;\n</code></pre>\n"
},
{
"answer_id": 174293,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>It appears that I can do the following:</p>\n\n<pre><code>using Button = MyPackage.MyClass.Button;\n</code></pre>\n\n<p>works and it preserves all references within the code to Button. Although Im tempted not to go down this route as it is still ambiguious (at least to the reader) which Button is being used.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
] |
I have inherited a c# class 'Button' (which I can't change) which clashes with the BCL class 'Windows.Forms.Button'. Normally, Id be very happy to go:
```
MyPackage.MyClass.Button;
```
But there are a large number or references to this class which is a pain to have to re-type.
Is there any way to get the compiler (linker?) to default to using the customised version of Button over the BCL version?
|
Add this to the top of the file:
```
using MyButton = MyPackage.MyClass.Button;
```
Now you can reference your custom button using a distinct name. You may need to do something similar for the stock button if you use that anywhere in the same file.
|
174,263 |
<p>This may be simple one, but 5 mins of Googling didn't give me the answer.
How do you save and load bitmaps using .Net librabries?</p>
<p>I have an Image object and I need to save it to disk in some format (preferably png) and load back in later.
A C# example would be great.</p>
|
[
{
"answer_id": 174276,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>About 10 seconds of google lead me to <a href=\"http://msdn.microsoft.com/en-us/library/9t4syfhh.aspx\" rel=\"nofollow noreferrer\">this example</a> for the save method, you can dig around a bit more for the others.</p>\n"
},
{
"answer_id": 174279,
"author": "Vincent McNabb",
"author_id": 16299,
"author_profile": "https://Stackoverflow.com/users/16299",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a really simple example.</p>\n\n<p><strong>Top of code file</strong></p>\n\n<pre><code>using System.Drawing;\n</code></pre>\n\n<p><strong>In code</strong></p>\n\n<pre><code>Image test = new Bitmap(\"picture.bmp\");\ntest.Save(\"picture.png\", System.Drawing.Imaging.ImageFormat.Png);\n</code></pre>\n\n<p>Remember to give write permissions to the ASPNET user for the folder where the image is to be saved.</p>\n"
},
{
"answer_id": 174281,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 1,
"selected": false,
"text": "<p>Hiya, use the Image.Save() method.</p>\n\n<p>A better explanation and code sample than I could provide can be found here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.save.aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1660/"
] |
This may be simple one, but 5 mins of Googling didn't give me the answer.
How do you save and load bitmaps using .Net librabries?
I have an Image object and I need to save it to disk in some format (preferably png) and load back in later.
A C# example would be great.
|
Here's a really simple example.
**Top of code file**
```
using System.Drawing;
```
**In code**
```
Image test = new Bitmap("picture.bmp");
test.Save("picture.png", System.Drawing.Imaging.ImageFormat.Png);
```
Remember to give write permissions to the ASPNET user for the folder where the image is to be saved.
|
174,292 |
<p>The array has lots of data and I need to delete two elements. </p>
<p>Below is the code snippet I am using,</p>
<pre><code>my @array = (1,2,3,4,5,5,6,5,4,9);
my $element_omitted = 5;
@array = grep { $_ != $element_omitted } @array;
</code></pre>
|
[
{
"answer_id": 174298,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.perlmonks.org/?node=perlfunc%3Asplice\" rel=\"noreferrer\">splice</a> will remove array element(s) by index. Use grep, as in your example, to search and remove.</p>\n"
},
{
"answer_id": 174313,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 7,
"selected": true,
"text": "<p>Use splice if you already know the index of the element you want to delete.</p>\n\n<p>Grep works if you are searching.</p>\n\n<p>If you need to do a lot of these, you will get much better performance if you keep your array in sorted order, since you can then do binary search to find the necessary index.</p>\n\n<p>If it makes sense in your context, you may want to consider using a \"magic value\" for deleted records, rather then deleting them, to save on data movement -- set deleted elements to undef, for example. Naturally, this has its own issues (if you need to know the number of \"live\" elements, you need to keep track of it separately, etc), but may be worth the trouble depending on your application.</p>\n\n<p><strong>Edit</strong> Actually now that I take a second look -- don't use the grep code above. It would be more efficient to find the index of the element you want to delete, then use splice to delete it (the code you have accumulates all the non-matching results..)</p>\n\n<pre><code>my $index = 0;\n$index++ until $arr[$index] eq 'foo';\nsplice(@arr, $index, 1);\n</code></pre>\n\n<p>That will delete the first occurrence.\nDeleting all occurrences is very similar, except you will want to get all indexes in one pass:</p>\n\n<pre><code>my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;\n</code></pre>\n\n<p>The rest is left as an excercise for the reader -- remember that the array changes as you splice it!</p>\n\n<p><strong>Edit2</strong> John Siracusa correctly pointed out I had a bug in my example.. fixed, sorry about that.</p>\n"
},
{
"answer_id": 174334,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "<p>If you know the array index, you can <a href=\"http://perldoc.perl.org/functions/delete.html\" rel=\"nofollow noreferrer\">delete()</a> it. The difference between splice() and delete() is that delete() does not renumber the remaining elements of the array.</p>\n"
},
{
"answer_id": 174353,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<p>Is this something you are going to be doing a lot? If so, you may want to consider a different data structure. Grep is going to search the entire array every time and for a large array could be quite costly. If speed is an issue then you may want to consider using a Hash instead.</p>\n\n<p>In your example, the key would be the number and the value would be the count of elements of that number.</p>\n"
},
{
"answer_id": 174860,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": false,
"text": "<h2>I think your solution is the simplest and most maintainable.</h2>\n\n<p>The rest of the post documents the difficulty of turning tests on elements into <code>splice</code> offsets. Thus, making it a more <em>complete</em> answer. </p>\n\n<p>Look at the <strong><em>gyrations</em></strong> you have to go through to have an efficient (i.e. one-pass) algorithm to turn tests on list items into indexes. And it's not that intuitive at all. </p>\n\n<pre><code>sub array_remove ( \\@& ) { \n my ( $arr_ref, $test_block ) = @_;\n my $sp_start = 0;\n my $sp_len = 0;\n for ( my $inx = 0; $inx <= $#$arr_ref; $inx++ ) {\n local $_ = $arr_ref->[$inx];\n next unless $test_block->( $_ );\n if ( $sp_len > 0 && $inx > $sp_start + $sp_len ) {\n splice( @$arr_ref, $sp_start, $sp_len );\n $inx = $inx - $sp_len;\n $sp_len = 0;\n }\n $sp_start = $inx if ++$sp_len == 1;\n }\n splice( @$arr_ref, $sp_start, $sp_len ) if $sp_len > 0;\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 11906012,
"author": "Tom Lime",
"author_id": 775159,
"author_profile": "https://Stackoverflow.com/users/775159",
"pm_score": 2,
"selected": false,
"text": "<p>Delete all occurrences of 'something' if array.</p>\n\n<p><strong>Based on SquareCog answer's:</strong></p>\n\n<pre><code>my @arr = ('1','2','3','4','3','2', '3','4','3');\nmy @dix = grep { $arr[$_] eq '4' } 0..$#arr;\nmy $o = 0;\nfor (@dix) {\n splice(@arr, $_-$o, 1);\n $o++;\n}\nprint join(\"\\n\", @arr);\n</code></pre>\n\n<p>Each time we remove index from <code>@arr</code>, the next correct index to delete will be <code>$_-current_loop_step</code>.</p>\n"
},
{
"answer_id": 14191738,
"author": "dean",
"author_id": 1954333,
"author_profile": "https://Stackoverflow.com/users/1954333",
"pm_score": 3,
"selected": false,
"text": "<p>if you change</p>\n\n<pre><code>my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;\n</code></pre>\n\n<p>to </p>\n\n<pre><code>my @del_indexes = reverse(grep { $arr[$_] eq 'foo' } 0..$#arr);\n</code></pre>\n\n<p>This avoids the array renumbering issue by removing elements from the back of the array first.\nPutting a splice() in a foreach loop cleans up @arr. Relatively simple and readable...</p>\n\n<pre><code>foreach $item (@del_indexes) {\n splice (@arr,$item,1);\n}\n</code></pre>\n"
},
{
"answer_id": 14766395,
"author": "Ariel Monaco",
"author_id": 445845,
"author_profile": "https://Stackoverflow.com/users/445845",
"pm_score": 2,
"selected": false,
"text": "<p>I use:</p>\n\n<pre><code>delete $array[$index];\n</code></pre>\n\n<p>Perldoc <a href=\"http://perldoc.perl.org/functions/delete.html\" rel=\"nofollow\"><strong>delete</strong></a>.</p>\n"
},
{
"answer_id": 15381061,
"author": "BBT",
"author_id": 2164625,
"author_profile": "https://Stackoverflow.com/users/2164625",
"pm_score": 0,
"selected": false,
"text": "<p>A similar code I once wrote to remove strings not starting with SB.1 from an array of strings</p>\n\n<pre><code>my @adoSymbols=('SB.1000','RT.10000','PC.10000');\n##Remove items from an array from backward\nfor(my $i=$#adoSymbols;$i>=0;$i--) { \n unless ($adoSymbols[$i] =~ m/^SB\\.1/) {splice(@adoSymbols,$i,1);}\n}\n</code></pre>\n"
},
{
"answer_id": 23017956,
"author": "Rich",
"author_id": 1222662,
"author_profile": "https://Stackoverflow.com/users/1222662",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the non-capturing group and a pipe delim list of items to remove.</p>\n\n<pre><code>\nperl -le '@ar=(1 .. 20);@x=(8,10,3,17);$x=join(\"|\",@x);@ar=grep{!/^(?:$x)$/o} @ar;print \"@ar\"'\n</code></pre>\n"
},
{
"answer_id": 36719021,
"author": "Federico",
"author_id": 6225021,
"author_profile": "https://Stackoverflow.com/users/6225021",
"pm_score": 2,
"selected": false,
"text": "<p>The best I found was a combination of \"undef\" and \"grep\":</p>\n\n<pre><code>foreach $index ( @list_of_indexes_to_be_skiped ) {\n undef($array[$index]);\n}\n@array = grep { defined($_) } @array;\n</code></pre>\n\n<p>That does the trick!\nFederico</p>\n"
},
{
"answer_id": 47399712,
"author": "oryan_dunn",
"author_id": 3362479,
"author_profile": "https://Stackoverflow.com/users/3362479",
"pm_score": 3,
"selected": false,
"text": "<p>You could use array slicing instead of splicing. Grep to return the indices you want keep and use slicing:</p>\n<pre><code>my @arr = ...;\n# run through each item.\nmy @indicesToKeep = grep { $arr[$_] ne 'foo' } 0..$#arr;\n@arr = @arr[@indicesToKeep];\n</code></pre>\n"
},
{
"answer_id": 54716603,
"author": "Gilles Maisonneuve",
"author_id": 3676932,
"author_profile": "https://Stackoverflow.com/users/3676932",
"pm_score": 1,
"selected": false,
"text": "<p>Just to be sure I have benchmarked grep and map solutions, first searching for indexes of matched elements (those to remove) and then directly removing the elements by grep without searching for the indexes.\nI appears that the first solution proposed by Sam when asking his question was already the fastest.</p>\n\n<pre><code> use Benchmark;\n my @A=qw(A B C A D E A F G H A I J K L A M N);\n my @M1; my @G; my @M2;\n my @Ashrunk;\n timethese( 1000000, {\n 'map1' => sub {\n my $i=0;\n @M1 = map { $i++; $_ eq 'A' ? $i-1 : ();} @A;\n },\n 'map2' => sub {\n my $i=0;\n @M2 = map { $A[$_] eq 'A' ? $_ : () ;} 0..$#A;\n },\n 'grep' => sub {\n @G = grep { $A[$_] eq 'A' } 0..$#A;\n },\n 'grem' => sub {\n @Ashrunk = grep { $_ ne 'A' } @A;\n },\n });\n</code></pre>\n\n<p>The result is:</p>\n\n<pre><code>Benchmark: timing 1000000 iterations of grem, grep, map1, map2...\n grem: 4 wallclock secs ( 3.37 usr + 0.00 sys = 3.37 CPU) @ 296823.98/s (n=1000000)\n grep: 3 wallclock secs ( 2.95 usr + 0.00 sys = 2.95 CPU) @ 339213.03/s (n=1000000)\n map1: 4 wallclock secs ( 4.01 usr + 0.00 sys = 4.01 CPU) @ 249438.76/s (n=1000000)\n map2: 2 wallclock secs ( 3.67 usr + 0.00 sys = 3.67 CPU) @ 272702.48/s (n=1000000)\nM1 = 0 3 6 10 15\nM2 = 0 3 6 10 15\nG = 0 3 6 10 15\nAshrunk = B C D E F G H I J K L M N\n</code></pre>\n\n<p>As shown by elapsed times, it's useless to try to implement a remove\nfunction using either grep or map defined indexes. Just grep-remove directly.</p>\n\n<p>Before testing I was thinking \"map1\" would be the most efficient... I should more often rely on Benchmark I guess. ;-)</p>\n"
},
{
"answer_id": 57323341,
"author": "Chetan",
"author_id": 2486083,
"author_profile": "https://Stackoverflow.com/users/2486083",
"pm_score": 3,
"selected": false,
"text": "<p>You can simply do this:</p>\n\n<pre><code>my $input_Color = 'Green';\nmy @array = qw(Red Blue Green Yellow Black);\n@array = grep {!/$input_Color/} @array;\nprint \"@array\";\n</code></pre>\n"
},
{
"answer_id": 67238432,
"author": "Jacques",
"author_id": 4814971,
"author_profile": "https://Stackoverflow.com/users/4814971",
"pm_score": 0,
"selected": false,
"text": "<p>This works well too:</p>\n<pre><code>my @array = (1,2,3,4,5,5,6,5,4,9);\nmy $element_omitted = 5;\nfor( my $i = 0; $i < scalar( @array ); $i++ )\n{\n splice( @array, $i ), $i-- if( $array[$i] == $element_omitted );\n}\nsay "@array"; # 1 2 3 4 6 4 9\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21246/"
] |
The array has lots of data and I need to delete two elements.
Below is the code snippet I am using,
```
my @array = (1,2,3,4,5,5,6,5,4,9);
my $element_omitted = 5;
@array = grep { $_ != $element_omitted } @array;
```
|
Use splice if you already know the index of the element you want to delete.
Grep works if you are searching.
If you need to do a lot of these, you will get much better performance if you keep your array in sorted order, since you can then do binary search to find the necessary index.
If it makes sense in your context, you may want to consider using a "magic value" for deleted records, rather then deleting them, to save on data movement -- set deleted elements to undef, for example. Naturally, this has its own issues (if you need to know the number of "live" elements, you need to keep track of it separately, etc), but may be worth the trouble depending on your application.
**Edit** Actually now that I take a second look -- don't use the grep code above. It would be more efficient to find the index of the element you want to delete, then use splice to delete it (the code you have accumulates all the non-matching results..)
```
my $index = 0;
$index++ until $arr[$index] eq 'foo';
splice(@arr, $index, 1);
```
That will delete the first occurrence.
Deleting all occurrences is very similar, except you will want to get all indexes in one pass:
```
my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;
```
The rest is left as an excercise for the reader -- remember that the array changes as you splice it!
**Edit2** John Siracusa correctly pointed out I had a bug in my example.. fixed, sorry about that.
|
174,297 |
<p>Try running these two simple statements on Oracle 10.2:</p>
<pre><code>CREATE TABLE mytest
(table_name varchar2(30),
index_name varchar2(30),
column_expression clob,
column_position number);
INSERT INTO mytest
(table_name,
index_name,
column_expression,
column_position)
SELECT table_name, index_name,
to_lob(column_expression), column_position
FROM user_ind_expressions EXPRA
WHERE NOT EXISTS
(SELECT 1 FROM user_constraints
WHERE constraint_name = EXPRA.index_name
AND table_name = EXPRA.table_name);
</code></pre>
<p>This results in this error:</p>
<p>ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got LONG</p>
<p>If I omit the WHERE NOT EXISTS like this:</p>
<pre><code>INSERT INTO mytest
(table_name,index_name,column_expression, column_position)
SELECT table_name,index_name,
to_lob(column_expression), column_position
FROM user_ind_expressions EXPRA;
</code></pre>
<p>It works:</p>
<p>23 rows created.</p>
<p>What is going on?</p>
|
[
{
"answer_id": 175474,
"author": "Michael OShea",
"author_id": 13178,
"author_profile": "https://Stackoverflow.com/users/13178",
"pm_score": 1,
"selected": false,
"text": "<p>If Michel Cadot <a href=\"http://www.orafaq.com/forum/mv/msg/125912/352199/0/\" rel=\"nofollow noreferrer\">says</a> its a bug, then its almost certainly a bug.</p>\n"
},
{
"answer_id": 177457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Yep, seems like it.</p>\n\n<p><a href=\"http://www.orafaq.com/forum/m/352199/130782/#msg_352199\" rel=\"nofollow noreferrer\">http://www.orafaq.com/forum/m/352199/130782/#msg_352199</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Try running these two simple statements on Oracle 10.2:
```
CREATE TABLE mytest
(table_name varchar2(30),
index_name varchar2(30),
column_expression clob,
column_position number);
INSERT INTO mytest
(table_name,
index_name,
column_expression,
column_position)
SELECT table_name, index_name,
to_lob(column_expression), column_position
FROM user_ind_expressions EXPRA
WHERE NOT EXISTS
(SELECT 1 FROM user_constraints
WHERE constraint_name = EXPRA.index_name
AND table_name = EXPRA.table_name);
```
This results in this error:
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got LONG
If I omit the WHERE NOT EXISTS like this:
```
INSERT INTO mytest
(table_name,index_name,column_expression, column_position)
SELECT table_name,index_name,
to_lob(column_expression), column_position
FROM user_ind_expressions EXPRA;
```
It works:
23 rows created.
What is going on?
|
If Michel Cadot [says](http://www.orafaq.com/forum/mv/msg/125912/352199/0/) its a bug, then its almost certainly a bug.
|
174,308 |
<p>Eclipse is a really great editor, which I prefer to use, but the GUI design tools for Eclipse are lacking. On the other hand, NetBeans works really well for GUI design. </p>
<p>Are there any tips, tricks or pitfalls for using NetBeans for GUI design and Eclipse for everything else on the same project?</p>
<p><strong>EDIT:</strong> I tried Maven, and it does not seem to work (too complex for my needs).</p>
|
[
{
"answer_id": 174377,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 3,
"selected": false,
"text": "<p>MyEclipse offers an integration of the Netbeans GUI editor (Matisse) with Eclipse.</p>\n\n<p>See <a href=\"http://www.myeclipseide.com/module-htmlpages-display-pid-5.html\" rel=\"nofollow noreferrer\">http://www.myeclipseide.com/module-htmlpages-display-pid-5.html</a></p>\n"
},
{
"answer_id": 174640,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 1,
"selected": false,
"text": "<p>Define your project dependencies with Maven, and use it to generate project configuration files for both Netbeans and Eclipse.</p>\n\n<p>Try to keep separate classes directories for Eclipse and Netbeans, since Eclipse doesn't like it when external tools touch its classes.</p>\n"
},
{
"answer_id": 174697,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 1,
"selected": false,
"text": "<p>A few gotchas:</p>\n\n<ul>\n<li>If you try to use both without any\nplugins/integration, you must be\ncareful not to edit the regions\nmarked \"DO NOT EDIT\" as Netbeans\nwill overwrite code in those\nsections quite frequently.</li>\n<li>You should use the \"Customize...\"\ncommand to add custom init code for\ncomponents.</li>\n<li>Adding/creating new components on a\nform using Java code will not be\nreflected in the GUI editor.</li>\n<li>Developers have to be discouraged\nfrom going into the code and adding\nswing customizations, effectively\nbypassing the GUI editor.</li>\n</ul>\n\n<p>Another tip is that you can create Java Beans using Eclipse and drag-and-drop them into the Matisse editor. This allows you to create a custom GUI component or a non-GUI component (models, listeners, etc) and add it to a Matisse form. With listeners and models, you can specify a component to use an instance of your custom listener/model instead of the default behavior. You can also drag-and-drop in custom GUI components and manipulate them like any other GUI widget.</p>\n"
},
{
"answer_id": 174736,
"author": "Andrew Harmel-Law",
"author_id": 2455,
"author_profile": "https://Stackoverflow.com/users/2455",
"pm_score": 2,
"selected": false,
"text": "<p>Echoing @Tom I'd use an external build tool (Maven 2 would be my pick). I've done this on projects before and as long as you don't walk all over Eclipse's .Xxxx files and folders you'll be fine. Then you get the full power of Netbeans (which integrates with Maven 2 <em>really</em> nicely) or Eclipse and also have the added value of an external build which can also be run by your CI tool. Everybody wins!</p>\n"
},
{
"answer_id": 177203,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 2,
"selected": false,
"text": "<p>Cloud Garden makes a GUI editor called <a href=\"http://www.cloudgarden.com/jigloo/\" rel=\"nofollow noreferrer\">Jigloo</a> that is quite nice if you are into that sort of thing (and the price is very, very reasonable). If that's all that's missing for you from Eclipse, I'd recommend that you take a look. Netbeans does a ton of stuff with source code that you aren't allowed to edit, etc...</p>\n\n<p>One other thing that I will mention: I have used GUI editors like Matisse and Jigloo for super rapid prototyping. However, within 3 or 4 iterations, I always find myself dropping back to hand coding the layouts. I also find that when I'm doing rapid prototyping, I am almost always more productive when I change the layout manager to absolute and just place components. Once the design starts the gel, implementing the design by hand coding using a good layout manager (I strongly recommend <a href=\"http://www.miglayout.com/\" rel=\"nofollow noreferrer\">MiG Layout</a>) is pretty easy, and gives much better results.</p>\n\n<p>I know that dragging and dropping a GUI layout is really enticing - but MiG Layout is incredibly productive for hand wiring GUIs, and I suspect that almost any developer will be more productive within a week going down that path.</p>\n"
},
{
"answer_id": 1451313,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>import project in netbeans create gui and then again open the project in eclipse</p>\n\n<p>it works with no error</p>\n"
},
{
"answer_id": 1492065,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Create your GUI with Netbeans. copy a Eclipse .project file (like below) into the project folder change the MyProjectName. Open Eclipse and import the project into your workspace, so you can open the projekt from your Eclipse workspace with Netbeans. Now you able to use Netbeans to create and change the GUI and editing the code with Eclipse.</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n <name>MyProject</name>\n <comment></comment>\n <projects>\n </projects>\n <buildSpec>\n <buildCommand>\n <name>org.eclipse.jdt.core.javabuilder</name>\n <arguments>\n </arguments>\n </buildCommand>\n </buildSpec>\n <natures>\n <nature>org.eclipse.jdt.core.javanature</nature>\n </natures>\n</projectDescription>\n</code></pre>\n"
},
{
"answer_id": 2671859,
"author": "mxro",
"author_id": 270662,
"author_profile": "https://Stackoverflow.com/users/270662",
"pm_score": 0,
"selected": false,
"text": "<p>For me using linked source folders works quite well. </p>\n\n<p>I build the GUIs in independent NetBeans projects - if they need some simple classes or interfaces, I use the \"link source\" (right click on project in NetBeans, choose properties), to include these in the NetBeans project.</p>\n\n<p>My main projects are in eclipse. Here I again use the link source feature to link to the NetBeans project (right click on project in eclipse, select \"build path\", then \"link source\").</p>\n\n<p>EDIT (Thx to Milhous :) ): in both projects in eclipse and NetBeans further all required JAR files need to be added to the build path (also the libraries added by NetBeans: eg beansbinding-1.2.1.jar, appframework-1.0.3.jar swing-worker-1.1.jar, ...)</p>\n\n<p>Now the GUI classes can be reused in eclipse. Also leads to need to have GUI and logic classes quite decoupled, which can be nothing bad.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712/"
] |
Eclipse is a really great editor, which I prefer to use, but the GUI design tools for Eclipse are lacking. On the other hand, NetBeans works really well for GUI design.
Are there any tips, tricks or pitfalls for using NetBeans for GUI design and Eclipse for everything else on the same project?
**EDIT:** I tried Maven, and it does not seem to work (too complex for my needs).
|
Create your GUI with Netbeans. copy a Eclipse .project file (like below) into the project folder change the MyProjectName. Open Eclipse and import the project into your workspace, so you can open the projekt from your Eclipse workspace with Netbeans. Now you able to use Netbeans to create and change the GUI and editing the code with Eclipse.
```
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>MyProject</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
```
|
174,348 |
<p>Will content requested over https still be cached by web browsers or do they consider this insecure behaviour? If this is the case is there anyway to tell them it's ok to cache?</p>
|
[
{
"answer_id": 174485,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 8,
"selected": true,
"text": "<p>By default web browsers should cache content over HTTPS the same as over HTTP, unless explicitly told otherwise via the <a href=\"http://en.wikipedia.org/wiki/List_of_HTTP_headers\" rel=\"nofollow noreferrer\">HTTP Headers</a> received.</p>\n<p><a href=\"https://www.mnot.net/cache_docs/\" rel=\"nofollow noreferrer\">This link</a> is a good introduction to setting cache setting in HTTP headers.</p>\n<blockquote>\n<p>is there anyway to tell them it's ok to cache?</p>\n</blockquote>\n<p>This can be achieved by setting the <code>max-age</code> value in the <code>Cache-Control</code> header to a non-zero value, e.g.</p>\n<pre><code>Cache-Control: max-age=3600\n</code></pre>\n<p>will tell the browser that this page can be cached for 3600 seconds (1 hour)</p>\n"
},
{
"answer_id": 174510,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 8,
"selected": false,
"text": "<p>As of 2010, <strong>all modern, current-ish browsers cache HTTPS content by default, unless explicitly told not to.</strong></p>\n<p>It is <em>not</em> required to set <code>cache-control:public</code> for this to happen.</p>\n<p>Source: <a href=\"https://web.archive.org/web/20160405131722/http://gent.ilcore.com/2011/02/chromes-10-caches.html?showComment=1297102528799#c5411401837359385517\" rel=\"nofollow noreferrer\">Chrome</a>, <a href=\"https://web.archive.org/web/20160217145028/http://blogs.msdn.com:80/b/ieinternals/archive/2010/04/21/internet-explorer-may-bypass-cache-for-cross-domain-https-content.aspx\" rel=\"nofollow noreferrer\">IE</a>, <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=531801\" rel=\"nofollow noreferrer\">Firefox</a>.</p>\n"
},
{
"answer_id": 34167234,
"author": "Ashim Nath",
"author_id": 5656599,
"author_profile": "https://Stackoverflow.com/users/5656599",
"pm_score": 0,
"selected": false,
"text": "<p>Https is cached by default. This is managed by a global setting that cannot be overridden by application-defined cache directives. To override the global setting, select the Internet Options applet in the control panel, and go to the advanced tab. Check the \"Do not save encrypted pages to disk\" box under the \"Security\" section, but the use of HTTPS alone has no impact on whether or not IE decides to cache a resource.</p>\n\n<p>WinINet only caches HTTP and FTP responses not HTTPS response.\n<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa383928%28v=vs.85%29.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/windows/desktop/aa383928%28v=vs.85%29.aspx</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21030/"
] |
Will content requested over https still be cached by web browsers or do they consider this insecure behaviour? If this is the case is there anyway to tell them it's ok to cache?
|
By default web browsers should cache content over HTTPS the same as over HTTP, unless explicitly told otherwise via the [HTTP Headers](http://en.wikipedia.org/wiki/List_of_HTTP_headers) received.
[This link](https://www.mnot.net/cache_docs/) is a good introduction to setting cache setting in HTTP headers.
>
> is there anyway to tell them it's ok to cache?
>
>
>
This can be achieved by setting the `max-age` value in the `Cache-Control` header to a non-zero value, e.g.
```
Cache-Control: max-age=3600
```
will tell the browser that this page can be cached for 3600 seconds (1 hour)
|
174,351 |
<p>What is an effective algorithm for nesting 1 dimensional lengths into predefined stock lengths?</p>
<p>For example, If you required steel bars in the following quantities and lengths,</p>
<ul>
<li>5 x 2 metres </li>
<li>5 x 3 metres</li>
<li>5 x 4 metres</li>
</ul>
<p>and these can be cut from 10 metre bars.
How could you calculate the pattern for cutting the 10m bars so that the minimum number of bars are used?</p>
<p>In addition, how could you incorporate multiple stock lengths into the algorithm?</p>
<hr>
<p>I've had a bit of time to work on this so I'm going to write up how I solved it. I hope this will be useful to someone.I'm not sure if it is ok to answer my own question like this. A moderator can change this to an answer if that is more appropriate.</p>
<p>First thanks to everyone that answered. This pointed me to the appropriate algorithm; <a href="http://en.wikipedia.org/wiki/Cutting_stock_problem" rel="nofollow noreferrer">the cutting stock problem</a>.</p>
<p>This post was also useful; <a href="https://stackoverflow.com/questions/22145/calculating-a-cutting-list-with-the-least-amount-of-off-cut-waste">"Calculating a cutting list with the least amount of off cut waste"</a>.</p>
<p>Ok, on to the solution.</p>
<p>I'll use the following terminology in my solution;</p>
<ul>
<li>Stock: a length of material that will be cut into smaller pieces</li>
<li>Cut: a length of material that has been cut from stock. multiple cuts may be taken from the same piece of stock</li>
<li>Waste: the length of material that is left in a piece of stock after all cuts have been made.</li>
</ul>
<p>There are three main stages to solving the problem,</p>
<ol>
<li>Identify all possible cut combinations</li>
<li>Identify which combinations can be taken from each piece of stock</li>
<li>Find the optimal mix of cut combinations.</li>
</ol>
<p><strong>Step 1</strong></p>
<p>With N cuts, there are 2^N-1 unique cut combinations. These combinations can be represented as a binary truth table.</p>
<p>Where A,B,C are unique cuts;</p>
<pre><code>A B C | Combination
-------------------
0 0 0 | None
0 0 1 | C
0 1 0 | B
0 1 1 | BC
1 0 0 | A
1 0 1 | AC
1 1 0 | AB
1 1 1 | ABC
</code></pre>
<p>A for-loop with some bitwise operators can be used to quickly create groupings of each cut combination.</p>
<p>This can get quite time consuming for large values of N.</p>
<p>In my situation there were multiple instances of the same cut. This produced duplicate combinations.</p>
<pre><code>A B B | Combination
-------------------
0 0 0 | None
0 0 1 | B
0 1 0 | B (same as previous)
0 1 1 | BB
1 0 0 | A
1 0 1 | AB
1 1 0 | AB (same as previous)
1 1 1 | ABB
</code></pre>
<p>I was able to exploit this redundancy to reduce the time to calculate the combinations. I grouped the duplicate cuts together and calculated the unique combinations of this group. I then appended this list of combinations to each unique combination in a second group to create a new group. </p>
<p>For example, with cuts AABBC, the process is as follows.</p>
<pre><code>A A | Combination
-------------------
0 1 | A
1 1 | AA
</code></pre>
<p>Call this group X.</p>
<p>Append X to unique instances of B,</p>
<pre><code>B B X | Combination
-------------------
0 0 1 | A
| AA
0 1 0 | B
0 1 1 | BA
| BAA
1 1 0 | BB
1 1 1 | BBA
| BBAA
</code></pre>
<p>Call this group Y.</p>
<p>Append Y to unique instances of C,</p>
<pre><code>C Y | Combination
-----------------
0 1 | A
| AA
| B
| BA
| BAA
| BB
| BBA
| BBAA
1 0 | C
1 1 | CA
| CAA
| CB
| CBA
| CBAA
| CBB
| CBBA
| CBBAA
</code></pre>
<p>This example produces 17 unique combinations instead of 31 (2^5-1). A saving of almost half.</p>
<p>Once all combinations are identified it is time to check how this fits into the stock.</p>
<p><strong>Step 2</strong></p>
<p>The aim of this step is to map the cut combinations identified in step 1 to the available stock sizes.</p>
<p>This is a relatively simple process.
For each cut combination, </p>
<pre><code> calculate the sum of all cut lengths.
for each item of stock,
if the sum of cuts is less than stock length,
store stock, cut combination and waste in a data structure.
Add this structure to a list of some sort.
</code></pre>
<p>This will result in a list of a valid nested cut combinations.
It is not strictly necessary to store the waste as this can be calculated from the cut lengths and stock length. However, storing waste reduces processing required in step 3.</p>
<p><strong>Step 3</strong></p>
<p>In this step we will identify the combination of cuts that produces the least waste. This is based on the list of valid nests generated in step 2.</p>
<p>In an ideal world we would calculate all possibilities and select the best one. For any non-trivial set of cuts it would take forever to calculate them all. We will just have to be satisfied with a non optimal solution.
There are various algorithms for accomplishing this task. </p>
<p>I chose a method that will look for a nest with the least waste. It will repeat this until all cuts have been accounted for.</p>
<p>Start with three lists</p>
<ul>
<li>cutList: a list of all required cuts (including duplicates).</li>
<li>nestList: The list of nests generated in step 2. This is sorted from lowest waste to highest waste.</li>
<li>finalList: Initially empty, this will store the list of cut combinations that will be output to the user.</li>
</ul>
<p>Method </p>
<pre><code>pick nest from nestList with the least waste
if EVERY cut in the nest is contained in cutList
remove cuts from cutList
copy this nest into the finalList
if some cuts in nest not in cutList
remove this nest from nestList
repeat until cutlist is empty
</code></pre>
<p>With this method I managed to get a total waste of around 2-4% for some typical test data. Hopefully I will get to revisit this problem at some point and have a go at implementing the <a href="http://en.wikipedia.org/wiki/Delayed_Column_Generation" rel="nofollow noreferrer">Delayed column generation</a> algorithm. This should give better results.</p>
<p>I hope this helped anyone else having this problem.</p>
<p>David</p>
|
[
{
"answer_id": 174357,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.nist.gov/dads/HTML/binpacking.html\" rel=\"nofollow noreferrer\">Least Cost Bin Packing</a></p>\n\n<p>edit: Here's a better link: <a href=\"http://en.wikipedia.org/wiki/Bin_packing_problem\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Bin_packing_problem</a></p>\n"
},
{
"answer_id": 174426,
"author": "Dave Turvey",
"author_id": 18966,
"author_profile": "https://Stackoverflow.com/users/18966",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for suggesting bin packing problem plinth. This lead me to the following post,\n<a href=\"https://stackoverflow.com/questions/22145/calculating-a-cutting-list-with-the-least-amount-of-off-cut-waste#23625\">Calculating a cutting list with the least amount of off cut waste</a>. This appears to cover my question well</p>\n"
},
{
"answer_id": 174505,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 4,
"selected": true,
"text": "<p>Actually, there's an even more specific problem that applies: The <a href=\"http://en.wikipedia.org/wiki/Cutting_stock_problem\" rel=\"noreferrer\">cutting stock problem</a>:</p>\n\n<blockquote>\n <p>The cutting stock problem is an\n optimization problem, or more\n specifically, an integer linear\n programming problem. It arises from\n many applications in industry. Imagine\n that you work in a paper mill and you\n have a number of rolls of paper of\n fixed width waiting to be cut, yet\n different customers want different\n numbers of rolls of various-sized\n widths. How are you going to cut the\n rolls so that you minimize the waste\n (amount of left-overs)?</p>\n</blockquote>\n\n<p>The reason this applies better than the bin packing problem is because you are trying to minimise the waste, rather than minimise the number of 'bins'. In a sense, the bin packing problem is the inverse of the cutting stock problem: How would you take lengths of steel and reassemble them into as few bars as possible under a certain size?</p>\n"
},
{
"answer_id": 174656,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 0,
"selected": false,
"text": "<p>Solved a problem similar to this years ago. I ended up using a genetic algorithm. That would be overkill for small problems. This program was somewhat fun to write, but not fun at the same time, being back in the 16-bit days.</p>\n\n<p>First, it made a list of all the ways a 10' piece of raw material could be cut, using the given lengths. For each the amount of wasted material was recorded. (Though it is fast math, it's faster to store these for lookup later.) Then it looked at the list of required pieces. In a loop, it would pick from the way-to-cut list a way of cutting stock that didn't cut more pieces of any size than required. A greedy algorithm would pick one with minimal waste, but sometimes a better solution could be found by loosening up on that. Eventually a genetic algorithm made the choices, the \"DNA\" being some set of ways-to-cut that did pretty well in past solutions. </p>\n\n<p>All this was way back in pre-internet days, hacked up with cleverness and experimentation. These days there's probably some .NET or java library thing to do it already black-boxed - but that would be less fun and less education, wouldn't it?</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18966/"
] |
What is an effective algorithm for nesting 1 dimensional lengths into predefined stock lengths?
For example, If you required steel bars in the following quantities and lengths,
* 5 x 2 metres
* 5 x 3 metres
* 5 x 4 metres
and these can be cut from 10 metre bars.
How could you calculate the pattern for cutting the 10m bars so that the minimum number of bars are used?
In addition, how could you incorporate multiple stock lengths into the algorithm?
---
I've had a bit of time to work on this so I'm going to write up how I solved it. I hope this will be useful to someone.I'm not sure if it is ok to answer my own question like this. A moderator can change this to an answer if that is more appropriate.
First thanks to everyone that answered. This pointed me to the appropriate algorithm; [the cutting stock problem](http://en.wikipedia.org/wiki/Cutting_stock_problem).
This post was also useful; ["Calculating a cutting list with the least amount of off cut waste"](https://stackoverflow.com/questions/22145/calculating-a-cutting-list-with-the-least-amount-of-off-cut-waste).
Ok, on to the solution.
I'll use the following terminology in my solution;
* Stock: a length of material that will be cut into smaller pieces
* Cut: a length of material that has been cut from stock. multiple cuts may be taken from the same piece of stock
* Waste: the length of material that is left in a piece of stock after all cuts have been made.
There are three main stages to solving the problem,
1. Identify all possible cut combinations
2. Identify which combinations can be taken from each piece of stock
3. Find the optimal mix of cut combinations.
**Step 1**
With N cuts, there are 2^N-1 unique cut combinations. These combinations can be represented as a binary truth table.
Where A,B,C are unique cuts;
```
A B C | Combination
-------------------
0 0 0 | None
0 0 1 | C
0 1 0 | B
0 1 1 | BC
1 0 0 | A
1 0 1 | AC
1 1 0 | AB
1 1 1 | ABC
```
A for-loop with some bitwise operators can be used to quickly create groupings of each cut combination.
This can get quite time consuming for large values of N.
In my situation there were multiple instances of the same cut. This produced duplicate combinations.
```
A B B | Combination
-------------------
0 0 0 | None
0 0 1 | B
0 1 0 | B (same as previous)
0 1 1 | BB
1 0 0 | A
1 0 1 | AB
1 1 0 | AB (same as previous)
1 1 1 | ABB
```
I was able to exploit this redundancy to reduce the time to calculate the combinations. I grouped the duplicate cuts together and calculated the unique combinations of this group. I then appended this list of combinations to each unique combination in a second group to create a new group.
For example, with cuts AABBC, the process is as follows.
```
A A | Combination
-------------------
0 1 | A
1 1 | AA
```
Call this group X.
Append X to unique instances of B,
```
B B X | Combination
-------------------
0 0 1 | A
| AA
0 1 0 | B
0 1 1 | BA
| BAA
1 1 0 | BB
1 1 1 | BBA
| BBAA
```
Call this group Y.
Append Y to unique instances of C,
```
C Y | Combination
-----------------
0 1 | A
| AA
| B
| BA
| BAA
| BB
| BBA
| BBAA
1 0 | C
1 1 | CA
| CAA
| CB
| CBA
| CBAA
| CBB
| CBBA
| CBBAA
```
This example produces 17 unique combinations instead of 31 (2^5-1). A saving of almost half.
Once all combinations are identified it is time to check how this fits into the stock.
**Step 2**
The aim of this step is to map the cut combinations identified in step 1 to the available stock sizes.
This is a relatively simple process.
For each cut combination,
```
calculate the sum of all cut lengths.
for each item of stock,
if the sum of cuts is less than stock length,
store stock, cut combination and waste in a data structure.
Add this structure to a list of some sort.
```
This will result in a list of a valid nested cut combinations.
It is not strictly necessary to store the waste as this can be calculated from the cut lengths and stock length. However, storing waste reduces processing required in step 3.
**Step 3**
In this step we will identify the combination of cuts that produces the least waste. This is based on the list of valid nests generated in step 2.
In an ideal world we would calculate all possibilities and select the best one. For any non-trivial set of cuts it would take forever to calculate them all. We will just have to be satisfied with a non optimal solution.
There are various algorithms for accomplishing this task.
I chose a method that will look for a nest with the least waste. It will repeat this until all cuts have been accounted for.
Start with three lists
* cutList: a list of all required cuts (including duplicates).
* nestList: The list of nests generated in step 2. This is sorted from lowest waste to highest waste.
* finalList: Initially empty, this will store the list of cut combinations that will be output to the user.
Method
```
pick nest from nestList with the least waste
if EVERY cut in the nest is contained in cutList
remove cuts from cutList
copy this nest into the finalList
if some cuts in nest not in cutList
remove this nest from nestList
repeat until cutlist is empty
```
With this method I managed to get a total waste of around 2-4% for some typical test data. Hopefully I will get to revisit this problem at some point and have a go at implementing the [Delayed column generation](http://en.wikipedia.org/wiki/Delayed_Column_Generation) algorithm. This should give better results.
I hope this helped anyone else having this problem.
David
|
Actually, there's an even more specific problem that applies: The [cutting stock problem](http://en.wikipedia.org/wiki/Cutting_stock_problem):
>
> The cutting stock problem is an
> optimization problem, or more
> specifically, an integer linear
> programming problem. It arises from
> many applications in industry. Imagine
> that you work in a paper mill and you
> have a number of rolls of paper of
> fixed width waiting to be cut, yet
> different customers want different
> numbers of rolls of various-sized
> widths. How are you going to cut the
> rolls so that you minimize the waste
> (amount of left-overs)?
>
>
>
The reason this applies better than the bin packing problem is because you are trying to minimise the waste, rather than minimise the number of 'bins'. In a sense, the bin packing problem is the inverse of the cutting stock problem: How would you take lengths of steel and reassemble them into as few bars as possible under a certain size?
|
174,352 |
<p>I currently have a DetailsView in ASP.NET that gets data from the database based on an ID passed through a QueryString. What I've been trying to do now is to then use that same ID in a new cookie that is created when a user clicks either a ButtonField or a HyperLinkField.</p>
<p>What I have in the .aspx is this:</p>
<pre><code><asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ArtID"
DataSourceID="AccessDataSource1" Height="50px" Width="125px">
<Fields>
<asp:ImageField DataAlternateTextField="Title" DataImageUrlField="FileLocation">
</asp:ImageField>
<asp:BoundField DataField="ArtID" HeaderText="ArtID" InsertVisible="False" ReadOnly="True"
SortExpression="ArtID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="ArtDate" HeaderText="ArtDate" SortExpression="ArtDate" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="FileLocation" HeaderText="FileLocation" SortExpression="FileLocation" />
<asp:BoundField DataField="Medium" HeaderText="Medium" SortExpression="Medium" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
<asp:BoundField DataField="PageViews" HeaderText="PageViews" SortExpression="PageViews" />
<asp:HyperLinkField DataNavigateUrlFields="ArtID" DataNavigateUrlFormatString="Purchase.aspx?ArtID={0}"
NavigateUrl="Purchase.aspx" Text="Add To Cart" />
<asp:ButtonField ButtonType="Button" DataTextField="ArtID" Text="Add to Cart" CommandName="btnAddToCart_Click" />
</Fields>
</asp:DetailsView>
</code></pre>
<p>When using a reguler asp.net button such as:</p>
<pre><code><asp:Button ID="btnAddArt" runat="server" Text="Add To Cart" />
</code></pre>
<p>I would have something like this in the VB:</p>
<pre><code>Protected Sub btnAddArt_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddArt.Click
Dim CartArtID As New HttpCookie("CartArtID")
CartArtID.Value = ArtID.DataField
CartArtID.Expires = Date.Today.AddDays(0.5)
Response.Cookies.Add(CartArtID)
Response.Redirect("Purchase.aspx")
End Sub
</code></pre>
<p>However, I can't figure out how I go about applying this to the ButtonField instead since the ButtonField does not allow me to give it an ID.</p>
<p>The ID that I need to add to the cookie is the ArtID in the first BoundField.</p>
<p>Any idea's/advice on how I would go about doing this are greatly appreciated!</p>
<p>Alternatively, if I could do it with the HyperLinkField or with the regular button, that would be just as good, but I'm having trouble using a regular button to access the ID within the DetailsView.</p>
<p>Thanks</p>
|
[
{
"answer_id": 174391,
"author": "Rob",
"author_id": 2595,
"author_profile": "https://Stackoverflow.com/users/2595",
"pm_score": 0,
"selected": false,
"text": "<p>I noticed you're putting the key in the grid itself (DataKeyNames=\"ArtID\"). You have access to that in your event handler -- the event args will get you the current index for indexing into the datakeys on the grid.</p>\n\n<p>Make sense?</p>\n"
},
{
"answer_id": 174675,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 0,
"selected": false,
"text": "<p>Since you set the DataKeyNames property of the DetailsView control, you can access the ArtID of the displayed item using the DetailsView1.DataKey(0). Alternatively you can use DetailsView1.SelectedValue to get the same.\nAs for handling the click event, you'll have to add an ItemCommand event handler to the DetailsView.</p>\n"
},
{
"answer_id": 174957,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": true,
"text": "<p>Use the CommandName and the CommandArgument parameters of the Button class. Specifying a CommandName will expose the ItemCommand event. From there you can check for the CommandName, easily grab the CommandArgument (the ID of your row or item) then push whatever data your need into your cookie that way.</p>\n\n<p>More formally, you're looking to have your button like this:</p>\n\n<pre><code><asp:Button ID=\"btnAddArt\" CommandName=\"AddCard\" CommandArgument=\"[ArtID]\" runat=\"server\" Text=\"Add To Cart\" />\n</code></pre>\n\n<p>Then your code behind can function like this:</p>\n\n<pre><code>Private Sub ProcessDetailsViewCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles DetailsView1.ItemCommand\n\n' Using Case statement makes it easy to add more custom commands later on.\nSelect Case e.CommandName\n\n Case \"AddCard\"\n Dim CartArtID As New HttpCookie(\"CartArtID\")\n CartArtID.Value = Integer.Parse(e.CommandArgument.ToString)\n CartArtID.Expires = Date.Today.AddDays(0.5)\n Response.Cookies.Add(CartArtID)\n Response.Redirect(\"Purchase.aspx\")\n\n End Select\nEnd Sub\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17020/"
] |
I currently have a DetailsView in ASP.NET that gets data from the database based on an ID passed through a QueryString. What I've been trying to do now is to then use that same ID in a new cookie that is created when a user clicks either a ButtonField or a HyperLinkField.
What I have in the .aspx is this:
```
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ArtID"
DataSourceID="AccessDataSource1" Height="50px" Width="125px">
<Fields>
<asp:ImageField DataAlternateTextField="Title" DataImageUrlField="FileLocation">
</asp:ImageField>
<asp:BoundField DataField="ArtID" HeaderText="ArtID" InsertVisible="False" ReadOnly="True"
SortExpression="ArtID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="ArtDate" HeaderText="ArtDate" SortExpression="ArtDate" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="FileLocation" HeaderText="FileLocation" SortExpression="FileLocation" />
<asp:BoundField DataField="Medium" HeaderText="Medium" SortExpression="Medium" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
<asp:BoundField DataField="PageViews" HeaderText="PageViews" SortExpression="PageViews" />
<asp:HyperLinkField DataNavigateUrlFields="ArtID" DataNavigateUrlFormatString="Purchase.aspx?ArtID={0}"
NavigateUrl="Purchase.aspx" Text="Add To Cart" />
<asp:ButtonField ButtonType="Button" DataTextField="ArtID" Text="Add to Cart" CommandName="btnAddToCart_Click" />
</Fields>
</asp:DetailsView>
```
When using a reguler asp.net button such as:
```
<asp:Button ID="btnAddArt" runat="server" Text="Add To Cart" />
```
I would have something like this in the VB:
```
Protected Sub btnAddArt_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddArt.Click
Dim CartArtID As New HttpCookie("CartArtID")
CartArtID.Value = ArtID.DataField
CartArtID.Expires = Date.Today.AddDays(0.5)
Response.Cookies.Add(CartArtID)
Response.Redirect("Purchase.aspx")
End Sub
```
However, I can't figure out how I go about applying this to the ButtonField instead since the ButtonField does not allow me to give it an ID.
The ID that I need to add to the cookie is the ArtID in the first BoundField.
Any idea's/advice on how I would go about doing this are greatly appreciated!
Alternatively, if I could do it with the HyperLinkField or with the regular button, that would be just as good, but I'm having trouble using a regular button to access the ID within the DetailsView.
Thanks
|
Use the CommandName and the CommandArgument parameters of the Button class. Specifying a CommandName will expose the ItemCommand event. From there you can check for the CommandName, easily grab the CommandArgument (the ID of your row or item) then push whatever data your need into your cookie that way.
More formally, you're looking to have your button like this:
```
<asp:Button ID="btnAddArt" CommandName="AddCard" CommandArgument="[ArtID]" runat="server" Text="Add To Cart" />
```
Then your code behind can function like this:
```
Private Sub ProcessDetailsViewCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles DetailsView1.ItemCommand
' Using Case statement makes it easy to add more custom commands later on.
Select Case e.CommandName
Case "AddCard"
Dim CartArtID As New HttpCookie("CartArtID")
CartArtID.Value = Integer.Parse(e.CommandArgument.ToString)
CartArtID.Expires = Date.Today.AddDays(0.5)
Response.Cookies.Add(CartArtID)
Response.Redirect("Purchase.aspx")
End Select
End Sub
```
|
174,356 |
<p>I'm tidying up some older code that uses 'magic numbers' all over the place to set hardware registers, and I would like to use constants instead of these numbers to make the code somewhat more expressive (in fact they will map to the names/values used to document the registers).</p>
<p>However, I'm concerned that with the volume of changes I might break the magic numbers. Here is a simplified example (the register set is more complex):</p>
<pre><code>const short mode0 = 0;
const short mode1 = 1;
const short mode2 = 2;
const short state0 = 0;
const short state1 = 4;
const short state2 = 8;
</code></pre>
<p>so instead of :</p>
<pre><code>set_register(5);
</code></pre>
<p>we have:</p>
<pre><code>set_register(state1|mode1);
</code></pre>
<p>What I'm looking for is a <strong>build time</strong> version of:</p>
<pre><code>ASSERT(5==(state1|mode1));
</code></pre>
<p><strong>Update</strong></p>
<p>@Christian, thanks for the quick response, I'm interested on a C / non-boost environment answer too because this is driver/kernel code.</p>
|
[
{
"answer_id": 174360,
"author": "Christian.K",
"author_id": 21567,
"author_profile": "https://Stackoverflow.com/users/21567",
"pm_score": 4,
"selected": false,
"text": "<p>Checkout boost's <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost_staticassert.html\" rel=\"noreferrer\">static assert</a></p>\n"
},
{
"answer_id": 174378,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 4,
"selected": false,
"text": "<p>You can roll your own static assert if you don't have access to a third-party library static assert function (like boost):</p>\n\n<pre><code>#define STATIC_ASSERT(x) \\\n do { \\\n const static char dummy[(x)?1:-1] = {0};\\\n } while(0)\n</code></pre>\n\n<p>The downside is, of course, that error message is not going to be very helpful, but at least, it will give you the line number.</p>\n"
},
{
"answer_id": 174413,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "<p>The common, portable option is</p>\n\n<pre><code>#if 5 != (state1|mode1)\n# error \"aaugh!\"\n#endif\n</code></pre>\n\n<p>but it doesn't work in this case, because they're C constants and not <code>#define</code>s.</p>\n\n<p>You can see the Linux kernel's <code>BUILD_BUG_ON</code> macro for something that handles your case:</p>\n\n<pre><code>#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))\n</code></pre>\n\n<p>When <code>condition</code> is true, this becomes <code>((void)sizeof(char[-1]))</code>, which is illegal and should fail at compile time, and otherwise it becomes <code>((void)sizeof(char[1]))</code>, which is just fine.</p>\n"
},
{
"answer_id": 174424,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 3,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>#define STATIC_ASSERT(x, error) \\\ndo { \\\n static const char error[(x)?1:-1];\\\n} while(0)\n</code></pre>\n\n<p>Then you can write:</p>\n\n<pre><code>STATIC_ASSERT(a == b, a_not_equal_to_b);\n</code></pre>\n\n<p>Which may give you a better error message (depending on your compiler).</p>\n"
},
{
"answer_id": 174441,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 6,
"selected": true,
"text": "<p><strong>NEW ANSWER </strong>:</p>\n\n<p>In my original answer (below), I had to have two different macros to support assertions in a function scope and at the global scope. I wondered if it was possible to come up with a single solution that would work in both scopes.</p>\n\n<p>I was able to find a solution that worked for Visual Studio and Comeau compilers using extern character arrays. But I was able to find a more complex solution that works for GCC. But GCC's solution doesn't work for Visual Studio. :( But adding a '#ifdef __ GNUC __', it's easy to choose the right set of macros for a given compiler.</p>\n\n<p><strong>Solution:</strong></p>\n\n<pre><code>#ifdef __GNUC__\n#define STATIC_ASSERT_HELPER(expr, msg) \\\n (!!sizeof \\ (struct { unsigned int STATIC_ASSERTION__##msg: (expr) ? 1 : -1; }))\n#define STATIC_ASSERT(expr, msg) \\\n extern int (*assert_function__(void)) [STATIC_ASSERT_HELPER(expr, msg)]\n#else\n #define STATIC_ASSERT(expr, msg) \\\n extern char STATIC_ASSERTION__##msg[1]; \\\n extern char STATIC_ASSERTION__##msg[(expr)?1:2]\n#endif /* #ifdef __GNUC__ */\n</code></pre>\n\n<p>Here are the error messages reported for <code>STATIC_ASSERT(1==1, test_message);</code> at line 22 of test.c:</p>\n\n<p><strong>GCC:</strong></p>\n\n<pre><code>line 22: error: negative width in bit-field `STATIC_ASSERTION__test_message'\n</code></pre>\n\n<p><strong>Visual Studio:</strong></p>\n\n<pre><code>test.c(22) : error C2369: 'STATIC_ASSERTION__test_message' : redefinition; different subscripts\n test.c(22) : see declaration of 'STATIC_ASSERTION__test_message'\n</code></pre>\n\n<p><strong>Comeau:</strong></p>\n\n<pre><code>line 22: error: declaration is incompatible with\n \"char STATIC_ASSERTION__test_message[1]\" (declared at line 22)\n</code></pre>\n\n<p><p> <br> <br></p>\n\n<p><strong>ORIGINAL ANSWER </strong>:</p>\n\n<p>I do something very similar to what Checkers does. But I include a message that'll show up in many compilers:</p>\n\n<pre><code>#define STATIC_ASSERT(expr, msg) \\\n{ \\\n char STATIC_ASSERTION__##msg[(expr)?1:-1]; \\\n (void)STATIC_ASSERTION__##msg[0]; \\\n}\n</code></pre>\n\n<p>And for doing something at the global scope (outside a function) use this:</p>\n\n<pre><code>#define GLOBAL_STATIC_ASSERT(expr, msg) \\\n extern char STATIC_ASSERTION__##msg[1]; \\\n extern char STATIC_ASSERTION__##msg[(expr)?1:2]\n</code></pre>\n"
},
{
"answer_id": 174742,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 3,
"selected": false,
"text": "<p>Any of the techniques listed here should work and when C++0x becomes available you will be able to use the built-in <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Static_assertions\" rel=\"noreferrer\"><code>static_assert</code></a> keyword.</p>\n"
},
{
"answer_id": 175216,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<p>If you have Boost then using <code>BOOST_STATIC_ASSERT</code> is the way to go. If you're using C or don't want to get Boost \nhere's my <code>c_assert.h</code> file that defines (and explains the workings of) a few macros to handle static assertions. </p>\n\n<p>It's a bit more convoluted that it should be because in ANSI C code you need 2 different macros - one that can work in the area where you have declarations and one that can work in the area where normal statements go. There is a also a bit of work that goes into making the macro work at global scope or in block scope and a bunch of gunk to ensure that there are no name collisions.</p>\n\n<p><code>STATIC_ASSERT()</code> can be used in the variable declaration block or global scope.</p>\n\n<p><code>STATIC_ASSERT_EX()</code> can be among regular statements.</p>\n\n<p>For C++ code (or C99 code that allow declarations mixed with statements) <code>STATIC_ASSERT()</code> will work anywhere.</p>\n\n<pre><code>/*\n Define macros to allow compile-time assertions.\n\n If the expression is false, an error something like\n\n test.c(9) : error XXXXX: negative subscript\n\n will be issued (the exact error and its format is dependent\n on the compiler).\n\n The techique used for C is to declare an extern (which can be used in\n file or block scope) array with a size of 1 if the expr is TRUE and\n a size of -1 if the expr is false (which will result in a compiler error).\n A counter or line number is appended to the name to help make it unique. \n Note that this is not a foolproof technique, but compilers are\n supposed to accept multiple identical extern declarations anyway.\n\n This technique doesn't work in all cases for C++ because extern declarations\n are not permitted inside classes. To get a CPP_ASSERT(), there is an \n implementation of something similar to Boost's BOOST_STATIC_ASSERT(). Boost's\n approach uses template specialization; when expr evaluates to 1, a typedef\n for the type \n\n ::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed<true>) >\n\n which boils down to \n\n ::interslice::StaticAssert_test< 1>\n\n which boils down to \n\n struct StaticAssert_test\n\n is declared. If expr is 0, the compiler will be unable to find a specialization for\n\n ::interslice::StaticAssert_failed<false>.\n\n STATIC_ASSERT() or C_ASSERT should work in either C or C++ code (and they do the same thing)\n\n CPP_ASSERT is defined only for C++ code.\n\n Since declarations can only occur at file scope or at the start of a block in \n standard C, the C_ASSERT() or STATIC_ASSERT() macros will only work there. For situations\n where you want to perform compile-time asserts elsewhere, use C_ASSERT_EX() or\n STATIC_ASSERT_X() which wrap an enum declaration inside it's own block.\n\n */\n\n#ifndef C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546\n#define C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546\n\n/* first some utility macros to paste a line number or counter to the end of an identifier\n * this will let us have some chance of generating names that are unique\n * there may be problems if a static assert ends up on the same line number in different headers\n * to avoid that problem in C++ use namespaces\n*/\n\n#if !defined( PASTE)\n#define PASTE2( x, y) x##y\n#define PASTE( x, y) PASTE2( x, y)\n#endif /* PASTE */\n\n#if !defined( PASTE_LINE)\n#define PASTE_LINE( x) PASTE( x, __LINE__)\n#endif /* PASTE_LINE */\n\n#if!defined( PASTE_COUNTER)\n#if (_MSC_VER >= 1300) /* __COUNTER__ introduced in VS 7 (VS.NET 2002) */\n #define PASTE_COUNTER( x) PASTE( x, __COUNTER__) /* __COUNTER__ is a an _MSC_VER >= 1300 non-Ansi extension */\n#else\n #define PASTE_COUNTER( x) PASTE( x, __LINE__) /* since there's no __COUNTER__ use __LINE__ as a more or less reasonable substitute */\n#endif\n#endif /* PASTE_COUNTER */\n\n\n\n#if __cplusplus\nextern \"C++\" { // required in case we're included inside an extern \"C\" block\n namespace interslice {\n template<bool b> struct StaticAssert_failed;\n template<> struct StaticAssert_failed<true> { enum {val = 1 }; };\n template<int x> struct StaticAssert_test { };\n }\n}\n #define CPP_ASSERT( expr) typedef ::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed< (bool) (expr) >) > PASTE_COUNTER( IntersliceStaticAssertType_)\n #define STATIC_ASSERT( expr) CPP_ASSERT( expr)\n #define STATIC_ASSERT_EX( expr) CPP_ASSERT( expr)\n#else\n #define C_ASSERT_STORAGE_CLASS extern /* change to typedef might be needed for some compilers? */\n #define C_ASSERT_GUID 4964f7ac50fa4661a1377e4c17509495 /* used to make sure our extern name doesn't collide with something else */\n #define STATIC_ASSERT( expr) C_ASSERT_STORAGE_CLASS char PASTE( PASTE( c_assert_, C_ASSERT_GUID), [(expr) ? 1 : -1])\n #define STATIC_ASSERT_EX(expr) do { enum { c_assert__ = 1/((expr) ? 1 : 0) }; } while (0)\n#endif /* __cplusplus */\n\n#if !defined( C_ASSERT) /* C_ASSERT() might be defined by winnt.h */\n#define C_ASSERT( expr) STATIC_ASSERT( expr)\n#endif /* !defined( C_ASSERT) */\n#define C_ASSERT_EX( expr) STATIC_ASSERT_EX( expr)\n\n\n\n#ifdef TEST_IMPLEMENTATION\nC_ASSERT( 1 < 2);\nC_ASSERT( 1 < 2);\n\nint main( )\n{\n C_ASSERT( 1 < 2);\n C_ASSERT( 1 < 2);\n\n int x;\n\n x = 1 + 4;\n\n C_ASSERT_EX( 1 < 2);\n C_ASSERT_EX( 1 < 2);\n\n\n\n return( 0);\n}\n#endif /* TEST_IMPLEMENTATION */\n#endif /* C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546 */\n</code></pre>\n"
},
{
"answer_id": 333854,
"author": "pesche",
"author_id": 3686,
"author_profile": "https://Stackoverflow.com/users/3686",
"pm_score": 4,
"selected": false,
"text": "<p>There is an article by\n<a href=\"http://www.drdobbs.com/184401873\" rel=\"noreferrer\">Ralf Holly</a> that examines different options for static asserts in C.</p>\n\n<p>He presents three different approaches:</p>\n\n<ul>\n<li>switch case values must be unique</li>\n<li>arrays must not have negative dimensions</li>\n<li>division by zero for constant expressions</li>\n</ul>\n\n<p>His conclusion for the best implementation is this:</p>\n\n<pre><code>#define assert_static(e) \\\n do { \\\n enum { assert_static__ = 1/(e) }; \\\n } while (0)\n</code></pre>\n"
},
{
"answer_id": 6087420,
"author": "Danyluk Tamás",
"author_id": 764711,
"author_profile": "https://Stackoverflow.com/users/764711",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#define static_assert(expr) \\\nint __static_assert(int static_assert_failed[(expr)?1:-1])\n</code></pre>\n\n<p>It can be used anywhere, any times. \nI think it is the easiest solution.</p>\n\n<p>Before usage, test it with your compiler carefully. </p>\n"
},
{
"answer_id": 50047342,
"author": "Toby Speight",
"author_id": 4850040,
"author_profile": "https://Stackoverflow.com/users/4850040",
"pm_score": 1,
"selected": false,
"text": "<p>Ensure you compile with a sufficiently recent compiler (e.g. <code>gcc -std=c11</code>).</p>\n\n<p>Then your statement is simply:</p>\n\n<pre><code>_Static_assert(state1|mode1 == 5, \"Unexpected change of bitflags\");\n</code></pre>\n"
},
{
"answer_id": 62394832,
"author": "rcpa0",
"author_id": 1707260,
"author_profile": "https://Stackoverflow.com/users/1707260",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#define MODE0 0\n#define MODE1 1\n#define MODE2 2\n\n#define STATE0 0\n#define STATE1 4\n#define STATE2 8\n\nset_register(STATE1|STATE1); //set_register(5);\n#if (!(5==(STATE1|STATE1))) //MY_ASSERT(5==(state1|mode1)); note the !\n#error \"error blah blah\"\n#endif\n</code></pre>\n\n<p>This is not as elegant as a one line MY_ASSERT(expr) solution. You could use sed, awk, or m4 macro processor before compiling your C code to generate the DEBUG code expansion of MY_ASSERT(expr) to multiple lines or NODEBUG code which removes them for production.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4071/"
] |
I'm tidying up some older code that uses 'magic numbers' all over the place to set hardware registers, and I would like to use constants instead of these numbers to make the code somewhat more expressive (in fact they will map to the names/values used to document the registers).
However, I'm concerned that with the volume of changes I might break the magic numbers. Here is a simplified example (the register set is more complex):
```
const short mode0 = 0;
const short mode1 = 1;
const short mode2 = 2;
const short state0 = 0;
const short state1 = 4;
const short state2 = 8;
```
so instead of :
```
set_register(5);
```
we have:
```
set_register(state1|mode1);
```
What I'm looking for is a **build time** version of:
```
ASSERT(5==(state1|mode1));
```
**Update**
@Christian, thanks for the quick response, I'm interested on a C / non-boost environment answer too because this is driver/kernel code.
|
**NEW ANSWER** :
In my original answer (below), I had to have two different macros to support assertions in a function scope and at the global scope. I wondered if it was possible to come up with a single solution that would work in both scopes.
I was able to find a solution that worked for Visual Studio and Comeau compilers using extern character arrays. But I was able to find a more complex solution that works for GCC. But GCC's solution doesn't work for Visual Studio. :( But adding a '#ifdef \_\_ GNUC \_\_', it's easy to choose the right set of macros for a given compiler.
**Solution:**
```
#ifdef __GNUC__
#define STATIC_ASSERT_HELPER(expr, msg) \
(!!sizeof \ (struct { unsigned int STATIC_ASSERTION__##msg: (expr) ? 1 : -1; }))
#define STATIC_ASSERT(expr, msg) \
extern int (*assert_function__(void)) [STATIC_ASSERT_HELPER(expr, msg)]
#else
#define STATIC_ASSERT(expr, msg) \
extern char STATIC_ASSERTION__##msg[1]; \
extern char STATIC_ASSERTION__##msg[(expr)?1:2]
#endif /* #ifdef __GNUC__ */
```
Here are the error messages reported for `STATIC_ASSERT(1==1, test_message);` at line 22 of test.c:
**GCC:**
```
line 22: error: negative width in bit-field `STATIC_ASSERTION__test_message'
```
**Visual Studio:**
```
test.c(22) : error C2369: 'STATIC_ASSERTION__test_message' : redefinition; different subscripts
test.c(22) : see declaration of 'STATIC_ASSERTION__test_message'
```
**Comeau:**
```
line 22: error: declaration is incompatible with
"char STATIC_ASSERTION__test_message[1]" (declared at line 22)
```
**ORIGINAL ANSWER** :
I do something very similar to what Checkers does. But I include a message that'll show up in many compilers:
```
#define STATIC_ASSERT(expr, msg) \
{ \
char STATIC_ASSERTION__##msg[(expr)?1:-1]; \
(void)STATIC_ASSERTION__##msg[0]; \
}
```
And for doing something at the global scope (outside a function) use this:
```
#define GLOBAL_STATIC_ASSERT(expr, msg) \
extern char STATIC_ASSERTION__##msg[1]; \
extern char STATIC_ASSERTION__##msg[(expr)?1:2]
```
|
174,375 |
<p>I am using my own db for phpbb3 forum, and I wish to insert some data from the forum into my own tables. Now, I can make my own connection and it runs my query but in trying to use the $db variable(which I think is what you're meant to use??) it gives me an error.</p>
<p>I would like someone to show me the bare bones which i insert my query into to be able to run it.</p>
|
[
{
"answer_id": 174395,
"author": "Cetra",
"author_id": 15087,
"author_profile": "https://Stackoverflow.com/users/15087",
"pm_score": 1,
"selected": false,
"text": "<p>Well.. You haven't given us very much information, but there are two things you need to do to connect and query to a database.</p>\n\n<p>For phpbb, you may want to read the documentation they have presented:</p>\n\n<p><a href=\"http://wiki.phpbb.com/Database_Abstraction_Layer\" rel=\"nofollow noreferrer\">http://wiki.phpbb.com/Database_Abstraction_Layer</a></p>\n\n<p>Here is a general overview of how you'd execute a query:</p>\n\n<pre><code>include($phpbb_root_path . 'includes/db/mysql.' . $phpEx);\n\n$db = new dbal_mysql();\n// we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D\n$db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);\n\n$sql = \"INSERT INTO (rest of sql statement)\";\n\n$result = $db->sql_query($sql);\n</code></pre>\n"
},
{
"answer_id": 174421,
"author": "Chris",
"author_id": 25491,
"author_profile": "https://Stackoverflow.com/users/25491",
"pm_score": 0,
"selected": false,
"text": "<p>I presumed that phpBB already had a connection to my database. Thus I wasnt going to use a new one? Can i make a new one and call it something else and not get an error?</p>\n\n<p>And $resultid = mysql_query($sql,$db345);</p>\n\n<p>Where $db345 is the name of my database connection</p>\n"
},
{
"answer_id": 63653357,
"author": "Lakalash Binks",
"author_id": 14189632,
"author_profile": "https://Stackoverflow.com/users/14189632",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$db = new dbal_mysql();\n// we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D\n$db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);\n\n$sql = "INSERT INTO (rest of sql statement)";\n$result = $db->sql_query($sql);\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25491/"
] |
I am using my own db for phpbb3 forum, and I wish to insert some data from the forum into my own tables. Now, I can make my own connection and it runs my query but in trying to use the $db variable(which I think is what you're meant to use??) it gives me an error.
I would like someone to show me the bare bones which i insert my query into to be able to run it.
|
Well.. You haven't given us very much information, but there are two things you need to do to connect and query to a database.
For phpbb, you may want to read the documentation they have presented:
<http://wiki.phpbb.com/Database_Abstraction_Layer>
Here is a general overview of how you'd execute a query:
```
include($phpbb_root_path . 'includes/db/mysql.' . $phpEx);
$db = new dbal_mysql();
// we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D
$db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);
$sql = "INSERT INTO (rest of sql statement)";
$result = $db->sql_query($sql);
```
|
174,380 |
<p>Within a spring webflow, i need to implement a navigation bar that will allow to "step back" or resume the flow to one of the previous view.</p>
<p>For example :</p>
<ul>
<li>View 1 = login</li>
<li>View 2 = My informations</li>
<li>View 3 = My messages</li>
<li>View 4 = Close session</li>
</ul>
<p>For this example, i would like to return back to view 2 from the view 4 page.</p>
|
[
{
"answer_id": 175279,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 2,
"selected": false,
"text": "<p>It depends how you're going about doing this. If you're doing this within a single flow, you'll have something like this:</p>\n\n<pre><code><view-state id=\"loginView\" view=\"login.jsp\">\n <action-state bean=\"someBean\" method=\"login\" />\n <transition on=\"success\" to=\"informationView\" />\n</view-state> \n\n<view-state id=\"informationView\" view=\"information.jsp\">\n <render-actions>\n <action-state bean=\"someBean\" method=\"retrieveInformation\" />\n </render-actions>\n <transition on=\"forward\" to=\"messageView\" />\n <transition on=\"back\" to=\"loginView\" />\n</view-state>\n\n<view-state id=\"messageView\" view=\"message.jsp\">\n <render-actions>\n <action-state bean=\"someBean\" method=\"retrieveMessage\" />\n </render-actions>\n <transition on=\"forward\" to=\"closeView\" />\n <transition on=\"back\" to=\"informationView\" />\n</view-state>\n\n<view-state id=\"closeView\" view=\"logout.jsp\">\n <transition on=\"jumpBack\" to=\"informationView\" />\n</view-state>\n</code></pre>\n\n<p>The \"jumpBack\" transition on \"closeView\" will jump you back to view state #2, which is your information view.</p>\n\n<p>With sub-flows it is tricky. You'd need to chain it: call a subflow, and if an event is signaled that states you need to end your flow with a specific state, immediately do so.</p>\n\n<p>For example, say that your flow chain is login->information->message->close.</p>\n\n<p>On the close flow, the end-state would be \"returnToInformation\".</p>\n\n<p>The message flow has a transition on=\"returnToInformation\" to=\"returnToInformation\".</p>\n\n<p>\"returnToInformation\" is also an end-state in the message flow.</p>\n\n<p>Then, the information flow has a transition on=\"returnToInformation\" to=\"displayInformationPage\", which would then re-display the information page.</p>\n"
},
{
"answer_id": 1322954,
"author": "mransley",
"author_id": 18977,
"author_profile": "https://Stackoverflow.com/users/18977",
"pm_score": 0,
"selected": false,
"text": "<p>I did this by defining some global flow that represented the tabs. I then defined an object that represented the tabs on the flows and indicated if the current tab was active. When the user moved through the tabs I updated the tab object as appropriate.</p>\n\n<p>When the user went to click on one of the tabs it used the global flows to allow them to move between the tabs (for my implementation I found it easier to call actions rather than view states because you may find the views may change depending on the user interaction to get there so you may need to recalculate them).</p>\n\n<p>For the tab bar itself, I put it in a single JSP that I then placed at the top of each form, this made updating it easier.</p>\n\n<p>Its not the nicest solution, but it does work.</p>\n\n<p>Good luck.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25492/"
] |
Within a spring webflow, i need to implement a navigation bar that will allow to "step back" or resume the flow to one of the previous view.
For example :
* View 1 = login
* View 2 = My informations
* View 3 = My messages
* View 4 = Close session
For this example, i would like to return back to view 2 from the view 4 page.
|
It depends how you're going about doing this. If you're doing this within a single flow, you'll have something like this:
```
<view-state id="loginView" view="login.jsp">
<action-state bean="someBean" method="login" />
<transition on="success" to="informationView" />
</view-state>
<view-state id="informationView" view="information.jsp">
<render-actions>
<action-state bean="someBean" method="retrieveInformation" />
</render-actions>
<transition on="forward" to="messageView" />
<transition on="back" to="loginView" />
</view-state>
<view-state id="messageView" view="message.jsp">
<render-actions>
<action-state bean="someBean" method="retrieveMessage" />
</render-actions>
<transition on="forward" to="closeView" />
<transition on="back" to="informationView" />
</view-state>
<view-state id="closeView" view="logout.jsp">
<transition on="jumpBack" to="informationView" />
</view-state>
```
The "jumpBack" transition on "closeView" will jump you back to view state #2, which is your information view.
With sub-flows it is tricky. You'd need to chain it: call a subflow, and if an event is signaled that states you need to end your flow with a specific state, immediately do so.
For example, say that your flow chain is login->information->message->close.
On the close flow, the end-state would be "returnToInformation".
The message flow has a transition on="returnToInformation" to="returnToInformation".
"returnToInformation" is also an end-state in the message flow.
Then, the information flow has a transition on="returnToInformation" to="displayInformationPage", which would then re-display the information page.
|
174,381 |
<p>I am trying to match floating-point decimal numbers with a regular expression. There may or may not be a number before the decimal, and the decimal may or may not be present, and if it is present it may or may not have digits after it. (For this application, a leading +/- or a trailing "E123" is not allowed). I have written this regex:</p>
<pre><code>/^([\d]*)(\.([\d]*))?$/
</code></pre>
<p>Which correctly matches the following:</p>
<pre><code>1
1.
1.23
.23
</code></pre>
<p>However, this also matches empty string or a string of just a decimal point, which I do not want.</p>
<p>Currently I am checking after running the regex that $1 or $3 has length greater than 0. If not, it is not valid. Is there a way I can do this directly in the regex?</p>
|
[
{
"answer_id": 174392,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 4,
"selected": true,
"text": "<p>I think this will do what you want. It either starts with a digit, in which case the decimal point and digits after it are optional, or it starts with a decimal point, in which case at least one digit is mandatory after it. </p>\n\n<pre><code>/^\\d+(\\.\\d*)?|\\.\\d+$/\n</code></pre>\n"
},
{
"answer_id": 174411,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>Create a regular expression for each case and OR them. Then you only need test if the expression matches.</p>\n\n<pre><code>/^(\\d+(\\.\\d*)?)|(\\d*\\.\\d+)$/\n</code></pre>\n"
},
{
"answer_id": 26633757,
"author": "Suganthan Madhavan Pillai",
"author_id": 2534236,
"author_profile": "https://Stackoverflow.com/users/2534236",
"pm_score": 0,
"selected": false,
"text": "<p>A very late answer, but like to answer, taken from <a href=\"http://www.regular-expressions.info/floatingpoint.html\" rel=\"nofollow\">regular-expressions.info</a></p>\n\n<pre><code>[-+]?[\\d]*\\.?[\\d]+?\n</code></pre>\n\n<p><strong>Update</strong> This <code>[\\d]*\\.?[\\d]+?|[\\d]+\\.</code> will help you matching <code>1.</code></p>\n\n<p><a href=\"http://regex101.com/r/lJ7fF4/7\" rel=\"nofollow\">http://regex101.com/r/lJ7fF4/7</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
I am trying to match floating-point decimal numbers with a regular expression. There may or may not be a number before the decimal, and the decimal may or may not be present, and if it is present it may or may not have digits after it. (For this application, a leading +/- or a trailing "E123" is not allowed). I have written this regex:
```
/^([\d]*)(\.([\d]*))?$/
```
Which correctly matches the following:
```
1
1.
1.23
.23
```
However, this also matches empty string or a string of just a decimal point, which I do not want.
Currently I am checking after running the regex that $1 or $3 has length greater than 0. If not, it is not valid. Is there a way I can do this directly in the regex?
|
I think this will do what you want. It either starts with a digit, in which case the decimal point and digits after it are optional, or it starts with a decimal point, in which case at least one digit is mandatory after it.
```
/^\d+(\.\d*)?|\.\d+$/
```
|
174,393 |
<p>This PHP code...</p>
<pre><code>207 if (getenv(HTTP_X_FORWARDED_FOR)) {
208 $ip = getenv('HTTP_X_FORWARD_FOR');
209 $host = gethostbyaddr($ip);
210 } else {
211 $ip = getenv('REMOTE_ADDR');
212 $host = gethostbyaddr($ip);
213 }
</code></pre>
<p>Throws this warning...</p>
<blockquote>
<p><strong>Warning:</strong> gethostbyaddr()
[function.gethostbyaddr]: Address is
not in a.b.c.d form in <strong>C:\inetpub...\filename.php</strong> on line <strong>212</strong></p>
</blockquote>
<p>It seems that <em>$ip</em> is blank.</p>
|
[
{
"answer_id": 174422,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Why don't you use </p>\n\n<pre><code>$_SERVER['REMOTE_ADDR'] \n</code></pre>\n\n<p>and </p>\n\n<pre><code>$_SERVER['HTTP_X_FORWARDED_FOR']\n</code></pre>\n"
},
{
"answer_id": 174425,
"author": "fly.floh",
"author_id": 25442,
"author_profile": "https://Stackoverflow.com/users/25442",
"pm_score": 5,
"selected": true,
"text": "<p>on php.net it says the following:</p>\n\n<blockquote>\n <p>The function <code>getenv</code> does not work if your Server API is ASAPI (IIS).\n So, try to don't use <code>getenv('REMOTE_ADDR')</code>, but <code>$_SERVER[\"REMOTE_ADDR\"]</code>.</p>\n</blockquote>\n\n<p>Did you maybe try to do it with <code>$_SERVER</code>?</p>\n"
},
{
"answer_id": 174455,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, getenv() takes a string as parameter. On line 207, you should use:</p>\n\n<pre><code>getenv('HTTP_X_FORWARDED_FOR')\n</code></pre>\n\n<p>...instead of:</p>\n\n<pre><code>getenv(HTTP_X_FORWARDED_FOR)\n</code></pre>\n\n<p>Secondly, accessing these variables through $_SERVER is a more reliable solution, as getenv() tends to display different behaviour on different platforms.</p>\n\n<p>Also, these variables will probably not work if you are running this script through CLI.</p>\n\n<p>Try a var_dump($ip); and see what the variable contains.</p>\n"
},
{
"answer_id": 3814138,
"author": "easyDaMan",
"author_id": 460372,
"author_profile": "https://Stackoverflow.com/users/460372",
"pm_score": 2,
"selected": false,
"text": "<p>A better solution has already been given. But still: </p>\n\n<pre><code>getenv('HTTP_X_FORWARD_FOR');\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>getenv('HTTP_X_FORWARDED_FOR');\n</code></pre>\n\n<p>Yeah... sometimes computers want to have strings they understand ;-)</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
This PHP code...
```
207 if (getenv(HTTP_X_FORWARDED_FOR)) {
208 $ip = getenv('HTTP_X_FORWARD_FOR');
209 $host = gethostbyaddr($ip);
210 } else {
211 $ip = getenv('REMOTE_ADDR');
212 $host = gethostbyaddr($ip);
213 }
```
Throws this warning...
>
> **Warning:** gethostbyaddr()
> [function.gethostbyaddr]: Address is
> not in a.b.c.d form in **C:\inetpub...\filename.php** on line **212**
>
>
>
It seems that *$ip* is blank.
|
on php.net it says the following:
>
> The function `getenv` does not work if your Server API is ASAPI (IIS).
> So, try to don't use `getenv('REMOTE_ADDR')`, but `$_SERVER["REMOTE_ADDR"]`.
>
>
>
Did you maybe try to do it with `$_SERVER`?
|
174,403 |
<p>In my vb.net program, I am using a webbrowser to show the user an HTML preview. I was previously hitting a server to grab the HTML, then returning on an asynchronous thread and raising an event to populate the WebBrowser.DocumentText with the HTML string I was returning.</p>
<p>Now I set it up to grab all of the information on the client, without ever having to hit the server, and I'm trying to raise the same event. I watch the code go through, and it has the HTML string correct and everything, but when I try to do</p>
<pre><code>browser.DocumentText = _emailHTML
</code></pre>
<p>the contents of DocumentText remain as "<code><HTML></HTML></code>"</p>
<p>I was just wondering why the DocumentText was not being set. Anyone have any suggestions?</p>
|
[
{
"answer_id": 174483,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 7,
"selected": true,
"text": "<p>Try the following:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>browser.Navigate("about:blank");\nHtmlDocument doc = browser.Document;\ndoc.Write(String.Empty);\nbrowser.DocumentText = _emailHTML;\n</code></pre>\n<p>I've found that the <code>WebBrowser</code> control usually needs to be initialized to <code>about:blank</code> anyway. The same needs to be done between navigates to different types of content (like text/xml to text/html) because the renderer is different (mshtml for text/html, something else for text/xml).</p>\n<p><strong>See Also</strong>: <a href=\"https://web.archive.org/web/20200217201946/http://geekswithblogs.net/paulwhitblog/archive/2005/12/12/62961.aspx\" rel=\"nofollow noreferrer\">C# 2.0 WebBrowser control - bug in DocumentText?</a></p>\n"
},
{
"answer_id": 3965190,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 1,
"selected": false,
"text": "<p>Just spotted this in some of our old code.</p>\n\n<pre><code>_webBrowser.DocumentText = builder.WriteToString( ... );\n\nApplication.DoEvents();\n</code></pre>\n\n<p>Apparently a DoEvents also kicks the browser into rendering</p>\n"
},
{
"answer_id": 4738473,
"author": "JOE SKEET",
"author_id": 518201,
"author_profile": "https://Stackoverflow.com/users/518201",
"pm_score": 0,
"selected": false,
"text": "<p>please refer to this answer <a href=\"https://stackoverflow.com/questions/4737823/c-filenotfoundexception-on-webbrowser/4738244#4738244\">c# filenotfoundexception on webbrowser?</a></p>\n"
},
{
"answer_id": 7418458,
"author": "AVIDeveloper",
"author_id": 287109,
"author_profile": "https://Stackoverflow.com/users/287109",
"pm_score": 0,
"selected": false,
"text": "<p>While <code>Application.DoEvents()</code> fix it in a WinForms project, it was irrelevant in a WPF project.</p>\n\n<p>I finally got it to work by using <code>webBrowser.Write( htmlContent )</code> (instead of <code>webBrowser.DocumentText = htmlContent</code>).</p>\n"
},
{
"answer_id": 7963984,
"author": "Prads",
"author_id": 413582,
"author_profile": "https://Stackoverflow.com/users/413582",
"pm_score": 0,
"selected": false,
"text": "<p><strong>This always works</strong></p>\n\n<pre><code>using mshtml;\n\n\nprivate IHTMLDocument2 Document\n{\n get\n {\n if (Browser.Document != null)\n {\n return Browser.Document.DomDocument as IHTMLDocument2;\n }\n\n return null;\n }\n}\n\n\nif (Document == null)\n{\n Browser.DocumentText = Contents;\n}\nelse\n{\n Document.body.innerHTML = Contents;\n}\n</code></pre>\n"
},
{
"answer_id": 15209861,
"author": "Matthias",
"author_id": 2133221,
"author_profile": "https://Stackoverflow.com/users/2133221",
"pm_score": 5,
"selected": false,
"text": "<p>I found the following and it worked!</p>\n\n<pre><code> webBrowser.Navigate(\"about:blank\");\n webBrowser.Document.OpenNew(false);\n webBrowser.Document.Write(html);\n webBrowser.Refresh();\n</code></pre>\n"
},
{
"answer_id": 16165355,
"author": "antgraf",
"author_id": 465062,
"author_profile": "https://Stackoverflow.com/users/465062",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure that you do not cancel <em>Navigating</em> event of <em>WebBrowser</em> for <strong>about:blank</strong> page. <em>WebBrowser</em> navigates to <strong>about:blank</strong> before setting <em>DocumentText</em>.\nSo if you want to handle links by yourself you need to create following handler of <em>Navigating</em> event:</p>\n\n<pre><code>private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n{\n if(e.Url.OriginalString.StartsWith(\"about:\"))\n {\n return;\n }\n e.Cancel = true;\n // ...\n}\n</code></pre>\n"
},
{
"answer_id": 17809649,
"author": "FreddieH",
"author_id": 2610510,
"author_profile": "https://Stackoverflow.com/users/2610510",
"pm_score": 4,
"selected": false,
"text": "<p>I found the best way to handle this, is as follows:</p>\n\n<pre><code>if (this.webBrowser1.Document == null)\n{\n this.webBrowser1.DocumentText = htmlSource;\n}\nelse\n{\n this.webBrowser1.Document.OpenNew(true);\n this.webBrowser1.Document.Write(htmlSource);\n}\n</code></pre>\n"
},
{
"answer_id": 40250353,
"author": "Interferank",
"author_id": 3353064,
"author_profile": "https://Stackoverflow.com/users/3353064",
"pm_score": 2,
"selected": false,
"text": "<p>That worked for me:</p>\n\n<pre><code>webBrowser.Navigate(\"about:blank\");\nwebBrowser.Document?.Write(htmlString);\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13244/"
] |
In my vb.net program, I am using a webbrowser to show the user an HTML preview. I was previously hitting a server to grab the HTML, then returning on an asynchronous thread and raising an event to populate the WebBrowser.DocumentText with the HTML string I was returning.
Now I set it up to grab all of the information on the client, without ever having to hit the server, and I'm trying to raise the same event. I watch the code go through, and it has the HTML string correct and everything, but when I try to do
```
browser.DocumentText = _emailHTML
```
the contents of DocumentText remain as "`<HTML></HTML>`"
I was just wondering why the DocumentText was not being set. Anyone have any suggestions?
|
Try the following:
```cs
browser.Navigate("about:blank");
HtmlDocument doc = browser.Document;
doc.Write(String.Empty);
browser.DocumentText = _emailHTML;
```
I've found that the `WebBrowser` control usually needs to be initialized to `about:blank` anyway. The same needs to be done between navigates to different types of content (like text/xml to text/html) because the renderer is different (mshtml for text/html, something else for text/xml).
**See Also**: [C# 2.0 WebBrowser control - bug in DocumentText?](https://web.archive.org/web/20200217201946/http://geekswithblogs.net/paulwhitblog/archive/2005/12/12/62961.aspx)
|
174,412 |
<p>I'm having trouble figuring out how to access a cookie from a compiled object. I'm trying to make a compiled (DLL) object that will check the users cookie and then compare that to a database to confirm they have the correct access. </p>
<p>I can pass in the cookie info fine and the component will work, but I'm trying to have the component check the users cookie as well. I'm not even sure what object to use. I've been searching all weekend and I've seen references to httprequest, httpcookie, cookie, and cookiecollection. </p>
<p>I can look up cookie values on the page itself using Request.Cookies("inet")("user_id") but this doesn't work in the component. </p>
|
[
{
"answer_id": 174427,
"author": "martin",
"author_id": 8421,
"author_profile": "https://Stackoverflow.com/users/8421",
"pm_score": 3,
"selected": true,
"text": "<p>Objects (App_Code/ compiled dlls) can only access Request via the static HttpContext.Current object</p>\n\n<pre><code>HttpCookie cookie = HttpContext.Current.Request.Cookies[\"CookieName\"];\n</code></pre>\n\n<p>(If it's not called from a web app, HttpContext.Current is null, so you may want to check for that when running in unit testing)\n(If this isn't App_Code, you'll need to reference System.Web)</p>\n"
},
{
"answer_id": 174435,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<p>If the component is a separate DLL from your web app you'd need to pass in a reference to the Request object.</p>\n\n<p>That said why not just read/check the cookie value in your ASP.NET code before calling into your DLL. It's not such a good idea to have your business logic coupled to your web tier like this.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9581/"
] |
I'm having trouble figuring out how to access a cookie from a compiled object. I'm trying to make a compiled (DLL) object that will check the users cookie and then compare that to a database to confirm they have the correct access.
I can pass in the cookie info fine and the component will work, but I'm trying to have the component check the users cookie as well. I'm not even sure what object to use. I've been searching all weekend and I've seen references to httprequest, httpcookie, cookie, and cookiecollection.
I can look up cookie values on the page itself using Request.Cookies("inet")("user\_id") but this doesn't work in the component.
|
Objects (App\_Code/ compiled dlls) can only access Request via the static HttpContext.Current object
```
HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieName"];
```
(If it's not called from a web app, HttpContext.Current is null, so you may want to check for that when running in unit testing)
(If this isn't App\_Code, you'll need to reference System.Web)
|
174,418 |
<p>I've written a little script to iterate across files in folders to count lines of code.</p>
<p>The heart of the script is this function to count lines of whitespace, comments, and code. (Note that for the moment it is tailored to C# and doesn't know about multi-line comments).</p>
<p>It just doesn't look very nice to me - has anyone got a cleaner version?</p>
<pre><code>// from list of strings return tuple with count of (whitespace, comments, code)
let loc (arr:List<string>) =
let innerloc (whitesp, comment, code) (l:string) =
let s = l.Trim([|' ';'\t'|]) // remove leading whitespace
match s with
| "" -> (whitesp + 1, comment, code) //blank lines
| "{" -> (whitesp + 1, comment, code) //opening blocks
| "}" -> (whitesp + 1, comment, code) //closing blocks
| _ when s.StartsWith("#") -> (whitesp + 1, comment, code) //regions
| _ when s.StartsWith("//") -> (whitesp, comment + 1, code) //comments
| _ -> (whitesp, comment, code + 1)
List.fold_left innerloc (0,0,0) arr
</code></pre>
|
[
{
"answer_id": 174429,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 1,
"selected": false,
"text": "<p>A better site for this might be <a href=\"http://refactormycode.com/\" rel=\"nofollow noreferrer\">refactormycode</a> - it's tailored exactly for these questions.</p>\n"
},
{
"answer_id": 174433,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 0,
"selected": false,
"text": "<p>Can't see much wrong with that other than the fact you will count a single brace with <em>trailing</em> spaces as code instead of whitespace.</p>\n"
},
{
"answer_id": 174928,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": true,
"text": "<p>I think what you have is fine, but here's some variety to mix it up. (This solution repeats your problem of ignoring trailing whitespace.)</p>\n\n<pre><code>type Line =\n | Whitespace = 0\n | Comment = 1\n | Code = 2\nlet Classify (l:string) = \n let s = l.TrimStart([|' ';'\\t'|])\n match s with \n | \"\" | \"{\" | \"}\" -> Line.Whitespace\n | _ when s.StartsWith(\"#\") -> Line.Whitespace\n | _ when s.StartsWith(\"//\") -> Line.Comment\n | _ -> Line.Code\nlet Loc (arr:list<_>) = \n let sums = Array.create 3 0\n arr \n |> List.iter (fun line -> \n let i = Classify line |> int\n sums.[i] <- sums.[i] + 1)\n sums\n</code></pre>\n\n<p>\"Classify\" as a separate entity might be useful in another context.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
I've written a little script to iterate across files in folders to count lines of code.
The heart of the script is this function to count lines of whitespace, comments, and code. (Note that for the moment it is tailored to C# and doesn't know about multi-line comments).
It just doesn't look very nice to me - has anyone got a cleaner version?
```
// from list of strings return tuple with count of (whitespace, comments, code)
let loc (arr:List<string>) =
let innerloc (whitesp, comment, code) (l:string) =
let s = l.Trim([|' ';'\t'|]) // remove leading whitespace
match s with
| "" -> (whitesp + 1, comment, code) //blank lines
| "{" -> (whitesp + 1, comment, code) //opening blocks
| "}" -> (whitesp + 1, comment, code) //closing blocks
| _ when s.StartsWith("#") -> (whitesp + 1, comment, code) //regions
| _ when s.StartsWith("//") -> (whitesp, comment + 1, code) //comments
| _ -> (whitesp, comment, code + 1)
List.fold_left innerloc (0,0,0) arr
```
|
I think what you have is fine, but here's some variety to mix it up. (This solution repeats your problem of ignoring trailing whitespace.)
```
type Line =
| Whitespace = 0
| Comment = 1
| Code = 2
let Classify (l:string) =
let s = l.TrimStart([|' ';'\t'|])
match s with
| "" | "{" | "}" -> Line.Whitespace
| _ when s.StartsWith("#") -> Line.Whitespace
| _ when s.StartsWith("//") -> Line.Comment
| _ -> Line.Code
let Loc (arr:list<_>) =
let sums = Array.create 3 0
arr
|> List.iter (fun line ->
let i = Classify line |> int
sums.[i] <- sums.[i] + 1)
sums
```
"Classify" as a separate entity might be useful in another context.
|
174,430 |
<p>I decided to use <a href="http://logging.apache.org/log4net/index.html" rel="noreferrer">log4net</a> as a logger for a new webservice project. Everything is working fine, but I get a lot of messages like the one below, for every log4net tag I am using in my <code>web.config</code>:</p>
<blockquote>
<p>Could not find schema information for
the element 'log4net'...</p>
</blockquote>
<p>Below are the relevant parts of my <code>web.config</code>:</p>
<pre class="lang-xml prettyprint-override"><code> <configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level: %message%newline" />
</layout>
</appender>
<logger name="TIMServerLog">
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</logger>
</log4net>
</code></pre>
<p>Solved:</p>
<ol>
<li>Copy every log4net specific tag to a separate <code>xml</code>-file. Make sure to use <code>.xml</code> as file extension.</li>
<li>Add the following line to <code>AssemblyInfo.cs</code>:</li>
</ol>
<pre class="lang-cs prettyprint-override"><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = "xmlFile.xml", Watch = true)]
</code></pre>
<p><a href="https://stackoverflow.com/users/20774/nemo">nemo</a> added:</p>
<blockquote>
<p>Just a word of warning to anyone
follow the advice of the answers in
this thread. There is a possible
security risk by having the log4net
configuration in an xml off the root
of the web service, as it will be
accessible to anyone by default. Just
be advised if your configuration
contains sensitive data, you may want
to put it else where.</p>
</blockquote>
<hr>
<p>@wcm: I tried using a separate file. I added the following line to <code>AssemblyInfo.cs</code></p>
<pre class="lang-cs prettyprint-override"><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
</code></pre>
<p>and put everything dealing with log4net in that file, but I still get the same messages.</p>
|
[
{
"answer_id": 174463,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried using a separate log4net.config file?</p>\n"
},
{
"answer_id": 174534,
"author": "Wheelie",
"author_id": 1131,
"author_profile": "https://Stackoverflow.com/users/1131",
"pm_score": 3,
"selected": false,
"text": "<p>I believe you are seeing the message because Visual Studio doesn't know how to validate the log4net section of the config file. You should be able to fix this by copying the log4net XSD into C:\\Program Files\\Microsoft Visual Studio 8\\XML\\Schemas (or wherever your Visual Studio is installed). As an added bonus you should now get intellisense support for log4net</p>\n"
},
{
"answer_id": 176119,
"author": "steve_mtl",
"author_id": 178,
"author_profile": "https://Stackoverflow.com/users/178",
"pm_score": 5,
"selected": true,
"text": "<p>I had a different take, and needed the following syntax:</p>\n<pre><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]\n</code></pre>\n<p>which differs from xsl's last post, but made a difference for me. Check out this <a href=\"https://web.archive.org/web/20160314225551/http://verysimple.com/2007/02/07/could-not-find-schema-information-for-the-element-log4net/\" rel=\"nofollow noreferrer\">blog post</a>, it helped me out.</p>\n"
},
{
"answer_id": 177500,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 2,
"selected": false,
"text": "<p>@steve_mtl: Changing the file extensions from <code>.config</code> to <code>.xml</code> solved the problem. Thank you.</p>\n\n<p>@Wheelie: I couldn't try your suggestion, because I needed a solution which works with an unmodified Visual Studio installation.</p>\n\n<hr>\n\n<p>To sum it up, here is how to solve the problem:</p>\n\n<ol>\n<li>Copy every log4net specific tag to a separate <code>xml</code>-file. Make sure to use <code>.xml</code> as file extension.</li>\n<li><p>Add the following line to <code>AssemblyInfo.cs</code>:</p>\n\n<p><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = \"xmlFile.xml\", Watch = true)]</code></p></li>\n</ol>\n"
},
{
"answer_id": 275197,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>You can bind in a schema to the <code>log4net</code> element. There are a few floating around, most do not fully provide for the various options available. I created the following xsd to provide as much verification as possible:\n<a href=\"http://csharptest.net/downloads/schema/log4net.xsd\" rel=\"noreferrer\">http://csharptest.net/downloads/schema/log4net.xsd</a></p>\n\n<p>You can bind it into the xml easily by modifying the <code>log4net</code> element:</p>\n\n<pre><code><log4net \n xsi:noNamespaceSchemaLocation=\"http://csharptest.net/downloads/schema/log4net.xsd\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n</code></pre>\n"
},
{
"answer_id": 315283,
"author": "James McMahon",
"author_id": 20774,
"author_profile": "https://Stackoverflow.com/users/20774",
"pm_score": 4,
"selected": false,
"text": "<p>Just a word of warning to anyone follow the advice of the answers in this thread. There is a possible security risk by having the log4net configuration in an xml off the root of the web service, as it will be accessible to anyone by default. Just be advised if your configuration contains sensitive data, you may want to put it else where.</p>\n"
},
{
"answer_id": 362127,
"author": "devstuff",
"author_id": 41321,
"author_profile": "https://Stackoverflow.com/users/41321",
"pm_score": 2,
"selected": false,
"text": "<p>For VS2008 just add the log4net.xsd file to your project; VS looks in the project folder as well as the installation directory that Wheelie mentioned.</p>\n\n<p>Also, using a .config extension instead of .xml avoids the security issue since IIS doesn't serve *.config files by default.</p>\n"
},
{
"answer_id": 1176561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Actually you don't need to stick to the .xml extension. You can specify any other extension in the ConfigFileExtension attribute:</p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = \"log4net.config\", ConfigFileExtension=\".config\", Watch = true)]\n</code></pre>\n"
},
{
"answer_id": 1212011,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I got a test asp project to build by puting the xsd file in the visual studio schemas folder as described above (for me it is C:\\Program Files\\Microsoft Visual Studio 8\\XML\\Schemas) and then making my <code>web.config</code> look like this:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version=\"1.0\"?>\n<!-- \n Note: As an alternative to hand editing this file you can use the \n web admin tool to configure settings for your application. Use\n the Website->Asp.Net Configuration option in Visual Studio.\n A full list of settings and comments can be found in \n machine.config.comments usually located in \n \\Windows\\Microsoft.Net\\Framework\\v2.x\\Config \n-->\n<configuration>\n <configSections>\n\n\n <section name=\"log4net\" \n type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net\"/>\n\n </configSections>\n <appSettings>\n\n </appSettings>\n <connectionStrings>\n\n </connectionStrings>\n <system.web>\n <trace enabled=\"true\" pageOutput=\"true\" />\n <!-- \n Set compilation debug=\"true\" to insert debugging \n symbols into the compiled page. Because this \n affects performance, set this value to true only \n during development.\n -->\n <compilation debug=\"true\" />\n <!--\n The <authentication> section enables configuration \n of the security authentication mode used by \n ASP.NET to identify an incoming user. \n -->\n <authentication mode=\"Windows\" />\n\n <customErrors mode=\"Off\"/>\n <!--\n <customErrors mode=\"Off\"/>\n\n The <customErrors> section enables configuration \n of what to do if/when an unhandled error occurs \n during the execution of a request. Specifically, \n it enables developers to configure html error pages \n to be displayed in place of a error stack trace.\n\n <customErrors mode=\"On\" defaultRedirect=\"GenericErrorPage.htm\">\n <error statusCode=\"403\" redirect=\"NoAccess.htm\" />\n <error statusCode=\"404\" redirect=\"FileNotFound.htm\" />\n </customErrors>\n -->\n\n\n\n\n\n </system.web>\n <log4net xsi:noNamespaceSchemaLocation=\"http://csharptest.net/downloads/schema/log4net.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n <appender name=\"LogFileAppender\" type=\"log4net.Appender.FileAppender\">\n <!-- Please make shure the ..\\\\Logs directory exists! -->\n <param name=\"File\" value=\"Logs\\\\Log4Net.log\"/>\n <!--<param name=\"AppendToFile\" value=\"true\"/>-->\n <layout type=\"log4net.Layout.PatternLayout\">\n <param name=\"ConversionPattern\" value=\"%d [%t] %-5p %c %m%n\"/>\n </layout>\n </appender>\n <appender name=\"SmtpAppender\" type=\"log4net.Appender.SmtpAppender\">\n <to value=\"\" />\n <from value=\"\" />\n <subject value=\"\" />\n <smtpHost value=\"\" />\n <bufferSize value=\"512\" />\n <lossy value=\"true\" />\n <evaluator type=\"log4net.Core.LevelEvaluator\">\n <threshold value=\"WARN\"/>\n </evaluator>\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%newline%date [%thread] %-5level %logger [%property] - %message%newline%newline%newline\" />\n </layout>\n </appender>\n\n <logger name=\"File\">\n <level value=\"ALL\" />\n <appender-ref ref=\"LogFileAppender\" />\n </logger>\n <logger name=\"EmailLog\">\n <level value=\"ALL\" />\n <appender-ref ref=\"SmtpAppender\" />\n </logger>\n </log4net>\n</configuration>\n</code></pre>\n"
},
{
"answer_id": 5226480,
"author": "Matt Enright",
"author_id": 2726,
"author_profile": "https://Stackoverflow.com/users/2726",
"pm_score": 0,
"selected": false,
"text": "<p>Without modifying your Visual Studio installation, and to take into account proper versioning/etc. amongst the rest of your team, add the .xsd file to your solution (as a 'Solution Item'), or if you only want it for a particular project, just embed it there.</p>\n"
},
{
"answer_id": 11780781,
"author": "Kit",
"author_id": 64348,
"author_profile": "https://Stackoverflow.com/users/64348",
"pm_score": 2,
"selected": false,
"text": "<p>In <a href=\"https://stackoverflow.com/a/275197/64348\">Roger's answer</a>, where he provided a schema, this worked very well for me except where a commenter mentioned</p>\n\n<blockquote>\n <p>This XSD is complaining about the use of custom appenders. It only allows for an appender from the default set (defined as an enum) instead of simply making this a string field</p>\n</blockquote>\n\n<p>I modified the original schema which had a <code>xs:simpletype</code> named <code>log4netAppenderTypes</code> and removed the enumerations. I instead restricted it to a basic .NET typing pattern (I say basic because it just supports <strong>typename</strong> only, or <strong>typename, assembly</strong> -- however someone can extend it.</p>\n\n<p>Simply replace the <code>log4netAppenderTypes</code> definition with the following in the XSD:</p>\n\n<pre><code><xs:simpleType name=\"log4netAppenderTypes\">\n <xs:restriction base=\"xs:string\">\n <xs:pattern value=\"[A-Za-z_]\\w*(\\.[A-Za-z_]\\w*)+(\\s*,\\s*[A-Za-z_]\\w*(\\.[A-Za-z_]\\w*)+)?\"/>\n </xs:restriction>\n</xs:simpleType>\n</code></pre>\n\n<p>I'm passing this back on to the original author if he wants to include it in his official version. Until then you'd have to download and modify the xsd and reference it in a relative manner, for example:</p>\n\n<pre><code><log4net\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:noNamespaceSchemaLocation=\"../../../Dependencies/log4net/log4net.xsd\">\n <!-- ... -->\n</log4net>\n</code></pre>\n"
},
{
"answer_id": 28528654,
"author": "Fysicus",
"author_id": 975748,
"author_profile": "https://Stackoverflow.com/users/975748",
"pm_score": 0,
"selected": false,
"text": "<p>I noticed it a bit late, but if you look into the examples log4net furnishes you can see them put all of the configuration data into an app.config, with one difference, the registration of configsection:</p>\n\n<pre><code><!-- Register a section handler for the log4net section -->\n<configSections>\n <section name=\"log4net\" type=\"System.Configuration.IgnoreSectionHandler\" />\n</configSections>\n</code></pre>\n\n<p>Could the definition it as type \"System.Configuration.IgnoreSectionHandler\" be the reason Visual Studio does not show any warning/error messages on the log4net stuff?</p>\n"
},
{
"answer_id": 42562811,
"author": "Volodymyr",
"author_id": 6139051,
"author_profile": "https://Stackoverflow.com/users/6139051",
"pm_score": 0,
"selected": false,
"text": "<p>I followed <a href=\"https://stackoverflow.com/users/64348/kit\">Kit</a>'s answer <a href=\"https://stackoverflow.com/a/11780781/6139051\">https://stackoverflow.com/a/11780781/6139051</a> and it didn't worked for AppenderType values like \"log4net.Appender.TraceAppender, log4net\". The log4net.dll assembly has the AssemblyTitle of \"log4net\", i.e. the assembly name does not have a dot inside, that was why the regex in Kit's answer didn't work. I has to add the question mark after the third parenthetical group in the regexp, and after that it worked flawlessly.</p>\n\n<p>The modified regex looks like the following:</p>\n\n<pre><code><xs:pattern value=\"[A-Za-z_]\\w*(\\.[A-Za-z_]\\w*)+(\\s*,\\s*[A-Za-z_]\\w*(\\.[A-Za-z_]\\w*)?+)?\"/>\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11387/"
] |
I decided to use [log4net](http://logging.apache.org/log4net/index.html) as a logger for a new webservice project. Everything is working fine, but I get a lot of messages like the one below, for every log4net tag I am using in my `web.config`:
>
> Could not find schema information for
> the element 'log4net'...
>
>
>
Below are the relevant parts of my `web.config`:
```xml
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level: %message%newline" />
</layout>
</appender>
<logger name="TIMServerLog">
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</logger>
</log4net>
```
Solved:
1. Copy every log4net specific tag to a separate `xml`-file. Make sure to use `.xml` as file extension.
2. Add the following line to `AssemblyInfo.cs`:
```cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "xmlFile.xml", Watch = true)]
```
[nemo](https://stackoverflow.com/users/20774/nemo) added:
>
> Just a word of warning to anyone
> follow the advice of the answers in
> this thread. There is a possible
> security risk by having the log4net
> configuration in an xml off the root
> of the web service, as it will be
> accessible to anyone by default. Just
> be advised if your configuration
> contains sensitive data, you may want
> to put it else where.
>
>
>
---
@wcm: I tried using a separate file. I added the following line to `AssemblyInfo.cs`
```cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
```
and put everything dealing with log4net in that file, but I still get the same messages.
|
I had a different take, and needed the following syntax:
```
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]
```
which differs from xsl's last post, but made a difference for me. Check out this [blog post](https://web.archive.org/web/20160314225551/http://verysimple.com/2007/02/07/could-not-find-schema-information-for-the-element-log4net/), it helped me out.
|
174,438 |
<p>I have two tables, <strong>Book</strong> and <strong>Tag</strong>, and books are tagged using the association table <strong>BookTag</strong>. I want to create a report that contains a list of books, and for each book a list of the book's tags. Tag IDs will suffice, tag names are not necessary.</p>
<p>Example:</p>
<pre><code>Book table:
Book ID | Book Name
28 | Dracula
BookTag table:
Book ID | Tag ID
28 | 101
28 | 102
</code></pre>
<p>In my report, I'd like to show that book #28 has the tags 101 and 102:</p>
<pre><code>Book ID | Book Name | Tags
28 | Dracula | 101, 102
</code></pre>
<p>Is there a way to do this in-line, without having to resort to functions or stored procedures? I am using SQL Server 2005.</p>
<p><em>Please note that the same question already has been asked in <a href="https://stackoverflow.com/questions/111341/combine-multiple-results-in-a-subquery-into-a-single-comma-separated-value">Combine multiple results in a subquery into a single comma-separated value</a>, but the solution involves creating a function. I am asking if there is a way to solve this without having to create a function or a stored procedure.</em></p>
|
[
{
"answer_id": 174466,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you know what the tag ids/names are and can hard code them into your query, I'm afraid the answer is no.</p>\n"
},
{
"answer_id": 174524,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>If you knew the maximum number of tags for a book, you could use a pivot to get them to the same row and then use COALESCE, but in general, I don't believe there is.</p>\n"
},
{
"answer_id": 174568,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 3,
"selected": true,
"text": "<p>You can almost do it. The only problem I haven't resolved is the comma delimiter. Here is a query on a similar structure that separates the tags using a space.</p>\n\n<pre><code>SELECT em.Code,\n (SELECT et.Name + ' ' AS 'data()'\n FROM tblEmployeeTag et\n JOIN tblEmployeeTagAssignment eta ON et.Id = eta.EmployeeTag_Id AND eta.Employee_Id = em.id\n FOR XML PATH('') ) AS Tags\nFROM tblEmployee em\n</code></pre>\n\n<p>Edit:</p>\n\n<p>Here is the complete version using your tables and using a comma delimiter:</p>\n\n<pre><code>SELECT bk.Id AS BookId,\n bk.Name AS BookName,\n REPLACE((SELECT LTRIM(STR(bt.TagId)) + ', ' AS 'data()'\n FROM BookTag bt\n WHERE bt.BookId = bk.Id \n FOR XML PATH('') ) + 'x', ', x','') AS Tags\nFROM Book bk\n</code></pre>\n\n<p>I suppose for future reference I should explain a bit about what is going on. The 'data()' column name is a special value that is related to the FOR XML PATH statement. It causes the XML document to be rendered as if you did an .InnerText on the root node of the resulting XML.<br>\nThe REPLACE statement is a trick to remove the trailing comma. By appending a unique character (I randomly chose 'x') to the end of the tag list I can search for comma-space-character and replace it with an empty string. That allows me to chop off just the last comma. This assumes that you are never going to have that sequence of characters in your tags.</p>\n"
},
{
"answer_id": 178773,
"author": "smerickson",
"author_id": 8807,
"author_profile": "https://Stackoverflow.com/users/8807",
"pm_score": 0,
"selected": false,
"text": "<p>The cleanest solution is probably to use a custom C# CLR aggregate function. We have found that this works really well. You can find instructions for creating this at <a href=\"http://dotnet-enthusiast.blogspot.com/2007/05/user-defined-aggregate-function-in-sql.html\" rel=\"nofollow noreferrer\">http://dotnet-enthusiast.blogspot.com/2007/05/user-defined-aggregate-function-in-sql.html</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6120/"
] |
I have two tables, **Book** and **Tag**, and books are tagged using the association table **BookTag**. I want to create a report that contains a list of books, and for each book a list of the book's tags. Tag IDs will suffice, tag names are not necessary.
Example:
```
Book table:
Book ID | Book Name
28 | Dracula
BookTag table:
Book ID | Tag ID
28 | 101
28 | 102
```
In my report, I'd like to show that book #28 has the tags 101 and 102:
```
Book ID | Book Name | Tags
28 | Dracula | 101, 102
```
Is there a way to do this in-line, without having to resort to functions or stored procedures? I am using SQL Server 2005.
*Please note that the same question already has been asked in [Combine multiple results in a subquery into a single comma-separated value](https://stackoverflow.com/questions/111341/combine-multiple-results-in-a-subquery-into-a-single-comma-separated-value), but the solution involves creating a function. I am asking if there is a way to solve this without having to create a function or a stored procedure.*
|
You can almost do it. The only problem I haven't resolved is the comma delimiter. Here is a query on a similar structure that separates the tags using a space.
```
SELECT em.Code,
(SELECT et.Name + ' ' AS 'data()'
FROM tblEmployeeTag et
JOIN tblEmployeeTagAssignment eta ON et.Id = eta.EmployeeTag_Id AND eta.Employee_Id = em.id
FOR XML PATH('') ) AS Tags
FROM tblEmployee em
```
Edit:
Here is the complete version using your tables and using a comma delimiter:
```
SELECT bk.Id AS BookId,
bk.Name AS BookName,
REPLACE((SELECT LTRIM(STR(bt.TagId)) + ', ' AS 'data()'
FROM BookTag bt
WHERE bt.BookId = bk.Id
FOR XML PATH('') ) + 'x', ', x','') AS Tags
FROM Book bk
```
I suppose for future reference I should explain a bit about what is going on. The 'data()' column name is a special value that is related to the FOR XML PATH statement. It causes the XML document to be rendered as if you did an .InnerText on the root node of the resulting XML.
The REPLACE statement is a trick to remove the trailing comma. By appending a unique character (I randomly chose 'x') to the end of the tag list I can search for comma-space-character and replace it with an empty string. That allows me to chop off just the last comma. This assumes that you are never going to have that sequence of characters in your tags.
|
174,446 |
<p>I have about 200 Excel files that are in standard Excel 2003 format. </p>
<p>I need them all to be saved as Excel xml - basically the same as opening each file and choosing <strong>Save As...</strong> and then choosing <strong>Save as type:</strong> <em>XML Spreadsheet</em></p>
<p>Would you know any simple way of automating that task?</p>
|
[
{
"answer_id": 174493,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>You could adapt the code I posted here:</p>\n\n<p><a href=\"http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/01/loading-office-documents-in-net.aspx\" rel=\"nofollow noreferrer\">http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/01/loading-office-documents-in-net.aspx</a></p>\n\n<p>It shows how to save as PDF (Word is shown in the blog, but if you download the solution, it has code for Excel and PPT).</p>\n\n<p>You need to find the function for saving as the new format instead of exporting (probably the easiest way is to record a macro of yourself doing it in Excel and then looking at the code).</p>\n"
},
{
"answer_id": 174581,
"author": "iafonov",
"author_id": 17308,
"author_profile": "https://Stackoverflow.com/users/17308",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way is to record macro for one file and then manually edit macros to do such actions for files in folder using loop. In macro you can use standart VB functions to get all files in directory and to filter them. You can look <a href=\"http://www.xtremevbtalk.com/archive/index.php/t-247211.html\" rel=\"nofollow noreferrer\">http://www.xtremevbtalk.com/archive/index.php/t-247211.html</a> for additional information.</p>\n"
},
{
"answer_id": 174587,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": false,
"text": "<p>Open them all up, and then press ALT+F11 to get to macro editor and enter something like:</p>\n\n<pre><code>Sub SaveAllAsXml()\n Dim wbk As Workbook\n For Each wbk In Application.Workbooks\n wbk.SaveAs FileFormat:=XlFileFormat.xlXMLSpreadsheet\n Next\nEnd Sub\n</code></pre>\n\n<p>And then press F5 to run it. May need some tweaking as I haven't tested it.</p>\n"
},
{
"answer_id": 176266,
"author": "BKimmel",
"author_id": 13776,
"author_profile": "https://Stackoverflow.com/users/13776",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like a job for my favorite-most-underrated language of all time: VBScript!!<br><br>Put this in a text file, and make the extension \".vbs\":</p>\n\n<pre><code>set xlapp = CreateObject(\"Excel.Application\")\nset fso = CreateObject(\"scripting.filesystemobject\")\nset myfolder = fso.GetFolder(\"YOURFOLDERPATHHERE\")\nset myfiles = myfolder.Files\nfor each f in myfiles\n set mybook = xlapp.Workbooks.Open(f.Path)\n mybook.SaveAs f.Name & \".xml\", 47\n mybook.Close\nnext\n</code></pre>\n\n<p>I haven't tested this, but it should work</p>\n"
},
{
"answer_id": 176608,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 4,
"selected": true,
"text": "<p>Here is a routine that will convert all files in a single directory that have a .xls extension.</p>\n\n<p>It takes a straight forward approach. Any VBA code in a workbook is stripped out, the workbook is not saved with a .xlsm extension. Any incompatability warning are not dislayed, instead the changes are automatically accepted.</p>\n\n<pre><code>Sub Convert_xls_Files()\n\nDim strFile As String\nDim strPath As String\n\n With Application\n .EnableEvents = False\n .DisplayAlerts = False\n .ScreenUpdating = False\n End With\n'Turn off events, alerts & screen updating\n\n strPath = \"C:\\temp\\excel\\\"\n strFile = Dir(strPath & \"*.xls\")\n'Change the path as required\n\n Do While strFile <> \"\"\n Workbooks.Open (strPath & strFile)\n strFile = Mid(strFile, 1, Len(strFile) - 4) & \".xlsx\"\n ActiveWorkbook.SaveAs Filename:=strPath & strFile, FileFormat:=xlOpenXMLWorkbook\n ActiveWorkbook.Close True\n strFile = Dir\n Loop\n'Opens the Workbook, set the file name, save in new format and close workbook\n\n With Application\n .EnableEvents = True\n .DisplayAlerts = True\n .ScreenUpdating = True\n End With\n'Turn on events, alerts & screen updating\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 27525667,
"author": "Kishore Relangi",
"author_id": 1568699,
"author_profile": "https://Stackoverflow.com/users/1568699",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Const xlXLSX = 51\n\nREM 51 = xlOpenXMLWorkbook (without macro's in 2007-2013, xlsx)\nREM 52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2013, xlsm)\nREM 50 = xlExcel12 (Excel Binary Workbook in 2007-2013 with or without macro's, xlsb)\nREM 56 = xlExcel8 (97-2003 format in Excel 2007-2013, xls)\n\ndim args\ndim file\ndim sFile\nset args=wscript.arguments\n\ndim wshell\nSet wshell = CreateObject(\"WScript.Shell\")\n\nSet objExcel = CreateObject(\"Excel.Application\")\n\nSet objWorkbook = objExcel.Workbooks.Open( wshell.CurrentDirectory&\"\\\"&args(0))\n\nobjExcel.DisplayAlerts = FALSE\n\nobjExcel.Visible = FALSE\n\nobjWorkbook.SaveAs wshell.CurrentDirectory&\"\\\"&args(1), xlXLSX\n\nobjExcel.Quit\n\nWscript.Quit\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3241/"
] |
I have about 200 Excel files that are in standard Excel 2003 format.
I need them all to be saved as Excel xml - basically the same as opening each file and choosing **Save As...** and then choosing **Save as type:** *XML Spreadsheet*
Would you know any simple way of automating that task?
|
Here is a routine that will convert all files in a single directory that have a .xls extension.
It takes a straight forward approach. Any VBA code in a workbook is stripped out, the workbook is not saved with a .xlsm extension. Any incompatability warning are not dislayed, instead the changes are automatically accepted.
```
Sub Convert_xls_Files()
Dim strFile As String
Dim strPath As String
With Application
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
End With
'Turn off events, alerts & screen updating
strPath = "C:\temp\excel\"
strFile = Dir(strPath & "*.xls")
'Change the path as required
Do While strFile <> ""
Workbooks.Open (strPath & strFile)
strFile = Mid(strFile, 1, Len(strFile) - 4) & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strPath & strFile, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close True
strFile = Dir
Loop
'Opens the Workbook, set the file name, save in new format and close workbook
With Application
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
End With
'Turn on events, alerts & screen updating
End Sub
```
|
174,458 |
<p>There is <a href="https://stackoverflow.com/questions/134698/catching-exceptions-as-expected-program-execution-flow-control">an interesting post over here</a> about this, in relation to cross-application flow of control. </p>
<p>Well, recently, I've come across an interesting problem. Generating the nth value in a potentially (practically) endless recursive sequence. This particular algorithm WILL be in atleast 10-15 stack references deep at the point that it succeeds. My first thought was to throw a SuccessException that looked something like this (C#):</p>
<pre><code>class SuccessException : Exception
{
public string Value
{ get; set; }
public SuccessException(string value)
: base()
{
Value = value;
}
}
</code></pre>
<p>Then do something like this:</p>
<pre><code>try
{
Walk_r(tree);
}
catch (SuccessException ex)
{
result = ex.Value;
}
</code></pre>
<p>Then my thoughts wandered back here, where I've heard over and over to never use Exceptions for flow control. Is there ever an excuse? And how would you structure something like this, if you were to implement it?</p>
|
[
{
"answer_id": 174469,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 4,
"selected": true,
"text": "<p>In this case I would be looking at your Walk_r method, you should have something that returns a value, throwing an exception to indicate success, is NOT a common practice, and at minimum is going to be VERY confusing to anyone that sees the code. Not to mention the overhead associated with exceptions.</p>\n"
},
{
"answer_id": 174487,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 0,
"selected": false,
"text": "<p>It's not a very good idea to throw exceptions as a part of an algorithm, especially in .net. In some languages/platforms, exceptions are pretty efficient when thrown, and they usually are, when an iterable gets exhausted for instance.</p>\n"
},
{
"answer_id": 174495,
"author": "schonarth",
"author_id": 22116,
"author_profile": "https://Stackoverflow.com/users/22116",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just return the resulting value? If it returns anything at all, assume it is successful. If it fails to return a value, then it means the loop failed.</p>\n\n<p>If you must bring back from a failure, then I'd recommend you throw an exception.</p>\n"
},
{
"answer_id": 174499,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>The issue with using exceptions is that tey (in the grand scheme of things) are very inefficient and slow. It would surely be as easy to have a if condition within the recursive function to just return as and when needed. To be honest, with the amount of memory on modern PC's its unlikely (not impossible though) that you'll get a stack overflow with only a small number of recursive calls (<100).</p>\n\n<p>If the stack is a real issue, then it might become necessary to be 'creative' and implement a 'depth limited search strategy', allow the function to return from the recursion and restart the search from the last (deepest) node.</p>\n\n<p>To sum up: Exceptions should only be used in exceptional circumstances, the success of a function call i don't believe qualifies as such.</p>\n"
},
{
"answer_id": 174511,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 0,
"selected": false,
"text": "<p>Using exceptions in normal program flow in my book is one of the worst practises ever.\nConsider the poor sap who is hunting for swallowed exceptions and is running a debugger set to stop whenever an exception happens. That dude is now getting mad.... and he has an axe. :P</p>\n"
},
{
"answer_id": 174513,
"author": "Robin",
"author_id": 21925,
"author_profile": "https://Stackoverflow.com/users/21925",
"pm_score": 1,
"selected": false,
"text": "<p>walk_r should simply return the value when it is hit. It's is a pretty standard recursion example. The only potential problem I see is that you said it is potentially endless, which will have to be compensated for in the walk_r code by keeping count of the recursion depth and stopping at some maximum value. </p>\n\n<p>The exception actually makes the coding very strange since the method call now throws an exception to return the value, instead of simply returning 'normally'.</p>\n\n<pre><code>try\n{\n Walk_r(tree);\n}\ncatch (SuccessException ex)\n{\n result = ex.Value;\n}\n</code></pre>\n\n<p>becomes </p>\n\n<pre><code>result = Walk_r(tree);\n</code></pre>\n"
},
{
"answer_id": 174641,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 1,
"selected": false,
"text": "<p>I'm going to play devil's advocate here and say stick with the exception to indicate success. It might be expensive to throw/catch but that may be insignificant compared with the cost of the search itself and possibly less confusing than an early exit from the method.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
There is [an interesting post over here](https://stackoverflow.com/questions/134698/catching-exceptions-as-expected-program-execution-flow-control) about this, in relation to cross-application flow of control.
Well, recently, I've come across an interesting problem. Generating the nth value in a potentially (practically) endless recursive sequence. This particular algorithm WILL be in atleast 10-15 stack references deep at the point that it succeeds. My first thought was to throw a SuccessException that looked something like this (C#):
```
class SuccessException : Exception
{
public string Value
{ get; set; }
public SuccessException(string value)
: base()
{
Value = value;
}
}
```
Then do something like this:
```
try
{
Walk_r(tree);
}
catch (SuccessException ex)
{
result = ex.Value;
}
```
Then my thoughts wandered back here, where I've heard over and over to never use Exceptions for flow control. Is there ever an excuse? And how would you structure something like this, if you were to implement it?
|
In this case I would be looking at your Walk\_r method, you should have something that returns a value, throwing an exception to indicate success, is NOT a common practice, and at minimum is going to be VERY confusing to anyone that sees the code. Not to mention the overhead associated with exceptions.
|
174,502 |
<p>Seeing as Java doesn't have nullable types, nor does it have a TryParse(),
how do you handle input validation without throwing an exceptions?</p>
<p>The usual way:</p>
<pre><code>String userdata = /*value from gui*/
int val;
try
{
val = Integer.parseInt(userdata);
}
catch (NumberFormatException nfe)
{
// bad data - set to sentinel
val = Integer.MIN_VALUE;
}
</code></pre>
<p>I could use a regex to check if it's parseable, but that seems like a lot of overhead as well.</p>
<p>What's the best practice for handling this situation?</p>
<p>EDIT: Rationale:
There's been a lot of talk on SO about exception handling, and the general attitude is that exceptions should be used for unexpected scenarios only. However, I think bad user input is EXPECTED, not rare. Yes, it really is an academic point.</p>
<p>Further Edits: </p>
<p>Some of the answers demonstrate exactly what is wrong with SO. You ignore the question being asked, and answer another question that has nothing to do with it. The question isn't asking about transition between layers. The question isn't asking what to return if the number is un-parseable. For all you know, val = Integer.MIN_VALUE; is exactly the right option for the application that this completely context free code snippet was take from.</p>
|
[
{
"answer_id": 174519,
"author": "arinte",
"author_id": 22763,
"author_profile": "https://Stackoverflow.com/users/22763",
"pm_score": -1,
"selected": false,
"text": "<p>Put some if statements in front of it.\nif (null != userdata )</p>\n"
},
{
"answer_id": 174523,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 5,
"selected": true,
"text": "<p>That's pretty much it, although returning MIN_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.</p>\n\n<p>Might also be useful (depending on the application) to log the bad input so you can trace.</p>\n"
},
{
"answer_id": 174525,
"author": "Shimi Bandiel",
"author_id": 15100,
"author_profile": "https://Stackoverflow.com/users/15100",
"pm_score": 1,
"selected": false,
"text": "<p>I think the best practice is the code you show.</p>\n\n<p>I wouldn't go for the regex alternative because of the overhead.</p>\n"
},
{
"answer_id": 174526,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 4,
"selected": false,
"text": "<p>What's the problem with your approach? I don't think doing it that way will hurt your application's performance at all. That's the correct way to do it. <strong>Don't optimize prematurely</strong>.</p>\n"
},
{
"answer_id": 174558,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 3,
"selected": false,
"text": "<p>I'm sure it is bad form, but I have a set of static methods on a Utilities class that do things like <code>Utilities.tryParseInt(String value)</code> which returns 0 if the String is unparseable and <code>Utilities.tryParseInt(String value, int defaultValue)</code> which allows you to specify a value to use if <code>parseInt()</code> throws an exception.</p>\n\n<p>I believe there are times when returning a known value on bad input is perfectly acceptable. A very contrived example: you ask the user for a date in the format YYYYMMDD and they give you bad input. It may be perfectly acceptable to do something like <code>Utilities.tryParseInt(date, 19000101)</code> or <code>Utilities.tryParseInt(date, 29991231);</code> depending on the program requirements.</p>\n"
},
{
"answer_id": 174566,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a Integer, which can be set to null if you have a bad value. If you are using java 1.6, it will provide auto boxing/unboxing for you.</p>\n"
},
{
"answer_id": 174644,
"author": "mjlee",
"author_id": 2829,
"author_profile": "https://Stackoverflow.com/users/2829",
"pm_score": -1,
"selected": false,
"text": "<p>The above code is bad because it is equivalent as the following. </p>\n\n<pre><code>// this is bad\nint val = Integer.MIN_VALUE;\ntry\n{\n val = Integer.parseInt(userdata);\n}\ncatch (NumberFormatException ignoreException) { }\n</code></pre>\n\n<p>The exception is ignored completely. Also, the magic token is bad because an user can pass in -2147483648 (Integer.MIN_VALUE).</p>\n\n<p>The generic parse-able question is not beneficial. Rather, it should be relevant to the context. Your application has a specific requirement. You can define your method as</p>\n\n<pre><code>private boolean isUserValueAcceptable(String userData)\n{\n return ( isNumber(userData) \n && isInteger(userData) \n && isBetween(userData, Integer.MIN_VALUE, Integer.MAX_VALUE ) \n );\n}\n</code></pre>\n\n<p>Where you can documentation the requirement and you can create well defined and testable rules.</p>\n"
},
{
"answer_id": 174666,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "<p>For user supplied data, Integer.parseInt is usually the wrong method because it doesn't support internationisation. The <code>java.text</code> package is your (verbose) friend.</p>\n\n<pre><code>try {\n NumberFormat format = NumberFormat.getIntegerInstance(locale);\n format.setParseIntegerOnly(true);\n format.setMaximumIntegerDigits(9);\n ParsePosition pos = new ParsePosition(0);\n int val = format.parse(str, pos).intValue();\n if (pos.getIndex() != str.length()) {\n // ... handle case of extraneous characters after digits ...\n }\n // ... use val ...\n} catch (java.text.ParseFormatException exc) {\n // ... handle this case appropriately ...\n}\n</code></pre>\n"
},
{
"answer_id": 174696,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how I do it:</p>\n\n<pre><code>public Integer parseInt(String data) {\n Integer val = null;\n try {\n val = Integer.parseInt(userdata);\n } catch (NumberFormatException nfe) { }\n return val;\n}\n</code></pre>\n\n<p>Then the null signals invalid data. If you want a default value, you could change it to:</p>\n\n<pre><code>public Integer parseInt(String data,int default) {\n Integer val = default;\n try {\n val = Integer.parseInt(userdata);\n } catch (NumberFormatException nfe) { }\n return val;\n}\n</code></pre>\n"
},
{
"answer_id": 174919,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": -1,
"selected": false,
"text": "<p>If you can avoid exceptions by testing beforehand like you said (isParsable()) it might be better--but not all libraries were designed with that in mind.</p>\n\n<p>I used your trick and it sucks because stack traces on my embedded system are printed regardless of if you catch them or not :(</p>\n"
},
{
"answer_id": 175498,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": -1,
"selected": false,
"text": "<p>The exception mechanism is valuable, as it is the only way to get a status indicator in combination with a response value. Furthermore, the status indicator is standardized. If there is an error you get an exception. That way you don't have to think of an error indicator yourself. \nThe controversy is not so much with exceptions, but with Checked Exceptions (e.g. the ones you have to catch or declare).</p>\n\n<p>Personally I feel you picked one of the examples where exceptions are really valuable. It is a common problem the user enters the wrong value, and typically you will need to get back to the user for the correct value. You normally don't revert to the default value if you ask the user; that gives the user the impression his input matters. </p>\n\n<p>If you do not want to deal with the exception, just wrap it in a RuntimeException (or derived class) and it will allow you to ignore the exception in your code (and kill your application when it occurs; that's fine too sometimes).</p>\n\n<p>Some examples on how I would handle NumberFormat exceptions:\nIn web app configuration data:</p>\n\n<pre><code>loadCertainProperty(String propVal) {\n try\n {\n val = Integer.parseInt(userdata);\n return val;\n }\n catch (NumberFormatException nfe)\n { // RuntimeException need not be declared\n throw new RuntimeException(\"Property certainProperty in your configuration is expected to be \" +\n \" an integer, but was '\" + propVal + \"'. Please correct your \" +\n \"configuration and start again\");\n // After starting an enterprise application the sysadmin should always check availability\n // and can now correct the property value\n }\n}\n</code></pre>\n\n<p>In a GUI:</p>\n\n<pre><code>public int askValue() {\n // TODO add opt-out button; see Swing docs for standard dialog handling\n boolean valueOk = false;\n while(!valueOk) {\n try {\n String val = dialog(\"Please enter integer value for FOO\");\n val = Integer.parseInt(userdata);\n return val; \n } catch (NumberFormatException nfe) {\n // Ignoring this; I don't care how many typo's the customer makes\n }\n }\n}\n</code></pre>\n\n<p>In a web form: return the form to the user with a usefull error message and a chance to\ncorrect. Most frameworks offer a standardized way of validation.</p>\n"
},
{
"answer_id": 177186,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 2,
"selected": false,
"text": "<p>I'm going to restate the point that stinkyminky was making towards the bottom of the post:</p>\n\n<p>A generally well accepted approach validating user input (or input from config files, etc...) is to use validation prior to actually processing the data. In <em>most</em> cases, this is a good design move, even though it can result in multiple calls to parsing algorithms.</p>\n\n<p>Once you know that you have properly validated the user input, <em>then</em> it is safe to parse it and ignore, log or convert to RuntimeException the NumberFormatException.</p>\n\n<p>Note that this approach requires you to consider your model in two pieces: the business model (Where we actually care about having values in int or float format) and the user interface model (where we really want to allow the user to put in whatever they want).</p>\n\n<p>In order for the data to migrate from the user interface model to the business model, it must pass through a validation step (this can occur on a field by field basis, but most scenarios call for validation on the entire object that is being configured).</p>\n\n<p>If validation fails, then the user is presented with feedback informing them of what they've done wrong and given a chance to fix it.</p>\n\n<p>Binding libraries like JGoodies Binding and JSR 295 make this sort of thing a lot easier to implement than it might sound - and many web frameworks provide constructs that separate user input from the actual business model, only populating business objects after validation is complete.</p>\n\n<p>In terms of validation of configuration files (the other use case presented in some of the comments), it's one thing to specify a default if a particular value isn't specified at all - but if the data is formatted wrong (someone types an 'oh' instead of a 'zero' - or they copied from MS Word and all the back-ticks got a funky unicode character), then some sort of system feedback is needed (even if it's just failing the app by throwing a runtime exception).</p>\n"
},
{
"answer_id": 4345423,
"author": "Andrej Fink",
"author_id": 252109,
"author_profile": "https://Stackoverflow.com/users/252109",
"pm_score": -1,
"selected": false,
"text": "<p>Integer.MIN_VALUE as NumberFormatException is bad idea.</p>\n\n<p>You can add proposal to Project Coin to add this method to Integer</p>\n\n<p>@Nullable public static Integer parseInteger (String src)...\nit will return null for bad input</p>\n\n<p>Then put link to your proposal here and we all will vote for it!</p>\n\n<p>PS: Look at this\n<a href=\"http://msdn.microsoft.com/en-us/library/bb397679.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb397679.aspx</a>\nthis is how ugly and bloated it could be</p>\n"
},
{
"answer_id": 13726535,
"author": "Zlosny",
"author_id": 186951,
"author_profile": "https://Stackoverflow.com/users/186951",
"pm_score": 1,
"selected": false,
"text": "<p>Try <code>org.apache.commons.lang.math.NumberUtils.createInteger(String s)</code>. That helped me a lot. There are similar methods there for doubles, longs etc.</p>\n"
},
{
"answer_id": 16699049,
"author": "Stephen Ostermiller",
"author_id": 1145388,
"author_profile": "https://Stackoverflow.com/users/1145388",
"pm_score": 5,
"selected": false,
"text": "<p>I asked <a href=\"https://stackoverflow.com/questions/16698647/java-library-that-has-parseint-parselong-parsedouble-etc-that-accept-default\">if there were open source utility libraries that had methods to do this parsing for you</a> and the answer is yes!</p>\n\n<p>From <a href=\"http://commons.apache.org/proper/commons-lang/\" rel=\"nofollow noreferrer\">Apache Commons Lang</a> you can use <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html#toInt%28java.lang.String,%20int%29\" rel=\"nofollow noreferrer\">NumberUtils.toInt</a>:</p>\n\n<pre><code>// returns defaultValue if the string cannot be parsed.\nint i = org.apache.commons.lang.math.NumberUtils.toInt(s, defaultValue);\n</code></pre>\n\n<p>From <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\">Google Guava</a> you can use <a href=\"https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Ints.html#tryParse(java.lang.String)\" rel=\"nofollow noreferrer\">Ints.tryParse</a>:</p>\n\n<pre><code>// returns null if the string cannot be parsed\n// Will throw a NullPointerException if the string is null\nInteger i = com.google.common.primitives.Ints.tryParse(s);\n</code></pre>\n\n<p>There is no need to write your own methods to parse numbers without throwing exceptions.</p>\n"
},
{
"answer_id": 45028739,
"author": "charles-allen",
"author_id": 2957169,
"author_profile": "https://Stackoverflow.com/users/2957169",
"pm_score": 0,
"selected": false,
"text": "<h1>Cleaner semantics (Java 8 OptionalInt)</h1>\n\n<p>For Java 8+, I would probably use RegEx to pre-filter (to avoid the exception as you noted) and then wrap the result in a primitive optional (to deal with the \"default\" problem):</p>\n\n<pre><code>public static OptionalInt toInt(final String input) {\n return input.matches(\"[+-]?\\\\d+\") \n ? OptionalInt.of(Integer.parseInt(input)) \n : OptionalInt.empty();\n}\n</code></pre>\n\n<p>If you have many String inputs, you might consider returning an <code>IntStream</code> instead of <code>OptionalInt</code> so that you can <code>flatMap()</code>.</p>\n\n<h1>References</h1>\n\n<ul>\n<li><em>RegEx based on <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#parseInt-java.lang.String-\" rel=\"nofollow noreferrer\">parseInt documentation</a></em></li>\n</ul>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18907/"
] |
Seeing as Java doesn't have nullable types, nor does it have a TryParse(),
how do you handle input validation without throwing an exceptions?
The usual way:
```
String userdata = /*value from gui*/
int val;
try
{
val = Integer.parseInt(userdata);
}
catch (NumberFormatException nfe)
{
// bad data - set to sentinel
val = Integer.MIN_VALUE;
}
```
I could use a regex to check if it's parseable, but that seems like a lot of overhead as well.
What's the best practice for handling this situation?
EDIT: Rationale:
There's been a lot of talk on SO about exception handling, and the general attitude is that exceptions should be used for unexpected scenarios only. However, I think bad user input is EXPECTED, not rare. Yes, it really is an academic point.
Further Edits:
Some of the answers demonstrate exactly what is wrong with SO. You ignore the question being asked, and answer another question that has nothing to do with it. The question isn't asking about transition between layers. The question isn't asking what to return if the number is un-parseable. For all you know, val = Integer.MIN\_VALUE; is exactly the right option for the application that this completely context free code snippet was take from.
|
That's pretty much it, although returning MIN\_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.
Might also be useful (depending on the application) to log the bad input so you can trace.
|
174,515 |
<p>I need to copy several tables from one DB to another in SQL Server 2000, using C# (VS 2005). The call needs to be parameterized - I need to be able to pass in the name of the database to which I am going to be copying these tables.</p>
<p>I could use DTS with parameters, but I can't find any sample code that does this from C#.</p>
<p>Alternatively, I could just use</p>
<pre><code>drop table TableName
select * into TableName from SourceDB..TableName
</code></pre>
<p>and then reconstruct the indexes etc - but that is <strong>really</strong> kludgy.</p>
<p>Any other ideas?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 174539,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<p>If the destination table is being dropped every time then why not do SELECT INTO? Doesn't seem like a kludge at all. </p>\n\n<p>If it works just fine and ticks all the requirements boxes why create a days worth of work growing code to do exactly the same thing?</p>\n\n<p>Let SQL do all the heavy lifting for you.</p>\n"
},
{
"answer_id": 174575,
"author": "Saif Khan",
"author_id": 23667,
"author_profile": "https://Stackoverflow.com/users/23667",
"pm_score": 1,
"selected": false,
"text": "<p>You could put the scripts (copy db) found here</p>\n\n<p><a href=\"http://www.codeproject.com/KB/database/CreateDatabaseScript.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/database/CreateDatabaseScript.aspx</a></p>\n\n<p>Into an application. Just replace the destination. To actually move the entite database, FOLLOW</p>\n\n<p><a href=\"http://support.microsoft.com/kb/314546\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/314546</a></p>\n\n<p>But remember, the database has to be taken offline first.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 175062,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 3,
"selected": true,
"text": "<p>For SQL Server 7.0 and 2000, we have SQLDMO for this. For SQL Server 2005 there is SMO. This allows you do to pretty much everything related to administering the database, scripting objects, enumerating databases, and much more. This is better, IMO, than trying a \"roll your own\" approach.</p>\n\n<p>SQL 2000:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa274758(SQL.80).aspx\" rel=\"nofollow noreferrer\">Developing SQL-DMO Applications</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa276080(SQL.80).aspx\" rel=\"nofollow noreferrer\">Transfer Object</a></p>\n\n<p>SQL 2005:\nHere is the SMO main page:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms162169(SQL.90).aspx\" rel=\"nofollow noreferrer\">Microsoft SQL Server Management Objects (SMO)</a></p>\n\n<p>Here is the Transfer functionality:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms162563(SQL.90).aspx\" rel=\"nofollow noreferrer\">Transferring Data</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms162138(SQL.90).aspx\" rel=\"nofollow noreferrer\">How to: Transfer Schema and Data from One Database to Another in Visual Basic .NET</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7850/"
] |
I need to copy several tables from one DB to another in SQL Server 2000, using C# (VS 2005). The call needs to be parameterized - I need to be able to pass in the name of the database to which I am going to be copying these tables.
I could use DTS with parameters, but I can't find any sample code that does this from C#.
Alternatively, I could just use
```
drop table TableName
select * into TableName from SourceDB..TableName
```
and then reconstruct the indexes etc - but that is **really** kludgy.
Any other ideas?
Thanks!
|
For SQL Server 7.0 and 2000, we have SQLDMO for this. For SQL Server 2005 there is SMO. This allows you do to pretty much everything related to administering the database, scripting objects, enumerating databases, and much more. This is better, IMO, than trying a "roll your own" approach.
SQL 2000:
[Developing SQL-DMO Applications](http://msdn.microsoft.com/en-us/library/aa274758(SQL.80).aspx)
[Transfer Object](http://msdn.microsoft.com/en-us/library/aa276080(SQL.80).aspx)
SQL 2005:
Here is the SMO main page:
[Microsoft SQL Server Management Objects (SMO)](http://msdn.microsoft.com/en-us/library/ms162169(SQL.90).aspx)
Here is the Transfer functionality:
[Transferring Data](http://msdn.microsoft.com/en-us/library/ms162563(SQL.90).aspx)
[How to: Transfer Schema and Data from One Database to Another in Visual Basic .NET](http://msdn.microsoft.com/en-us/library/ms162138(SQL.90).aspx)
|
174,516 |
<p>I have a table that records a sequence of actions with a field that records the sequence order:</p>
<pre><code>user data sequence
1 foo 0
1 bar 1
1 baz 2
2 foo 0
3 bar 0
3 foo 1
</code></pre>
<p>Selecting the first item for each user is easy enough with WHERE sequence = '0' but is there a way to select the last item for each user in SQL?</p>
<p>The result I am after should look like this:</p>
<pre><code>user data sequence
1 baz 2
2 foo 0
3 foo 1
</code></pre>
<p>I'm using MySQL if there are any implementation specific tricksters answering.</p>
|
[
{
"answer_id": 174537,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": true,
"text": "<p>This sql will return the record with the highest sequence value for each user:</p>\n\n<pre><code>select a.user, a.data, a.sequence\nfrom table as a\n inner join (\n select user, max(sequence) as 'last'\n from table \n group by user) as b\n on a.user = b.user and \n a.sequence = b.last\n</code></pre>\n"
},
{
"answer_id": 8088189,
"author": "plucka",
"author_id": 1040821,
"author_profile": "https://Stackoverflow.com/users/1040821",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select top 1 \n user\n ,data\n ,sequence\n from table\norder\n by sequence\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11651/"
] |
I have a table that records a sequence of actions with a field that records the sequence order:
```
user data sequence
1 foo 0
1 bar 1
1 baz 2
2 foo 0
3 bar 0
3 foo 1
```
Selecting the first item for each user is easy enough with WHERE sequence = '0' but is there a way to select the last item for each user in SQL?
The result I am after should look like this:
```
user data sequence
1 baz 2
2 foo 0
3 foo 1
```
I'm using MySQL if there are any implementation specific tricksters answering.
|
This sql will return the record with the highest sequence value for each user:
```
select a.user, a.data, a.sequence
from table as a
inner join (
select user, max(sequence) as 'last'
from table
group by user) as b
on a.user = b.user and
a.sequence = b.last
```
|
174,531 |
<p>What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string (char*, char[], whatever)?</p>
|
[
{
"answer_id": 174552,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 8,
"selected": true,
"text": "<p>I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.</p>\n\n<p>This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).</p>\n\n<pre><code>char * buffer = 0;\nlong length;\nFILE * f = fopen (filename, \"rb\");\n\nif (f)\n{\n fseek (f, 0, SEEK_END);\n length = ftell (f);\n fseek (f, 0, SEEK_SET);\n buffer = malloc (length);\n if (buffer)\n {\n fread (buffer, 1, length, f);\n }\n fclose (f);\n}\n\nif (buffer)\n{\n // start to process your data / extract strings here...\n}\n</code></pre>\n"
},
{
"answer_id": 174743,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 4,
"selected": false,
"text": "<p>If \"read its contents into a string\" means that the file does not contain characters with code 0, you can also use getdelim() function, that either accepts a block of memory and reallocates it if necessary, or just allocates the entire buffer for you, and reads the file into it until it encounters a specified delimiter or end of file. Just pass '\\0' as the delimiter to read the entire file.</p>\n\n<p>This function is available in the GNU C Library, <a href=\"http://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getdelim-994\" rel=\"noreferrer\">http://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getdelim-994</a></p>\n\n<p>The sample code might look as simple as</p>\n\n<pre><code>char* buffer = NULL;\nsize_t len;\nssize_t bytes_read = getdelim( &buffer, &len, '\\0', fp);\nif ( bytes_read != -1) {\n /* Success, now the entire file is in the buffer */\n</code></pre>\n"
},
{
"answer_id": 174808,
"author": "Jeff Mc",
"author_id": 25521,
"author_profile": "https://Stackoverflow.com/users/25521",
"pm_score": 5,
"selected": false,
"text": "<p>Another, unfortunately highly OS-dependent, solution is memory mapping the file. The benefits generally include performance of the read, and reduced memory use as the applications view and operating systems file cache can actually share the physical memory.</p>\n\n<p>POSIX code would look like this:</p>\n\n<pre><code>int fd = open(\"filename\", O_RDONLY);\nint len = lseek(fd, 0, SEEK_END);\nvoid *data = mmap(0, len, PROT_READ, MAP_PRIVATE, fd, 0);\n</code></pre>\n\n<p>Windows on the other hand is little more tricky, and unfortunately I don't have a compiler in front of me to test, but the functionality is provided by <code>CreateFileMapping()</code> and <code>MapViewOfFile()</code>.</p>\n"
},
{
"answer_id": 184907,
"author": "selwyn",
"author_id": 16314,
"author_profile": "https://Stackoverflow.com/users/16314",
"pm_score": 2,
"selected": false,
"text": "<p>If the file is text, and you want to get the text line by line, the easiest way is to use fgets().</p>\n\n<pre><code>char buffer[100];\nFILE *fp = fopen(\"filename\", \"r\"); // do not use \"rb\"\nwhile (fgets(buffer, sizeof(buffer), fp)) {\n... do something\n}\nfclose(fp);\n</code></pre>\n"
},
{
"answer_id": 20179997,
"author": "Jake",
"author_id": 498804,
"author_profile": "https://Stackoverflow.com/users/498804",
"pm_score": 3,
"selected": false,
"text": "<p>If you are reading special files like stdin or a pipe, you are not going to be able to use fstat to get the file size beforehand. Also, if you are reading a binary file fgets is going to lose the string size information because of embedded '\\0' characters. Best way to read a file then is to use read and realloc:</p>\n\n<pre><code>#include <stdio.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n\nint main () {\n char buf[4096];\n ssize_t n;\n char *str = NULL;\n size_t len = 0;\n while (n = read(STDIN_FILENO, buf, sizeof buf)) {\n if (n < 0) {\n if (errno == EAGAIN)\n continue;\n perror(\"read\");\n break;\n }\n str = realloc(str, len + n + 1);\n memcpy(str + len, buf, n);\n len += n;\n str[len] = '\\0';\n }\n printf(\"%.*s\\n\", len, str);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 37241679,
"author": "Entalpi",
"author_id": 1548601,
"author_profile": "https://Stackoverflow.com/users/1548601",
"pm_score": 1,
"selected": false,
"text": "<pre><code>// Assumes the file exists and will seg. fault otherwise.\nconst GLchar *load_shader_source(char *filename) {\n FILE *file = fopen(filename, \"r\"); // open \n fseek(file, 0L, SEEK_END); // find the end\n size_t size = ftell(file); // get the size in bytes\n GLchar *shaderSource = calloc(1, size); // allocate enough bytes\n rewind(file); // go back to file beginning\n fread(shaderSource, size, sizeof(char), file); // read each char into ourblock\n fclose(file); // close the stream\n return shaderSource;\n}\n</code></pre>\n\n<p>This is a pretty crude solution because nothing is checked against null. </p>\n"
},
{
"answer_id": 39915037,
"author": "sleepycal",
"author_id": 1267398,
"author_profile": "https://Stackoverflow.com/users/1267398",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using <code>glib</code>, then you can use <a href=\"https://developer.gnome.org/glib/stable/glib-File-Utilities.html#g-file-get-contents\" rel=\"nofollow\">g_file_get_contents</a>;</p>\n\n<pre><code>gchar *contents;\nGError *err = NULL;\n\ng_file_get_contents (\"foo.txt\", &contents, NULL, &err);\ng_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));\nif (err != NULL)\n {\n // Report error to user, and free error\n g_assert (contents == NULL);\n fprintf (stderr, \"Unable to read file: %s\\n\", err->message);\n g_error_free (err);\n }\nelse\n {\n // Use file contents\n g_assert (contents != NULL);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47195924,
"author": "BaiJiFeiLong",
"author_id": 5254103,
"author_profile": "https://Stackoverflow.com/users/5254103",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Just modified from the accepted answer above.</strong></p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n\nchar *readFile(char *filename) {\n FILE *f = fopen(filename, \"rt\");\n assert(f);\n fseek(f, 0, SEEK_END);\n long length = ftell(f);\n fseek(f, 0, SEEK_SET);\n char *buffer = (char *) malloc(length + 1);\n buffer[length] = '\\0';\n fread(buffer, 1, length, f);\n fclose(f);\n return buffer;\n}\n\nint main() {\n char *content = readFile(\"../hello.txt\");\n printf(\"%s\", content);\n}\n</code></pre>\n"
},
{
"answer_id": 54057690,
"author": "Joe Cool",
"author_id": 7428740,
"author_profile": "https://Stackoverflow.com/users/7428740",
"pm_score": 3,
"selected": false,
"text": "<p>Note: This is a modification of the accepted answer above.</p>\n<p>Here's a way to do it, complete with error checking.</p>\n<p>I've added a size checker to quit when file was bigger than 1 GiB. I did this because the program puts the whole file into a string which may use too much ram and crash a computer. However, if you don't care about that you could just remove it from the code.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <stdlib.h>\n\n#define FILE_OK 0\n#define FILE_NOT_EXIST 1\n#define FILE_TOO_LARGE 2\n#define FILE_READ_ERROR 3\n\nchar * c_read_file(const char * f_name, int * err, size_t * f_size) {\n char * buffer;\n size_t length;\n FILE * f = fopen(f_name, "rb");\n size_t read_length;\n \n if (f) {\n fseek(f, 0, SEEK_END);\n length = ftell(f);\n fseek(f, 0, SEEK_SET);\n \n // 1 GiB; best not to load a whole large file in one string\n if (length > 1073741824) {\n *err = FILE_TOO_LARGE;\n \n return NULL;\n }\n \n buffer = (char *)malloc(length + 1);\n \n if (length) {\n read_length = fread(buffer, 1, length, f);\n \n if (length != read_length) {\n free(buffer);\n *err = FILE_READ_ERROR;\n\n return NULL;\n }\n }\n \n fclose(f);\n \n *err = FILE_OK;\n buffer[length] = '\\0';\n *f_size = length;\n }\n else {\n *err = FILE_NOT_EXIST;\n \n return NULL;\n }\n \n return buffer;\n}\n</code></pre>\n<p>And to check for errors:</p>\n<pre class=\"lang-c prettyprint-override\"><code>int err;\nsize_t f_size;\nchar * f_data;\n\nf_data = c_read_file("test.txt", &err, &f_size);\n\nif (err) {\n // process error\n}\nelse {\n // process data\n free(f_data);\n}\n</code></pre>\n"
},
{
"answer_id": 56924271,
"author": "Erik Campobadal",
"author_id": 8280247,
"author_profile": "https://Stackoverflow.com/users/8280247",
"pm_score": 0,
"selected": false,
"text": "<p>I will add my own version, based on the answers here, just for reference. My code takes into consideration sizeof(char) and adds a few comments to it.</p>\n\n<pre><code>// Open the file in read mode.\nFILE *file = fopen(file_name, \"r\");\n// Check if there was an error.\nif (file == NULL) {\n fprintf(stderr, \"Error: Can't open file '%s'.\", file_name);\n exit(EXIT_FAILURE);\n}\n// Get the file length\nfseek(file, 0, SEEK_END);\nlong length = ftell(file);\nfseek(file, 0, SEEK_SET);\n// Create the string for the file contents.\nchar *buffer = malloc(sizeof(char) * (length + 1));\nbuffer[length] = '\\0';\n// Set the contents of the string.\nfread(buffer, sizeof(char), length, file);\n// Close the file.\nfclose(file);\n// Do something with the data.\n// ...\n// Free the allocated string space.\nfree(buffer);\n</code></pre>\n"
},
{
"answer_id": 57511398,
"author": "Ahmed Ibrahim El Gendy",
"author_id": 7396930,
"author_profile": "https://Stackoverflow.com/users/7396930",
"pm_score": -1,
"selected": false,
"text": "<p>easy and neat(assuming contents in the file are less than 10000):</p>\n\n<pre><code>void read_whole_file(char fileName[1000], char buffer[10000])\n{\n FILE * file = fopen(fileName, \"r\");\n if(file == NULL)\n {\n puts(\"File not found\");\n exit(1);\n }\n char c;\n int idx=0;\n while (fscanf(file , \"%c\" ,&c) == 1)\n {\n buffer[idx] = c;\n idx++;\n }\n buffer[idx] = 0;\n}\n</code></pre>\n"
},
{
"answer_id": 70409447,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p>What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string ...?</p>\n</blockquote>\n<p>Sadly, even after years, answers are error prone and many lack proper <em>string</em> formation and error checking.</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\n// Read the file into allocated memory.\n// Return NULL on error.\nchar* readfile(FILE *f) {\n // f invalid? fseek() fail?\n if (f == NULL || fseek(f, 0, SEEK_END)) {\n return NULL;\n }\n\n long length = ftell(f);\n rewind(f);\n // Did ftell() fail? Is the length too long?\n if (length == -1 || (unsigned long) length >= SIZE_MAX) {\n return NULL;\n }\n\n // Convert from long to size_t\n size_t ulength = (size_t) length;\n char *buffer = malloc(ulength + 1);\n // Allocation failed? Read incomplete?\n if (buffer == NULL || fread(buffer, 1, ulength, f) != ulength) {\n free(buffer);\n return NULL;\n }\n buffer[ulength] = '\\0'; // Now buffer points to a string\n\n return buffer;\n}\n</code></pre>\n<p>Note that if the text file contains <em>null characters</em>, the allocated data will contain all the file data, yet the string will appear to be short. Better code would also return the length information so the caller can handle that.</p>\n<pre><code>char* readfile(FILE *f, size_t *ulength_ptr) {\n ...\n if (ulength_ptr) *ulength_ptr == *ulength;\n ...\n} \n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string (char\*, char[], whatever)?
|
I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.
This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).
```
char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
if (buffer)
{
// start to process your data / extract strings here...
}
```
|
174,532 |
<p>I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1*1000 + Part2).<br>
I normalized that column, but I cannot change the old values.
So now I have</p>
<pre><code>select ID from table order by ID
ID
100001
100002
101001
...
</code></pre>
<p>I want to find the "holes" in the table (more precisely, the first "hole" after 100000) for new rows.<br>
I'm using the following select, but is there a better way to do that?</p>
<pre><code>select /* top 1 */ ID+1 as newID from table
where ID > 100000 and
ID + 1 not in (select ID from table)
order by ID
newID
100003
101029
...
</code></pre>
<p>The database is Microsoft SQL Server 2000. I'm ok with using SQL extensions.</p>
|
[
{
"answer_id": 174561,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT (ID+1) FROM table AS t1\nLEFT JOIN table as t2\nON t1.ID+1 = t2.ID\nWHERE t2.ID IS NULL\n</code></pre>\n"
},
{
"answer_id": 176219,
"author": "Thorsten",
"author_id": 25320,
"author_profile": "https://Stackoverflow.com/users/25320",
"pm_score": 5,
"selected": true,
"text": "<pre><code>select ID +1 From Table t1\nwhere not exists (select * from Table t2 where t1.id +1 = t2.id);\n</code></pre>\n\n<p>not sure if this version would be faster than the one you mentioned originally.</p>\n"
},
{
"answer_id": 210675,
"author": "Jeff Jones",
"author_id": 22391,
"author_profile": "https://Stackoverflow.com/users/22391",
"pm_score": 4,
"selected": false,
"text": "<p>This solution should give you the first and last ID values of the \"holes\" you are seeking. I use this in Firebird 1.5 on a table of 500K records, and although it does take a little while, it gives me what I want.</p>\n\n<pre><code>SELECT l.id + 1 start_id, MIN(fr.id) - 1 stop_id\nFROM (table l\nLEFT JOIN table r\nON l.id = r.id - 1)\nLEFT JOIN table fr\nON l.id < fr.id\nWHERE r.id IS NULL AND fr.id IS NOT NULL\nGROUP BY l.id, r.id\n</code></pre>\n\n<p>For example, if your data looks like this:</p>\n\n<pre><code>ID\n1001\n1002\n1005\n1006\n1007\n1009\n1011\n</code></pre>\n\n<p>You would receive this:</p>\n\n<pre><code>start_id stop_id\n1003 1004\n1008 1008\n1010 1010\n</code></pre>\n\n<p>I wish I could take full credit for this solution, but I found it at <a href=\"http://www.xaprb.com/blog/2005/12/06/find-missing-numbers-in-a-sequence-with-sql/\" rel=\"noreferrer\">Xaprb</a>.</p>\n"
},
{
"answer_id": 2317619,
"author": "Zeljko Vlasic",
"author_id": 279397,
"author_profile": "https://Stackoverflow.com/users/279397",
"pm_score": 2,
"selected": false,
"text": "<p>This solution doesn't give all holes in table, only next free ones + first available max number on table - works if you want to fill in gaps in id-es, + get free id number if you don't have a gap..</p>\n<pre><code>select numb + 1 from temp\nminus\nselect numb from temp;\n</code></pre>\n"
},
{
"answer_id": 17432002,
"author": "Carter Medlin",
"author_id": 324479,
"author_profile": "https://Stackoverflow.com/users/324479",
"pm_score": 2,
"selected": false,
"text": "<p>from <a href=\"https://stackoverflow.com/questions/1312101/how-to-find-a-gap-in-running-counter-with-sql/17431748#17431748\">How do I find a "gap" in running counter with SQL?</a></p>\n\n<pre><code>select\n MIN(ID)\nfrom (\n select\n 100001 ID\n union all\n select\n [YourIdColumn]+1\n from\n [YourTable]\n where\n --Filter the rest of your key--\n ) foo\nleft join\n [YourTable]\n on [YourIdColumn]=ID\n and --Filter the rest of your key--\nwhere\n [YourIdColumn] is null\n</code></pre>\n"
},
{
"answer_id": 20586130,
"author": "Fernando Reis Guimaraes",
"author_id": 2643058,
"author_profile": "https://Stackoverflow.com/users/2643058",
"pm_score": 2,
"selected": false,
"text": "<p>The best way is building a temp table with all IDs</p>\n\n<p>Than make a left join.</p>\n\n<pre><code>declare @maxId int\nselect @maxId = max(YOUR_COLUMN_ID) from YOUR_TABLE_HERE\n\n\ndeclare @t table (id int)\n\ndeclare @i int\nset @i = 1\n\nwhile @i <= @maxId\nbegin\n insert into @t values (@i)\n set @i = @i +1\nend\n\nselect t.id\nfrom @t t\nleft join YOUR_TABLE_HERE x on x.YOUR_COLUMN_ID = t.id\nwhere x.YOUR_COLUMN_ID is null\n</code></pre>\n"
},
{
"answer_id": 20856776,
"author": "user3149203",
"author_id": 3149203,
"author_profile": "https://Stackoverflow.com/users/3149203",
"pm_score": 1,
"selected": false,
"text": "<p>This will give you the complete picture, where <strong>'Bottom'</strong> stands for <strong>gap start</strong> and <strong>'Top'</strong> stands for <strong>gap end</strong>:</p>\n\n<pre><code> select *\n from \n ( \n (select <COL>+1 as id, 'Bottom' AS 'Pos' from <TABLENAME> /*where <CONDITION*/>\n except\n select <COL>, 'Bottom' AS 'Pos' from <TABLENAME> /*where <CONDITION>*/)\n union\n (select <COL>-1 as id, 'Top' AS 'Pos' from <TABLENAME> /*where <CONDITION>*/\n except\n select <COL>, 'Top' AS 'Pos' from <TABLENAME> /*where <CONDITION>*/)\n ) t\n order by t.id, t.Pos\n</code></pre>\n\n<p><strong>Note: First</strong> and <strong>Last</strong> results are <strong><em>WRONG</em></strong> and should not be regarded, but taking them out would make this query a lot more complicated, so this will do for now.</p>\n"
},
{
"answer_id": 33285657,
"author": "Denis Reznik",
"author_id": 3130226,
"author_profile": "https://Stackoverflow.com/users/3130226",
"pm_score": 2,
"selected": false,
"text": "<p>Have thought about this question recently, and looks like this is the most elegant way to do that:</p>\n\n<pre><code>SELECT TOP(@MaxNumber) ROW_NUMBER() OVER (ORDER BY t1.number) \nFROM master..spt_values t1 CROSS JOIN master..spt_values t2 \nEXCEPT\nSELECT Id FROM <your_table>\n</code></pre>\n"
},
{
"answer_id": 41195455,
"author": "pdenti",
"author_id": 993706,
"author_profile": "https://Stackoverflow.com/users/993706",
"pm_score": 1,
"selected": false,
"text": "<p>Many of the previous answer are quite good. However they all miss to return the first value of the sequence and/or miss to consider the lower limit 100000. They all returns intermediate holes but not the very first one (100001 if missing).</p>\n\n<p>A full solution to the question is the following one:</p>\n\n<pre><code>select id + 1 as newid from\n (select 100000 as id union select id from tbl) t\n where (id + 1 not in (select id from tbl)) and\n (id >= 100000)\n order by id\n limit 1;\n</code></pre>\n\n<p>The number 100000 is to be used if the first number of the sequence is 100001 (as in the original question); otherwise it is to be modified accordingly\n\"limit 1\" is used in order to have just the first available number instead of the full sequence</p>\n"
},
{
"answer_id": 46884832,
"author": "Xavier Dury",
"author_id": 599011,
"author_profile": "https://Stackoverflow.com/users/599011",
"pm_score": 1,
"selected": false,
"text": "<p>For people using Oracle, the following can be used:</p>\n\n<pre><code>select a, b from (\n select ID + 1 a, max(ID) over (order by ID rows between current row and 1 following) - 1 b from MY_TABLE\n) where a <= b order by a desc;\n</code></pre>\n"
},
{
"answer_id": 73123361,
"author": "Luca Rinaldi",
"author_id": 19625026,
"author_profile": "https://Stackoverflow.com/users/19625026",
"pm_score": 1,
"selected": false,
"text": "<p>The following SQL code works well with SqLite, but should be used without issues also on MySQL, MS SQL and so on.</p>\n<p>On SqLite this takes only 2 seconds on a table with 1 million rows (and about 100 spared missing rows)</p>\n<pre><code>WITH holes AS (\n SELECT \n IIF(c2.id IS NULL,c1.id+1,null) as start,\n IIF(c3.id IS NULL,c1.id-1,null) AS stop,\n ROW_NUMBER () OVER (\n ORDER BY c1.id ASC\n ) AS rowNum\n FROM |mytable| AS c1\n LEFT JOIN |mytable| AS c2 ON c1.id+1 = c2.id\n LEFT JOIN |mytable| AS c3 ON c1.id-1 = c3.id\n WHERE c2.id IS NULL OR c3.id IS NULL\n)\nSELECT h1.start AS start, h2.stop AS stop FROM holes AS h1\nLEFT JOIN holes AS h2 ON h1.rowNum+1 = h2.rowNum\nWHERE h1.start IS NOT NULL AND h2.stop IS NOT NULL\nUNION ALL \nSELECT 1 AS start, h1.stop AS stop FROM holes AS h1\nWHERE h1.rowNum = 1 AND h1.stop > 0\nORDER BY h1.start ASC\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25324/"
] |
I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1\*1000 + Part2).
I normalized that column, but I cannot change the old values.
So now I have
```
select ID from table order by ID
ID
100001
100002
101001
...
```
I want to find the "holes" in the table (more precisely, the first "hole" after 100000) for new rows.
I'm using the following select, but is there a better way to do that?
```
select /* top 1 */ ID+1 as newID from table
where ID > 100000 and
ID + 1 not in (select ID from table)
order by ID
newID
100003
101029
...
```
The database is Microsoft SQL Server 2000. I'm ok with using SQL extensions.
|
```
select ID +1 From Table t1
where not exists (select * from Table t2 where t1.id +1 = t2.id);
```
not sure if this version would be faster than the one you mentioned originally.
|
174,560 |
<p>How can you depend on test code from another module in Maven? </p>
<p>Example, I have 2 modules:</p>
<ul>
<li>Base</li>
<li>Main</li>
</ul>
<p>I would like a test case in Main to extend a base test class in Base. Is this possible?</p>
<p>Update: Found an <a href="https://stackoverflow.com/questions/174560/sharing-test-code-in-maven#174670">acceptable answer</a>, which involves creating a test jar.</p>
|
[
{
"answer_id": 174572,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": -1,
"selected": false,
"text": "<p>Yep ... just include the Base module as a dependency in Main. If you're only inheriting test code, then you can use the scope tag to make sure Maven doesn't include the code in your artifact when deployed. Something like this should work:</p>\n\n<pre><code><dependency>\n <groupId>BaseGroup</groupId>\n <artifactId>Base</artifactId>\n <version>0.1.0-SNAPSHOT</version>\n <scope>test</scope>\n</dependency>\n</code></pre>\n"
},
{
"answer_id": 174583,
"author": "sal",
"author_id": 13753,
"author_profile": "https://Stackoverflow.com/users/13753",
"pm_score": 4,
"selected": false,
"text": "<p>We solved this by making a maven project with test code as the src/main/java and adding the following dependency to projects:</p>\n\n<pre><code> <dependency>\n <groupId>foo</groupId>\n <artifactId>test-base</artifactId>\n <version>1</version>\n <scope>test</scope>\n </dependency>\n</code></pre>\n"
},
{
"answer_id": 174670,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 8,
"selected": false,
"text": "<p>Thanks for the base module suggestion. However, I'd rather not create a new module for just this purpose.</p>\n\n<p>Found an acceptable answer in the <a href=\"http://maven.apache.org/guides/mini/guide-attached-tests.html\" rel=\"noreferrer\">Surefire Maven documentation</a> and <a href=\"https://www.waltercedric.com/index.php?option=com_content&view=article&id=1349&catid=129&Itemid=332\" rel=\"noreferrer\">a blog</a>. See also \"<a href=\"https://maven.apache.org/plugins/maven-jar-plugin/examples/create-test-jar.html\" rel=\"noreferrer\">How to create a jar containing test classes</a>\".</p>\n\n<p>This creates jar file of code from <code>src/test/java</code> using the <a href=\"https://maven.apache.org/plugins/maven-jar-plugin/\" rel=\"noreferrer\">jar plugin</a> so that modules with tests can share code.</p>\n\n<pre><code><project>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-jar-plugin</artifactId>\n <version>2.4</version>\n <executions>\n <execution>\n <goals>\n <goal>test-jar</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>\n</code></pre>\n\n<p>In order to use the attached test JAR that was created above you simply specify a dependency on the main artifact with a specified classifier of tests:</p>\n\n<pre><code><project>\n ...\n <dependencies>\n <dependency>\n <groupId>com.myco.app</groupId>\n <artifactId>foo</artifactId>\n <version>1.0-SNAPSHOT</version>\n <type>test-jar</type>\n <scope>test</scope>\n </dependency>\n </dependencies>\n ...\n</project> \n</code></pre>\n"
},
{
"answer_id": 174937,
"author": "Ben",
"author_id": 24795,
"author_profile": "https://Stackoverflow.com/users/24795",
"pm_score": 9,
"selected": true,
"text": "<p>I recommend using <a href=\"https://maven.apache.org/pom.html#Dependencies\" rel=\"noreferrer\">type instead of classifier</a> (see also: <a href=\"http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html\" rel=\"noreferrer\">classifier</a>). It tells Maven a bit more explicitly what you are doing (and I've found that m2eclipse and q4e both like it better).</p>\n\n<pre><code><dependency>\n <groupId>com.myco.app</groupId>\n <artifactId>foo</artifactId>\n <version>1.0-SNAPSHOT</version>\n <type>test-jar</type>\n <scope>test</scope>\n</dependency>\n</code></pre>\n"
},
{
"answer_id": 73889110,
"author": "Krzysiek",
"author_id": 7994171,
"author_profile": "https://Stackoverflow.com/users/7994171",
"pm_score": 0,
"selected": false,
"text": "<p>Worked for me for 1 project, but I didn't for another after doing exactly the same steps.</p>\n<p>So I debugged:</p>\n<ol>\n<li>After mvn clean install I checked /target directory: .jar was there so thats good</li>\n<li>Ran mvn dependency:tree on a project which should use those test classes. Noticed that generated jar file with test classes is marked as dependency, so thats good.</li>\n<li>Conclusion could be only one - <strong>I restarted my Intellj</strong>. At first class import was still not visible, but after a minute it started to see it!</li>\n</ol>\n<p>Note: I only restarted Intellj, no caches removal etc</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12880/"
] |
How can you depend on test code from another module in Maven?
Example, I have 2 modules:
* Base
* Main
I would like a test case in Main to extend a base test class in Base. Is this possible?
Update: Found an [acceptable answer](https://stackoverflow.com/questions/174560/sharing-test-code-in-maven#174670), which involves creating a test jar.
|
I recommend using [type instead of classifier](https://maven.apache.org/pom.html#Dependencies) (see also: [classifier](http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html)). It tells Maven a bit more explicitly what you are doing (and I've found that m2eclipse and q4e both like it better).
```
<dependency>
<groupId>com.myco.app</groupId>
<artifactId>foo</artifactId>
<version>1.0-SNAPSHOT</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
```
|
174,570 |
<p>I have the following code in one of my aspx pages:</p>
<pre><code><% foreach (Dependency dep in this.Common.GetDependencies(this.Request.QueryString["Name"]))
{ %>
<ctl:DependencyEditor DependencyKey='<%= dep.Key %>' runat="server" />
<% } %>
</code></pre>
<p>When I run it, I get the following error: <pre><strong>Parser Error Message:</strong> Cannot create an object of type 'System.Guid' from its string representation '<%= dep.Key %>' for the 'DependencyKey' property.</pre></p>
<p>Is there any way that I can create a control and pass in a Guid in the aspx page? I'd really hate to have to loop through and create these controls in the code behind just because of that...</p>
<p>NOTE: The Key property on the Dependency object <em>is</em> a Guid.</p>
|
[
{
"answer_id": 174626,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 1,
"selected": false,
"text": "<p>The key property of the Dependency object may be a Guid, but is the DependencyKey Property of the DependencyEditor a Guid too? If not it should be, otherwise the correct TypeConverter won't be invoked upon assignment. </p>\n\n<p>If I'm not mistaken, you could also use dep.Key.ToString() also.</p>\n"
},
{
"answer_id": 174629,
"author": "scootdawg",
"author_id": 25512,
"author_profile": "https://Stackoverflow.com/users/25512",
"pm_score": 0,
"selected": false,
"text": "<p>is your control taking the value and assuming its a GUID? Have you tried instantiating a GUID with the value? Looks like this is a cast problem</p>\n"
},
{
"answer_id": 174925,
"author": "scootdawg",
"author_id": 25512,
"author_profile": "https://Stackoverflow.com/users/25512",
"pm_score": 0,
"selected": false,
"text": "<p>ok, here's the deal...try using the # symbol instead of the = symbol. I replicated your problem and that gets past the compile issue.</p>\n\n<p>It should look like this \"<%# dep.Key %>\"</p>\n\n<p>good luck!</p>\n"
},
{
"answer_id": 464127,
"author": "CRice",
"author_id": 55693,
"author_profile": "https://Stackoverflow.com/users/55693",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming dep.Key is a string representation of a guid... and DependencyKey is a property of type Guid</p>\n\n<pre><code> <ctl:DependencyEditor DependencyKey=\"<%= new Guid(dep.Key) %>\" runat=\"server\" />\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226/"
] |
I have the following code in one of my aspx pages:
```
<% foreach (Dependency dep in this.Common.GetDependencies(this.Request.QueryString["Name"]))
{ %>
<ctl:DependencyEditor DependencyKey='<%= dep.Key %>' runat="server" />
<% } %>
```
When I run it, I get the following error:
```
**Parser Error Message:** Cannot create an object of type 'System.Guid' from its string representation '<%= dep.Key %>' for the 'DependencyKey' property.
```
Is there any way that I can create a control and pass in a Guid in the aspx page? I'd really hate to have to loop through and create these controls in the code behind just because of that...
NOTE: The Key property on the Dependency object *is* a Guid.
|
The key property of the Dependency object may be a Guid, but is the DependencyKey Property of the DependencyEditor a Guid too? If not it should be, otherwise the correct TypeConverter won't be invoked upon assignment.
If I'm not mistaken, you could also use dep.Key.ToString() also.
|
174,582 |
<p>If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?</p>
<p>This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.</p>
|
[
{
"answer_id": 174586,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 7,
"selected": false,
"text": "<p>Specifically for SQL Server, use <a href=\"http://msdn.microsoft.com/en-us/library/ms188351.aspx\" rel=\"noreferrer\"><code>sp_rename</code></a></p>\n\n<pre><code>USE AdventureWorks;\nGO\nEXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';\nGO\n</code></pre>\n"
},
{
"answer_id": 174632,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 8,
"selected": true,
"text": "<p>On PostgreSQL (and many other RDBMS), you can do it with regular <code>ALTER TABLE</code> statement:</p>\n\n<pre><code>=> SELECT * FROM Test1;\n id | foo | bar \n----+-----+-----\n 2 | 1 | 2\n\n=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;\nALTER TABLE\n\n=> SELECT * FROM Test1;\n id | baz | bar \n----+-----+-----\n 2 | 1 | 2\n</code></pre>\n"
},
{
"answer_id": 174655,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>ALTER TABLE is standard SQL. But it's not completely implemented in many database systems.</p>\n"
},
{
"answer_id": 193190,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>In Informix, you can use:</p>\n\n<pre><code>RENAME COLUMN TableName.OldName TO NewName;\n</code></pre>\n\n<p>This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.</p>\n"
},
{
"answer_id": 193203,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 2,
"selected": false,
"text": "<p>The standard would be <code>ALTER TABLE</code>, but that's not necessarily supported by every DBMS you're likely to encounter, so if you're looking for an all-encompassing syntax, you may be out of luck.</p>\n"
},
{
"answer_id": 19579861,
"author": "Shadow Man",
"author_id": 2167531,
"author_profile": "https://Stackoverflow.com/users/2167531",
"pm_score": 5,
"selected": false,
"text": "<p>Unfortunately, for a database independent solution, you will need to know everything about the column. If it is used in other tables as a foreign key, they will need to be modified as well.</p>\n\n<pre><code>ALTER TABLE MyTable ADD MyNewColumn OLD_COLUMN_TYPE;\nUPDATE MyTable SET MyNewColumn = MyOldColumn;\n-- add all necessary triggers and constraints to the new column...\n-- update all foreign key usages to point to the new column...\nALTER TABLE MyTable DROP COLUMN MyOldColumn;\n</code></pre>\n\n<p>For the very simplest of cases (no constraints, triggers, indexes or keys), it will take the above 3 lines. For anything more complicated it can get very messy as you fill in the missing parts.</p>\n\n<p>However, as mentioned above, there are simpler database specific methods if you know which database you need to modify ahead of time.</p>\n"
},
{
"answer_id": 26906635,
"author": "Syed Uzair Uddin",
"author_id": 3006390,
"author_profile": "https://Stackoverflow.com/users/3006390",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively to <code>SQL</code>, you can do this in Microsoft SQL Server Management Studio, from the table Design Panel.</p>\n\n<p>First Way</p>\n\n<p>Slow double-click on the column. The column name will become an editable text box.</p>\n\n<p>Second Way </p>\n\n<blockquote>\n <p>SqlManagement Studio>>DataBases>>tables>>specificTable>>Column\n Folder>>Right Click on column>>Reman</p>\n</blockquote>\n\n<p>Third Way</p>\n\n<p>Table>>RightClick>>Design</p>\n"
},
{
"answer_id": 30655490,
"author": "jaspher chloe",
"author_id": 4508165,
"author_profile": "https://Stackoverflow.com/users/4508165",
"pm_score": 5,
"selected": false,
"text": "<p>In MySQL, the syntax is <a href=\"http://dev.mysql.com/doc/en/alter-table.html\"><code>ALTER TABLE ... CHANGE</code></a>:</p>\n\n<pre><code>ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <data_type> ...\n</code></pre>\n\n<p>Note that you can't just rename and leave the type and constraints as is; you must retype the data type and constraints after the new name of the column.</p>\n"
},
{
"answer_id": 31740124,
"author": "Kunal Relan",
"author_id": 3193919,
"author_profile": "https://Stackoverflow.com/users/3193919",
"pm_score": 5,
"selected": false,
"text": "<p>I think this is the easiest way to change column name.</p>\n\n<pre><code>SP_RENAME 'TABLE_NAME.OLD_COLUMN_NAME','NEW_COLUMN_NAME'\n</code></pre>\n"
},
{
"answer_id": 40019241,
"author": "Bimzee",
"author_id": 1729330,
"author_profile": "https://Stackoverflow.com/users/1729330",
"pm_score": 4,
"selected": false,
"text": "<p>In sql server you can use </p>\n\n<pre><code>exec sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'\n</code></pre>\n\n<p>or</p>\n\n<pre><code>sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'\n</code></pre>\n"
},
{
"answer_id": 43244867,
"author": "Prabhat Kumar Yadav",
"author_id": 7824141,
"author_profile": "https://Stackoverflow.com/users/7824141",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the following command to rename the column of any table in SQL Server:</p>\n\n<pre><code>exec sp_rename 'TableName.OldColumnName', 'New colunmName'\n</code></pre>\n"
},
{
"answer_id": 71421601,
"author": "Gulshan Prajapati",
"author_id": 12020542,
"author_profile": "https://Stackoverflow.com/users/12020542",
"pm_score": 0,
"selected": false,
"text": "<p><strong>To rename you have to change the column</strong></p>\n<p>e.g</p>\n<p>Suppose</p>\n<p>*registration is Table Name</p>\n<p>newRefereeName is a column name That I want to change to refereeName\nSO my SQL Query will be*</p>\n<p><strong>ALTER TABLE 'registration' CHANGE 'newRefereeName' 'refereeName' VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL;</strong></p>\n"
},
{
"answer_id": 72423251,
"author": "Rohn Kerry",
"author_id": 9595761,
"author_profile": "https://Stackoverflow.com/users/9595761",
"pm_score": 0,
"selected": false,
"text": "<p>exec sp_rename 'Tablename.OldColumnName', 'NewColumnName', 'Column';</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8026/"
] |
If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?
This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.
|
On PostgreSQL (and many other RDBMS), you can do it with regular `ALTER TABLE` statement:
```
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
```
|
174,595 |
<p>What is the difference between <code>ROWNUM</code> and <code>ROW_NUMBER</code> ? </p>
|
[
{
"answer_id": 174628,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 6,
"selected": true,
"text": "<p>ROWNUM is a \"pseudocolumn\" that assigns a number to each row returned by a query:</p>\n\n<pre><code>SQL> select rownum, ename, deptno\n 2 from emp;\n\n ROWNUM ENAME DEPTNO\n---------- ---------- ----------\n 1 SMITH 99\n 2 ALLEN 30\n 3 WARD 30\n 4 JONES 20\n 5 MARTIN 30\n 6 BLAKE 30\n 7 CLARK 10\n 8 SCOTT 20\n 9 KING 10\n 10 TURNER 30\n 11 FORD 20\n 12 MILLER 10\n</code></pre>\n\n<p>ROW_NUMBER is an analytic function that assigns a number to each row according to its ordering within a group of rows:</p>\n\n<pre><code>SQL> select ename, deptno, row_number() over (partition by deptno order by ename) rn\n 2 from emp;\n\nENAME DEPTNO RN\n---------- ---------- ----------\nCLARK 10 1\nKING 10 2\nMILLER 10 3\nFORD 20 1\nJONES 20 2\nSCOTT 20 3\nALLEN 30 1\nBLAKE 30 2\nMARTIN 30 3\nTURNER 30 4\nWARD 30 5\nSMITH 99 1\n</code></pre>\n"
},
{
"answer_id": 174635,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "<p>From a little reading, ROWNUM is a value automatically assigned by Oracle to a rowset (prior to ORDER BY being evaluated, so don't <strong>ever</strong> <code>ORDER BY ROWNUM</code> or use a <code>WHERE ROWNUM < 10</code> with an <code>ORDER BY</code>).</p>\n\n<p><a href=\"http://download.oracle.com/docs/cd/B10500_01/server.920/a96540/functions105a.htm\" rel=\"nofollow noreferrer\">ROW_NUMBER()</a> appears to be a function for assigning row numbers to a result set returned by a subquery or partition.</p>\n"
},
{
"answer_id": 174645,
"author": "Michael OShea",
"author_id": 13178,
"author_profile": "https://Stackoverflow.com/users/13178",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://www.adp-gmbh.ch/ora/sql/rownum.html\" rel=\"nofollow noreferrer\">rownum</a> is a pseudocolumn which can be added to any select query, to number the rows returned (starting with 1). They are ordered according to when they were identified as being part of the final result set. (<a href=\"https://stackoverflow.com/users/6742/david-aldridge\">#ref</a>)</p>\n\n<p><a href=\"http://www.adp-gmbh.ch/ora/sql/analytical/row_number.html\" rel=\"nofollow noreferrer\">row_number</a> is an analytic's function, which can be used to number the rows returned by the query in an order mandated by the row_number() function.</p>\n"
},
{
"answer_id": 11538632,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 1,
"selected": false,
"text": "<p>Apart from the other differences mentioned in answers, you should also consider performance. There is a non-authoritative but very interesting report here, comparing various means of pagination, among which the use of <code>ROWNUM</code> compared to <code>ROW_NUMBER() OVER()</code>:</p>\n\n<p><a href=\"http://www.inf.unideb.hu/~gabora/pagination/results.html\" rel=\"nofollow\">http://www.inf.unideb.hu/~gabora/pagination/results.html</a></p>\n"
},
{
"answer_id": 30694322,
"author": "darshan kamat",
"author_id": 3471396,
"author_profile": "https://Stackoverflow.com/users/3471396",
"pm_score": -1,
"selected": false,
"text": "<p>Rownum starts with 1 ..increases after condition evaluated results to true .\nHence rownum >=1 returns all rows in table </p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9581/"
] |
What is the difference between `ROWNUM` and `ROW_NUMBER` ?
|
ROWNUM is a "pseudocolumn" that assigns a number to each row returned by a query:
```
SQL> select rownum, ename, deptno
2 from emp;
ROWNUM ENAME DEPTNO
---------- ---------- ----------
1 SMITH 99
2 ALLEN 30
3 WARD 30
4 JONES 20
5 MARTIN 30
6 BLAKE 30
7 CLARK 10
8 SCOTT 20
9 KING 10
10 TURNER 30
11 FORD 20
12 MILLER 10
```
ROW\_NUMBER is an analytic function that assigns a number to each row according to its ordering within a group of rows:
```
SQL> select ename, deptno, row_number() over (partition by deptno order by ename) rn
2 from emp;
ENAME DEPTNO RN
---------- ---------- ----------
CLARK 10 1
KING 10 2
MILLER 10 3
FORD 20 1
JONES 20 2
SCOTT 20 3
ALLEN 30 1
BLAKE 30 2
MARTIN 30 3
TURNER 30 4
WARD 30 5
SMITH 99 1
```
|
174,600 |
<p>In SQL Server 2005, is there a way for a trigger to find out what object is responsible for firing the trigger? I would like to use this to disable the trigger for one stored procedure.</p>
<p>Is there any other way to disable the trigger only for the current transaction? I could use the following code, but if I'm not mistaken, it would affect concurrent transactions as well - which would be a bad thing.</p>
<pre><code>DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ]
ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ]
</code></pre>
<p>If possible, I would like to avoid the technique of having a "NoTrigger" field in my table and doing a <code>NoTrigger = null</code>, because I would like to keep the table as small as possible.</p>
<p>The reason I would like to avoid the trigger is because it contains logic that is important for manual updates to the table, but my stored procedure will take care of this logic. Because this will be a highly used procedure, I want it to be fast.</p>
<blockquote>
<p>Triggers impose additional overhead on the server because they initiate an implicit transaction. As soon as a trigger is executed, a new implicit transaction is started, and any data retrieval within a transaction will hold locks on affected tables.</p>
</blockquote>
<p>From: <a href="http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1170220,00.html#trigger" rel="nofollow noreferrer">http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1170220,00.html#trigger</a></p>
|
[
{
"answer_id": 174695,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 2,
"selected": false,
"text": "<p>ALTER TABLE tbl DISABLE TRIGGER trg</p>\n\n<p><a href=\"http://doc.ddart.net/mssql/sql70/aa-az_5.htm\" rel=\"nofollow noreferrer\">http://doc.ddart.net/mssql/sql70/aa-az_5.htm</a></p>\n\n<p>I don't understand the meaning of your 1st paragraph though</p>\n"
},
{
"answer_id": 174714,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 1,
"selected": false,
"text": "<p>Do not disable the trigger. You are correct that will disable for any concurrent transactions.</p>\n\n<p>Why do you want to disable the trigger? What does it do? WHy is the trigger casuing a problem? It is usually a bad idea to disable a tigger from a data integrity perspective. </p>\n"
},
{
"answer_id": 174782,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 3,
"selected": false,
"text": "<p>If your trigger is causing performance problems in your application, then the best approach is to remove all manual updates to the table, and require all updates to go through the insert/update stored procedures that contain the correct update logic. Then you may remove the trigger completely. </p>\n\n<p>I suggest denying table update permissions if nothing else works.</p>\n\n<p>This also solves the problem of duplicate code. Duplicating code in the update SP and in the trigger is a violation of good software engineering principles and will be a maintenance problem.</p>\n"
},
{
"answer_id": 174810,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 2,
"selected": false,
"text": "<p>Since you indicate that the trigger contains logic to handle all updates, even manual updates, then that should be where the logic resides. The example you mention, wherein a stored procedure \"will take care of this logic\" implies duplicate code. Additionally, if you want to be sure that every UPDATE statement has this logic applied regardless of author, then the trigger is the place for it. What happens when someone authors a procedure but forgets to duplicate the logic yet again? What happens when it is time to modify the logic?</p>\n"
},
{
"answer_id": 174900,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 1,
"selected": false,
"text": "<p>Consider rewriting the trigger to imporve performance if performance is the issue.</p>\n"
},
{
"answer_id": 174905,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 0,
"selected": false,
"text": "<p>I concur with some other answers. Do not disable the trigger.</p>\n\n<p>This is pure opinion, but I avoid triggers like the plague. I have found very few cases where a trigger was used to enforce database rules. There are obvious edge cases in my experience, and I have only my experience on which to make this statement. I have typically seen triggers used to insert some relational data (which should be done from the business logic), for insert data into reporting table ie denormalizing the data (which can be done with a process outside the transaction), or for transforming the data in some way. </p>\n\n<p>There are legitimate uses for triggers, but I think that in everyday business programming they are few and far between. This may not help in your current problem, but you might consider removing the trigger altogether and accomplishing the work the trigger is doing in some other fashion.</p>\n"
},
{
"answer_id": 175917,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 1,
"selected": false,
"text": "<p>I waffled a bit on this one. On the one hand I'm very anti-trigger mostly because it's one more place for me to look for code executing against my table, in addition to the reasons stated in the article linked in the question post. </p>\n\n<p>On the other hand, if you have logic to enforce stable and immutable business rules or cross-table actions (like maintaining a history table) then it would be safer to get this into a trigger so procedure authors and programmers don't need to deal with it - it just works. </p>\n\n<p>So, my recommendation is to put the necessary logic in your trigger rather than in this one proc which, will inevitably grow to several procs with the same exemption.</p>\n"
},
{
"answer_id": 178192,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 7,
"selected": true,
"text": "<p>I just saw this article recently highlighted on the SQL Server Central newsletter and it appears to offer a way which you may find useful using the Context_Info on the connection:</p>\n\n<p><a href=\"http://www.mssqltips.com/tip.asp?tip=1591\" rel=\"noreferrer\">http://www.mssqltips.com/tip.asp?tip=1591</a></p>\n\n<hr>\n\n<p>EDIT by Terrapin:</p>\n\n<p>The above link includes the following code:</p>\n\n<pre><code>USE AdventureWorks; \nGO \n-- creating the table in AdventureWorks database \nIF OBJECT_ID('dbo.Table1') IS NOT NULL \nDROP TABLE dbo.Table1 \nGO \nCREATE TABLE dbo.Table1(ID INT) \nGO \n-- Creating a trigger \nCREATE TRIGGER TR_Test ON dbo.Table1 FOR INSERT,UPDATE,DELETE \nAS \nDECLARE @Cinfo VARBINARY(128) \nSELECT @Cinfo = Context_Info() \nIF @Cinfo = 0x55555 \nRETURN \nPRINT 'Trigger Executed' \n-- Actual code goes here \n-- For simplicity, I did not include any code \nGO \n</code></pre>\n\n<p>If you want to prevent the trigger from being executed you can do the following:</p>\n\n<pre><code>SET Context_Info 0x55555 \nINSERT dbo.Table1 VALUES(100)\n</code></pre>\n"
},
{
"answer_id": 2204970,
"author": "Hoyacoder",
"author_id": 266765,
"author_profile": "https://Stackoverflow.com/users/266765",
"pm_score": 0,
"selected": false,
"text": "<p>I just confronted the same problem and came up with the following solution, which works for me.</p>\n\n<ol>\n<li><p>Create a permanent DB table that contains one record for each trigger that you want to disable (e.g. refTriggerManager); each row contains the trigger name (e.g. strTriggerName = 'myTrigger') and a bit flag (e.g. blnDisabled, default to 0).</p></li>\n<li><p>At the beginning of the trigger body, look up strTriggerName = 'myTrigger' in refTriggerManager. If blnDisabled = 1, then return without executing the rest of the trigger code, else continue the trigger code to completion. </p></li>\n<li><p>In the stored proc in which you want to disable the trigger, do the following:</p></li>\n</ol>\n\n<hr>\n\n<p>BEGIN TRANSACTION</p>\n\n<p>UPDATE refTriggerManager SET blnDisabled = 1 WHERE strTriggerName = 'myTrigger'</p>\n\n<p>/* UPDATE the table that owns 'myTrigger,' but which you want disabled. Since refTriggerManager.blnDisabled = 1, 'myTrigger' returns without executing its code. */</p>\n\n<p>UPDATE refTriggerManager SET blnDisabled= 0 WHERE triggerName = 'myTrigger'</p>\n\n<p>/* Optional final UPDATE code that fires trigger. Since refTriggerManager.blnDisabled = 0, 'myTrigger' executes in full. */</p>\n\n<p>COMMIT TRANSACTION</p>\n\n<hr>\n\n<p>All of this takes place within a transaction, so it's isolated from the outside world and won't affect other UPDATEs on the target table.</p>\n\n<p>Does anyone see any problem with this approach?</p>\n\n<p>Bill</p>\n"
},
{
"answer_id": 5116718,
"author": "Steve",
"author_id": 634027,
"author_profile": "https://Stackoverflow.com/users/634027",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this is a good idea but it seems to work for me. Transaction should prevent inserts to the table from other processes while trigger is disabled.</p>\n\n<pre><code>IF OBJECT_ID('dbo.TriggerTest') IS NOT NULL\n DROP PROCEDURE dbo.TriggerTest\nGO\n\nCREATE PROCEDURE [dbo].[TriggerTest]\nAS\nBEGIN TRANSACTION trnInsertTable1s\n;\nDISABLE TRIGGER trg_tblTable1_IU ON tblTable1\n;\nBEGIN -- Procedure Code\n PRINT '@@trancount'\n PRINT @@TRANCOUNT\n -- Do Stuff\n\nEND -- Procedure Code\n;\nENABLE TRIGGER trg_tblTable1_IU ON tblTable1\n\nIF @@ERROR <> 0 ROLLBACK TRANSACTION\nELSE COMMIT TRANSACTION\n</code></pre>\n"
},
{
"answer_id": 13804699,
"author": "Nader Sghir",
"author_id": 1071859,
"author_profile": "https://Stackoverflow.com/users/1071859",
"pm_score": 0,
"selected": false,
"text": "<p>you can use '<strong><em>Exec</em></strong>' function to diable and enable triggers from a stored procedure. Example: <code>EXEC ('ENABLE TRIGGER dbo.TriggerName on dbo.TriggeredTable')</code></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
In SQL Server 2005, is there a way for a trigger to find out what object is responsible for firing the trigger? I would like to use this to disable the trigger for one stored procedure.
Is there any other way to disable the trigger only for the current transaction? I could use the following code, but if I'm not mistaken, it would affect concurrent transactions as well - which would be a bad thing.
```
DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ]
ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ]
```
If possible, I would like to avoid the technique of having a "NoTrigger" field in my table and doing a `NoTrigger = null`, because I would like to keep the table as small as possible.
The reason I would like to avoid the trigger is because it contains logic that is important for manual updates to the table, but my stored procedure will take care of this logic. Because this will be a highly used procedure, I want it to be fast.
>
> Triggers impose additional overhead on the server because they initiate an implicit transaction. As soon as a trigger is executed, a new implicit transaction is started, and any data retrieval within a transaction will hold locks on affected tables.
>
>
>
From: <http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1170220,00.html#trigger>
|
I just saw this article recently highlighted on the SQL Server Central newsletter and it appears to offer a way which you may find useful using the Context\_Info on the connection:
<http://www.mssqltips.com/tip.asp?tip=1591>
---
EDIT by Terrapin:
The above link includes the following code:
```
USE AdventureWorks;
GO
-- creating the table in AdventureWorks database
IF OBJECT_ID('dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
GO
CREATE TABLE dbo.Table1(ID INT)
GO
-- Creating a trigger
CREATE TRIGGER TR_Test ON dbo.Table1 FOR INSERT,UPDATE,DELETE
AS
DECLARE @Cinfo VARBINARY(128)
SELECT @Cinfo = Context_Info()
IF @Cinfo = 0x55555
RETURN
PRINT 'Trigger Executed'
-- Actual code goes here
-- For simplicity, I did not include any code
GO
```
If you want to prevent the trigger from being executed you can do the following:
```
SET Context_Info 0x55555
INSERT dbo.Table1 VALUES(100)
```
|
174,602 |
<p>It seems like searching with CAML and SPQuery doesn't work properly against custom metadata, when searching for SPFolders instead of files, or when searching for custom content types. I've been using U2U to test a variety of queries, and just not getting anywhere. The doc's aren't very complete on the topic, and google isn't helping either.</p>
<p>In one test, I'm trying to locate any SPFolders in the tree that are a specific custom content-type. If I understand CAML correctly, this should work:</p>
<pre><code><Query>
<Where>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>CustomTypeName</Value>
</Eq>
</Where>
</Query>
</code></pre>
<p>In another test, I'm trying to locate any SPFolder that has a custom metadata property set to a specific value.</p>
<pre><code><Query>
<Where>
<Eq>
<FieldRef Name='CustomProp' />
<Value Type='Text'>SpecificPropValue</Value>
</Eq>
</Where>
</Query>
</code></pre>
<p>In both cases, I'm setting the root for the search to a document library that contains folders, which contain folders, which contain folders (phew.) Also, I'm setting the SPQuery to search recursively.</p>
<p>The folder I'm searching for a two steps down are the farthest down in the tree. I don't want to iterate all the way in to manually locate the folders in question.</p>
<p><strong>EDIT</strong> It might also be helpful to know that I'm using both SPList.GetItems with an SPQuery as an argument, and SPWeb.GetSiteData with an SPSiteDataQuery as an argument. At the moment it appears that folders aren't included in the search-set for either of these queries.</p>
<p>Any help would be greatly appreciated.</p>
|
[
{
"answer_id": 175986,
"author": "Nat",
"author_id": 13813,
"author_profile": "https://Stackoverflow.com/users/13813",
"pm_score": 1,
"selected": false,
"text": "<p>Try adding <a href=\"http://www.codeplex.com/spm\" rel=\"nofollow noreferrer\">SharePoint Manager</a> and <a href=\"http://www.codeplex.com/SPCamlViewer\" rel=\"nofollow noreferrer\">Stramit CAML Viewer</a> to your toolset.</p>\n\n<p>I have found both to be very important for figuring out CAML problems.</p>\n"
},
{
"answer_id": 180168,
"author": "David Hill",
"author_id": 1181217,
"author_profile": "https://Stackoverflow.com/users/1181217",
"pm_score": 3,
"selected": true,
"text": "<p>After more research, I'm answering my own question.</p>\n\n<p>Apparently the methods that I'm using to query don't return SPFolders as items in the result set. Only list items are returned, basically just documents.</p>\n\n<p>My fix was to execute a CAML query for all the documents with a certain metadata tag/value, and then using the parent folder of the first one as the representative folder for the set. Works well enough for my needs.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1181217/"
] |
It seems like searching with CAML and SPQuery doesn't work properly against custom metadata, when searching for SPFolders instead of files, or when searching for custom content types. I've been using U2U to test a variety of queries, and just not getting anywhere. The doc's aren't very complete on the topic, and google isn't helping either.
In one test, I'm trying to locate any SPFolders in the tree that are a specific custom content-type. If I understand CAML correctly, this should work:
```
<Query>
<Where>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>CustomTypeName</Value>
</Eq>
</Where>
</Query>
```
In another test, I'm trying to locate any SPFolder that has a custom metadata property set to a specific value.
```
<Query>
<Where>
<Eq>
<FieldRef Name='CustomProp' />
<Value Type='Text'>SpecificPropValue</Value>
</Eq>
</Where>
</Query>
```
In both cases, I'm setting the root for the search to a document library that contains folders, which contain folders, which contain folders (phew.) Also, I'm setting the SPQuery to search recursively.
The folder I'm searching for a two steps down are the farthest down in the tree. I don't want to iterate all the way in to manually locate the folders in question.
**EDIT** It might also be helpful to know that I'm using both SPList.GetItems with an SPQuery as an argument, and SPWeb.GetSiteData with an SPSiteDataQuery as an argument. At the moment it appears that folders aren't included in the search-set for either of these queries.
Any help would be greatly appreciated.
|
After more research, I'm answering my own question.
Apparently the methods that I'm using to query don't return SPFolders as items in the result set. Only list items are returned, basically just documents.
My fix was to execute a CAML query for all the documents with a certain metadata tag/value, and then using the parent folder of the first one as the representative folder for the set. Works well enough for my needs.
|
174,612 |
<p>On a cross platform c/c++ project (Win32, Linux, OSX), I need to use the *printf functions to print some variables of type size_t. In some environments size_t's are 8 bytes and on others they are 4. On glibc I have %zd, and on Win32 I can use <a href="http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx" rel="noreferrer">%Id</a>. Is there an elegant way to handle this?</p>
|
[
{
"answer_id": 174648,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know of any satisfying solution, but you might consider a specialized function to format size_t items to a string, and print the string.</p>\n\n<p>(Alternatively, if you can get away with it, boost::format handles this kind of thing with ease.)</p>\n"
},
{
"answer_id": 174674,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "<p>The only thing I can think of, is the typical:</p>\n\n<pre><code>#ifdef __WIN32__ // or whatever\n#define SSIZET_FMT \"%ld\"\n#else\n#define SSIZET_FMT \"%zd\"\n#endif\n</code></pre>\n\n<p>and then taking advantage of constant folding:</p>\n\n<pre><code>fprintf(stream, \"Your size_t var has value \" SSIZET_FMT \".\", your_var);\n</code></pre>\n"
},
{
"answer_id": 174716,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 4,
"selected": false,
"text": "<p>The <code>PRIuPTR</code> macro (from <inttypes.h>) defines a decimal format for <code>uintptr_t</code>, which should always be large enough that you can cast a <code>size_t</code> to it without truncating, e.g.</p>\n\n<pre><code>fprintf(stream, \"Your size_t var has value %\" PRIuPTR \".\", (uintptr_t) your_var);\n</code></pre>\n"
},
{
"answer_id": 175361,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Dan Saks wrote an article in Embedded Systems Design which <a href=\"http://www.embedded.com/columns/programmingpointers/201803576?pgno=2\" rel=\"nofollow noreferrer\">covered</a> this matter. According to Dan, %zu is the standard way, but few compilers supported this. As an alternative, he recommended using %lu together with an explicit cast of the argument to unsigned long:</p>\n\n<blockquote>\n<pre><code>size_t n;\n...\nprintf(\"%lu\", (unsigned long)n);\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 175794,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 2,
"selected": false,
"text": "<p>Use <code>boost::format</code>. It's typesafe, so it'll print <code>size_t</code> correctly with <code>%d</code>, also you don't need to remember to put <code>c_str()</code> on <code>std::string</code>s when using it, and even if you pass a number to <code>%s</code> or vice versa, it'll work.</p>\n"
},
{
"answer_id": 1324516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>There are really two questions here. The first question is what the correct printf specifier string for the three platforms is. Note that <code>size_t</code> is an unsigned type.</p>\n\n<p>On <a href=\"http://msdn.microsoft.com/en-us/library/tcxf1dw6%28VS.71%29.aspx\" rel=\"noreferrer\">Windows</a>, use \"<code>%Iu</code>\".</p>\n\n<p>On <a href=\"http://linux.die.net/man/3/printf\" rel=\"noreferrer\">Linux</a> and <a href=\"http://developer.apple.com/documentation/Darwin/Reference/Manpages/man3/printf.3.html\" rel=\"noreferrer\">OSX</a>, use \"<code>%zu</code>\".</p>\n\n<p>The second question is how to support multiple platforms, given that things like format strings might be different on each platform. As other people have pointed out, using <code>#ifdef</code> gets ugly quickly.</p>\n\n<p>Instead, write a separate makefile or project file for each target platform. Then refer to the specifier by some macro name in your source files, defining the macro appropriately in each makefile. In particular, both GCC and Visual Studio accept a 'D' switch to define macros on the command line.</p>\n\n<p>If your build system is very complicated (multiple build options, generated sources, etc.), maintaining 3 separate makefiles might get unwieldly, and you are going to have to use some kind of advanced build system like CMake or the GNU autotools. But the basic principle is the same-- use the build system to define platform-specific macros instead of putting platform-detection logic in your source files.</p>\n"
},
{
"answer_id": 1325913,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You just have to find an integer type with the largest storage class, cast the value to it, and then use the appropriate format string for the larger type. Note this solution will work for any type (ptrdiff_t, etc.), not just size_t.</p>\n\n<p>What you want to use is uintmax_t and the format macro PRIuMAX. For Visual C++, you are going to need to download c99-compatible stdint.h and inttypes.h headers, because Microsoft doesn't provide them.</p>\n\n<p>Also see</p>\n\n<p><a href=\"http://www.embedded.com/columns/technicalinsights/204700432\" rel=\"nofollow noreferrer\">http://www.embedded.com/columns/technicalinsights/204700432</a></p>\n\n<p>This article corrects the mistakes in the article quoted by Frederico.</p>\n"
},
{
"answer_id": 5330382,
"author": "paniq",
"author_id": 81145,
"author_profile": "https://Stackoverflow.com/users/81145",
"pm_score": 0,
"selected": false,
"text": "<p>My choice for that problem is to simply cast the size_t argument to unsigned long and use %lu everywhere - this of course only where values are not expected to exceed 2^32-1. If this is too short for you, you could always cast to unsigned long long and format it as %llu.</p>\n\n<p>Either way, your strings will never be awkward.</p>\n"
},
{
"answer_id": 45422410,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": -1,
"selected": false,
"text": "<p><code>size_t</code> is an <em>unsigned</em> type of at least 16 bits. Widths of 32 and 64 are often seen.</p>\n\n<pre><code>printf(\"%zu\\n\", some_size_t_object); // Standard since C99\n</code></pre>\n\n<p>Above is the best way going forward, yet if code needs to also port to pre-C99 platforms, covert the value to some wide type. <code>unsigned long</code> is reasonable candidate yet may be lacking.</p>\n\n<pre><code>// OK, yet insufficient with large sizes > ULONG_MAX\nprintf(\"%lu\\n\", (unsigned long) some_size_t_object); \n</code></pre>\n\n<p>or with conditional code</p>\n\n<pre><code>#ifdef ULLONG_MAX\n printf(\"%llu\\n\", (unsigned long long) some_size_t_object); \n#else\n printf(\"%lu\\n\", (unsigned long) some_size_t_object); \n#endif\n</code></pre>\n\n<p>Lastly consider <code>double</code>. It is a bit inefficient yet should handle all ancient and new platforms until about the years 2030-2040 considering <a href=\"https://softwareengineering.stackexchange.com/q/38213/94903\">Moore's law</a> when <code>double</code> may lack a precise result.</p>\n\n<pre><code>printf(\"%.0f\\n\", (double) some_size_t_object);\n</code></pre>\n"
},
{
"answer_id": 55943527,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 0,
"selected": false,
"text": "<h1>Option 1:</h1>\n\n<p>Since on most (if not all?) systems, the <code>PRIuPTR</code> <a href=\"http://www.cplusplus.com/reference/cstdio/printf/\" rel=\"nofollow noreferrer\">printf format string</a> from <a href=\"http://www.cplusplus.com/reference/cinttypes/\" rel=\"nofollow noreferrer\"></a> is also long enough to hold a <code>size_t</code> type, I recommend using the following defines for <code>size_t</code> printf format strings.</p>\n\n<p><em>However, it is important that you verify this will work for your particular architecture (compiler, hardware, etc), as the standard does not enforce this.</em></p>\n\n<pre><code>#include <inttypes.h>\n\n// Printf format strings for `size_t` variable types.\n#define PRIdSZT PRIdPTR\n#define PRIiSZT PRIiPTR\n#define PRIoSZT PRIoPTR\n#define PRIuSZT PRIuPTR\n#define PRIxSZT PRIxPTR\n#define PRIXSZT PRIXPTR\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>size_t my_variable;\nprintf(\"%\" PRIuSZT \"\\n\", my_variable);\n</code></pre>\n\n<h1>Option 2:</h1>\n\n<p>Where possible, however, just use the <code>%zu</code> \"z\" length specifier, <a href=\"http://www.cplusplus.com/reference/cstdio/printf/\" rel=\"nofollow noreferrer\">as shown here</a>, for <code>size_t</code> types:</p>\n\n<p><a href=\"https://i.stack.imgur.com/XvzKt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XvzKt.png\" alt=\"enter image description here\"></a></p>\n\n<p>Example usage:</p>\n\n<pre><code>size_t my_variable;\nprintf(\"%zu\\n\", my_variable);\n</code></pre>\n\n<p><em>On some systems, however, such as STM32 microcontrollers using gcc as the compiler, the <code>%z</code> length specifier isn't necessarily implemented, and doing something like <code>printf(\"%zu\\n\", my_size_t_num);</code> may simply end up printing out a literal \"%zu\" (I personally tested this and found it to be true) instead of the value of your <code>size_t</code> variable.</em></p>\n\n<h1>Option 3:</h1>\n\n<p>Where you need it to be <strong>absolutely guaranteed to work</strong>, however, or where you aren't sure about your particular architecture, just cast and print as a <code>uint64_t</code> and be done, as this is guaranteed to work, but requires the extra step of casting. </p>\n\n<p>Example usage:</p>\n\n<pre><code>#include <stdint.h> // for uint64_t\n#include <inttypes.h> // for PRIu64\n\nsize_t my_variable;\nprintf(\"%\" PRIu64 \"\\n\", (uint64_t)my_variable);\n</code></pre>\n\n<h1>Sources Cited:</h1>\n\n<ol>\n<li><a href=\"http://www.cplusplus.com/reference/cstdio/printf/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/cstdio/printf/</a></li>\n<li><a href=\"http://www.cplusplus.com/reference/cinttypes/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/cinttypes/</a></li>\n<li><a href=\"http://www.cplusplus.com/reference/cstdint/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/cstdint/</a></li>\n</ol>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23524/"
] |
On a cross platform c/c++ project (Win32, Linux, OSX), I need to use the \*printf functions to print some variables of type size\_t. In some environments size\_t's are 8 bytes and on others they are 4. On glibc I have %zd, and on Win32 I can use [%Id](http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx). Is there an elegant way to handle this?
|
The `PRIuPTR` macro (from <inttypes.h>) defines a decimal format for `uintptr_t`, which should always be large enough that you can cast a `size_t` to it without truncating, e.g.
```
fprintf(stream, "Your size_t var has value %" PRIuPTR ".", (uintptr_t) your_var);
```
|
174,633 |
<p>My regular expression needs to be able to find the strings:</p>
<ol>
<li>Visual Studio 2008</li>
<li>Visual Studio Express 2008</li>
<li>Visual Basic 2008</li>
<li>Visual Basic Express 2008</li>
<li>Visual C++ 2008</li>
<li>Visual C++ Express 2008</li>
</ol>
<p>and a host of other similar variants, to be replaced with this one single string</p>
<blockquote>
<p>Visual Studio 2005</p>
</blockquote>
<p>I tried "Visual (Basic|C++|Studio) (Express)? 2008", but it is not working. Any ideas?</p>
<p><strong><em>Edit</strong>:
Now I have tried "Visual (Basic)|(C++)|(Studio) (Express )?2008", but the replaced line becomes "Visual Studio 2005 Express 2008" for the input "Visual Basic Express 2008".</em> </p>
|
[
{
"answer_id": 174638,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "<p>You need to escape the special characters (like +). Also the 'express' bit, should have a space on either side.</p>\n"
},
{
"answer_id": 174660,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>In the case without an Express, you are looking for 2 spaces before the year. That is no good. Try this:</p>\n\n<pre><code>\"Visual (Basic|C\\+\\+|Studio) (Express )?2008\"\n</code></pre>\n\n<p>Depending on the input, it might be enough to use:</p>\n\n<pre><code>\"Visual [^ ]+ (Express )?2008\"\n</code></pre>\n"
},
{
"answer_id": 174665,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 2,
"selected": false,
"text": "<p>How about this: </p>\n\n<pre><code>Visual (Basic|C\\\\+\\\\+|Studio) (Express )?2008\n</code></pre>\n"
},
{
"answer_id": 174669,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>It should be</p>\n\n<pre><code>\"Visual (Basic|C\\+\\+|Studio)( Express)? 2008\"\n\n>>> import re\n>>> repl = 'Visual Studio 2005'\n>>> regexp = re.compile('Visual (Studio|Basic|C\\+\\+)( Express)? 2008')\n>>> test1 = 'Visual Studio 2008'\n>>> test2 = 'Visual Studio Express 2008'\n>>> test3 = 'Visual C++ Express 2008'\n>>> test4 = 'Visual C++ Express 1008'\n>>> re.sub(regexp,repl,test1)\n'Visual Studio 2005'\n>>> re.sub(regexp,repl,test2)\n'Visual Studio 2005'\n>>> re.sub(regexp,repl,test3)\n'Visual Studio 2005'\n>>> re.sub(regexp,repl,test4)\n'Visual C++ Express 1008'\n</code></pre>\n"
},
{
"answer_id": 174680,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 0,
"selected": false,
"text": "<p>Try with:</p>\n\n<pre><code>Visual (Basic|C\\+\\+|Studio)( Express)? 2008\n</code></pre>\n\n<p>that is, quote the '+' of 'C++' and include the space in \"Express\"</p>\n\n<p>Since it's Python and you don't need the parenthesized parts:</p>\n\n<pre><code>Visual (?:Basic|C\\+\\+|Studio)(?: Express)? 2008\n</code></pre>\n"
},
{
"answer_id": 174683,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 0,
"selected": false,
"text": "<p>This is more explicit with spaces:</p>\n\n<pre><code>Visual\\s(Basic|C\\+\\+|Studio)(\\sExpress)?\\s2008\n</code></pre>\n"
},
{
"answer_id": 174701,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 1,
"selected": false,
"text": "<p>Unless your sample input is riddled with all sorts of permutations of your keywords, you could simplify it immensely with this:</p>\n\n<pre><code>Visual .+? 2008\n</code></pre>\n"
},
{
"answer_id": 174821,
"author": "Komang",
"author_id": 19463,
"author_profile": "https://Stackoverflow.com/users/19463",
"pm_score": 1,
"selected": false,
"text": "<p>i think this should works </p>\n\n<pre><code>/visual (studio|basic|c\\+\\+)? (express)?\\s?2008/i\n</code></pre>\n"
},
{
"answer_id": 26632301,
"author": "Suganthan Madhavan Pillai",
"author_id": 2534236,
"author_profile": "https://Stackoverflow.com/users/2534236",
"pm_score": -1,
"selected": false,
"text": "<p>A very late answer, but like to answer.You can simply try this</p>\n\n<pre><code>/Visual.*2008/g\n</code></pre>\n\n<p><a href=\"http://regex101.com/r/fI0yU1/1\" rel=\"nofollow\">http://regex101.com/r/fI0yU1/1</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
My regular expression needs to be able to find the strings:
1. Visual Studio 2008
2. Visual Studio Express 2008
3. Visual Basic 2008
4. Visual Basic Express 2008
5. Visual C++ 2008
6. Visual C++ Express 2008
and a host of other similar variants, to be replaced with this one single string
>
> Visual Studio 2005
>
>
>
I tried "Visual (Basic|C++|Studio) (Express)? 2008", but it is not working. Any ideas?
***Edit***:
Now I have tried "Visual (Basic)|(C++)|(Studio) (Express )?2008", but the replaced line becomes "Visual Studio 2005 Express 2008" for the input "Visual Basic Express 2008".
|
It should be
```
"Visual (Basic|C\+\+|Studio)( Express)? 2008"
>>> import re
>>> repl = 'Visual Studio 2005'
>>> regexp = re.compile('Visual (Studio|Basic|C\+\+)( Express)? 2008')
>>> test1 = 'Visual Studio 2008'
>>> test2 = 'Visual Studio Express 2008'
>>> test3 = 'Visual C++ Express 2008'
>>> test4 = 'Visual C++ Express 1008'
>>> re.sub(regexp,repl,test1)
'Visual Studio 2005'
>>> re.sub(regexp,repl,test2)
'Visual Studio 2005'
>>> re.sub(regexp,repl,test3)
'Visual Studio 2005'
>>> re.sub(regexp,repl,test4)
'Visual C++ Express 1008'
```
|
174,659 |
<p>I'm writing a little tile-based game, for which I'd like to support light sources. But my algorithm-fu is too weak, hence I come to you for help.</p>
<p>The situation is like this: There is a tile-based map (held as a 2D array), containing a single light source and several items standing around. I want to calculate which tiles are lit up by the light source, and which are in shadow.</p>
<p>A visual aid of what it would look like, approximately. The L is the light source, the Xs are items blocking the light, the 0s are lit tiles, and the -s are tiles in shadow.</p>
<pre><code>0 0 0 0 0 0 - - 0
0 0 0 0 0 0 - 0 0
0 0 0 0 0 X 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 L 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 X X X X 0 0
0 0 0 - - - - - 0
0 0 - - - - - - -
</code></pre>
<p>A fractional system would be even better, of course, where a tile can be in half-shadow due to being partially obscured. The algorithm wouldn't have to be perfect - just not obviously wrong and reasonably fast.</p>
<p>(Of course, there would be multiple light sources, but that's just a loop.)</p>
<p>Any takers?</p>
|
[
{
"answer_id": 174679,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 3,
"selected": false,
"text": "<p>Quick and dirty:</p>\n\n<p>(Depending on how big the array is)</p>\n\n<ul>\n<li>Loop through each tile </li>\n<li>draw a line to the Light</li>\n<li>If any pary of the line hits an X, then it is in shadow</li>\n<li>(Optional): calculate the amount of X the line passes through and do fancy maths to determint the proportion of the tile in shadow. NB: This could be done by anti-aliasing the line between the tile and the Light (therefore looking at other tiles along the route back to the light source) during the thresholding procedure these will appear as small anomolies. Depending on the logic used you could potentially determine how much (if at all) the tile is in shadow.</li>\n</ul>\n\n<p>You could also keep a track of which pixels have been tested, therefore optimize the solution a little and not re-test pixels twice.</p>\n\n<p>This could be dome pretty well by using image manipulation and drawing straight lines between pixles (tiles) If the lines are semi transparent and the X blocks are semi-transparent again. You can threshold the image to determine if the line has intersected an 'X'</p>\n\n<p>If you have an option to use a 3rd party tool, then Id probably take it. In the long run it might turn out to be quicker, but you'd understand less about your game.</p>\n"
},
{
"answer_id": 174690,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>To check if a tile is in shadow you need to draw a straight line back to the light source. If the line intersects another tile that's occupied, then the tile you were testing is in shadow. Raytracing algorithms do this for every object (in your case tile) in the view.</p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Ray_tracing_(graphics)#Algorithm:_classical_recursive_ray_tracing\" rel=\"nofollow noreferrer\">Raytracing article</a> on Wikipedia has pseudocode.</p>\n"
},
{
"answer_id": 174704,
"author": "Scottie T",
"author_id": 6688,
"author_profile": "https://Stackoverflow.com/users/6688",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want to spend the time to reinvent/re-implement this, there are plenty of game engines out there. <a href=\"http://www.ogre3d.org/\" rel=\"nofollow noreferrer\">Ogre3D</a> is an open source game engine that fully supports lighting, as well as sound and game controls.</p>\n"
},
{
"answer_id": 174718,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 4,
"selected": false,
"text": "<p>You can get into all sorts of complexities with calculating occlusion etc, or you can go for the simple brute force method: For every cell, use a line drawing algorithm such as the <a href=\"http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm\" rel=\"noreferrer\">Bresenham Line Algorithm</a> to examine every cell between the current one and the light source. If any are filled cells or (if you have only one light source) cells that have already been tested and found to be in shadow, your cell is in shadow. If you encounter a cell known to be lit, your cell will likewise be lit. An easy optimisation to this is to set the state of any cells you encounter along the line to whatever the final outcome is.</p>\n\n<p>This is more or less what I used in my <a href=\"http://www0.us.ioccc.org/years.html#2004\" rel=\"noreferrer\">2004 IOCCC winning entry</a>. Obviously that doesn't make good example code, though. ;)</p>\n\n<p>Edit: As loren points out, with these optimisations, you only need to pick the pixels along the edge of the map to trace from.</p>\n"
},
{
"answer_id": 174735,
"author": "Carl",
"author_id": 951280,
"author_profile": "https://Stackoverflow.com/users/951280",
"pm_score": 2,
"selected": false,
"text": "<p>TK's solution is the one that you would generally use for this sort of thing.</p>\n\n<p>For the partial lighting scenario, you could have it so that if a tile results in being in shadow, that tile is then split up into 4 tiles and each one of those is tested. You could then split that up as much as you wanted?</p>\n\n<p>Edit:</p>\n\n<p>You can also optimise it out a bit by not testing any of the tiles adjacent to a light - this would be more important to do when you have multiple light sources, I guess...</p>\n"
},
{
"answer_id": 174746,
"author": "Loren Pechtel",
"author_id": 10659,
"author_profile": "https://Stackoverflow.com/users/10659",
"pm_score": 3,
"selected": false,
"text": "<p>The algorithms being presented here seem to me to be doing more calculations than I think are needed. I have not tested this but I think it would work:</p>\n\n<p>Initially, mark all pixels as lit.</p>\n\n<p>For every pixel on the edge of the map: As Arachnid suggested, use Bresenham to trace a line from the pixel to the light. If that line strikes an obstruction then mark all pixels from the edge to just beyond the obstruction as being in shadow.</p>\n"
},
{
"answer_id": 174793,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 6,
"selected": true,
"text": "<p>The roguelike development community has a bit of an obsession with line-of-sight, field-of-view algorithms.</p>\n\n<p>Here's a link to a roguelike wiki article on the subject:\n<a href=\"http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision\" rel=\"noreferrer\">http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision</a></p>\n\n<p>For my roguelike game, I implemented a shadow casting algorithm (<a href=\"http://roguebasin.roguelikedevelopment.org/index.php?title=Shadow_casting\" rel=\"noreferrer\">http://roguebasin.roguelikedevelopment.org/index.php?title=Shadow_casting</a>) in Python. It was a bit complicated to put together, but ran reasonably efficiently (even in pure Python) and generated nice results.</p>\n\n<p>The \"Permissive Field of View\" seems to be gaining popularity as well:\n<a href=\"http://roguebasin.roguelikedevelopment.org/index.php?title=Permissive_Field_of_View\" rel=\"noreferrer\">http://roguebasin.roguelikedevelopment.org/index.php?title=Permissive_Field_of_View</a></p>\n"
},
{
"answer_id": 175004,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 2,
"selected": false,
"text": "<p>This is just for fun:</p>\n\n<p>You can replicate the Doom 3 approach in 2D if you first do a step to convert your tiles into lines. For instance,</p>\n\n<pre><code>- - - - -\n- X X X -\n- X X - -\n- X - - -\n- - - - L\n</code></pre>\n\n<p>...would be reduced into three lines connecting the corners of the solid object in a triangle.</p>\n\n<p>Then, do what the Doom 3 engine does: From the perspective of the light source, consider each \"wall\" that faces the light. (In this scene, only the diagonal line would be considered.) For each such line, project it into a trapezoid whose front edge is the original line, whose sides lie on lines from the light source through each end point, and whose back is far away, past the whole scene. So, it's a trapezoid that \"points at\" the light. It contains all the space that the wall casts its shadow on. Fill every tile in this trapezoid with darkness.</p>\n\n<p>Proceed through all such lines and you will end up with a \"stencil\" that includes all the tiles visible from the light source. Fill these tiles with the light color. You may wish to light the tile a little less as you get away from the source (\"attenuation\") or do other fancy stuff.</p>\n\n<p>Repeat for every light source in your scene.</p>\n"
},
{
"answer_id": 497739,
"author": "DShook",
"author_id": 370,
"author_profile": "https://Stackoverflow.com/users/370",
"pm_score": 2,
"selected": false,
"text": "<p>I've actually just recently wrote this functionality into one of my projects.</p>\n\n<pre><code>void Battle::CheckSensorRange(Unit* unit,bool fog){\n int sensorRange = 0;\n for(int i=0; i < unit->GetSensorSlots(); i++){\n if(unit->GetSensorSlot(i)->GetSlotEmpty() == false){\n sensorRange += unit->GetSensorSlot(i)->GetSensor()->GetRange()+1;\n }\n }\n int originX = unit->GetUnitX();\n int originY = unit->GetUnitY();\n\n float lineLength;\n vector <Place> maxCircle;\n\n //get a circle around the unit\n for(int i = originX - sensorRange; i < originX + sensorRange; i++){\n if(i < 0){\n continue;\n }\n for(int j = originY - sensorRange; j < originY + sensorRange; j++){\n if(j < 0){\n continue;\n }\n lineLength = sqrt( (float)((originX - i)*(originX - i)) + (float)((originY - j)*(originY - j)));\n if(lineLength < (float)sensorRange){\n Place tmp;\n tmp.x = i;\n tmp.y = j;\n maxCircle.push_back(tmp);\n }\n }\n }\n\n //if we're supposed to fog everything we don't have to do any fancy calculations\n if(fog){\n for(int circleI = 0; circleI < (int) maxCircle.size(); circleI++){\n Map->GetGrid(maxCircle[circleI].x,maxCircle[circleI].y)->SetFog(fog);\n }\n }else{\n\n bool LOSCheck = true;\n vector <bool> placeCheck;\n\n //have to check all of the tiles to begin with \n for(int circleI = 0; circleI < (int) maxCircle.size(); circleI++){\n placeCheck.push_back(true);\n }\n\n //for all tiles in the circle, check LOS\n for(int circleI = 0; circleI < (int) maxCircle.size(); circleI++){\n vector<Place> lineTiles;\n lineTiles = line(originX, originY, maxCircle[circleI].x, maxCircle[circleI].y);\n\n //check each tile in the line for LOS\n for(int lineI = 0; lineI < (int) lineTiles.size(); lineI++){\n if(false == CheckPlaceLOS(lineTiles[lineI], unit)){\n LOSCheck = false;\n\n //mark this tile not to be checked again\n placeCheck[circleI] = false;\n }\n if(false == LOSCheck){\n break;\n }\n }\n\n if(LOSCheck){\n Map->GetGrid(maxCircle[circleI].x,maxCircle[circleI].y)->SetFog(fog);\n }else{\n LOSCheck = true;\n }\n }\n }\n\n}\n</code></pre>\n\n<p>There's some extra stuff in there that you wouldn't need if you're adapting it for your own use. The type Place is just defined as an x and y position for conveniences sake.</p>\n\n<p>The line function is taken from Wikipedia with very small modifications. Instead of printing out x y coordinates I changed it to return a place vector with all the points in the line. The CheckPlaceLOS function just returns true or false based on if the tile has an object on it. There's some more optimizations that could be done with this but this is fine for my needs.</p>\n"
},
{
"answer_id": 11635950,
"author": "pents90",
"author_id": 369833,
"author_profile": "https://Stackoverflow.com/users/369833",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a very simple but fairly effective approach that uses linear time in the number of tiles on screen. Each tile is either opaque or transparent (that's given to us), and each can be visible or shaded (that's what we're trying to compute).</p>\n\n<p>We start by marking the avatar itself as \"visible\".</p>\n\n<p>We then apply this recursive rule to determine the visibility of the remaining tiles.</p>\n\n<ol>\n<li>If the tile is on the same row or column as the avatar, then it is only visible if the adjacent tile nearer to the avatar is visible and transparent.</li>\n<li>If the tile is on a 45 degree diagonal from the avatar, then it is only visible if the neighboring diagonal tile (towards the avatar) is visible and transparent.</li>\n<li>In all other cases, consider the three neighboring tiles that are closer to the avatar than the tile in question. For example, if this tile is at (x,y) and is above and to the right of the avatar, then the three tiles to consider are (x-1, y), (x, y-1) and (x-1, y-1). The tile in question is visible if <strong>any</strong> of those three tiles are visible and transparent.</li>\n</ol>\n\n<p>In order to make this work, the tiles must be inspected in a specific order to ensure that the recursive cases are already computed. Here is an example of a working ordering, starting from 0 (which is the avatar itself) and counting up:</p>\n\n<pre><code>9876789\n8543458\n7421247\n6310136\n7421247\n8543458\n9876789\n</code></pre>\n\n<p>Tiles with the same number can be inspected in any order amongst themselves.</p>\n\n<p>The result is not beautiful shadow-casting, but computes believable tile visibility.</p>\n"
},
{
"answer_id": 22411416,
"author": "Stoiko",
"author_id": 3360682,
"author_profile": "https://Stackoverflow.com/users/3360682",
"pm_score": 1,
"selected": false,
"text": "<p>i have implemented tilebased field of view in a single C function. here it is:\n<a href=\"https://gist.github.com/zloedi/9551625\" rel=\"nofollow\">https://gist.github.com/zloedi/9551625</a></p>\n"
},
{
"answer_id": 30893324,
"author": "Guest",
"author_id": 5019917,
"author_profile": "https://Stackoverflow.com/users/5019917",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is years old question, but for anyone searching for this style of stuff I'd like to offer a solution I used once for a roguelike of my own; manually \"precalculated\" FOV. If you field of view of light source has a maximum outer distance it's really not very much effort to hand draw the shadows created by blocking objects. You only need to draw 1/8 th of the circle (plus the straight and diagonal directions); you can use symmerty for the other eigths. You'll have as many shadowmaps as you have squares in that 1/8th of a circle. Then just OR them together according to objects. </p>\n\n<p>The three major pros for this are: \n1. It's very quick if implemented right\n2. You get to decide how the shadow should be cast, no comparing which algorith handles which situation the best\n3. No weird algorith induced edge cases which you have to somehow fix</p>\n\n<p>The con is you don't really get to implement a fun algorithm.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15255/"
] |
I'm writing a little tile-based game, for which I'd like to support light sources. But my algorithm-fu is too weak, hence I come to you for help.
The situation is like this: There is a tile-based map (held as a 2D array), containing a single light source and several items standing around. I want to calculate which tiles are lit up by the light source, and which are in shadow.
A visual aid of what it would look like, approximately. The L is the light source, the Xs are items blocking the light, the 0s are lit tiles, and the -s are tiles in shadow.
```
0 0 0 0 0 0 - - 0
0 0 0 0 0 0 - 0 0
0 0 0 0 0 X 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 L 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 X X X X 0 0
0 0 0 - - - - - 0
0 0 - - - - - - -
```
A fractional system would be even better, of course, where a tile can be in half-shadow due to being partially obscured. The algorithm wouldn't have to be perfect - just not obviously wrong and reasonably fast.
(Of course, there would be multiple light sources, but that's just a loop.)
Any takers?
|
The roguelike development community has a bit of an obsession with line-of-sight, field-of-view algorithms.
Here's a link to a roguelike wiki article on the subject:
<http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision>
For my roguelike game, I implemented a shadow casting algorithm (<http://roguebasin.roguelikedevelopment.org/index.php?title=Shadow_casting>) in Python. It was a bit complicated to put together, but ran reasonably efficiently (even in pure Python) and generated nice results.
The "Permissive Field of View" seems to be gaining popularity as well:
<http://roguebasin.roguelikedevelopment.org/index.php?title=Permissive_Field_of_View>
|
174,662 |
<p>I hope this isn't considered a duplicate since it's more pointed than similar questions (I'm curious about a specific weakness in C# to VB.net conversion utilities).</p>
<p>I've been looking at using a tool like this <a href="http://www.developerfusion.com/tools/convert/csharp-to-vb/" rel="nofollow noreferrer">.net code converter</a> to convert a class library to VB since I'm the only one in my group comfortable with C#. The problem I've run into is that it doesn't generate proper VB for automatic properties. It creates empty get/set routines. </p>
<p>So this:</p>
<pre><code>public string TransactionType { get; private set; }
</code></pre>
<p>Becomes this:</p>
<pre><code>Public Property TransactionType() As String
Get
End Get
Private Set(ByVal value As String)
End Set
End Property
</code></pre>
<p>The tools linked <a href="https://stackoverflow.com/questions/102956/c-vbnet-conversion" title="here">here</a> and <a href="https://stackoverflow.com/questions/88359/what-is-the-best-c-to-vbnet-converter">here</a> have similar issues - some create valid properties, but they don't respect the access level of the set routine.</p>
<p>Side question - If you were going to fix the converter on DeveloperFusion, would you have it return something like this?</p>
<pre><code>Private _TransactionType As String
Public Property TransactionType() As String
Get
Return _TransactionType
End Get
Private Set(ByVal value As String)
_TransactionType = value
End Set
End Property
</code></pre>
|
[
{
"answer_id": 174677,
"author": "Chad Moran",
"author_id": 25416,
"author_profile": "https://Stackoverflow.com/users/25416",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend compiling the code and using something like Red-Gate's reflector <a href=\"http://www.red-gate.com/products/reflector/index.htm\" rel=\"nofollow noreferrer\">http://www.red-gate.com/products/reflector/index.htm</a> to handle the conversion. Now it's not \"perfect,\" and I'm not sure if it handles automatic properties (though I'd imagine it would).</p>\n\n<p>What makes this possible is that when you compile .NET language down to IL they're exactly the same. The language is just another layer on top of that. So 2 properties that would look at the same in their native languages compile to the exact same IL code. So reversing this to other languages using something like Reflector is easy and quick.</p>\n"
},
{
"answer_id": 174711,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>As an answer to your side question: yes, that code is pretty much exactly what I'd get it to produce. You can't get it to do exactly what the C# code does, which is to make the name of the variable \"unspeakable\" (i.e. impossible to reference in code) but that's probably close enough.</p>\n"
},
{
"answer_id": 174713,
"author": "theraccoonbear",
"author_id": 7210,
"author_profile": "https://Stackoverflow.com/users/7210",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest checking out <a href=\"http://www.icsharpcode.net/OpenSource/SD/\" rel=\"nofollow noreferrer\">SharpDevelop</a> (sometimes written as #develop). It's an Open Source .NET IDE that, among other things, can convert (with some issues) from C# to VB.NET and vice versa.</p>\n"
},
{
"answer_id": 209425,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 2,
"selected": false,
"text": "<p>I stumbled on this while looking for a way to automate using reflector to translate code (since there are several plugins for it to generate code in other languages (even PowerShell)), but you made me wonder, so I tried it. With the compatibility set to .Net 3.5, it converts your example to this:</p>\n\n<pre><code>Property TransactionType As String\n Public Get\n Private Set(ByVal value As String)\nEnd Property\n</code></pre>\n\n<p>If you dig in, it does report that there are compiler generated methods which it doesn't export in VB.Net or C# with 3.5 compatability on ... HOWEVER, if you switch it to 2.0, the same code will generate this:</p>\n\n<pre><code>Property TransactionType As String\n Public Get\n Return Me.<TransactionType>k__BackingField\n End Get\n Private Set(ByVal value As String)\n Me.<TransactionType>k__BackingField = value\n End Set\nEnd Property\n\n<CompilerGenerated> _\nPrivate <TransactionType>k__BackingField As String\n</code></pre>\n\n<p>P.S.: if you try using a disassembler like Reflector to generate code, remember to keep the .pdb file around so you get proper names for the variables ;)</p>\n"
},
{
"answer_id": 259035,
"author": "James Crowley",
"author_id": 33682,
"author_profile": "https://Stackoverflow.com/users/33682",
"pm_score": 3,
"selected": true,
"text": "<p>We've now updated the code generator to support this scenario. If you spot any others that we're not doing very well, please do drop me a line.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8513/"
] |
I hope this isn't considered a duplicate since it's more pointed than similar questions (I'm curious about a specific weakness in C# to VB.net conversion utilities).
I've been looking at using a tool like this [.net code converter](http://www.developerfusion.com/tools/convert/csharp-to-vb/) to convert a class library to VB since I'm the only one in my group comfortable with C#. The problem I've run into is that it doesn't generate proper VB for automatic properties. It creates empty get/set routines.
So this:
```
public string TransactionType { get; private set; }
```
Becomes this:
```
Public Property TransactionType() As String
Get
End Get
Private Set(ByVal value As String)
End Set
End Property
```
The tools linked [here](https://stackoverflow.com/questions/102956/c-vbnet-conversion "here") and [here](https://stackoverflow.com/questions/88359/what-is-the-best-c-to-vbnet-converter) have similar issues - some create valid properties, but they don't respect the access level of the set routine.
Side question - If you were going to fix the converter on DeveloperFusion, would you have it return something like this?
```
Private _TransactionType As String
Public Property TransactionType() As String
Get
Return _TransactionType
End Get
Private Set(ByVal value As String)
_TransactionType = value
End Set
End Property
```
|
We've now updated the code generator to support this scenario. If you spot any others that we're not doing very well, please do drop me a line.
|
174,664 |
<p>I need to evaluate a mathmatical expression that is presented to me as a string in C#. Example noddy but gets the point across that the string as the expression.</p>
<p>I need the evaluate to then populate an int.</p>
<p>There is no Eval() in C# like in others langugaes...</p>
<pre><code>String myString = "3*4";
</code></pre>
<p>Edit:</p>
<p>I am on VS2008 </p>
<p>Tried the Microsoft.JScript. = Its deprecated method (but still complies - warning)</p>
<p>However the Microsoft.JScript dll that I have doens work on </p>
<blockquote>
<p>public object InvokeMember(string
name, BindingFlags invokeAttr, Binder
binder, object target, object[] args);</p>
</blockquote>
<p>Complains that there is a missing ";" go figure...</p>
<p>EDIT 2</p>
<p>Solution - was the codeDom one - it worked for as there are no security issue - only me ever going to be running the code. Many thanks for the replies ...</p>
<p>And the link to the new Dragon Book awesome </p>
<p>EDIT 3</p>
<p>Matt dataTable.Compute() also works - even better for the security conscious. (parameter checking noted)</p>
|
[
{
"answer_id": 174678,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the jscript interpreter.\nA great article for it is here: <a href=\"http://www.odetocode.com/Articles/80.aspx\" rel=\"nofollow noreferrer\">http://www.odetocode.com/Articles/80.aspx</a></p>\n"
},
{
"answer_id": 174682,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>When you say, \"like in other languages\" you should instead say, \"like in dynamic languages\". </p>\n\n<p>For dynamic languages like python, ruby, and many <em>interpreted</em> languages, an Eval() function is a natural element. In fact, it's probably even pretty trivial to implement your own.</p>\n\n<p>Howver, .Net is at it's core a static, strongly-typed, <em>compiled</em> platform (at least until the Dynamic Language Runtime gets more support). This has natural advantages like code-injection security and compile-time type checking that are hard to ignore. But it means an Eval() function isn't such a good fit- it wants to be able to compile the expression ahead of time. In this kind of platform, there are generally other, safer, ways to accomplish the same task.</p>\n"
},
{
"answer_id": 174686,
"author": "Mike Kantor",
"author_id": 14607,
"author_profile": "https://Stackoverflow.com/users/14607",
"pm_score": 0,
"selected": false,
"text": "<p>In an interpreted language you might have a chance of evaluating the string using the interpreter. In C# you need a parser for the language the string is written in (the language of mathematical expressions). This is a non-trivial exercise. If you want to do it, use a recursive-descent parser. The early chapters of the \"Dragon Book\" (Compilers: Design, etc. by Aho, Sethi and Ullman - 1st ed 1977 or 2nd ed 2007) have a good explanation of what you need to do.</p>\n\n<p>An alternative might be to include in your project a component written in perl, which is supposed to be available for .NET now, and use perl to do the evaluation.</p>\n"
},
{
"answer_id": 174689,
"author": "Luk",
"author_id": 5789,
"author_profile": "https://Stackoverflow.com/users/5789",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://www.odetocode.com/Articles/80.aspx\" rel=\"nofollow noreferrer\">jscript interpreter</a> could do, or you can write your own parser if the expression is simple (beware, it becomes complicated really fast). </p>\n\n<p>I'm pretty sure there is no direct \"Eval(string)\" method in C# since it is not interpreted.</p>\n\n<p>Keep in mind though that code interpretation is subject to code injection, be extra careful :)</p>\n"
},
{
"answer_id": 174691,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 0,
"selected": false,
"text": "<p>Will you need to access the values of other variables when calculating an expression?</p>\n"
},
{
"answer_id": 174722,
"author": "Tsvetomir Tsonev",
"author_id": 25449,
"author_profile": "https://Stackoverflow.com/users/25449",
"pm_score": 5,
"selected": true,
"text": "<p>The way I see it, you have two options - use an expression evaluator or construct, compile \nand run C# code on the fly.</p>\n\n<p>I would go with an expression evaluator library, as you do not have to worry about any security issues. That is, you might not be able to use code generation in medium trust environments, such as most shared hosting servers.</p>\n\n<p>Here is an example for generating code to evaluate expressions:\n<a href=\"http://www.vbforums.com/showthread.php?t=397264\" rel=\"nofollow noreferrer\">http://www.vbforums.com/showthread.php?t=397264</a></p>\n"
},
{
"answer_id": 174766,
"author": "Luk",
"author_id": 5789,
"author_profile": "https://Stackoverflow.com/users/5789",
"pm_score": 0,
"selected": false,
"text": "<p>After some googling, I see there's the possibility to create and compile code on the fly using CodeDom. (See a <a href=\"http://www.csharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx\" rel=\"nofollow noreferrer\">tutorial</a>). </p>\n\n<p>I personally don't think that approach is a very good idea, since the user can enter whatever code he wants, but that may be an area to explore (for example by only validating the input, and only allowing numbers and simple math operations).</p>\n"
},
{
"answer_id": 174949,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 1,
"selected": false,
"text": "<p>Check out <a href=\"http://codeplex.com/Flee\" rel=\"nofollow noreferrer\">Flee</a></p>\n"
},
{
"answer_id": 175262,
"author": "Matt Crouch",
"author_id": 1670022,
"author_profile": "https://Stackoverflow.com/users/1670022",
"pm_score": 5,
"selected": false,
"text": "<p>All the other answers are possible overkill.</p>\n\n<p>If all you need is simple arithmetic, do this.</p>\n\n<pre><code> DataTable dummy = new DataTable();\n Console.WriteLine(dummy.Compute(\"15 / 3\",string.Empty));\n</code></pre>\n\n<p>EDIT: a little more information. Check out the MSDN documentation for the <code>Expression</code> property of the <code>System.Data.DataColumn</code> class. The stuff on \"Expression Syntax\" outlines a list of commands you can use in addition to the arithmetic operators. (ex. IIF, LEN, etc.). Thanks everyone for voting up my first posted answer!</p>\n"
},
{
"answer_id": 175825,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 0,
"selected": false,
"text": "<p>Some other suggestions: </p>\n\n<ul>\n<li>Mono 2.0 (came out today) has an eval method. </li>\n<li>You can easily write a small domain specific in boo. </li>\n<li>You can create an old school recursive-descent EBNF parser.</li>\n</ul>\n"
},
{
"answer_id": 176336,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 4,
"selected": false,
"text": "<p>I did this as a personal exercise in C# a few weeks ago.</p>\n\n<p>It is quite a bit of code and is poorly commented in places. But it did work with a lot of test cases.</p>\n\n<p>Enjoy!</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\n\nnamespace StackOverflow\n{\n class Start\n {\n public static void Main(string[] args)\n {\n Evaluator ev;\n string variableValue, eq;\n Console.Write(\"Enter equation: \");\n eq = Console.ReadLine();\n\n while (eq != \"quit\")\n {\n ev = new Evaluator(eq);\n foreach (Variable v in ev.Variables)\n {\n Console.Write(v.Name + \" = \");\n variableValue = Console.ReadLine();\n ev.SetVariable(v.Name, Convert.ToDecimal(variableValue));\n }\n\n Console.WriteLine(ev.Evaluate());\n\n Console.Write(\"Enter equation: \");\n eq = Console.ReadLine();\n }\n }\n}\n\nclass EvalNode\n{\n public virtual decimal Evaluate()\n {\n return decimal.Zero;\n }\n}\n\nclass ValueNode : EvalNode\n{\n decimal value;\n\n public ValueNode(decimal v)\n {\n value = v;\n }\n\n public override decimal Evaluate()\n {\n return value;\n }\n\n public override string ToString()\n {\n return value.ToString();\n }\n}\n\nclass FunctionNode : EvalNode\n{\n EvalNode lhs = new ValueNode(decimal.Zero);\n EvalNode rhs = new ValueNode(decimal.Zero);\n string op = \"+\";\n\n public string Op\n {\n get { return op; }\n set\n {\n op = value;\n }\n }\n\n internal EvalNode Rhs\n {\n get { return rhs; }\n set\n {\n rhs = value;\n }\n }\n\n internal EvalNode Lhs\n {\n get { return lhs; }\n set\n {\n lhs = value;\n }\n }\n\n public override decimal Evaluate()\n {\n decimal result = decimal.Zero;\n\n switch (op)\n {\n case \"+\":\n result = lhs.Evaluate() + rhs.Evaluate();\n break;\n\n case \"-\":\n result = lhs.Evaluate() - rhs.Evaluate();\n break;\n\n case \"*\":\n result = lhs.Evaluate() * rhs.Evaluate();\n break;\n\n case \"/\":\n result = lhs.Evaluate() / rhs.Evaluate();\n break;\n\n case \"%\":\n result = lhs.Evaluate() % rhs.Evaluate();\n break;\n\n case \"^\":\n double x = Convert.ToDouble(lhs.Evaluate());\n double y = Convert.ToDouble(rhs.Evaluate());\n\n result = Convert.ToDecimal(Math.Pow(x, y));\n break;\n\n case \"!\":\n result = Factorial(lhs.Evaluate());\n break;\n }\n\n return result;\n }\n\n private decimal Factorial(decimal factor)\n {\n if (factor < 1)\n return 1;\n\n return factor * Factorial(factor - 1);\n }\n\n public override string ToString()\n {\n return \"(\" + lhs.ToString() + \" \" + op + \" \" + rhs.ToString() + \")\";\n }\n}\n\npublic class Evaluator\n{\n string equation = \"\";\n Dictionary<string, Variable> variables = new Dictionary<string, Variable>();\n\n public string Equation\n {\n get { return equation; }\n set { equation = value; }\n }\n\n public Variable[] Variables\n {\n get { return new List<Variable>(variables.Values).ToArray(); }\n }\n\n public void SetVariable(string name, decimal value)\n {\n if (variables.ContainsKey(name))\n {\n Variable x = variables[name];\n x.Value = value;\n variables[name] = x;\n }\n }\n\n public Evaluator(string equation)\n {\n this.equation = equation;\n SetVariables();\n }\n\n public decimal Evaluate()\n {\n return Evaluate(equation, new List<Variable>(variables.Values));\n }\n\n public decimal Evaluate(string text)\n {\n decimal result = decimal.Zero;\n equation = text;\n EvalNode parsed;\n\n equation = equation.Replace(\" \", \"\");\n\n parsed = Parse(equation, \"qx\");\n\n if (parsed != null)\n result = parsed.Evaluate();\n\n return result;\n }\n\n public decimal Evaluate(string text, List<Variable> variables)\n {\n foreach (Variable v in variables)\n {\n text = text.Replace(v.Name, v.Value.ToString());\n }\n\n return Evaluate(text);\n }\n\n private static bool EquationHasVariables(string equation)\n {\n Regex letters = new Regex(@\"[A-Za-z]\");\n\n return letters.IsMatch(equation);\n }\n\n private void SetVariables()\n {\n Regex letters = new Regex(@\"([A-Za-z]+)\");\n Variable v;\n\n foreach (Match m in letters.Matches(equation, 0))\n {\n v = new Variable(m.Groups[1].Value, decimal.Zero);\n\n if (!variables.ContainsKey(v.Name))\n {\n variables.Add(v.Name, v);\n }\n }\n }\n\n #region Parse V2\n\n private Dictionary<string, string> parenthesesText = new Dictionary<string, string>();\n\n /*\n * 1. All the text in first-level parentheses is replaced with replaceText plus an index value.\n * (All nested parentheses are parsed in recursive calls)\n * 2. The simple function is parsed given the order of operations (reverse priority to \n * keep the order of operations correct when evaluating).\n * a. Addition (+), subtraction (-) -> left to right\n * b. Multiplication (*), division (/), modulo (%) -> left to right\n * c. Exponents (^) -> right to left\n * d. Factorials (!) -> left to right\n * e. No op (number, replaced parentheses) \n * 3. When an op is found, a two recursive calls are generated -- parsing the LHS and \n * parsing the RHS.\n * 4. An EvalNode representing the root node of the evaluations tree is returned.\n * \n * Ex. 3 + 5 (3 + 5) * 8\n * + *\n * / \\ / \\\n * 3 5 + 8\n * / \\ \n * 3 + 5 * 8 3 5\n * +\n * / \\\n * 3 *\n * / \\\n * 5 8\n */\n\n /// <summary>\n /// Parses the expression and returns the root node of a tree.\n /// </summary>\n /// <param name=\"eq\">Equation to be parsed</param>\n /// <param name=\"replaceText\">Text base that replaces text in parentheses</param>\n /// <returns></returns>\n private EvalNode Parse(string eq, string replaceText)\n {\n int randomKeyIndex = 0;\n\n eq = eq.Replace(\" \", \"\");\n if (eq.Length == 0)\n {\n return new ValueNode(decimal.Zero);\n }\n\n int leftParentIndex = -1;\n int rightParentIndex = -1;\n SetIndexes(eq, ref leftParentIndex, ref rightParentIndex);\n\n //remove extraneous outer parentheses\n while (leftParentIndex == 0 && rightParentIndex == eq.Length - 1)\n {\n eq = eq.Substring(1, eq.Length - 2);\n SetIndexes(eq, ref leftParentIndex, ref rightParentIndex);\n }\n\n //Pull out all expressions in parentheses\n replaceText = GetNextReplaceText(replaceText, randomKeyIndex);\n\n while (leftParentIndex != -1 && rightParentIndex != -1)\n {\n //replace the string with a random set of characters, stored extracted text in dictionary keyed on the random set of chars\n\n string p = eq.Substring(leftParentIndex, rightParentIndex - leftParentIndex + 1);\n eq = eq.Replace(p, replaceText);\n parenthesesText.Add(replaceText, p);\n\n leftParentIndex = 0;\n rightParentIndex = 0;\n\n replaceText = replaceText.Remove(replaceText.LastIndexOf(randomKeyIndex.ToString()));\n randomKeyIndex++;\n replaceText = GetNextReplaceText(replaceText, randomKeyIndex);\n\n SetIndexes(eq, ref leftParentIndex, ref rightParentIndex);\n }\n\n /*\n * Be sure to implement these operators in the function node class\n */\n char[] ops_order0 = new char[2] { '+', '-' };\n char[] ops_order1 = new char[3] { '*', '/', '%' };\n char[] ops_order2 = new char[1] { '^' };\n char[] ops_order3 = new char[1] { '!' };\n\n /*\n * In order to evaluate nodes LTR, the right-most node must be the root node\n * of the tree, which is why we find the last index of LTR ops. The reverse \n * is the case for RTL ops.\n */\n\n int order0Index = eq.LastIndexOfAny(ops_order0);\n\n if (order0Index > -1)\n {\n return CreateFunctionNode(eq, order0Index, replaceText + \"0\");\n }\n\n int order1Index = eq.LastIndexOfAny(ops_order1);\n\n if (order1Index > -1)\n {\n return CreateFunctionNode(eq, order1Index, replaceText + \"0\");\n }\n\n int order2Index = eq.IndexOfAny(ops_order2);\n\n if (order2Index > -1)\n {\n return CreateFunctionNode(eq, order2Index, replaceText + \"0\");\n }\n\n int order3Index = eq.LastIndexOfAny(ops_order3);\n\n if (order3Index > -1)\n {\n return CreateFunctionNode(eq, order3Index, replaceText + \"0\");\n }\n\n //no operators...\n eq = eq.Replace(\"(\", \"\");\n eq = eq.Replace(\")\", \"\");\n\n if (char.IsLetter(eq[0]))\n {\n return Parse(parenthesesText[eq], replaceText + \"0\");\n }\n\n return new ValueNode(decimal.Parse(eq));\n }\n\n private string GetNextReplaceText(string replaceText, int randomKeyIndex)\n {\n while (parenthesesText.ContainsKey(replaceText))\n {\n replaceText = replaceText + randomKeyIndex.ToString();\n }\n return replaceText;\n }\n\n private EvalNode CreateFunctionNode(string eq, int index, string randomKey)\n {\n FunctionNode func = new FunctionNode();\n func.Op = eq[index].ToString();\n func.Lhs = Parse(eq.Substring(0, index), randomKey);\n func.Rhs = Parse(eq.Substring(index + 1), randomKey);\n\n return func;\n }\n\n #endregion\n\n /// <summary>\n /// Find the first set of parentheses\n /// </summary>\n /// <param name=\"eq\"></param>\n /// <param name=\"leftParentIndex\"></param>\n /// <param name=\"rightParentIndex\"></param>\n private static void SetIndexes(string eq, ref int leftParentIndex, ref int rightParentIndex)\n {\n leftParentIndex = eq.IndexOf('(');\n rightParentIndex = eq.IndexOf(')');\n int tempIndex = eq.IndexOf('(', leftParentIndex + 1);\n\n while (tempIndex != -1 && tempIndex < rightParentIndex)\n {\n rightParentIndex = eq.IndexOf(')', rightParentIndex + 1);\n tempIndex = eq.IndexOf('(', tempIndex + 1);\n }\n }\n}\n\npublic struct Variable\n{\n public string Name;\n public decimal Value;\n\n public Variable(string n, decimal v)\n {\n Name = n;\n Value = v;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 199944,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 1,
"selected": false,
"text": "<p>MS has a sample called Dynamic Query Library. It is provided by the LINQ team to dynamically construct LINQ queries such as:\n Dim query = Northwind.Products.Where(\"CategoryID=2\")\nYou might check to see if it offers rudimentary math capabilities.</p>\n"
},
{
"answer_id": 375707,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 0,
"selected": false,
"text": "<p>I have posted source for an ultra compact (1 class, < 10 KiB) Java Math Evaluator on my web site. It should be trivial to port this to C#. There are other ones out there that might do more, but this is very capable, and it's <em>tiny</em>.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to evaluate a mathmatical expression that is presented to me as a string in C#. Example noddy but gets the point across that the string as the expression.
I need the evaluate to then populate an int.
There is no Eval() in C# like in others langugaes...
```
String myString = "3*4";
```
Edit:
I am on VS2008
Tried the Microsoft.JScript. = Its deprecated method (but still complies - warning)
However the Microsoft.JScript dll that I have doens work on
>
> public object InvokeMember(string
> name, BindingFlags invokeAttr, Binder
> binder, object target, object[] args);
>
>
>
Complains that there is a missing ";" go figure...
EDIT 2
Solution - was the codeDom one - it worked for as there are no security issue - only me ever going to be running the code. Many thanks for the replies ...
And the link to the new Dragon Book awesome
EDIT 3
Matt dataTable.Compute() also works - even better for the security conscious. (parameter checking noted)
|
The way I see it, you have two options - use an expression evaluator or construct, compile
and run C# code on the fly.
I would go with an expression evaluator library, as you do not have to worry about any security issues. That is, you might not be able to use code generation in medium trust environments, such as most shared hosting servers.
Here is an example for generating code to evaluate expressions:
<http://www.vbforums.com/showthread.php?t=397264>
|
174,705 |
<p>We have TFS 2008 our build set up to checkout all AssemblyInfo.cs files in the project, update them with AssemblyInfoTask, and then either undo the checkout or checkin depending on whether the build passed or not. Unfortunately, when two builds are queued close together this results in a Partially completed build as the AssemblyInfo.cs files seem to be checked out at an earlier version to the previous checkin.</p>
<p>In order to get around this I thought that I could use the "Get" task to force the AssemblyInfo.cs files to the latest version before updating them, but this appears to have no effect. Any ideas?</p>
<pre><code><Target Name="AfterGet" Condition="'$(IsDesktopBuild)'!='true'">
<Message Text="SolutionRoot = $(SolutionRoot)" />
<Message Text="OutDir = $(OutDir)" />
<!-- Set the AssemblyInfoFiles items dynamically -->
<CreateItem Include="$(SolutionRoot)\Main\Source\InputApplicationSln\**\$(AssemblyInfoSpec)">
<Output ItemName="AssemblyInfoFiles" TaskParameter="Include" />
</CreateItem>
<Message Text="$(AssemblyInfoFiles)" />
<!-- When builds are queued up successively, it is possible for the next build to be set up before the AssemblyInfoSpec is checked in so we need to force
the latest these versions of these files to be got before a checkout -->
<Get Condition=" '$(SkipGet)'!='true' " TeamFoundationServerUrl="$(TeamFoundationServerUrl)" Workspace="$(WorkspaceName)" Filespec="$(AssemblyInfoSpec)" Recursive="$(RecursiveGet)" Force="$(ForceGet)" />
<Exec WorkingDirectory="$(SolutionRoot)\Main\Source\InputApplicationSln"
Command="$(TF) checkout /recursive $(AssemblyInfoSpec)"/>
</code></pre>
<p></p>
<p>
</p>
|
[
{
"answer_id": 174710,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried running it in <a href=\"http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx\" rel=\"nofollow noreferrer\">safe mode</a> - if that doesn't let you sort it out you can try the /resetsettings switch, which has sorted out similar problems for me in the past.</p>\n\n<p>/resetuserdata can also help.</p>\n"
},
{
"answer_id": 174737,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>look at the event log for you machine and see if VS threw any useful info in there; you may have to uninstall and reinstall</p>\n"
},
{
"answer_id": 776167,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I have VMWare installed on my machine. This was the cause of my problem!</p>\n\n<p>I started VS2005 in Windows compatibility 2000 mode as suggested above - it started up then shut down immediately. I then ran without compatibility mode and VS2005 now runs perfectly!</p>\n\n<p>I wasted half a day trying to sort this out!</p>\n\n<p>Thank you for your post!</p>\n\n<p>:)</p>\n"
},
{
"answer_id": 889430,
"author": "sean e",
"author_id": 103912,
"author_profile": "https://Stackoverflow.com/users/103912",
"pm_score": 0,
"selected": false,
"text": "<p>Try starting up with the log command:</p>\n\n<pre><code>devenv.exe /Log c:\\vs.log\n</code></pre>\n\n<p>And see if anything is noted in it.</p>\n\n<p>Another thing to try is to run VS in a temporary user account to see if the problem is strictly with your user environment or is system-wide. See <a href=\"https://stackoverflow.com/questions/851477/visual-studion-2008-exits-as-soon-as-i-open-it/853198#853198\">this post</a>.</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12565/"
] |
We have TFS 2008 our build set up to checkout all AssemblyInfo.cs files in the project, update them with AssemblyInfoTask, and then either undo the checkout or checkin depending on whether the build passed or not. Unfortunately, when two builds are queued close together this results in a Partially completed build as the AssemblyInfo.cs files seem to be checked out at an earlier version to the previous checkin.
In order to get around this I thought that I could use the "Get" task to force the AssemblyInfo.cs files to the latest version before updating them, but this appears to have no effect. Any ideas?
```
<Target Name="AfterGet" Condition="'$(IsDesktopBuild)'!='true'">
<Message Text="SolutionRoot = $(SolutionRoot)" />
<Message Text="OutDir = $(OutDir)" />
<!-- Set the AssemblyInfoFiles items dynamically -->
<CreateItem Include="$(SolutionRoot)\Main\Source\InputApplicationSln\**\$(AssemblyInfoSpec)">
<Output ItemName="AssemblyInfoFiles" TaskParameter="Include" />
</CreateItem>
<Message Text="$(AssemblyInfoFiles)" />
<!-- When builds are queued up successively, it is possible for the next build to be set up before the AssemblyInfoSpec is checked in so we need to force
the latest these versions of these files to be got before a checkout -->
<Get Condition=" '$(SkipGet)'!='true' " TeamFoundationServerUrl="$(TeamFoundationServerUrl)" Workspace="$(WorkspaceName)" Filespec="$(AssemblyInfoSpec)" Recursive="$(RecursiveGet)" Force="$(ForceGet)" />
<Exec WorkingDirectory="$(SolutionRoot)\Main\Source\InputApplicationSln"
Command="$(TF) checkout /recursive $(AssemblyInfoSpec)"/>
```
|
Have you tried running it in [safe mode](http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx) - if that doesn't let you sort it out you can try the /resetsettings switch, which has sorted out similar problems for me in the past.
/resetuserdata can also help.
|
174,727 |
<p>Oracle FAQ defines temp table space as follows:</p>
<blockquote>
<p>Temporary tablespaces are used to
manage space for database sort
operations and for storing global
temporary tables. For example, if you
join two large tables, and Oracle
cannot do the sort in memory, space
will be allocated in a temporary
tablespace for doing the sort
operation.</p>
</blockquote>
<p>That's great, but I need more detail about what exactly is using the space. Due to quirks of the application design most queries do some kind of sorting, so I need to narrow it down to client executable, target table, or SQL statement.</p>
<p>Essentially, I'm looking for clues to tell me more precisely what might be wrong with this (rather large application). Any sort of clue might be useful, so long as it is more precise than "sorting".</p>
|
[
{
"answer_id": 174765,
"author": "Michael OShea",
"author_id": 13178,
"author_profile": "https://Stackoverflow.com/users/13178",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not sure exactly what information you have to hand already, but using the following query will point out which program/user/sessions etc are currently using your temp space.</p>\n\n<pre><code>SELECT b.TABLESPACE\n , b.segfile#\n , b.segblk#\n , ROUND ( ( ( b.blocks * p.VALUE ) / 1024 / 1024 ), 2 ) size_mb\n , a.SID\n , a.serial#\n , a.username\n , a.osuser\n , a.program\n , a.status\n FROM v$session a\n , v$sort_usage b\n , v$process c\n , v$parameter p\n WHERE p.NAME = 'db_block_size'\n AND a.saddr = b.session_addr\n AND a.paddr = c.addr\nORDER BY b.TABLESPACE\n , b.segfile#\n , b.segblk#\n , b.blocks;\n</code></pre>\n\n<p>Once you find out which session is doing the damage, then have a look at the SQL being executed, and you should be on the right path.</p>\n"
},
{
"answer_id": 176665,
"author": "Andrew not the Saint",
"author_id": 23670,
"author_profile": "https://Stackoverflow.com/users/23670",
"pm_score": 2,
"selected": false,
"text": "<p>One rule of thumb is that almost any query that takes more than a second probably uses some TEMP space, and these are not the just ones involving ORDER BYs but also:</p>\n\n<ol>\n<li>GROUP BYs (SORT GROUPBY before 10.2 and HASH GROUPBY from 10.2 onwards)</li>\n<li>HASH JOINs or MERGE JOINs</li>\n<li>Global Temp Tables (obviously)</li>\n<li>Index rebuilds</li>\n</ol>\n\n<p>Occasionally, used space in temp tablespaces doesn't get released by Oracle (bug/quirk) so you need to manually drop a file from the tablespace, drop it from the file system and create another one.</p>\n"
},
{
"answer_id": 28084107,
"author": "Najee Ghanim",
"author_id": 4481610,
"author_profile": "https://Stackoverflow.com/users/4481610",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks goes for Michael OShea for his answer , </p>\n\n<p>but in case you have Oracle RAC multiple instances , then you will need this ...</p>\n\n<pre><code>SELECT b.TABLESPACE\n , b.segfile#\n , b.segblk#\n , ROUND ( ( ( b.blocks * p.VALUE ) / 1024 / 1024 ), 2 ) size_mb\n , a.inst_ID\n , a.SID\n , a.serial#\n , a.username\n , a.osuser\n , a.program\n , a.status\n FROM gv$session a\n , gv$sort_usage b\n , gv$process c\n , gv$parameter p\n WHERE p.NAME = 'db_block_size'\n AND a.saddr = b.session_addr\n AND a.paddr = c.addr\n -- AND b.TABLESPACE='TEMP2'\nORDER BY a.inst_ID , b.TABLESPACE\n , b.segfile#\n , b.segblk#\n , b.blocks;\n</code></pre>\n\n<p>and this the script to generate the kill statements:\nPlease review which sessions you will be killing ...</p>\n\n<pre><code>SELECT b.TABLESPACE, a.username , a.osuser , a.program , a.status ,\n 'ALTER SYSTEM KILL SESSION '''||a.SID||','||a.SERIAL#||',@'||a.inst_ID||''' IMMEDIATE;'\n FROM gv$session a\n , gv$sort_usage b\n , gv$process c\n , gv$parameter p\n WHERE p.NAME = 'db_block_size'\n AND a.saddr = b.session_addr\n AND a.paddr = c.addr\n -- AND b.TABLESPACE='TEMP'\nORDER BY a.inst_ID , b.TABLESPACE\n , b.segfile#\n , b.segblk#\n , b.blocks;\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13935/"
] |
Oracle FAQ defines temp table space as follows:
>
> Temporary tablespaces are used to
> manage space for database sort
> operations and for storing global
> temporary tables. For example, if you
> join two large tables, and Oracle
> cannot do the sort in memory, space
> will be allocated in a temporary
> tablespace for doing the sort
> operation.
>
>
>
That's great, but I need more detail about what exactly is using the space. Due to quirks of the application design most queries do some kind of sorting, so I need to narrow it down to client executable, target table, or SQL statement.
Essentially, I'm looking for clues to tell me more precisely what might be wrong with this (rather large application). Any sort of clue might be useful, so long as it is more precise than "sorting".
|
I'm not sure exactly what information you have to hand already, but using the following query will point out which program/user/sessions etc are currently using your temp space.
```
SELECT b.TABLESPACE
, b.segfile#
, b.segblk#
, ROUND ( ( ( b.blocks * p.VALUE ) / 1024 / 1024 ), 2 ) size_mb
, a.SID
, a.serial#
, a.username
, a.osuser
, a.program
, a.status
FROM v$session a
, v$sort_usage b
, v$process c
, v$parameter p
WHERE p.NAME = 'db_block_size'
AND a.saddr = b.session_addr
AND a.paddr = c.addr
ORDER BY b.TABLESPACE
, b.segfile#
, b.segblk#
, b.blocks;
```
Once you find out which session is doing the damage, then have a look at the SQL being executed, and you should be on the right path.
|
174,730 |
<p>Given a credit card number and no additional information, what is the best way in PHP to determine whether or not it is a valid number?</p>
<p>Right now I need something that will work with American Express, Discover, MasterCard, and Visa, but it might be helpful if it will also work with other types.</p>
|
[
{
"answer_id": 174738,
"author": "Chad Moran",
"author_id": 25416,
"author_profile": "https://Stackoverflow.com/users/25416",
"pm_score": -1,
"selected": false,
"text": "<p>This is only to make sure that the numbers are valid using some basic RegEX patterns.</p>\n\n<p>Note, this does not check to see if the numbers are in-use by someone.</p>\n\n<p><a href=\"http://www.roscripts.com/How_to_validate_credit_card_numbers-106.html\" rel=\"nofollow noreferrer\">http://www.roscripts.com/How_to_validate_credit_card_numbers-106.html</a></p>\n"
},
{
"answer_id": 174747,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": "<p><strong>PHP Code</strong></p>\n\n<pre><code>function validateCC($cc_num, $type) {\n\n if($type == \"American\") {\n $denum = \"American Express\";\n } elseif($type == \"Dinners\") {\n $denum = \"Diner's Club\";\n } elseif($type == \"Discover\") {\n $denum = \"Discover\";\n } elseif($type == \"Master\") {\n $denum = \"Master Card\";\n } elseif($type == \"Visa\") {\n $denum = \"Visa\";\n }\n\n if($type == \"American\") {\n $pattern = \"/^([34|37]{2})([0-9]{13})$/\";//American Express\n if (preg_match($pattern,$cc_num)) {\n $verified = true;\n } else {\n $verified = false;\n }\n\n\n } elseif($type == \"Dinners\") {\n $pattern = \"/^([30|36|38]{2})([0-9]{12})$/\";//Diner's Club\n if (preg_match($pattern,$cc_num)) {\n $verified = true;\n } else {\n $verified = false;\n }\n\n\n } elseif($type == \"Discover\") {\n $pattern = \"/^([6011]{4})([0-9]{12})$/\";//Discover Card\n if (preg_match($pattern,$cc_num)) {\n $verified = true;\n } else {\n $verified = false;\n }\n\n\n } elseif($type == \"Master\") {\n $pattern = \"/^([51|52|53|54|55]{2})([0-9]{14})$/\";//Mastercard\n if (preg_match($pattern,$cc_num)) {\n $verified = true;\n } else {\n $verified = false;\n }\n\n\n } elseif($type == \"Visa\") {\n $pattern = \"/^([4]{1})([0-9]{12,15})$/\";//Visa\n if (preg_match($pattern,$cc_num)) {\n $verified = true;\n } else {\n $verified = false;\n }\n\n }\n\n if($verified == false) {\n //Do something here in case the validation fails\n echo \"Credit card invalid. Please make sure that you entered a valid <em>\" . $denum . \"</em> credit card \";\n\n } else { //if it will pass...do something\n echo \"Your <em>\" . $denum . \"</em> credit card is valid\";\n }\n\n\n}\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code>echo validateCC(\"1738292928284637\", \"Dinners\");\n</code></pre>\n\n<p><strong>More theoric information can be found here:</strong></p>\n\n<p><a href=\"http://www.beachnet.com/~hstiles/cardtype.html\" rel=\"nofollow noreferrer\">Credit Card Validation - Check Digits</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"nofollow noreferrer\">Checksum</a></p>\n"
},
{
"answer_id": 174750,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 8,
"selected": true,
"text": "<p>There are three parts to the validation of the card number:</p>\n\n<ol>\n<li><strong>PATTERN</strong> - does it match an issuers pattern (e.g. VISA/Mastercard/etc.)</li>\n<li><strong>CHECKSUM</strong> - does it actually check-sum (e.g. not just 13 random numbers after \"34\" to make it an AMEX card number)</li>\n<li><strong>REALLY EXISTS</strong> - does it actually have an associated account (you are unlikely to get this without a merchant account)</li>\n</ol>\n\n<h2>Pattern</h2>\n\n<ul>\n<li>MASTERCARD Prefix=51-55, Length=16 (Mod10 checksummed)</li>\n<li>VISA Prefix=4, Length=13 or 16 (Mod10)</li>\n<li>AMEX Prefix=34 or 37, Length=15 (Mod10)</li>\n<li>Diners Club/Carte Prefix=300-305, 36 or 38, Length=14 (Mod10)</li>\n<li>Discover Prefix=6011,622126-622925,644-649,65, Length=16, (Mod10)</li>\n<li>etc. (<a href=\"http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29\" rel=\"noreferrer\">detailed list of prefixes</a>)</li>\n</ul>\n\n<h2>Checksum</h2>\n\n<p>Most cards use the Luhn algorithm for checksums:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"noreferrer\">Luhn Algorithm described on Wikipedia</a></p>\n\n<p>There are links to many implementations on the Wikipedia link, including PHP:</p>\n\n<pre><code><?\n/* Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org *\n * This code has been released into the public domain, however please *\n * give credit to the original author where possible. */\n\nfunction luhn_check($number) {\n\n // Strip any non-digits (useful for credit card numbers with spaces and hyphens)\n $number=preg_replace('/\\D/', '', $number);\n\n // Set the string length and parity\n $number_length=strlen($number);\n $parity=$number_length % 2;\n\n // Loop through each digit and do the maths\n $total=0;\n for ($i=0; $i<$number_length; $i++) {\n $digit=$number[$i];\n // Multiply alternate digits by two\n if ($i % 2 == $parity) {\n $digit*=2;\n // If the sum is two digits, add them together (in effect)\n if ($digit > 9) {\n $digit-=9;\n }\n }\n // Total up the digits\n $total+=$digit;\n }\n\n // If the total mod 10 equals 0, the number is valid\n return ($total % 10 == 0) ? TRUE : FALSE;\n\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 174759,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"nofollow noreferrer\">luhn algorithm</a> is a checksum that can used to validate the format of a lot of credit card formats (and also Canadian social insurance numbers...)</p>\n\n<p>The wikipedia article also links to many different implementations; here's a PHP one:</p>\n\n<p><a href=\"http://planzero.org/code/bits/viewcode.php?src=luhn_check.phps\" rel=\"nofollow noreferrer\">http://planzero.org/code/bits/viewcode.php?src=luhn_check.phps</a></p>\n"
},
{
"answer_id": 174772,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"http://web.archive.org/web/20080918014358/http://www.roughguidetophp.com/10-regular-expressions-you-just-cant-live-without-in-php/\" rel=\"noreferrer\">10 regular expressions you can't live without in PHP</a>:</p>\n\n<pre><code>function check_cc($cc, $extra_check = false){\n $cards = array(\n \"visa\" => \"(4\\d{12}(?:\\d{3})?)\",\n \"amex\" => \"(3[47]\\d{13})\",\n \"jcb\" => \"(35[2-8][89]\\d\\d\\d{10})\",\n \"maestro\" => \"((?:5020|5038|6304|6579|6761)\\d{12}(?:\\d\\d)?)\",\n \"solo\" => \"((?:6334|6767)\\d{12}(?:\\d\\d)?\\d?)\",\n \"mastercard\" => \"(5[1-5]\\d{14})\",\n \"switch\" => \"(?:(?:(?:4903|4905|4911|4936|6333|6759)\\d{12})|(?:(?:564182|633110)\\d{10})(\\d\\d)?\\d?)\",\n );\n $names = array(\"Visa\", \"American Express\", \"JCB\", \"Maestro\", \"Solo\", \"Mastercard\", \"Switch\");\n $matches = array();\n $pattern = \"#^(?:\".implode(\"|\", $cards).\")$#\";\n $result = preg_match($pattern, str_replace(\" \", \"\", $cc), $matches);\n if($extra_check && $result > 0){\n $result = (validatecard($cc))?1:0;\n }\n return ($result>0)?$names[sizeof($matches)-2]:false;\n}\n</code></pre>\n\n<p>Sample input:</p>\n\n<pre><code>$cards = array(\n \"4111 1111 1111 1111\",\n);\n\nforeach($cards as $c){\n $check = check_cc($c, true);\n if($check!==false)\n echo $c.\" - \".$check;\n else\n echo \"$c - Not a match\";\n echo \"<br/>\";\n}\n</code></pre>\n\n<p>This gives us</p>\n\n<pre>4111 1111 1111 1111 - Visa\n</pre>\n"
},
{
"answer_id": 178117,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": 2,
"selected": false,
"text": "<p>There is a PEAR package which handles the validation of many financial numbers, also credit card validation: <a href=\"http://pear.php.net/package/Validate_Finance_CreditCard\" rel=\"nofollow noreferrer\">http://pear.php.net/package/Validate_Finance_CreditCard</a></p>\n\n<p>By the way, here are some <a href=\"http://www.paypal.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm\" rel=\"nofollow noreferrer\">Test Credit Card Account Numbers</a> by PayPal.</p>\n"
},
{
"answer_id": 603361,
"author": "PartialOrder",
"author_id": 49529,
"author_profile": "https://Stackoverflow.com/users/49529",
"pm_score": 4,
"selected": false,
"text": "<p>It's probably better NOT to validate in code at your end. Send the card info right over to your payment gateway and then deal with their response. It helps them detect fraud if you don't do anything like Luhn checking first -- let them see the failed attempts.</p>\n"
},
{
"answer_id": 27445765,
"author": "parkamark",
"author_id": 241812,
"author_profile": "https://Stackoverflow.com/users/241812",
"pm_score": 0,
"selected": false,
"text": "<p>Just throwing in some further code snippets that others may find useful (not PHP code).</p>\n\n<p><strong>PYTHON</strong> (single line code; probably not that efficient)</p>\n\n<p>To validate:</p>\n\n<pre><code>>>> not(sum(map(int, ''.join(str(n*(i%2+1)) for i, n in enumerate(map(int, reversed('1234567890123452'))))))%10)\nTrue\n>>> not(sum(map(int, ''.join(str(n*(i%2+1)) for i, n in enumerate(map(int, reversed('1234567890123451'))))))%10)\nFalse\n</code></pre>\n\n<p>To return the required check digit:</p>\n\n<pre><code>>>> (10-sum(map(int, ''.join(str(n*(i%2+1)) for i, n in enumerate(map(int, reversed('123456789012345')), start=1)))))%10\n2\n>>> (10-sum(map(int, ''.join(str(n*(i%2+1)) for i, n in enumerate(map(int, reversed('234567890123451')), start=1)))))%10\n1\n</code></pre>\n\n<hr>\n\n<p><strong>MySQL Functions</strong></p>\n\n<p>Functions \"ccc\" and \"ccd\" (credit-card-check and credit-card-digit)</p>\n\n<p>Note that the \"ccc\" function has an additional check where if the calculated sum is 0, the returned result will always be FALSE, so an all zero CC number will never validate as being correct (under normal behaviour, it would validate correctly). This feature can be added/removed as required; maybe useful, depending on specific requirements.</p>\n\n<pre><code>DROP FUNCTION IF EXISTS ccc;\nDROP FUNCTION IF EXISTS ccd;\n\nDELIMITER //\n\nCREATE FUNCTION ccc (n TINYTEXT) RETURNS BOOL\nBEGIN\n DECLARE x TINYINT UNSIGNED;\n DECLARE l TINYINT UNSIGNED DEFAULT length(n);\n DECLARE i TINYINT UNSIGNED DEFAULT l;\n DECLARE s SMALLINT UNSIGNED DEFAULT 0;\n WHILE i > 0 DO\n SET x = mid(n,i,1);\n IF (l-i) mod 2 = 1 THEN\n SET x = x * 2;\n END IF;\n SET s = s + x div 10 + x mod 10;\n SET i = i - 1;\n END WHILE;\n RETURN s != 0 && s mod 10 = 0;\nEND;\n\nCREATE FUNCTION ccd (n TINYTEXT) RETURNS TINYINT\nBEGIN\n DECLARE x TINYINT UNSIGNED;\n DECLARE l TINYINT UNSIGNED DEFAULT length(n);\n DECLARE i TINYINT UNSIGNED DEFAULT l;\n DECLARE s SMALLINT UNSIGNED DEFAULT 0;\n WHILE i > 0 DO\n SET x = mid(n,i,1);\n IF (l-i) mod 2 = 0 THEN\n SET x = x * 2;\n END IF;\n SET s = s + x div 10 + x mod 10;\n SET i = i - 1;\n END WHILE;\n RETURN ceil(s/10)*10-s;\nEND;\n</code></pre>\n\n<p>Functions can then be used directly in SQL queries:</p>\n\n<pre><code>mysql> SELECT ccc(1234567890123452);\n+-----------------------+\n| ccc(1234567890123452) |\n+-----------------------+\n| 1 |\n+-----------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT ccc(1234567890123451);\n+-----------------------+\n| ccc(1234567890123451) |\n+-----------------------+\n| 0 |\n+-----------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT ccd(123456789012345);\n+----------------------+\n| ccd(123456789012345) |\n+----------------------+\n| 2 |\n+----------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT ccd(234567890123451);\n+----------------------+\n| ccd(234567890123451) |\n+----------------------+\n| 1 |\n+----------------------+\n1 row in set (0.00 sec)\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18986/"
] |
Given a credit card number and no additional information, what is the best way in PHP to determine whether or not it is a valid number?
Right now I need something that will work with American Express, Discover, MasterCard, and Visa, but it might be helpful if it will also work with other types.
|
There are three parts to the validation of the card number:
1. **PATTERN** - does it match an issuers pattern (e.g. VISA/Mastercard/etc.)
2. **CHECKSUM** - does it actually check-sum (e.g. not just 13 random numbers after "34" to make it an AMEX card number)
3. **REALLY EXISTS** - does it actually have an associated account (you are unlikely to get this without a merchant account)
Pattern
-------
* MASTERCARD Prefix=51-55, Length=16 (Mod10 checksummed)
* VISA Prefix=4, Length=13 or 16 (Mod10)
* AMEX Prefix=34 or 37, Length=15 (Mod10)
* Diners Club/Carte Prefix=300-305, 36 or 38, Length=14 (Mod10)
* Discover Prefix=6011,622126-622925,644-649,65, Length=16, (Mod10)
* etc. ([detailed list of prefixes](http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29))
Checksum
--------
Most cards use the Luhn algorithm for checksums:
[Luhn Algorithm described on Wikipedia](http://en.wikipedia.org/wiki/Luhn_algorithm)
There are links to many implementations on the Wikipedia link, including PHP:
```
<?
/* Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org *
* This code has been released into the public domain, however please *
* give credit to the original author where possible. */
function luhn_check($number) {
// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
$number=preg_replace('/\D/', '', $number);
// Set the string length and parity
$number_length=strlen($number);
$parity=$number_length % 2;
// Loop through each digit and do the maths
$total=0;
for ($i=0; $i<$number_length; $i++) {
$digit=$number[$i];
// Multiply alternate digits by two
if ($i % 2 == $parity) {
$digit*=2;
// If the sum is two digits, add them together (in effect)
if ($digit > 9) {
$digit-=9;
}
}
// Total up the digits
$total+=$digit;
}
// If the total mod 10 equals 0, the number is valid
return ($total % 10 == 0) ? TRUE : FALSE;
}
?>
```
|
174,748 |
<p>I have a table with one field that can point to a foreign key in one of 3 other tables based on what the descriminator value is (Project, TimeKeep, or CostCenter. Usually this is implemented with subclasses, and I am wondering if what I have below will work. <strong>Note the subclass name is the same as the parent class and the noteObject property is mapped to an instance variable of type java.lang.Object</strong> so it should accept either a Project, TimeKeep or CostCenter object as long as we cast to the correct type. Will hibernate allow this? Thanks.</p>
<pre><code><hibernate-mapping package="com.tlr.finance.mappings">
<class name="AdminNotes" table="admin_notes">
<id name="adminNoteId" column="admin_note_id" type="integer">
<generator class="identity" />
</id>
<discriminator column="note_type" type="string" />
<!-- make this property an enumerated type. It is the discriminator -->
<property name="adminNoteType" column="note_type" type="string" not-null="true" />
<property name="adminNote" column="note" type="string" not-null="true" />
<property name="adminNoteAdded" column="note_date" type="timestamp"
not-null="true" />
<subclass name="AdminNotes" discriminator-value="project" >
<many-to-one name="noteObject" column="object_id" class="PsData" /><!-- Project -->
</subclass>
<subclass name="AdminNotes" discriminator-value="user" >
<!-- rename timekeep to user -->
<many-to-one name="noteObject" column="object_id" class="Timekeep" /><!-- user -->
</subclass>
<subclass name="AdminNotes" discriminator-value="costCenter" >
<!-- rename timekeep to user -->
<many-to-one name="noteObject" column="object_id" class="CostCenter" /><!-- cost center -->
</subclass>
</class>
</hibernate-mapping>
</code></pre>
|
[
{
"answer_id": 175046,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 4,
"selected": true,
"text": "<p>Discriminators are used for storing class hierarchies in a single table. What you have there is a single class with multiple meanings. </p>\n\n<p><a href=\"http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/mapping.html#mapping-declaration-discriminator\" rel=\"nofollow noreferrer\">http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/mapping.html#mapping-declaration-discriminator</a></p>\n\n<blockquote>\n <p>The element is\n required for polymorphic persistence\n using the table-per-class-hierarchy\n mapping strategy and declares a\n discriminator column of the table. The\n discriminator column contains marker\n values that tell the persistence layer\n what subclass to instantiate for a\n particular row.</p>\n</blockquote>\n\n<p>I don't think you'll be able to use a single AdminNote class for each of those different meanings. The discriminator is used at the database level to help distinguish one subclass from another - it's not actually part of the java object model.</p>\n\n<p>You'll need to define multiple subclasses of AdminNote, one for each discriminator value.</p>\n"
},
{
"answer_id": 1109321,
"author": "Anton",
"author_id": 110311,
"author_profile": "https://Stackoverflow.com/users/110311",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK, you can reuse Java class names for subclass mappings if you use entity-names.</p>\n\n<p>Try the mapping below. Here the super class mapping itself is abstract. The subclasses use the same Java class and an entity-name for each subclass. You might need to put entity-name to the super class mapping. However, I would personally use separate Java subclasses for each subclass mapping, as with entity-names you would have to provide entity-name when you need to persist an object via the Session <a href=\"http://en.wikipedia.org/wiki/Application_programming_interface\" rel=\"nofollow noreferrer\">API</a>, or implement entity-names resolution in Tuplizer (<a href=\"http://en.wikipedia.org/wiki/Hibernate_%28Java%29\" rel=\"nofollow noreferrer\">Hibernate</a> 3.3.2) based on the adminNoteType field.</p>\n\n<pre><code><hibernate-mapping package=\"com.tlr.finance.mappings\">\n\n <class name=\"AdminNotes\" table=\"admin_notes\" abstract=\"true\">\n <id name=\"adminNoteId\" column=\"admin_note_id\" type=\"integer\">\n <generator class=\"identity\" />\n </id>\n\n <discriminator column=\"note_type\" type=\"string\" />\n\n <!-- Make this property an enumerated type. It is the discriminator. -->\n <property name=\"adminNoteType\" column=\"note_type\" type=\"string\" not-null=\"true\" />\n <property name=\"adminNote\" column=\"note\" type=\"string\" not-null=\"true\" />\n <property name=\"adminNoteAdded\" column=\"note_date\" type=\"timestamp\"\n not-null=\"true\" />\n\n <subclass name=\"AdminNotes\" discriminator-value=\"project\" entity-name=\"project\">\n <many-to-one name=\"noteObject\" column=\"object_id\" class=\"PsData\" /><!-- Project -->\n </subclass>\n\n <subclass name=\"AdminNotes\" discriminator-value=\"user\" entity-name=\"user\">\n <!-- rename timekeep to user -->\n <many-to-one name=\"noteObject\" column=\"object_id\" class=\"Timekeep\" /><!-- user -->\n </subclass>\n\n <subclass name=\"AdminNotes\" discriminator-value=\"costCenter\" entity-name=\"costCenter\">\n <!-- rename timekeep to user -->\n <many-to-one name=\"noteObject\" column=\"object_id\" class=\"CostCenter\" /><!-- cost center -->\n </subclass>\n </class>\n</hibernate-mapping>\n</code></pre>\n"
},
{
"answer_id": 1349412,
"author": "iammichael",
"author_id": 43367,
"author_profile": "https://Stackoverflow.com/users/43367",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of trying to use the inheritance capabilities to get the reference to the right class, you should instead consider using the <code><any/></code> mapping type where you use the <code>note_type</code> to determine the type that the <code>object_id</code> is referencing and thus setting your <code>noteObject</code> value to the proper object reference.</p>\n\n<p>For details on <code><any/></code>, see '<a href=\"http://www.nhforge.org/doc/nh/en/#mapping-types-anymapping\" rel=\"nofollow noreferrer\">Any type mappings</a>' in the <a href=\"http://en.wikipedia.org/wiki/NHibernate\" rel=\"nofollow noreferrer\">NHibernate</a> documentation, and the blog post <em><a href=\"http://ayende.com/Blog/archive/2009/04/21/nhibernate-mapping-ltanygt.aspx\" rel=\"nofollow noreferrer\">NHibernate Mapping</a></em>.</p>\n"
},
{
"answer_id": 3194612,
"author": "Damian Leszczyński - Vash",
"author_id": 390695,
"author_profile": "https://Stackoverflow.com/users/390695",
"pm_score": 1,
"selected": false,
"text": "<h3>Discriminator as integer</h3>\n<p>Normally, if you specify the discriminator-value as integer in subclass, you get the error</p>\n<blockquote>\n<p>Could not format discriminator value 'TYPE' to SQL string using the (...)</p>\n</blockquote>\n<p>If you wish to use the discriminator as an integer value, you need to first of all specify it for the base class as an integer by setting the discriminator-value attribute in the class element:</p>\n<pre><code><class name="AdminNotes" table="admin_notes" abstract="true" discriminator-value= "-1">\n</code></pre>\n<p>This replaces the default behavior where the discriminator is a class name when a value is not found.</p>\n<pre><code><hibernate-mapping package="com.tlr.finance.mappings">\n\n <class name="AdminNotes" table="admin_notes" abstract="true" discriminator-value= "-1">\n <id name="adminNoteId" column="admin_note_id" type="integer">\n <generator class="identity" />\n </id>\n <discriminator column="note_type" type="integer" />\n\n <!-- Make this property an enumerated type. It is the discriminator. -->\n <property name="adminNoteType" column="note_type" type="string" not-null="true" />\n <property name="adminNote" column="note" type="string" not-null="true" />\n <property name="adminNoteAdded" column="note_date" type="timestamp"\n not-null="true" />\n\n <subclass name="AdminNotes" discriminator-value="0" entity-name="project">\n <many-to-one name="noteObject" column="object_id" class="PsData" /><!-- Project -->\n </subclass>\n\n <subclass name="AdminNotes" discriminator-value="1" entity-name="user">\n <!-- Rename timekeep to user -->\n <many-to-one name="noteObject" column="object_id" class="Timekeep" /><!-- user -->\n </subclass>\n\n <subclass name="AdminNotes" discriminator-value="2" entity-name="costCenter">\n <!-- Rename timekeep to user -->\n <many-to-one name="noteObject" column="object_id" class="CostCenter" /><!-- cost center -->\n </subclass>\n </class>\n</hibernate-mapping>\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16404/"
] |
I have a table with one field that can point to a foreign key in one of 3 other tables based on what the descriminator value is (Project, TimeKeep, or CostCenter. Usually this is implemented with subclasses, and I am wondering if what I have below will work. **Note the subclass name is the same as the parent class and the noteObject property is mapped to an instance variable of type java.lang.Object** so it should accept either a Project, TimeKeep or CostCenter object as long as we cast to the correct type. Will hibernate allow this? Thanks.
```
<hibernate-mapping package="com.tlr.finance.mappings">
<class name="AdminNotes" table="admin_notes">
<id name="adminNoteId" column="admin_note_id" type="integer">
<generator class="identity" />
</id>
<discriminator column="note_type" type="string" />
<!-- make this property an enumerated type. It is the discriminator -->
<property name="adminNoteType" column="note_type" type="string" not-null="true" />
<property name="adminNote" column="note" type="string" not-null="true" />
<property name="adminNoteAdded" column="note_date" type="timestamp"
not-null="true" />
<subclass name="AdminNotes" discriminator-value="project" >
<many-to-one name="noteObject" column="object_id" class="PsData" /><!-- Project -->
</subclass>
<subclass name="AdminNotes" discriminator-value="user" >
<!-- rename timekeep to user -->
<many-to-one name="noteObject" column="object_id" class="Timekeep" /><!-- user -->
</subclass>
<subclass name="AdminNotes" discriminator-value="costCenter" >
<!-- rename timekeep to user -->
<many-to-one name="noteObject" column="object_id" class="CostCenter" /><!-- cost center -->
</subclass>
</class>
</hibernate-mapping>
```
|
Discriminators are used for storing class hierarchies in a single table. What you have there is a single class with multiple meanings.
<http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/mapping.html#mapping-declaration-discriminator>
>
> The element is
> required for polymorphic persistence
> using the table-per-class-hierarchy
> mapping strategy and declares a
> discriminator column of the table. The
> discriminator column contains marker
> values that tell the persistence layer
> what subclass to instantiate for a
> particular row.
>
>
>
I don't think you'll be able to use a single AdminNote class for each of those different meanings. The discriminator is used at the database level to help distinguish one subclass from another - it's not actually part of the java object model.
You'll need to define multiple subclasses of AdminNote, one for each discriminator value.
|
174,752 |
<p>I've got a lightbox textbox that is displayed using an AJAX call from an ASP.NET UpdatePanel. When the lightbox is displayed, I use the <code>focus()</code> method of a textbox that is in the lightbox to bring focus to the textbox right away.</p>
<p>When in Firefox, the text box gains focus with no problem. In IE, the text box does not gain focus unless I use </p>
<pre><code>setTimeout(function(){txtBx.focus()}, 500);
</code></pre>
<p>to make the focus method fire slightly later, after the DOM element has been loaded I'm assuming.</p>
<p>The problem is, immediately above that line, I'm already checking to see if the element is null/undefined, so the object already should exist if it hits that line, it just won't allow itself to gain focus right away for some reason.</p>
<p>Obviously setting a timer to "fix" this problem isn't the best or most elegant way to solve this. I'd like to be able to do something like the following: </p>
<pre><code>var txtBx = document.getElementById('txtBx');
if (txtPassword != null) {
txtPassword.focus();
while (txtPassword.focus === false) {
txtPassword.focus();
}
}
</code></pre>
<p>Is there any way to tell that a text box has focus so I could do something like above?</p>
<p>Or am I looking at this the wrong way?</p>
<p><strong>Edit</strong><br>
To clarify, I'm not calling the code on page load. The script <strong>is</strong> at the top of the page, however it is inside of a function that is called when ASP.NET's Asynchronous postback is complete, not when the page loads.</p>
<p>Because this is displayed after an Ajax update, the DOM should already be loaded, so I'm assuming that jQuery's <code>$(document).ready()</code> event won't be helpful here.</p>
|
[
{
"answer_id": 175046,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 4,
"selected": true,
"text": "<p>Discriminators are used for storing class hierarchies in a single table. What you have there is a single class with multiple meanings. </p>\n\n<p><a href=\"http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/mapping.html#mapping-declaration-discriminator\" rel=\"nofollow noreferrer\">http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/mapping.html#mapping-declaration-discriminator</a></p>\n\n<blockquote>\n <p>The element is\n required for polymorphic persistence\n using the table-per-class-hierarchy\n mapping strategy and declares a\n discriminator column of the table. The\n discriminator column contains marker\n values that tell the persistence layer\n what subclass to instantiate for a\n particular row.</p>\n</blockquote>\n\n<p>I don't think you'll be able to use a single AdminNote class for each of those different meanings. The discriminator is used at the database level to help distinguish one subclass from another - it's not actually part of the java object model.</p>\n\n<p>You'll need to define multiple subclasses of AdminNote, one for each discriminator value.</p>\n"
},
{
"answer_id": 1109321,
"author": "Anton",
"author_id": 110311,
"author_profile": "https://Stackoverflow.com/users/110311",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK, you can reuse Java class names for subclass mappings if you use entity-names.</p>\n\n<p>Try the mapping below. Here the super class mapping itself is abstract. The subclasses use the same Java class and an entity-name for each subclass. You might need to put entity-name to the super class mapping. However, I would personally use separate Java subclasses for each subclass mapping, as with entity-names you would have to provide entity-name when you need to persist an object via the Session <a href=\"http://en.wikipedia.org/wiki/Application_programming_interface\" rel=\"nofollow noreferrer\">API</a>, or implement entity-names resolution in Tuplizer (<a href=\"http://en.wikipedia.org/wiki/Hibernate_%28Java%29\" rel=\"nofollow noreferrer\">Hibernate</a> 3.3.2) based on the adminNoteType field.</p>\n\n<pre><code><hibernate-mapping package=\"com.tlr.finance.mappings\">\n\n <class name=\"AdminNotes\" table=\"admin_notes\" abstract=\"true\">\n <id name=\"adminNoteId\" column=\"admin_note_id\" type=\"integer\">\n <generator class=\"identity\" />\n </id>\n\n <discriminator column=\"note_type\" type=\"string\" />\n\n <!-- Make this property an enumerated type. It is the discriminator. -->\n <property name=\"adminNoteType\" column=\"note_type\" type=\"string\" not-null=\"true\" />\n <property name=\"adminNote\" column=\"note\" type=\"string\" not-null=\"true\" />\n <property name=\"adminNoteAdded\" column=\"note_date\" type=\"timestamp\"\n not-null=\"true\" />\n\n <subclass name=\"AdminNotes\" discriminator-value=\"project\" entity-name=\"project\">\n <many-to-one name=\"noteObject\" column=\"object_id\" class=\"PsData\" /><!-- Project -->\n </subclass>\n\n <subclass name=\"AdminNotes\" discriminator-value=\"user\" entity-name=\"user\">\n <!-- rename timekeep to user -->\n <many-to-one name=\"noteObject\" column=\"object_id\" class=\"Timekeep\" /><!-- user -->\n </subclass>\n\n <subclass name=\"AdminNotes\" discriminator-value=\"costCenter\" entity-name=\"costCenter\">\n <!-- rename timekeep to user -->\n <many-to-one name=\"noteObject\" column=\"object_id\" class=\"CostCenter\" /><!-- cost center -->\n </subclass>\n </class>\n</hibernate-mapping>\n</code></pre>\n"
},
{
"answer_id": 1349412,
"author": "iammichael",
"author_id": 43367,
"author_profile": "https://Stackoverflow.com/users/43367",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of trying to use the inheritance capabilities to get the reference to the right class, you should instead consider using the <code><any/></code> mapping type where you use the <code>note_type</code> to determine the type that the <code>object_id</code> is referencing and thus setting your <code>noteObject</code> value to the proper object reference.</p>\n\n<p>For details on <code><any/></code>, see '<a href=\"http://www.nhforge.org/doc/nh/en/#mapping-types-anymapping\" rel=\"nofollow noreferrer\">Any type mappings</a>' in the <a href=\"http://en.wikipedia.org/wiki/NHibernate\" rel=\"nofollow noreferrer\">NHibernate</a> documentation, and the blog post <em><a href=\"http://ayende.com/Blog/archive/2009/04/21/nhibernate-mapping-ltanygt.aspx\" rel=\"nofollow noreferrer\">NHibernate Mapping</a></em>.</p>\n"
},
{
"answer_id": 3194612,
"author": "Damian Leszczyński - Vash",
"author_id": 390695,
"author_profile": "https://Stackoverflow.com/users/390695",
"pm_score": 1,
"selected": false,
"text": "<h3>Discriminator as integer</h3>\n<p>Normally, if you specify the discriminator-value as integer in subclass, you get the error</p>\n<blockquote>\n<p>Could not format discriminator value 'TYPE' to SQL string using the (...)</p>\n</blockquote>\n<p>If you wish to use the discriminator as an integer value, you need to first of all specify it for the base class as an integer by setting the discriminator-value attribute in the class element:</p>\n<pre><code><class name="AdminNotes" table="admin_notes" abstract="true" discriminator-value= "-1">\n</code></pre>\n<p>This replaces the default behavior where the discriminator is a class name when a value is not found.</p>\n<pre><code><hibernate-mapping package="com.tlr.finance.mappings">\n\n <class name="AdminNotes" table="admin_notes" abstract="true" discriminator-value= "-1">\n <id name="adminNoteId" column="admin_note_id" type="integer">\n <generator class="identity" />\n </id>\n <discriminator column="note_type" type="integer" />\n\n <!-- Make this property an enumerated type. It is the discriminator. -->\n <property name="adminNoteType" column="note_type" type="string" not-null="true" />\n <property name="adminNote" column="note" type="string" not-null="true" />\n <property name="adminNoteAdded" column="note_date" type="timestamp"\n not-null="true" />\n\n <subclass name="AdminNotes" discriminator-value="0" entity-name="project">\n <many-to-one name="noteObject" column="object_id" class="PsData" /><!-- Project -->\n </subclass>\n\n <subclass name="AdminNotes" discriminator-value="1" entity-name="user">\n <!-- Rename timekeep to user -->\n <many-to-one name="noteObject" column="object_id" class="Timekeep" /><!-- user -->\n </subclass>\n\n <subclass name="AdminNotes" discriminator-value="2" entity-name="costCenter">\n <!-- Rename timekeep to user -->\n <many-to-one name="noteObject" column="object_id" class="CostCenter" /><!-- cost center -->\n </subclass>\n </class>\n</hibernate-mapping>\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
I've got a lightbox textbox that is displayed using an AJAX call from an ASP.NET UpdatePanel. When the lightbox is displayed, I use the `focus()` method of a textbox that is in the lightbox to bring focus to the textbox right away.
When in Firefox, the text box gains focus with no problem. In IE, the text box does not gain focus unless I use
```
setTimeout(function(){txtBx.focus()}, 500);
```
to make the focus method fire slightly later, after the DOM element has been loaded I'm assuming.
The problem is, immediately above that line, I'm already checking to see if the element is null/undefined, so the object already should exist if it hits that line, it just won't allow itself to gain focus right away for some reason.
Obviously setting a timer to "fix" this problem isn't the best or most elegant way to solve this. I'd like to be able to do something like the following:
```
var txtBx = document.getElementById('txtBx');
if (txtPassword != null) {
txtPassword.focus();
while (txtPassword.focus === false) {
txtPassword.focus();
}
}
```
Is there any way to tell that a text box has focus so I could do something like above?
Or am I looking at this the wrong way?
**Edit**
To clarify, I'm not calling the code on page load. The script **is** at the top of the page, however it is inside of a function that is called when ASP.NET's Asynchronous postback is complete, not when the page loads.
Because this is displayed after an Ajax update, the DOM should already be loaded, so I'm assuming that jQuery's `$(document).ready()` event won't be helpful here.
|
Discriminators are used for storing class hierarchies in a single table. What you have there is a single class with multiple meanings.
<http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/mapping.html#mapping-declaration-discriminator>
>
> The element is
> required for polymorphic persistence
> using the table-per-class-hierarchy
> mapping strategy and declares a
> discriminator column of the table. The
> discriminator column contains marker
> values that tell the persistence layer
> what subclass to instantiate for a
> particular row.
>
>
>
I don't think you'll be able to use a single AdminNote class for each of those different meanings. The discriminator is used at the database level to help distinguish one subclass from another - it's not actually part of the java object model.
You'll need to define multiple subclasses of AdminNote, one for each discriminator value.
|
174,762 |
<p>I have a form that I would like to style. specifcally I would like to chnage the background color of the form item's label. (the backgorundColor attribute changes both the label and the inputs background color)</p>
<p>i.e.</p>
<pre>
<code>
<mx:Form>
<mx:FormItem label="username:">
<mx:TextInput />
</mx:FormItem>
</mx:Form>
</code>
</pre>
<p>I would like to make the label with 'username:' have a different background color, but have the text input still be the default background color. </p>
<p>is this possible with a FormItem ?</p>
|
[
{
"answer_id": 175076,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": -1,
"selected": false,
"text": "<p>Try using the flex style explorers to create your desired style:</p>\n\n<ul>\n<li><p><a href=\"http://examples.adobe.com/flex3/consulting/styleexplorer/Flex3StyleExplorer.html\" rel=\"nofollow noreferrer\">Flex 3 Style Explorer</a></p></li>\n<li><p><a href=\"http://examples.adobe.com/flex2/consulting/styleexplorer/Flex2StyleExplorer.html\" rel=\"nofollow noreferrer\">Flex 2 Style Explorer</a></p></li>\n</ul>\n\n<p>I used the TextArea in the style explorer and formatted the background color which gave the following css output:</p>\n\n<pre><code>TextArea {\n backgroundColor: #0000ff;\n}\n</code></pre>\n\n<p>You can change this to the following to include in you stylesheet:</p>\n\n<pre><code>.formLabel {\n backgroundColor: #0000ff;\n}\n</code></pre>\n\n<p>Then in the FormItem tag:</p>\n\n<pre><code><FormItem label=\"Label\" styleName=\"formLabel\" />\n</code></pre>\n\n<p>More info on Flex Style Sheets:\n<a href=\"http://www.adobe.com/devnet/flex/quickstart/styling_components/\" rel=\"nofollow noreferrer\">Flex Style Sheets</a></p>\n\n<p>These examples will show that you can declare styles within the mxml Style tags rather than an external style sheet if you would like.</p>\n"
},
{
"answer_id": 176096,
"author": "JustLogic",
"author_id": 21664,
"author_profile": "https://Stackoverflow.com/users/21664",
"pm_score": 3,
"selected": true,
"text": "<p>A formitem has an object it uses to display the label called the FormItemLabel, this objects purpose is so you can style the label of a form item.</p>\n\n<p>In flex 2 to change the style you can try:</p>\n\n<pre><code>FormItemLabel {\n\n}\n</code></pre>\n\n<p>However I looked over the flex 2 lang ref and it doesn't seem like you can change the background color of the label. <a href=\"http://livedocs.adobe.com/flex/2/langref/mx/controls/FormItemLabel.html#styleSummary\" rel=\"nofollow noreferrer\">Click here for lang ref link</a></p>\n\n<p>If you are using flex 3 the desired way to change the label of the FormItem is through the formitems labelStyleName</p>\n\n<pre><code>FormItem {\n labelStyleName: newStyle;\n}\n</code></pre>\n\n<p>However once again I don't believe they added the ability to change the background color of the label itself. <a href=\"http://livedocs.adobe.com/flex/3/langref/mx/controls/FormItemLabel.html\" rel=\"nofollow noreferrer\">Click here for lang ref link</a></p>\n\n<p>Best choice of action if this is required would be to extend the formitem class, unless anyone else has any ideas.</p>\n\n<p>Hope this helps...</p>\n"
},
{
"answer_id": 5143340,
"author": "Zmogas",
"author_id": 301769,
"author_profile": "https://Stackoverflow.com/users/301769",
"pm_score": 0,
"selected": false,
"text": "<p>As I see problem \"hangs unanswered\" for two years... and I need exactly the same functionality - different background color for label side.</p>\n\n<p>I am using Flex3. I tried Form background - that changes whole form. Then tried FormItem - if you have only text entry - it does cover background, but if you have few buttons, gap between them is also of the same color. You then need extra HBox with another background. And also there is no gap between Label background and input control.</p>\n\n<p>I do not want to rewrite FormItem control.</p>\n\n<p>Seems I will need to use my ancestors style: Grid instead of forms and GridItem instead of FormItem. Then you can style each cell in whatever color. :o(</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
I have a form that I would like to style. specifcally I would like to chnage the background color of the form item's label. (the backgorundColor attribute changes both the label and the inputs background color)
i.e.
```
<mx:Form>
<mx:FormItem label="username:">
<mx:TextInput />
</mx:FormItem>
</mx:Form>
```
I would like to make the label with 'username:' have a different background color, but have the text input still be the default background color.
is this possible with a FormItem ?
|
A formitem has an object it uses to display the label called the FormItemLabel, this objects purpose is so you can style the label of a form item.
In flex 2 to change the style you can try:
```
FormItemLabel {
}
```
However I looked over the flex 2 lang ref and it doesn't seem like you can change the background color of the label. [Click here for lang ref link](http://livedocs.adobe.com/flex/2/langref/mx/controls/FormItemLabel.html#styleSummary)
If you are using flex 3 the desired way to change the label of the FormItem is through the formitems labelStyleName
```
FormItem {
labelStyleName: newStyle;
}
```
However once again I don't believe they added the ability to change the background color of the label itself. [Click here for lang ref link](http://livedocs.adobe.com/flex/3/langref/mx/controls/FormItemLabel.html)
Best choice of action if this is required would be to extend the formitem class, unless anyone else has any ideas.
Hope this helps...
|
174,773 |
<p>I have TurtoiseSVN and ankhSVN installed. I created a repository on my computer.. "C:\Documents and Settings\user1\My Documents\Subversion\Repository\"</p>
<p>I am trying to connect to this repository from my co-workers computer. What should this URL be?</p>
<p>Any help would be great. Thanks.</p>
|
[
{
"answer_id": 174789,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "<p>Try svn://xxx.xxx.xxx.xxx/Repository/</p>\n\n<p>The default port is 3690 if you have a firewall to configure.</p>\n"
},
{
"answer_id": 174798,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 1,
"selected": false,
"text": "<p>Off the top of my head...</p>\n\n<p>svn://YOURCOMPUTERNAME/repository/project/trunk</p>\n\n<p>or</p>\n\n<p>svn://xxx.yyy.zzz.www/repository/project/trunk</p>\n\n<p>Don't forget to open the firewall if you are running on WindowsXP.</p>\n"
},
{
"answer_id": 174809,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "<pre><code>file:///\\\\COMPUTERNAME\\SharedFolderName\\\n</code></pre>\n\n<p>I probably don't have the slashes right, but it's something crazy like that.</p>\n\n<p>Oh, and he'll have to create a folder share. That would be the easiest way to do it.</p>\n"
},
{
"answer_id": 174818,
"author": "iainmcgin",
"author_id": 24068,
"author_profile": "https://Stackoverflow.com/users/24068",
"pm_score": 5,
"selected": true,
"text": "<p>You will need to run the svnserve daemon on your computer, or run an apache server with the necessary modules, to allow your colleague to access this locally stored repository. For a simple case like this I would recommend svnserve, it should be simpler to configure and run.</p>\n\n<p>The url would then be:</p>\n\n<pre><code>svn://<your_ip>/<repository_name>\n</code></pre>\n\n<p>As opposed to an http or file protocol URL for apache and local filesystem based repositories.</p>\n\n<p>Read this page for details on how to set up svnserve it on Windows:</p>\n\n<p><a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-serversetup-svnserve.html\" rel=\"noreferrer\">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-serversetup-svnserve.html</a></p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316/"
] |
I have TurtoiseSVN and ankhSVN installed. I created a repository on my computer.. "C:\Documents and Settings\user1\My Documents\Subversion\Repository\"
I am trying to connect to this repository from my co-workers computer. What should this URL be?
Any help would be great. Thanks.
|
You will need to run the svnserve daemon on your computer, or run an apache server with the necessary modules, to allow your colleague to access this locally stored repository. For a simple case like this I would recommend svnserve, it should be simpler to configure and run.
The url would then be:
```
svn://<your_ip>/<repository_name>
```
As opposed to an http or file protocol URL for apache and local filesystem based repositories.
Read this page for details on how to set up svnserve it on Windows:
<http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-serversetup-svnserve.html>
|
174,774 |
<p>I created an <code>ObjectInputSteam</code> and <code>ObjectOutputStream</code> on a blocking <code>SocketChannel</code> and am trying to read and write concurrently. My code is something like this:</p>
<pre><code>socketChannel = SocketChannel.open(destNode);
objectOutputStream = new ObjectOutputStream(Channels.newOutputStream(socketChannel));
objectInputStream = new ObjectInputStream(Channels.newInputStream(socketChannel));
Thread replyThread = new Thread("SendRunnable-ReplyThread") {
@Override
public void run() {
try {
byte reply = objectInputStream.readByte();//(A)
//..process reply
} catch (Throwable e) {
logger.warn("Problem reading receive reply.", e);
}
}
};
replyThread.start();
objectOutputStream.writeObject(someObject);//(B)
//..more writing
</code></pre>
<p>Problem is the write at line (B) blocks until the read at line (A) completes (blocks on the object returned by <code>SelectableChannel#blockingLock()</code> ). But app logic dictates that the read will not complete until all the writes complete, so we have an effective deadlock.</p>
<p><code>SocketChannel</code> javadocs say that concurrent reads and writes are supported.</p>
<p>I experienced no such problem when I tried a regular Socket solution:</p>
<pre><code>Socket socket = new Socket();
socket.connect(destNode);
final OutputStream outputStream = socket.getOutputStream();
objectOutputStream = new ObjectOutputStream(outputStream);
objectInputStream = new ObjectInputStream(socket.getInputStream());
</code></pre>
<p>However, then I cannot take advantage of the performance benefits of <code>FileChannel#transferTo(...)</code></p>
|
[
{
"answer_id": 175025,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to use InputStream and OutputStream concurrently with SocketChannel, from looking at the source, it appears that you need to call SocketChannel.socket() and use the streams from that which behave slightly differently.</p>\n"
},
{
"answer_id": 179104,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 3,
"selected": false,
"text": "<p>This seems to be a bug in <code>java.nio.channels.Channels</code> (thanks to Tom Hawtin; post it as an answer next time). A good description and workaround are described <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4774871\" rel=\"noreferrer\">here</a> (actually a duplicate of the bug Tom listed):</p>\n\n<p>I tested the workaround and it works.</p>\n"
},
{
"answer_id": 179806,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting bug! You say though that you can't use FileChannel#transferTo. How about wrapping the I/O streams of the non-NIO socket into channels using Channesl#newChannel before passing to FileChannel#transferTo?</p>\n"
},
{
"answer_id": 546419,
"author": "Nick",
"author_id": 21399,
"author_profile": "https://Stackoverflow.com/users/21399",
"pm_score": 2,
"selected": false,
"text": "<p>The workaround in the bug report worked for me. It's worth noting that only <em>one</em> of input or output needs to be wrapped for the workaround to work - so if performance is especially important in one direction then you can wrap the less important one and be sure that the other will get all the optimisations available to it.</p>\n\n<pre><code>public InputStream getInputStream() throws IOException {\n return Channels.newInputStream(new ReadableByteChannel() {\n public int read(ByteBuffer dst) throws IOException {\n return socketChannel.read(dst);\n }\n public void close() throws IOException {\n socketChannel.close();\n }\n public boolean isOpen() {\n return socketChannel.isOpen();\n }\n });\n}\n\npublic OutputStream getOutputStream() throws IOException {\n return Channels.newOutputStream(socketChannel);\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792/"
] |
I created an `ObjectInputSteam` and `ObjectOutputStream` on a blocking `SocketChannel` and am trying to read and write concurrently. My code is something like this:
```
socketChannel = SocketChannel.open(destNode);
objectOutputStream = new ObjectOutputStream(Channels.newOutputStream(socketChannel));
objectInputStream = new ObjectInputStream(Channels.newInputStream(socketChannel));
Thread replyThread = new Thread("SendRunnable-ReplyThread") {
@Override
public void run() {
try {
byte reply = objectInputStream.readByte();//(A)
//..process reply
} catch (Throwable e) {
logger.warn("Problem reading receive reply.", e);
}
}
};
replyThread.start();
objectOutputStream.writeObject(someObject);//(B)
//..more writing
```
Problem is the write at line (B) blocks until the read at line (A) completes (blocks on the object returned by `SelectableChannel#blockingLock()` ). But app logic dictates that the read will not complete until all the writes complete, so we have an effective deadlock.
`SocketChannel` javadocs say that concurrent reads and writes are supported.
I experienced no such problem when I tried a regular Socket solution:
```
Socket socket = new Socket();
socket.connect(destNode);
final OutputStream outputStream = socket.getOutputStream();
objectOutputStream = new ObjectOutputStream(outputStream);
objectInputStream = new ObjectInputStream(socket.getInputStream());
```
However, then I cannot take advantage of the performance benefits of `FileChannel#transferTo(...)`
|
This seems to be a bug in `java.nio.channels.Channels` (thanks to Tom Hawtin; post it as an answer next time). A good description and workaround are described [here](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4774871) (actually a duplicate of the bug Tom listed):
I tested the workaround and it works.
|
174,841 |
<p>Why is it that when I use a converter in my binding expression in WPF, the value is not updated when the data is updated.</p>
<p>I have a simple Person data model:</p>
<pre><code>class Person : INotifyPropertyChanged
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
</code></pre>
<p>My binding expression looks like this:</p>
<pre><code><TextBlock Text="{Binding Converter={StaticResource personNameConverter}" />
</code></pre>
<p>My converter looks like this:</p>
<pre><code>class PersonNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Person p = value as Person;
return p.FirstName + " " + p.LastName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>If I bind the data without a converter it works great:</p>
<pre><code><TextBlock Text="{Binding Path=FirstName}" />
<TextBlock Text="{Binding Path=LastName}" />
</code></pre>
<p>What am I missing?</p>
<p>EDIT:
Just to clarify a few things, both Joel and Alan are correct regarding the INotifyPropertyChanged interface that needs to be implemented. In reality I do actually implement it but it still doesn't work.</p>
<p>I can't use multiple TextBlock elements because I'm trying to bind the Window Title to the full name, and the Window Title does not take a template.</p>
<p>Finally, it is an option to add a compound property "FullName" and bind to it, but I'm still wondering why updating does not happen when the binding uses a converter. Even when I put a break point in the converter code, the debugger just doesn't get there when an update is done to the underlying data :-(</p>
<p>Thanks,
Uri</p>
|
[
{
"answer_id": 175050,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 5,
"selected": true,
"text": "<p><strong>(see edits below; latest: #2)</strong></p>\n\n<p>It isn't updating because your <code>Person</code> object is not capable of notifying anything that the value of <code>FirstName</code> or <code>LastName</code> has changed. <a href=\"https://stackoverflow.com/questions/159088/dependencyproperty-and-databinding\">See this Question</a>.</p>\n\n<p>And here's how you implement <code>INotifyPropertyChanged</code>. (<strong>Updated, see Edit 2</strong>)</p>\n\n<pre><code>using System.ComponentModel;\n\nclass Person : INotifyPropertyChanged {\n public event PropertyChangedEventHandler PropertyChanged;\n\n string _firstname;\n public string FirstName {\n get {\n return _firstname;\n }\n set {\n _firstname = value;\n onPropertyChanged( \"FirstName\", \"FullName\" );\n }\n }\n\n string _lastname;\n public string LastName {\n get {\n return _lastname;\n }\n set {\n _lastname = value;\n onPropertyChanged( \"LastName\", \"FullName\" );\n }\n }\n\n public string FullName {\n get {\n return _firstname + \" \" + _lastname;\n }\n }\n\n void onPropertyChanged( params string[] propertyNames ) {\n PropertyChangedEventHandler handler = PropertyChanged;\n\n if ( handler != null ) {\n foreach ( var pn in propertyNames ) {\n handler( this, new PropertyChangedEventArgs( pn ) );\n }\n }\n }\n}\n</code></pre>\n\n<p><strong>Edit 1</strong></p>\n\n<p>Actually, since you're after the first name and last name updating, and <code>Path=FirstName</code> and such works just fine, I don't think you'll need the converter at all. Multiple <code>TextBlocks</code> are just as valid, and can actually work better when you're localizing to a right-to-left language.</p>\n\n<p><strong>Edit 2</strong></p>\n\n<p>I've figured it out. It's not being notified that the properties have updated because it is binding to the object itself, not one of those properties. Even when I made <code>Person</code> a <code>DependencyObject</code> and made <code>FirstName</code> and <code>LastName</code> <code>DependencyProperties</code>, it wouldn't update.</p>\n\n<p>You <em>will</em> have to use a <code>FullName</code> property, and I've update the code of the <code>Person</code> class above to reflect that. Then you can bind the <code>Title</code>. (<strong>Note:</strong> I've set the <code>Person</code> object as the <code>Window</code>'s <code>DataContext</code>.)</p>\n\n<pre><code>Title=\"{Binding Path=FullName, Mode=OneWay}\"\n</code></pre>\n\n<p>If you're editing the names in a <code>TextBox</code> and want the name changed reflected immediately instead of when the <code>TextBox</code> loses focus, you can do this:</p>\n\n<pre><code><TextBox Name=\"FirstNameEdit\"\n Text=\"{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}\" />\n</code></pre>\n\n<p>I know you didn't want to use a <code>FullName</code> property, but anything that would accomplish what you want would probably be a bit of a Rube Goldberg device. Such as implementing <code>INotifyPropertyChanged</code> and a <code>Person</code> property on the <code>Window</code> class itself, having the <code>Window</code> listen on the <code>PropertyChanged</code> event in order to fire the <code>Window</code>'s <code>PropertyChanged</code> event, and using a relative binding like the following. You'd also have set the <code>Person</code> property before <code>InitializeComponent()</code> or fire <code>PropertyChanged</code> after setting the <code>Person</code> property so that it shows up, of course. (Otherwise it will be <code>null</code> during <code>InitializeComponent()</code> and needs to know when it's a <code>Person</code>.)</p>\n\n<pre><code><Window.Resources>\n <loc:PersonNameConverter\n x:Key=\"conv\" />\n</Window.Resources>\n<Window.Title>\n <Binding\n RelativeSource=\"{RelativeSource Self}\"\n Converter=\"{StaticResource conv}\"\n Path=\"Person\"\n Mode=\"OneWay\" />\n</Window.Title>\n</code></pre>\n"
},
{
"answer_id": 175121,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 1,
"selected": false,
"text": "<p>In Order for the binding to be updated, your person class needs to implement INotifyPropertyChanged to let the binding know that the object's properties have been udpated. You can also save yourself from the extra converter by providing a fullName property.</p>\n\n<pre><code>using System.ComponentModel;\n\nnamespace INotifyPropertyChangeSample\n{\n public class Person : INotifyPropertyChanged\n {\n private string firstName;\n public string FirstName\n {\n get { return firstName; }\n set\n {\n if (firstName != value)\n {\n firstName = value;\n OnPropertyChanged(\"FirstName\");\n OnPropertyChanged(\"FullName\");\n }\n }\n }\n\n private string lastName;\n public string LastName\n {\n get { return lastName; }\n set\n {\n if (lastName != value)\n {\n lastName = value;\n OnPropertyChanged(\"LastName\");\n OnPropertyChanged(\"FullName\");\n }\n }\n }\n\n public string FullName\n {\n get { return firstName + \" \" + lastName; }\n } \n\n #region INotifyPropertyChanged Members\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected void OnPropertyChanged(string name)\n {\n if (PropertyChanged != null)\n PropertyChanged(this, new PropertyChangedEventArgs(name));\n }\n\n #endregion\n }\n}\n</code></pre>\n\n<p>Your Binding will now look like this:</p>\n\n<pre><code><TextBlock Text=\"{Binding Person.FullName}\" />\n</code></pre>\n"
},
{
"answer_id": 177370,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't check it but can you also try the following</p>\n\n<pre><code><TextBlock Text=\"{Binding Path=/, Converter={StaticResource personNameConverter}}\" />\n</code></pre>\n"
},
{
"answer_id": 177888,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use a MultiBinding.. Bind to the Person object, the FirstName and LastName. That way, the value gets updated as soon as FirstName or LastName throws the property changed event.</p>\n\n<pre><code><MultiBinding Converter=\"{IMultiValueConverter goes here..}\">\n <Binding />\n <Binding Path=\"FirstName\" />\n <Binding Path=\"LastName\" />\n</MultiBinding>\n</code></pre>\n\n<p>Or if you only use the FirstName and LastName, strip the Person object from the binding to something like this:</p>\n\n<pre><code><MultiBinding Converter=\"{IMultiValueConverter goes here..}\">\n <Binding Path=\"FirstName\" />\n <Binding Path=\"LastName\" />\n</MultiBinding>\n</code></pre>\n\n<p>And the MultiValueConverter looks like this:</p>\n\n<pre><code>class PersonNameConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return values[0].ToString() + \" \" + values[1].ToString();\n }\n\n public object ConvertBack(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n</code></pre>\n\n<p>But of course, the selected answer works as well, but a MultiBinding works more elegantly...</p>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] |
Why is it that when I use a converter in my binding expression in WPF, the value is not updated when the data is updated.
I have a simple Person data model:
```
class Person : INotifyPropertyChanged
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
```
My binding expression looks like this:
```
<TextBlock Text="{Binding Converter={StaticResource personNameConverter}" />
```
My converter looks like this:
```
class PersonNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Person p = value as Person;
return p.FirstName + " " + p.LastName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
```
If I bind the data without a converter it works great:
```
<TextBlock Text="{Binding Path=FirstName}" />
<TextBlock Text="{Binding Path=LastName}" />
```
What am I missing?
EDIT:
Just to clarify a few things, both Joel and Alan are correct regarding the INotifyPropertyChanged interface that needs to be implemented. In reality I do actually implement it but it still doesn't work.
I can't use multiple TextBlock elements because I'm trying to bind the Window Title to the full name, and the Window Title does not take a template.
Finally, it is an option to add a compound property "FullName" and bind to it, but I'm still wondering why updating does not happen when the binding uses a converter. Even when I put a break point in the converter code, the debugger just doesn't get there when an update is done to the underlying data :-(
Thanks,
Uri
|
**(see edits below; latest: #2)**
It isn't updating because your `Person` object is not capable of notifying anything that the value of `FirstName` or `LastName` has changed. [See this Question](https://stackoverflow.com/questions/159088/dependencyproperty-and-databinding).
And here's how you implement `INotifyPropertyChanged`. (**Updated, see Edit 2**)
```
using System.ComponentModel;
class Person : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
string _firstname;
public string FirstName {
get {
return _firstname;
}
set {
_firstname = value;
onPropertyChanged( "FirstName", "FullName" );
}
}
string _lastname;
public string LastName {
get {
return _lastname;
}
set {
_lastname = value;
onPropertyChanged( "LastName", "FullName" );
}
}
public string FullName {
get {
return _firstname + " " + _lastname;
}
}
void onPropertyChanged( params string[] propertyNames ) {
PropertyChangedEventHandler handler = PropertyChanged;
if ( handler != null ) {
foreach ( var pn in propertyNames ) {
handler( this, new PropertyChangedEventArgs( pn ) );
}
}
}
}
```
**Edit 1**
Actually, since you're after the first name and last name updating, and `Path=FirstName` and such works just fine, I don't think you'll need the converter at all. Multiple `TextBlocks` are just as valid, and can actually work better when you're localizing to a right-to-left language.
**Edit 2**
I've figured it out. It's not being notified that the properties have updated because it is binding to the object itself, not one of those properties. Even when I made `Person` a `DependencyObject` and made `FirstName` and `LastName` `DependencyProperties`, it wouldn't update.
You *will* have to use a `FullName` property, and I've update the code of the `Person` class above to reflect that. Then you can bind the `Title`. (**Note:** I've set the `Person` object as the `Window`'s `DataContext`.)
```
Title="{Binding Path=FullName, Mode=OneWay}"
```
If you're editing the names in a `TextBox` and want the name changed reflected immediately instead of when the `TextBox` loses focus, you can do this:
```
<TextBox Name="FirstNameEdit"
Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />
```
I know you didn't want to use a `FullName` property, but anything that would accomplish what you want would probably be a bit of a Rube Goldberg device. Such as implementing `INotifyPropertyChanged` and a `Person` property on the `Window` class itself, having the `Window` listen on the `PropertyChanged` event in order to fire the `Window`'s `PropertyChanged` event, and using a relative binding like the following. You'd also have set the `Person` property before `InitializeComponent()` or fire `PropertyChanged` after setting the `Person` property so that it shows up, of course. (Otherwise it will be `null` during `InitializeComponent()` and needs to know when it's a `Person`.)
```
<Window.Resources>
<loc:PersonNameConverter
x:Key="conv" />
</Window.Resources>
<Window.Title>
<Binding
RelativeSource="{RelativeSource Self}"
Converter="{StaticResource conv}"
Path="Person"
Mode="OneWay" />
</Window.Title>
```
|
174,849 |
<p>I've read <a href="http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/" rel="noreferrer">ASP.NET Routing… Goodbye URL rewriting?</a> and <a href="http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx" rel="noreferrer">Using Routing With WebForms</a> which are great articles, but limited to simple, illustrative, "hello world"-complexity examples.</p>
<p>Is anyone out there using ASP.NET routing with web forms in a non-trivial way? Any gotchas to be aware of? Performance issues? Further recommended reading I should look at before ploughing into an implementation of my own?</p>
<p><strong>EDIT</strong>
Found these additional useful URLs:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/cc668202.aspx" rel="noreferrer">How to: Use Routing with Web Forms (MSDN)</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/cc668201.aspx" rel="noreferrer">ASP.NET Routing (MSDN)</a> </li>
<li><a href="http://msdn.microsoft.com/en-us/library/cc668176.aspx" rel="noreferrer">How to: Construct a URL from a Route(MSDN)</a></li>
</ul>
|
[
{
"answer_id": 174867,
"author": "Chad Moran",
"author_id": 25416,
"author_profile": "https://Stackoverflow.com/users/25416",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this is your answer but this may get you in the right direction it's Scott Hanselman (MSFT) showing how to get ASP.NET WebForms, ASP.NET MVC and ASP.NET Dynamic Data -- oh and AJAX to work together in harmony.</p>\n\n<p><a href=\"http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx\" rel=\"nofollow noreferrer\">http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx</a></p>\n"
},
{
"answer_id": 200531,
"author": "jammus",
"author_id": 984,
"author_profile": "https://Stackoverflow.com/users/984",
"pm_score": 1,
"selected": false,
"text": "<p>I saw this podcast linked to from ScottGu's blog the other day which might be useful to you</p>\n\n<p><a href=\"http://morewally.com/cs/blogs/wallym/archive/2008/10/08/asp-net-podcast-show-125-routing-with-webforms.aspx\" rel=\"nofollow noreferrer\">http://morewally.com/cs/blogs/wallym/archive/2008/10/08/asp-net-podcast-show-125-routing-with-webforms.aspx</a></p>\n"
},
{
"answer_id": 468687,
"author": "kristian",
"author_id": 20377,
"author_profile": "https://Stackoverflow.com/users/20377",
"pm_score": 0,
"selected": false,
"text": "<p>Mike Ormond's step-by-step guide to setting up URL routing with ASP.NET is excellent (<a href=\"http://blogs.msdn.com/mikeormond/archive/2008/11/06/getting-asp-net-routing-up-and-running-the-definitive-guide.aspx\" rel=\"nofollow noreferrer\">Getting ASP.NET Routing Up and Running - The Definitive Guide </a>) </p>\n"
},
{
"answer_id": 5443358,
"author": "Roy",
"author_id": 678147,
"author_profile": "https://Stackoverflow.com/users/678147",
"pm_score": 2,
"selected": false,
"text": "<p>Two very useful links for .net 4.0 and ASP.net routing</p>\n\n<ul>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/dd329551.aspx\" rel=\"nofollow\">Walkthrough: Using ASP.NET Routing in a Web Forms Application</a></p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/cc668201.aspx\" rel=\"nofollow\">ASP.net Routing</a></p></li>\n</ul>\n"
},
{
"answer_id": 19225085,
"author": "Munjal Pandya",
"author_id": 2838424,
"author_profile": "https://Stackoverflow.com/users/2838424",
"pm_score": 0,
"selected": false,
"text": "<p>You can find the URL Routing explained in a simple way at the following articles. It provides info like, send request on a Route, retrieve URL parameters on destination page, setting default values for parameters.</p>\n\n<p><a href=\"http://karmic-development.blogspot.in/2013/10/url-routing-in-aspnet-web-forms-part-1.html\" rel=\"nofollow\">URL Routing in ASP.Net Web Forms Part - 1</a></p>\n\n<p><a href=\"http://karmic-development.blogspot.in/2013/10/url-routing-in-aspnet-web-forms-part-2.html\" rel=\"nofollow\">URL Routing in ASP.Net Web Forms Part - 2</a></p>\n"
},
{
"answer_id": 47417864,
"author": "fufuz9000",
"author_id": 8980836,
"author_profile": "https://Stackoverflow.com/users/8980836",
"pm_score": 3,
"selected": false,
"text": "<p>A simple example of how to use routing in ASP.NET </p>\n\n<ol>\n<li>Create Empty Web Application</li>\n<li>Add first form - Default.aspx</li>\n<li>Add second form - Second.aspx</li>\n<li>Add third form - Third.aspx</li>\n<li><p>Add to default.aspx 3 buttons -</p>\n\n<pre><code>protected void Button1_Click(object sender, EventArgs e)\n{\n Response.Redirect(\"Second.aspx\");\n}\n\nprotected void Button2_Click(object sender, EventArgs e)\n{\n Response.Redirect(\"Third.aspx?Name=Pants\");\n}\n\nprotected void Button3_Click(object sender, EventArgs e)\n{\n Response.Redirect(\"Third.aspx?Name=Shoes\");\n}\n</code></pre></li>\n<li><p>Read query string on third page</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n Response.Write(Request.QueryString[\"Name\"]);\n}\n</code></pre></li>\n</ol>\n\n<p>Now if you run the program, you will be able to navigate to second and third form.\nThis is how it used to be.\nLet's add routing.</p>\n\n<ol start=\"7\">\n<li><p>Add new item - Global.aspx\n using System.Web.Routing;</p>\n\n<pre><code>protected void Application_Start(object sender, EventArgs e)\n{\n RegisterRoutes(RouteTable.Routes);\n}\nvoid RegisterRoutes(RouteCollection routes)\n{\n routes.MapPageRoute(\n \"HomeRoute\",\n \"Home\",\n \"~/Default.aspx\"\n );\n routes.MapPageRoute(\n \"SecondRoute\",\n \"Second\",\n \"~/Second.aspx\"\n );\n routes.MapPageRoute(\n \"ThirdRoute\",\n \"Third/{Name}\",\n \"~/Third.aspx\"\n );\n}\n</code></pre></li>\n<li><p>In default.aspx modify\n protected void Button1_Click(object sender, EventArgs e)\n {\n // Response.Redirect(\"Second.aspx\");\n Response.Redirect(GetRouteUrl(\"SecondRoute\", null));\n }</p>\n\n<pre><code>protected void Button2_Click(object sender, EventArgs e)\n{\n //Response.Redirect(\"Third.aspx?Name=Pants\");\n Response.Redirect(GetRouteUrl(\"ThirdRoute\", new {Name = \"Pants\"}));\n}\n\nprotected void Button3_Click(object sender, EventArgs e)\n{\n // Response.Redirect(\"Third.aspx?Name=Shoes\");\n Response.Redirect(GetRouteUrl(\"ThirdRoute\", new { Name = \"Shoes\" }));\n}\n</code></pre></li>\n<li><p>Modify page load in third.aspx</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n //Response.Write(Request.QueryString[\"Name\"]);\n Response.Write(RouteData.Values[\"Name\"]);\n}\n</code></pre></li>\n</ol>\n\n<p>Run the program, Please note that url looks much cleaner - there are not file extensions in it (Second.aspx becomes just Second)</p>\n\n<ol start=\"10\">\n<li><p>To pass more then one argument</p>\n\n<ul>\n<li><p>add new button to default.aspx with the following code:</p>\n\n<pre><code>protected void Button4_Click(object sender, EventArgs e)\n{\n Response.Redirect(GetRouteUrl(\"FourthRoute\", new { Name = \"Shoes\" , Gender = \"Male\"}));\n}\n</code></pre></li>\n<li><p>add the following code to global.asax</p>\n\n<pre><code> routes.MapPageRoute(\n \"FourthRoute\",\n \"Fourth/{Name}-{Gender}\",\n \"~/Fourth.aspx\"\n );\n</code></pre></li>\n<li><p>create Fourth.aspx page with the following page load:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\nResponse.Write(\"Name is: \" + RouteData.Values[\"Name\"] + \" and Gender is \" + RouteData.Values[\"Gender\"]);\n}\n</code></pre></li>\n</ul></li>\n</ol>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20377/"
] |
I've read [ASP.NET Routing… Goodbye URL rewriting?](http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/) and [Using Routing With WebForms](http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx) which are great articles, but limited to simple, illustrative, "hello world"-complexity examples.
Is anyone out there using ASP.NET routing with web forms in a non-trivial way? Any gotchas to be aware of? Performance issues? Further recommended reading I should look at before ploughing into an implementation of my own?
**EDIT**
Found these additional useful URLs:
* [How to: Use Routing with Web Forms (MSDN)](http://msdn.microsoft.com/en-us/library/cc668202.aspx)
* [ASP.NET Routing (MSDN)](http://msdn.microsoft.com/en-us/library/cc668201.aspx)
* [How to: Construct a URL from a Route(MSDN)](http://msdn.microsoft.com/en-us/library/cc668176.aspx)
|
A simple example of how to use routing in ASP.NET
1. Create Empty Web Application
2. Add first form - Default.aspx
3. Add second form - Second.aspx
4. Add third form - Third.aspx
5. Add to default.aspx 3 buttons -
```
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Second.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Third.aspx?Name=Pants");
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("Third.aspx?Name=Shoes");
}
```
6. Read query string on third page
```
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.QueryString["Name"]);
}
```
Now if you run the program, you will be able to navigate to second and third form.
This is how it used to be.
Let's add routing.
7. Add new item - Global.aspx
using System.Web.Routing;
```
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"HomeRoute",
"Home",
"~/Default.aspx"
);
routes.MapPageRoute(
"SecondRoute",
"Second",
"~/Second.aspx"
);
routes.MapPageRoute(
"ThirdRoute",
"Third/{Name}",
"~/Third.aspx"
);
}
```
8. In default.aspx modify
protected void Button1\_Click(object sender, EventArgs e)
{
// Response.Redirect("Second.aspx");
Response.Redirect(GetRouteUrl("SecondRoute", null));
}
```
protected void Button2_Click(object sender, EventArgs e)
{
//Response.Redirect("Third.aspx?Name=Pants");
Response.Redirect(GetRouteUrl("ThirdRoute", new {Name = "Pants"}));
}
protected void Button3_Click(object sender, EventArgs e)
{
// Response.Redirect("Third.aspx?Name=Shoes");
Response.Redirect(GetRouteUrl("ThirdRoute", new { Name = "Shoes" }));
}
```
9. Modify page load in third.aspx
```
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write(Request.QueryString["Name"]);
Response.Write(RouteData.Values["Name"]);
}
```
Run the program, Please note that url looks much cleaner - there are not file extensions in it (Second.aspx becomes just Second)
10. To pass more then one argument
* add new button to default.aspx with the following code:
```
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect(GetRouteUrl("FourthRoute", new { Name = "Shoes" , Gender = "Male"}));
}
```
* add the following code to global.asax
```
routes.MapPageRoute(
"FourthRoute",
"Fourth/{Name}-{Gender}",
"~/Fourth.aspx"
);
```
* create Fourth.aspx page with the following page load:
```
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Name is: " + RouteData.Values["Name"] + " and Gender is " + RouteData.Values["Gender"]);
}
```
|
174,853 |
<p>A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script after all kids are collected.</p>
<p>What is the best way to work it out? Thanks. </p>
|
[
{
"answer_id": 174984,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at the <a href=\"http://pyprocessing.berlios.de/\" rel=\"nofollow noreferrer\">pyprocessing</a> module?</p>\n"
},
{
"answer_id": 174989,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 1,
"selected": false,
"text": "<p>The traditional, UNIX-y way to communicate with sub-processes is to open pipes to their standard input/output, and use the <code>select()</code> system call to multiplex the communications in the parent process (available in Python via... the <code>select</code> module).</p>\n\n<p>If you need to kill a slow-running child process, you can just save its process ID (returned by the <code>os.fork()</code> call) and then use <code>os.kill()</code> to kill it when not needed anymore. Of course, it would probably be cleaner to be able to communicate with the child process explicitly and <em>tell it</em> to shut itself down.</p>\n"
},
{
"answer_id": 175038,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 5,
"selected": true,
"text": "<p>Simple example:</p>\n\n<pre><code>import os\nchidren = []\nfor job in jobs:\n child = os.fork()\n if child:\n children.append(child)\n else:\n pass # really should exec the job\nfor child in children:\n os.waitpid(child, 0)\n</code></pre>\n\n<p>Timing out a slow child is a little more work; you can use <code>wait</code> instead of <code>waitpid</code>, and cull the returned values from the list of children, instead of waiting on each one in turn (as here). If you set up an <code>alarm</code> with a <code>SIGALRM</code> handler, you can terminate the waiting after a specified delay. This is all standard UNIX stuff, not Python-specific...</p>\n"
},
{
"answer_id": 177237,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 3,
"selected": false,
"text": "<p><em>Ephemient</em>: each child in your code will stay in the for loop after his job ends. He will fork again and again. Moreover, the children that start when children[] is not empty will try to wait for some of their brothers at the end of the loop. Eventually someone will crash. This is a workaround:</p>\n\n<pre><code>import os, time\n\ndef doTheJob(job):\n for i in xrange(10):\n print job, i\n time.sleep(0.01*ord(os.urandom(1)))\n # random.random() would be the same for each process\n\njobs = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\"]\nimTheFather = True\nchildren = []\n\nfor job in jobs:\n child = os.fork()\n if child:\n children.append(child)\n else:\n imTheFather = False\n doTheJob(job)\n break\n\n# in the meanwhile \n# ps aux|grep python|grep -v grep|wc -l == 11 == 10 children + the father\n\nif imTheFather:\n for child in children:\n os.waitpid(child, 0)\n</code></pre>\n"
},
{
"answer_id": 52410335,
"author": "Radiumcola",
"author_id": 3987140,
"author_profile": "https://Stackoverflow.com/users/3987140",
"pm_score": 0,
"selected": false,
"text": "<p>I have done this in perl a time or two. Learning python and wanted to replicate the function. A scheduler for an unknown number of forked tasks must keep track of running tasks, ended tasks, and return codes. This code includes the code for the SIGCHLD handler, the parent task, and a simple child task.</p>\n\n<pre><code>#!/usr/bin/env python3\nimport signal, traceback\nimport os, subprocess\nimport time\n#\n# sigchild handler for reaping dead children\n#\ndef handler(signum, frame):\n#\n# report stat of child tasks \n print(children)\n#\n# use waitpid to collect the dead task pid and status\n pid, stat = os.waitpid(-1, 0)\n term=(pid,stat)\n print('Reaped: pid=%d stat=%d\\n' % term)\n#\n# add pid and return code to dead kids list for post processing\n ripkids.append(term)\n print(ripkids)\n print('\\n')\n#\n# update children to remove pid just reaped\n index = children.index(pid)\n children.pop(index)\n print(children) \n print('\\n')\n\n# Set the signal handler \nsignal.signal(signal.SIGCHLD, handler)\n\ndef child():\n print('\\nA new child ', os.getpid())\n print('\\n')\n time.sleep(15)\n os._exit(0) \n\ndef parent():\n#\n# lists for started and dead children\n global children\n children = []\n global ripkids\n ripkids = []\n\n while True:\n newpid = os.fork()\n if newpid == 0:\n child()\n else:\n pidx = (os.getpid(), newpid)\n children = children+[newpid]\n print(\"parent: %d, child: %d\\n\" % pidx)\n print(children)\n print('\\n')\n reply = input(\"q for quit / c for new fork\")\n if reply == 'c': \n continue\n else:\n break\n\nparent()\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140995/"
] |
A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script after all kids are collected.
What is the best way to work it out? Thanks.
|
Simple example:
```
import os
chidren = []
for job in jobs:
child = os.fork()
if child:
children.append(child)
else:
pass # really should exec the job
for child in children:
os.waitpid(child, 0)
```
Timing out a slow child is a little more work; you can use `wait` instead of `waitpid`, and cull the returned values from the list of children, instead of waiting on each one in turn (as here). If you set up an `alarm` with a `SIGALRM` handler, you can terminate the waiting after a specified delay. This is all standard UNIX stuff, not Python-specific...
|
174,881 |
<p>I'm using jmockit with my tests and with one class I wish to test, uses <code>InitialContext</code> directly. So I have the following:</p>
<pre><code>public class MyClass {
public void myMethod() {
InitialContext ic = new InitialContext();
javax.mail.Session mailSession = ic.lookup("my.mail.session");
// rest of method follows.....
}
</code></pre>
<p>In my test case, I call this to use my "mocked" <code>InitialContext</code> class:</p>
<pre><code>Mockit.redefineMethods(InitialContext.class, MockInitialContext.class);
</code></pre>
<p>What is the best way to mock the <code>InitialContext</code> class with jmockit.</p>
<p>I've already tried a few ways (such as using my own <code>MockInitialContextFactory</code>), but keeping stumbling into the same error:</p>
<pre><code>NoClassDefFoundError: my.class.MockInitialContext
</code></pre>
<p>From what I can see on Google, mocking with JNDI is quite nasty. Please can anyone provide me with some guidance, or point me to a solution? That would be much appreciated. Thank you.</p>
|
[
{
"answer_id": 175207,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 2,
"selected": false,
"text": "<p>In general, to mock JNDI, you will need to use a framework, such as EJBMock, that can provide a mock container in which to deploy your beans.</p>\n\n<p>The other alternative is to refactor creating the context out of your code so that it is passed in (this is dependency injection refactoring), and then you should be able to substitute a mock at will.</p>\n"
},
{
"answer_id": 213650,
"author": "Josh Brown",
"author_id": 2030,
"author_profile": "https://Stackoverflow.com/users/2030",
"pm_score": 1,
"selected": false,
"text": "<p>You're getting the NoClassDefFoundError because my.class.MockInitialContext doesn't exist. You need to create that class if you're going to pass it as an argument to Mockit.redefineMethods(). Your MockInitialContext class would just need a method named lookup() that accepts a String parameter and returns a javax.mail.Session.</p>\n\n<p>I like <a href=\"https://jmockit.dev.java.net/#annotations\" rel=\"nofollow noreferrer\">JMockit annotations</a>, but you can look through the rest of that page for other examples of how to use JMockit.</p>\n"
},
{
"answer_id": 1634106,
"author": "jc.",
"author_id": 197705,
"author_profile": "https://Stackoverflow.com/users/197705",
"pm_score": 2,
"selected": false,
"text": "<p>I now its being a year since someone posted here, but since recently i was mocking EJB calls using JMockit i felt is the right thing to share. (Even though i haven't test it the code should be very similar)</p>\n\n<p>You can define some Mocked object as field in your TestCase like:</p>\n\n<pre><code>@Mocked InitialContext mockedInitialContext;\n@Mocked javax.mail.Session mockedSession;\n</code></pre>\n\n<p>then in your testXXX method you can define your Expectations(), after doing so is just matter of calling the method you want o test.</p>\n\n<pre><code>public void testSendindMail(){\n new Expectations(){\n {\n mockedInitialContext.lookup(\"my.mail.session\");returns(mockedSession); \n }\n };\n MyClass cl = new MyClass ();\n cl.MyMethod();//This need JNDI Lookup\n}\n</code></pre>\n"
}
] |
2008/10/06
|
[
"https://Stackoverflow.com/questions/174881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm using jmockit with my tests and with one class I wish to test, uses `InitialContext` directly. So I have the following:
```
public class MyClass {
public void myMethod() {
InitialContext ic = new InitialContext();
javax.mail.Session mailSession = ic.lookup("my.mail.session");
// rest of method follows.....
}
```
In my test case, I call this to use my "mocked" `InitialContext` class:
```
Mockit.redefineMethods(InitialContext.class, MockInitialContext.class);
```
What is the best way to mock the `InitialContext` class with jmockit.
I've already tried a few ways (such as using my own `MockInitialContextFactory`), but keeping stumbling into the same error:
```
NoClassDefFoundError: my.class.MockInitialContext
```
From what I can see on Google, mocking with JNDI is quite nasty. Please can anyone provide me with some guidance, or point me to a solution? That would be much appreciated. Thank you.
|
In general, to mock JNDI, you will need to use a framework, such as EJBMock, that can provide a mock container in which to deploy your beans.
The other alternative is to refactor creating the context out of your code so that it is passed in (this is dependency injection refactoring), and then you should be able to substitute a mock at will.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.