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
|
---|---|---|---|---|---|---|
228,268 |
<p><a href="http://blogs.msdn.com/drnick/archive/2007/03/23/preventing-anonymous-access.aspx" rel="noreferrer">http://blogs.msdn.com/drnick/archive/2007/03/23/preventing-anonymous-access.aspx</a> </p>
<p>Can someone clarify whether it is possible to use wsHttpBinding in WCF and disable anonymous access in IIS without transport (ssl) or message security being required?</p>
|
[
{
"answer_id": 232142,
"author": "Keith Patton",
"author_id": 25255,
"author_profile": "https://Stackoverflow.com/users/25255",
"pm_score": 0,
"selected": false,
"text": "<p>we want to use windows integrated security. If you disable anonymous access in IIS and allow just windows, you cannot seem to use wsHttpBinding with WCF without using some security mode (e.g. transprot security which requires ssl). </p>\n\n<p>We only want to use windows authentication we don't necessarily want to use ssl for transport security. </p>\n\n<p>I was a little amazed this wasn't possible out of the box (as seemed to be confirmed by my link) as it would seem quite a common scenario for intern applications. </p>\n\n<p>We don't want to downgrade to basicHttpBinding which would support windows authentication only.</p>\n"
},
{
"answer_id": 265895,
"author": "Tobias Hertkorn",
"author_id": 33827,
"author_profile": "https://Stackoverflow.com/users/33827",
"pm_score": 2,
"selected": false,
"text": "<p>you are right, afaik in the scenario you describe wsHttpBinding requires us to use the internal WCF security stack. So what you would typically do is</p>\n\n<ul>\n<li>leave anonymous access enabled</li>\n<li>create a serviceBehavior with <serviceAuthorization principalPermissionMode=\"UseWindowsGroups\" /></li>\n<li>annotate every concrete implementation of a service method using the PrincipalPermissionAttribute, which is a quite powerful tool with many different options to control access</li>\n</ul>\n\n<p>Would that be an acceptable solution for you or are there any other things to consider?</p>\n\n<p>Basic Example:</p>\n\n<pre><code>public class TestService : ITestService\n{\n [PrincipalPermission(SecurityAction.Demand, Name = \"testdomain\\\\administrator\")]\n public string DoWork()\n { \n return \"Hello World \" + Thread.CurrentPrincipal.Identity.Name;\n }\n}\n\n <system.serviceModel>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"WcfSecurity.Www.TestServiceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"false\" />\n <serviceAuthorization principalPermissionMode=\"UseWindowsGroups\" />\n </behavior>\n </serviceBehaviors>\n </behaviors>\n <services>\n <service behaviorConfiguration=\"WcfSecurity.Www.TestServiceBehavior\" name=\"WcfSecurity.Www.TestService\">\n <endpoint address=\"\" binding=\"wsHttpBinding\" contract=\"WcfSecurity.Www.ITestService\" />\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" contract=\"IMetadataExchange\" />\n </service>\n </services> \n </system.serviceModel>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25255/"
] |
<http://blogs.msdn.com/drnick/archive/2007/03/23/preventing-anonymous-access.aspx>
Can someone clarify whether it is possible to use wsHttpBinding in WCF and disable anonymous access in IIS without transport (ssl) or message security being required?
|
you are right, afaik in the scenario you describe wsHttpBinding requires us to use the internal WCF security stack. So what you would typically do is
* leave anonymous access enabled
* create a serviceBehavior with <serviceAuthorization principalPermissionMode="UseWindowsGroups" />
* annotate every concrete implementation of a service method using the PrincipalPermissionAttribute, which is a quite powerful tool with many different options to control access
Would that be an acceptable solution for you or are there any other things to consider?
Basic Example:
```
public class TestService : ITestService
{
[PrincipalPermission(SecurityAction.Demand, Name = "testdomain\\administrator")]
public string DoWork()
{
return "Hello World " + Thread.CurrentPrincipal.Identity.Name;
}
}
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WcfSecurity.Www.TestServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceAuthorization principalPermissionMode="UseWindowsGroups" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="WcfSecurity.Www.TestServiceBehavior" name="WcfSecurity.Www.TestService">
<endpoint address="" binding="wsHttpBinding" contract="WcfSecurity.Www.ITestService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
```
|
228,274 |
<p>I have a block of code intended to pull text descriptions from a database table and save them to a text file. It looks like this (C# .NET):</p>
<pre><code> OdbcCommand getItemsCommand = new OdbcCommand("SELECT ID FROM ITEMS", databaseConnection);
OdbcDataReader getItemsReader = getItemsCommand.ExecuteReader();
OdbcCommand getDescriptionCommand = new OdbcCommand("SELECT ITEMDESCRIPTION FROM ITEMS WHERE ID = ?", databaseConnection);
getDescriptionCommand.Prepare();
while (getItemsReader.Read())
{
long id = getItemsReader.GetInt64(0);
String outputPath = "c:\\text\\" + id + ".txt";
if (!File.Exists(outputPath))
{
getDescriptionCommand.Parameters.Clear();
getDescriptionCommand.Parameters.AddWithValue("id", id);
String description = (String)getDescriptionCommand.ExecuteScalar();
StreamWriter outputWriter = new StreamWriter(outputPath);
outputWriter.Write(description);
outputWriter.Close();
}
}
getItemsReader.Close();
</code></pre>
<p>This code has successfully saved a portion of the data to .txt files, but for many rows, an AccessViolationException is thrown on the following line:</p>
<pre><code> String description = (String)getDescriptionCommand.ExecuteScalar();
</code></pre>
<p>The Exception text is "Attempted to read or write protected memory. This is often an indication that other memory is corrupt".</p>
<p>The program will usually throw the exception on the same rows of the table, but it doesn't appear to be 100% consistent. Sometimes data that had thrown the exception in the past will suddenly work.</p>
<p>Some people are undoubtedly wondering why I didn't just SELECT ID, ITEMDESCRIPTION FROM ITEMS in the getItemsCommand and skip the second query. Actually, I did it that way initially, and I was encountering the same error with getItemsCommand.GetString(). I was afraid that perhaps the dataset was taking up too much memory and maybe that was causing the error. So I decided to try this method to see if it would help. It didn't. Does anyone know why this might be happening?</p>
<p>By the way, ID is an INT and ITEMDESCRIPTION is a VARCHAR(32000) column. If it makes any difference, the database is Borland Interbase 6.0 (Ick!)</p>
<p>EDIT: I gave the wrong line when describing where the exception was being thrown!! ARGH!! Fixed now. Also, I've tried the things suggested so far, but they didn't help. However, I found that only very old records in the database were causing this error, which is strange. If I change the query to only pull records inserted in the last 5 years, there are no problems. Someone suggested to me this might be an encoding conversion problem or something like that?</p>
<p><b>Update:</b> Solved it. The problem turned out to be a bug in the ODBC driver for our not-very-reliable database software. A workaround with other drivers fixed the problem.</p>
|
[
{
"answer_id": 228365,
"author": "mmcdole",
"author_id": 2635,
"author_profile": "https://Stackoverflow.com/users/2635",
"pm_score": 5,
"selected": true,
"text": "<p>As I understand, the first time you run D* it finds the same path as A* with nearly the same runtime. However, when a node changes it's edge value or nodes are added A* recomputes ALL of the path while D* simply recomputes the inconsistent nodes the second time around rather than the whole thing.</p>\n\n<p>Anthony Stentz's D* algorithm (original whitepaper <a href=\"http://www.frc.ri.cmu.edu/~axs/doc/icra94.pdf\" rel=\"noreferrer\">here</a>) has largely been deprecated by derivatives of his work. D* Lite and LPA* are the most commonly found and are much easier to code/implement.</p>\n\n<p>As far as real world experience, Joseph Carsten and Art Rankin from NASA's Jet Propulsion Laboratory installed a version of Field D* using elements of D* Lite on the mars rovers \"Spirit\" and \"Opportunity\" (slideshow of rovers using D* <a href=\"http://www.ceng.metu.edu.tr/~erogul/ceng585/13_DEC_2007_Presentation/d-star-hidden-slides-deleted.ppt\" rel=\"noreferrer\">here</a>). In Feburary 2007 it was used to fully navigate the mars rover autonomously. </p>\n\n<p><a href=\"http://asm.arc.nasa.gov/Gallery/images/generic/rover.jpg\" rel=\"noreferrer\">alt text http://asm.arc.nasa.gov/Gallery/images/generic/rover.jpg</a></p>\n\n<p>Apparently D* is really useful in the robotics domain because the robots on-board sensors are constantly re-evaluating edge values. That would make it pretty \"battle tested\" in my own opinion. </p>\n\n<p>Similarly, I found another <a href=\"http://www.stes.fi/scai2006/proceedings/176-182.pdf\" rel=\"noreferrer\">whitepaper</a> that mentions the use of the D* Lite algorithm in Mobile Gaming.</p>\n\n<p>I'll end this answer by stating that I've never implemented D* before, only A*. Because of the significant increase in complexity I would say that D* (or D* Lite) should only be used in cases where there is a significant and frequent changes in the graph. You described your situation as being similar to that so I would say definately go for D* Lite. If NASA uses it you could safely bet it has been thoroughly investigated.</p>\n"
},
{
"answer_id": 26512743,
"author": "Truc Nguyen",
"author_id": 4170885,
"author_profile": "https://Stackoverflow.com/users/4170885",
"pm_score": 0,
"selected": false,
"text": "<p>I have implemented both D* and A* algorithm. So, I advice you that, if your map has no dynamic obstacles, you should implement A*. Else, implement D*. For the main reason is:\nAt the first search, D* calculates all nodes in the map, then shows you the shortest path, while A* only calculates a limited area around goal and start points in the map. So, it is much faster than D*.\nIn dynamic environment, D* is faster and more efficient than A*. Because on the way robot goes, if it detects a new obstacle, it only updates a few nodes around the unexpected obstacle. While, A* will calculates again all things. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8409/"
] |
I have a block of code intended to pull text descriptions from a database table and save them to a text file. It looks like this (C# .NET):
```
OdbcCommand getItemsCommand = new OdbcCommand("SELECT ID FROM ITEMS", databaseConnection);
OdbcDataReader getItemsReader = getItemsCommand.ExecuteReader();
OdbcCommand getDescriptionCommand = new OdbcCommand("SELECT ITEMDESCRIPTION FROM ITEMS WHERE ID = ?", databaseConnection);
getDescriptionCommand.Prepare();
while (getItemsReader.Read())
{
long id = getItemsReader.GetInt64(0);
String outputPath = "c:\\text\\" + id + ".txt";
if (!File.Exists(outputPath))
{
getDescriptionCommand.Parameters.Clear();
getDescriptionCommand.Parameters.AddWithValue("id", id);
String description = (String)getDescriptionCommand.ExecuteScalar();
StreamWriter outputWriter = new StreamWriter(outputPath);
outputWriter.Write(description);
outputWriter.Close();
}
}
getItemsReader.Close();
```
This code has successfully saved a portion of the data to .txt files, but for many rows, an AccessViolationException is thrown on the following line:
```
String description = (String)getDescriptionCommand.ExecuteScalar();
```
The Exception text is "Attempted to read or write protected memory. This is often an indication that other memory is corrupt".
The program will usually throw the exception on the same rows of the table, but it doesn't appear to be 100% consistent. Sometimes data that had thrown the exception in the past will suddenly work.
Some people are undoubtedly wondering why I didn't just SELECT ID, ITEMDESCRIPTION FROM ITEMS in the getItemsCommand and skip the second query. Actually, I did it that way initially, and I was encountering the same error with getItemsCommand.GetString(). I was afraid that perhaps the dataset was taking up too much memory and maybe that was causing the error. So I decided to try this method to see if it would help. It didn't. Does anyone know why this might be happening?
By the way, ID is an INT and ITEMDESCRIPTION is a VARCHAR(32000) column. If it makes any difference, the database is Borland Interbase 6.0 (Ick!)
EDIT: I gave the wrong line when describing where the exception was being thrown!! ARGH!! Fixed now. Also, I've tried the things suggested so far, but they didn't help. However, I found that only very old records in the database were causing this error, which is strange. If I change the query to only pull records inserted in the last 5 years, there are no problems. Someone suggested to me this might be an encoding conversion problem or something like that?
**Update:** Solved it. The problem turned out to be a bug in the ODBC driver for our not-very-reliable database software. A workaround with other drivers fixed the problem.
|
As I understand, the first time you run D\* it finds the same path as A\* with nearly the same runtime. However, when a node changes it's edge value or nodes are added A\* recomputes ALL of the path while D\* simply recomputes the inconsistent nodes the second time around rather than the whole thing.
Anthony Stentz's D\* algorithm (original whitepaper [here](http://www.frc.ri.cmu.edu/~axs/doc/icra94.pdf)) has largely been deprecated by derivatives of his work. D\* Lite and LPA\* are the most commonly found and are much easier to code/implement.
As far as real world experience, Joseph Carsten and Art Rankin from NASA's Jet Propulsion Laboratory installed a version of Field D\* using elements of D\* Lite on the mars rovers "Spirit" and "Opportunity" (slideshow of rovers using D\* [here](http://www.ceng.metu.edu.tr/~erogul/ceng585/13_DEC_2007_Presentation/d-star-hidden-slides-deleted.ppt)). In Feburary 2007 it was used to fully navigate the mars rover autonomously.
[alt text http://asm.arc.nasa.gov/Gallery/images/generic/rover.jpg](http://asm.arc.nasa.gov/Gallery/images/generic/rover.jpg)
Apparently D\* is really useful in the robotics domain because the robots on-board sensors are constantly re-evaluating edge values. That would make it pretty "battle tested" in my own opinion.
Similarly, I found another [whitepaper](http://www.stes.fi/scai2006/proceedings/176-182.pdf) that mentions the use of the D\* Lite algorithm in Mobile Gaming.
I'll end this answer by stating that I've never implemented D\* before, only A\*. Because of the significant increase in complexity I would say that D\* (or D\* Lite) should only be used in cases where there is a significant and frequent changes in the graph. You described your situation as being similar to that so I would say definately go for D\* Lite. If NASA uses it you could safely bet it has been thoroughly investigated.
|
228,319 |
<p>I am using a navigation controller, and I have the style set to :</p>
<pre><code>navController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
</code></pre>
<p>But when I run my program, the navigation controller looks like it is on top of a white background, not my background. When I push a controller, left or right, all my view, the current one, shifts to the top exactly the size of the navigation bar. And it is there where I can see my background through the navigation controller bar. Any ideas? When my barStyle is set to opaque, everything looks fine. I was thinking on setting my view frame a negative 'y' value, but I think there should a more elegant way.</p>
|
[
{
"answer_id": 228349,
"author": "Marco",
"author_id": 30480,
"author_profile": "https://Stackoverflow.com/users/30480",
"pm_score": 4,
"selected": true,
"text": "<p>I believe the UINavigationController assumes that your controller view frames don't include the area beneath the navigation bar.</p>\n\n<p>UIBarStyleBlackTranslucent is more often used for UIToolbar, so Apple probably didn't make it easy to use it nicely with UINavigationBar. You'll probably need to abandon the UINavigationController, or start hacking the frames (careful with rotations), if you want to reliably render under the bar area.</p>\n\n<p>Also, if your intention is to hide the navigation bar after a few seconds, you'll have a <strong>much</strong> easier time if you make it fade out (like the Photos app) instead of trying to slide it up (like Mobile Safari). Trust me on that one... that took me a <em>lot</em> of time to learn the hard way.</p>\n"
},
{
"answer_id": 228409,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 1,
"selected": false,
"text": "<p>The navigation controller offsets the coordinate sytem of all it's subviews so they draw below the navigation bar.</p>\n\n<p>Extend your view's frame into the negative y domain for it to draw under the navigation bar.</p>\n"
},
{
"answer_id": 230344,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 0,
"selected": false,
"text": "<p>If you set your nav controller's navigationBar to transparent in your App delegate early enough (It worked for me before adding the nav controller to the window), it will automatically shift your view up underneath the navigation bar.</p>\n\n<p>Unfortunately it does not also shift your view underneath the status bar. Sad, it looks like you need to implement your own version of UINavigationController. Luckily, it's not too bad as UINavigationBar is pretty reusable.</p>\n"
},
{
"answer_id": 231443,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem, and I solved it by making the background of the root view the same as my view. The white area behind the navigation bar turned out to be the root view.</p>\n"
},
{
"answer_id": 244272,
"author": "philsquared",
"author_id": 32136,
"author_profile": "https://Stackoverflow.com/users/32136",
"pm_score": 1,
"selected": false,
"text": "<p>You need to set the barstyle in your info.plist file for it offset everything correctly.</p>\n\n<p>However, I haven't tried it since the 2.1 f/w was released, but when I tried this in 2.0 I found that the setting was lost after a rotation from portrait to landscape.</p>\n"
},
{
"answer_id": 2876401,
"author": "Shizam",
"author_id": 155513,
"author_profile": "https://Stackoverflow.com/users/155513",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this same problem (in 3.1.3) and while you can't set the bar style after the navigationBar has already been setup you CAN set the tintColor and translucent values whenever you like:</p>\n\n<pre><code> self.navigationController.navigationBar.tintColor = [UIColor blackColor];\n self.navigationController.navigationBar.translucent = YES;\n</code></pre>\n\n<p>Will create the 'blackTranslucent' bar, I change the navigationBar look when I push certain view controllers onto the stack.</p>\n"
},
{
"answer_id": 3979693,
"author": "Harpreet",
"author_id": 475548,
"author_profile": "https://Stackoverflow.com/users/475548",
"pm_score": 1,
"selected": false,
"text": "<p>try to use this, may be it will helpful.</p>\n\n<pre><code>_topToolBar.barStyle = UIBarStyleBlackTranslucent;\n_topToolBar.alpha = 0.3;\n</code></pre>\n"
},
{
"answer_id": 4132534,
"author": "xiaogong",
"author_id": 501727,
"author_profile": "https://Stackoverflow.com/users/501727",
"pm_score": 1,
"selected": false,
"text": "<p>I had a same problem.I solved!</p>\n\n<pre><code>ImageViewExtendController *detailImageController = [[ImageViewExtendController alloc] init]; \n[detailImageController loadImage:url];\n[self.navigationController pushViewController:detailImageController animated:YES];\n</code></pre>\n"
},
{
"answer_id": 4213088,
"author": "Hanno",
"author_id": 511877,
"author_profile": "https://Stackoverflow.com/users/511877",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>self.tabBarController.tabBar.superview.backgroundColor = [UIColor blackColor];\n</code></pre>\n"
},
{
"answer_id": 12173058,
"author": "Pill Gong",
"author_id": 1299641,
"author_profile": "https://Stackoverflow.com/users/1299641",
"pm_score": 2,
"selected": false,
"text": "<pre><code>self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.169 green:0.373 blue:0.192 alpha:0.9];\nself.navigationController.navigationBar.translucent = YES;\n</code></pre>\n\n<p>Note:</p>\n\n<ol>\n<li>Don't use <code>self.navigationBarStyle</code> and <code>self.navigationBarTintColor</code> to change.</li>\n<li>Add the last two statements to your <code>viewDidLoad</code>.</li>\n</ol>\n"
},
{
"answer_id": 13818316,
"author": "Resh32",
"author_id": 1611950,
"author_profile": "https://Stackoverflow.com/users/1611950",
"pm_score": 3,
"selected": false,
"text": "<p>Simply use a transparent background image, and translucent = YES to allow the content to flow below the bar. Works on iOS 5 / 6. Add in viewDidLoad.</p>\n\n<pre><code>self.navigationController.navigationBar.translucent = YES;\nUIImage * backgroundImage = [UIImage imageNamed:@\"spacer.gif\"];\n[self.navigationController.navigationBar setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:UIBarMetricsDefault];\n</code></pre>\n\n<p>I attached the spacer.gif image here, a single 1px x 1px transparent image.</p>\n\n<p><img src=\"https://i.stack.imgur.com/MzQkt.gif\" alt=\"spacer.gif\"></p>\n"
},
{
"answer_id": 23548800,
"author": "Alejandro Teixeira Muñoz",
"author_id": 3617531,
"author_profile": "https://Stackoverflow.com/users/3617531",
"pm_score": 0,
"selected": false,
"text": "<p>Change the Extend Edges options in child viewControllers</p>\n\n<p>As for example, in xcode editor, go to your first viewcontroller child and unset the options:</p>\n\n<pre><code>Extend Edges;\n Under Top Bars;\n Under Bottom Bars;\n Under Opaque Bars;\n</code></pre>\n\n<p>This way your child ViewController will not layout starting below the status bar of the navigation controller, neither the tabbar or the toolbars</p>\n\n<p>hope it may help anyone </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29642/"
] |
I am using a navigation controller, and I have the style set to :
```
navController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
```
But when I run my program, the navigation controller looks like it is on top of a white background, not my background. When I push a controller, left or right, all my view, the current one, shifts to the top exactly the size of the navigation bar. And it is there where I can see my background through the navigation controller bar. Any ideas? When my barStyle is set to opaque, everything looks fine. I was thinking on setting my view frame a negative 'y' value, but I think there should a more elegant way.
|
I believe the UINavigationController assumes that your controller view frames don't include the area beneath the navigation bar.
UIBarStyleBlackTranslucent is more often used for UIToolbar, so Apple probably didn't make it easy to use it nicely with UINavigationBar. You'll probably need to abandon the UINavigationController, or start hacking the frames (careful with rotations), if you want to reliably render under the bar area.
Also, if your intention is to hide the navigation bar after a few seconds, you'll have a **much** easier time if you make it fade out (like the Photos app) instead of trying to slide it up (like Mobile Safari). Trust me on that one... that took me a *lot* of time to learn the hard way.
|
228,321 |
<p>On an embedded target I use far pointers to access some parts of the memory map. </p>
<p>near pointer (without explicitely specifying __near):</p>
<pre>unsigned int *VariableOnePtr;</pre>
<p>Pointer to near pointer: <pre>unsigned int **VariableOnePtrPtr;</pre></p>
<p>far pointer: <pre>unsigned int *__far VariableTwoPtr;</pre> </p>
<p>What is the correct way to declare a pointer to a far pointer? Does this pointer have to be a far pointer itself?</p>
|
[
{
"answer_id": 228331,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "<p>I believe you would do this:</p>\n\n<pre><code>unsigned int * __far *VariableThreePtrPtr;\n</code></pre>\n\n<p>A far pointer to a far pointer would be:</p>\n\n<pre><code>unsigned int * __far * __far VariableFourPtrPtr;\n</code></pre>\n"
},
{
"answer_id": 228482,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use typedefs for that, for example</p>\n\n<pre><code>typedef unsigned int *__far VariableTwoPtr_t;\nVariableTwoPtr_t* VariableTwoPtrPtr;\n</code></pre>\n"
},
{
"answer_id": 351320,
"author": "mh.",
"author_id": 44134,
"author_profile": "https://Stackoverflow.com/users/44134",
"pm_score": 2,
"selected": false,
"text": "<p>\"__far\" is a proprietary, non-standard extension of your platform, so there can't exist any generic way to use it. See the compiler and standard library manufaturer's manuals for how to use it correctly.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
] |
On an embedded target I use far pointers to access some parts of the memory map.
near pointer (without explicitely specifying \_\_near):
```
unsigned int *VariableOnePtr;
```
Pointer to near pointer:
```
unsigned int **VariableOnePtrPtr;
```
far pointer:
```
unsigned int *__far VariableTwoPtr;
```
What is the correct way to declare a pointer to a far pointer? Does this pointer have to be a far pointer itself?
|
I believe you would do this:
```
unsigned int * __far *VariableThreePtrPtr;
```
A far pointer to a far pointer would be:
```
unsigned int * __far * __far VariableFourPtrPtr;
```
|
228,353 |
<p>A lambda expression which takes a function (of one argument) and a number, and applies the function to twice the number.</p>
|
[
{
"answer_id": 228361,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>Applying the function to twice the number:</p>\n\n<pre><code>(lambda (f x) (f (* 2 x)))\n</code></pre>\n\n<p>Applying the function to the number twice (which is what you may have intended to ask):</p>\n\n<pre><code>(lambda (f x) (f (f x)))\n</code></pre>\n"
},
{
"answer_id": 228456,
"author": "grettke",
"author_id": 121526,
"author_profile": "https://Stackoverflow.com/users/121526",
"pm_score": 3,
"selected": false,
"text": "<p>Greg's answer is correct, but you might think about how you might break apart this problem to find the answer yourself. Here is one approach:</p>\n\n<pre><code>; A lambda expression\n;(lambda () )\n\n; which takes a function (of one argument) and a number\n;(lambda (fun num) )\n\n; and applies the function\n;(lambda (fun num) (fun num))\n\n; to twice the number\n;(lambda (fun num) (fun (* 2 num)))\n\n((lambda (fun num) (fun (* 2 num))) + 12)\n</code></pre>\n"
},
{
"answer_id": 228487,
"author": "grettke",
"author_id": 121526,
"author_profile": "https://Stackoverflow.com/users/121526",
"pm_score": 2,
"selected": false,
"text": "<p>Here is another way to approach it:</p>\n\n<p>Write a Contract, Purpose, and Header:</p>\n\n<pre><code>;; apply-double : function -> number -> any\n;; to apply a given function to double a given number\n(define (apply-double fun num) ...)\n</code></pre>\n\n<p>Write some Tests:</p>\n\n<pre><code>(= (apply-double identity 10) 20)\n(= (apply-double - 15) -30)\n(= (apply-double / 7) 1/14)\n</code></pre>\n\n<p>Define the function:</p>\n\n<pre><code>(define (apply-double fun num) \n (fun (* 2 num)))\n</code></pre>\n\n<p>This is an abbreviation of the recipe here: <a href=\"http://www.htdp.org/2003-09-26/Book/\" rel=\"nofollow noreferrer\">http://www.htdp.org/2003-09-26/Book/</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30622/"
] |
A lambda expression which takes a function (of one argument) and a number, and applies the function to twice the number.
|
Applying the function to twice the number:
```
(lambda (f x) (f (* 2 x)))
```
Applying the function to the number twice (which is what you may have intended to ask):
```
(lambda (f x) (f (f x)))
```
|
228,377 |
<p>I want to run a psychological study for which participants have to look at large images.</p>
<p>The experiment is done on the web and therefore in a browser window. Is it possible to tell the browser to go into fullscreen, for example on button press?</p>
<p>I know there is the possibility to open a fixed-size popup window. Do you think this would be a feasable alternative? And if, what would be the best way to do it? Are there elegant ways of detecting a popup-blocker, to fallback and run the study in the original browser window.</p>
<p>The main concern is that the participants of this study are not familiar with technical details and should not be bothered by them.</p>
|
[
{
"answer_id": 228383,
"author": "Scottie T",
"author_id": 6688,
"author_profile": "https://Stackoverflow.com/users/6688",
"pm_score": 0,
"selected": false,
"text": "<p>F11 takes IE and Firefox into fullscreen mode. I'm sure it's possible to go fullscreen, since YouTube and other video streaming sites can do it with Flash, but I don't know how with javascript.</p>\n"
},
{
"answer_id": 228388,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>In the past, I've seen websites do this. However, as it's incredibly annoying and generally used by ads for pr0n websites, the technique may be blocked in recent browsers.</p>\n\n<p>But I think the important point is: it's incredibly annoying and generally used by ads for pr0n websites, so you probably don't want to associate yourself which such things, so your probably best off just asking your users to maximize their browsers.</p>\n"
},
{
"answer_id": 228390,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 3,
"selected": false,
"text": "<p>There isn't a way to resize the current window to full screen, but you can open a popup in full screen:</p>\n\n<pre><code><script type=\"text/javascript\">\n<!--\nfunction popup(url) \n{\n params = 'width='+screen.width;\n params += ', height='+screen.height;\n params += ', top=0, left=0'\n params += ', fullscreen=yes';\n\n newwin=window.open(url,'windowname4', params);\n if (window.focus) {newwin.focus()}\n return false;\n}\n// -->\n</script>\n\n<a href=\"javascript: void(0)\" \n onclick=\"popup('popup.html')\">Fullscreen popup window</a>\n</code></pre>\n"
},
{
"answer_id": 228399,
"author": "mqsoh",
"author_id": 8710,
"author_profile": "https://Stackoverflow.com/users/8710",
"pm_score": 3,
"selected": false,
"text": "<p>You could just tell the user to press F11. Next to it, put a 'why?' link and explain why you feel like they need to be in fullscreen mode.</p>\n\n<p>I don't think you can force a browser to go full screen and, in fact, if you were able to do that I'd be furious at my browser. It's too invasive. Even Flash has security so that forcing the plugin to go to fullscreen requires the event to originate with a user interaction. So, if it's that important to you, this might be a good reason to use the Flash plugin because you could attach the go-fullscreen call to a misleading button that says 'start quiz' (or whatever).</p>\n\n<p>But, please don't do that. Just be straight forward with the user and tell them to hit F11.</p>\n\n<p>EDIT: I just tried the sample code provided in another comment and I'm happy to say that Firefox opens up a maximized window with an address bar, not a fullscreen window.</p>\n"
},
{
"answer_id": 228414,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<p>Open a new window in full screen mode on IE:</p>\n\n<pre><code><script>\n<!--\nwindow.open(\"page.html\",\"fs\",\"fullscreen,scrollbars\")\n//-->\n</script> \n</code></pre>\n\n<p>Putting in a \"Close\" link on page.html may be a good idea:</p>\n\n<pre><code><a href=\"#\" onclick=\"window.close()\">Close Window</a>\n</code></pre>\n"
},
{
"answer_id": 228422,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "<p>To modify the parent window, try something like:</p>\n\n<pre><code>window.opener.location.href = '/confirmation/page.html';\n</code></pre>\n"
},
{
"answer_id": 20643560,
"author": "Swen",
"author_id": 2387714,
"author_profile": "https://Stackoverflow.com/users/2387714",
"pm_score": 4,
"selected": true,
"text": "<p>I have found some code after searching.</p>\n\n<pre><code>function fullscreen() {\n var element = document.getElementById(\"content\");\n if (element.requestFullScreen) {\n if (!document.fullScreen) {\n element.requestFullscreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize_actual.png\");\n } else {\n document.exitFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize.png\");\n }\n\n } else if (element.mozRequestFullScreen) {\n\n if (!document.mozFullScreen) {\n element.mozRequestFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize_actual.png\");\n google.maps.event.trigger(map, 'resize');\n } else {\n document.mozCancelFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize.png\");\n }\n\n } else if (element.webkitRequestFullScreen) {\n\n if (!document.webkitIsFullScreen) {\n element.webkitRequestFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize_actual.png\");\n google.maps.event.trigger(map, 'resize');\n } else {\n document.webkitCancelFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize.png\");\n } \n } \n}\n</code></pre>\n\n<p>It will use html5 api. I switch with jquery the a special picture for it. Hope that will help out. At the moment, i don't know if you can force it, 'cause it was forbitten due security. </p>\n"
},
{
"answer_id": 20783505,
"author": "Swen",
"author_id": 2387714,
"author_profile": "https://Stackoverflow.com/users/2387714",
"pm_score": 0,
"selected": false,
"text": "<p>This feature is more interesting for mobile browsers, which support fullscreen. The most mobile browser wont have an option for fullscreen by tap an option. You have a change to switch to fullscreen to get a little bit app feeling.</p>\n"
},
{
"answer_id": 71458531,
"author": "misterferien",
"author_id": 18455200,
"author_profile": "https://Stackoverflow.com/users/18455200",
"pm_score": -1,
"selected": false,
"text": "<p>forget java script! For app feeling put this this to your body tag or div tag or css, it will work with all browsers, except Opera:</p>\n<p>´\n:-webkit-full-screen\n:-moz-full-screen\n:-ms-fullscreen\n:fullscreen ´</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21974/"
] |
I want to run a psychological study for which participants have to look at large images.
The experiment is done on the web and therefore in a browser window. Is it possible to tell the browser to go into fullscreen, for example on button press?
I know there is the possibility to open a fixed-size popup window. Do you think this would be a feasable alternative? And if, what would be the best way to do it? Are there elegant ways of detecting a popup-blocker, to fallback and run the study in the original browser window.
The main concern is that the participants of this study are not familiar with technical details and should not be bothered by them.
|
I have found some code after searching.
```
function fullscreen() {
var element = document.getElementById("content");
if (element.requestFullScreen) {
if (!document.fullScreen) {
element.requestFullscreen();
$(".fullscreen").attr('src',"img/icons/panel_resize_actual.png");
} else {
document.exitFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize.png");
}
} else if (element.mozRequestFullScreen) {
if (!document.mozFullScreen) {
element.mozRequestFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize_actual.png");
google.maps.event.trigger(map, 'resize');
} else {
document.mozCancelFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize.png");
}
} else if (element.webkitRequestFullScreen) {
if (!document.webkitIsFullScreen) {
element.webkitRequestFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize_actual.png");
google.maps.event.trigger(map, 'resize');
} else {
document.webkitCancelFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize.png");
}
}
}
```
It will use html5 api. I switch with jquery the a special picture for it. Hope that will help out. At the moment, i don't know if you can force it, 'cause it was forbitten due security.
|
228,382 |
<p>I need to parse a large amount of text that uses HTML font tags for formatting,</p>
<p>For example:</p>
<pre><code><font face="fontname" ...>Some text</font>
</code></pre>
<p>Specifically, I need to determine which characters would be rendered using each font used in the text. I need to be able to handle stuff like font tags inside another font tag.</p>
<p>I need to use C# for this. Is there some sort of C# parser class to make this easier? Or would I have to write it myself?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 228391,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p>I have not used it, but I have seen the <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">HTML Agility Pack</a> frequently mentioned for this type of thing.</p>\n"
},
{
"answer_id": 228402,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this is applicable to your situation as I don't know what the intended use is, but what about the use of XSLT tempaltes?</p>\n"
},
{
"answer_id": 228933,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 0,
"selected": false,
"text": "<p>You could load the HTML into Internet Explorer, and then query the DOM for font tags, (or CSS style).</p>\n\n<p>Don't know if this is the best option performance wise.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18494/"
] |
I need to parse a large amount of text that uses HTML font tags for formatting,
For example:
```
<font face="fontname" ...>Some text</font>
```
Specifically, I need to determine which characters would be rendered using each font used in the text. I need to be able to handle stuff like font tags inside another font tag.
I need to use C# for this. Is there some sort of C# parser class to make this easier? Or would I have to write it myself?
Thanks!
|
I have not used it, but I have seen the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) frequently mentioned for this type of thing.
|
228,412 |
<p>If you could help me with ANY part of this question, I would appreciate it. Thanks.</p>
<pre><code>2^0 = 1
2^N = 2^(N-1) + 2^(N-1)
</code></pre>
<ol>
<li><p>Convert this definition into an exactly equivalent tree-recursive function called two-to-the-power-of. Describe its asymptotic time complexity and explain why it has this time complexity.</p></li>
<li><p>Now write a function called tttpo_rec which computes the exact same thing, but which uses a linear recursive process which has an O(n) time complexity and also uses O(n) space for its pending operations.</p></li>
<li><p>Now write a function called tttpo_iter which computes the exact same thing, but which uses a linear iterative process which has an O(n) time complexity and also uses constant space.</p></li>
<li><p>Now let's say you want to generalize one of the preceding definitions so that it will handle arbitrary integer powers, so that you can compute 2^N, 3^N etc. Write a function called to-the-power-of that takes two arguments and raises one to the power of the other.</p></li>
</ol>
<p>Here's the template:</p>
<pre><code>;; to-the-power-of: integer integer -> integer
;; This function raises m to the power of n, returning the result.
;; m must be > 0 and n >= 0.
(define (to-the-power-of m n)
...)
(check-expect (to-the-power-of 1 0) 1) ; base case
(check-expect (to-the-power-of 2 3) 8) ; recursive case
(check-expect (to-the-power-of 3 2) 9) ; recursive case
</code></pre>
<p>We'll add one more restriction: you can't use the * operator; you can only use the following recursive function to do multiplications:</p>
<pre><code>;;; multiply: integer integer -> integer
;; This function multiplies two non-negative integers, returning the result.
;; Its time complexity is O(a).
(define (multiply a b)
...)
</code></pre>
<p>Write the function, and describe what its time complexity is and why.</p>
|
[
{
"answer_id": 228415,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": true,
"text": "<p>The hues of magenta, yellow, and cyan are primary for subtractive combination (e.g. paints or inks) rather than additive combination such as light where red, green, and blue are primary.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Primary_colors\" rel=\"noreferrer\">Wikipedia has more detail on the whys and wherefores</a>.</p>\n"
},
{
"answer_id": 228417,
"author": "jmatthias",
"author_id": 2768,
"author_profile": "https://Stackoverflow.com/users/2768",
"pm_score": 0,
"selected": false,
"text": "<p>Because combining light sources (which computer monitors do) does not work the same way as combining printed ink. It's just a guess.</p>\n"
},
{
"answer_id": 228423,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 3,
"selected": false,
"text": "<p>Computers use the additive colour model, which involves adding together RGB to form white, and is the usual way of forming colours when using a light source. </p>\n\n<p>Printers use subtractive color, normally using Cyan(C), Magenta(M), and Yellow(Y), and often Black(K). Abbreviated CMYK </p>\n\n<p>Cyan is opposite to Red, Magenta is opposite to Green, and Yellow is opposite to Blue. </p>\n\n<p>This is a really simple explanation of a complex issue, the guy that came up with additive colour was James Maxwell (yes, that one), so if you dig into the many articles about him, that may explain much better.</p>\n"
},
{
"answer_id": 228426,
"author": "Scottie T",
"author_id": 6688,
"author_profile": "https://Stackoverflow.com/users/6688",
"pm_score": 2,
"selected": false,
"text": "<p>For efficiency: the RGB model is additive. For example, superimpose pure red and pure blue light, and you get magenta. It's also easy to build into monitors. If you take a magnifying glass and look at your monitor, you'll be able to see individual red, green and blue dots that vary in intensity to compose the colors needed. As <a href=\"https://stackoverflow.com/questions/228407/rgb-for-color-composition-rather-than-primary-hues#228415\">ffpf</a> mentioned, check out Wikipedia. Here's a link to the article on the <a href=\"http://en.wikipedia.org/wiki/RGB_color_model\" rel=\"nofollow noreferrer\">RGB color model</a>.</p>\n"
},
{
"answer_id": 228428,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<p>Computer screens emit light to display pixels. Mixing different colours of light is called <a href=\"http://en.wikipedia.org/wiki/Additive_color\" rel=\"nofollow noreferrer\">Additive colour</a>. Additive colour uses red, green, and blue as primary colours.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Subtractive_color\" rel=\"nofollow noreferrer\">Subtractive colour</a> is how different colours of materials mix, such as paints. Subtractive colour uses red, yellow, and blue as primary colours.</p>\n\n<p>How I think of it is that when light reflects off an object into your eyes, the object absorbs some of the colour, and reflects the rest to your eyes. So if an object's green, it means it's absorbing the red and the blue out of the white light. This is why mixing red, green, and blue light creates white light, but mixing red, yellow, and blue paint creates black (the mixed paint now absorbs all primary colours.) That is the reason for the difference between additive and subtractive light.</p>\n"
},
{
"answer_id": 228443,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 2,
"selected": false,
"text": "<p>Just for clarification, the primary colours you learn at school are incorrectly given as red, yellow & blue. In fact they are Cyan, Yellow & Magenta, just like your inkjet printer. As the previous posts state, Cyan, Yellow & Magenta are the subtractive prime colours; you see what the pigments reflect. Red, Green & Blue are the additive primary colours that CRTs, Plasmas & LCDs use.</p>\n"
},
{
"answer_id": 59610373,
"author": "Myndex",
"author_id": 10315269,
"author_profile": "https://Stackoverflow.com/users/10315269",
"pm_score": 0,
"selected": false,
"text": "<h2>Color is Not Real</h2>\n\n<p>Color is a perception. Light exists in different wavelengths or frequencies, but the only thing that makes a certain wavelength appear to be a \"color\" is the nature of human perception.</p>\n\n<h2>The Long, Medium, and Short of it</h2>\n\n<p>The eye has three types of \"cone\" cells where are sensitive to one of three bands of light, long, medium, or short wavelengths (about 700nm to 380nm). \"Long\" we think of as red, medium—green, and short—blue. But each cone type covers a wider band, and there is definite overlap, especially of the long and medium cones.</p>\n\n<h2>It's All In Your Head</h2>\n\n<p>Most of the human visual system (HVS) is in the brain (62% of the brain is involved in visual processing). The overlapping cone responses are filtered by ganglion cells in the back of the eye, sent over the optic nerve, and then further filtered and processed by the visual cortex.</p>\n\n<h2>No Such Thing As \"Primaries\"</h2>\n\n<p>While we may call some colors \"primary\", there is no set of just three real colors that can make up all other colors. Pantone requires 14 different dyes to make up that set of colors for instance, and a typical artist will load their paulette with a dozen colors from which to mix.</p>\n\n<p>TVs/Monitors use red, green, and blue \"primaries\" with wavelengths chosen with the intent to stimulate each of the three types of cones in the eye as independently as possible. However this is impossible to achieve due to the cone bandwidth overlap.</p>\n\n<p>As such, you \"could\" say that red, green, blue were the primary colors of light, but even that is not completely correct. Yellow stimulates the \"red\" and \"green\" cones about equally, in the middle of the cone overlap. When a computer monitor displays yellow, it is displaying separate green and red, which does not mix in the air to make yellow — it just stimulates the red and green cones causing the brain to <em>perceive</em> yellow.</p>\n\n<p>We perceive yellow, and not a reddish-green nor a greenish-red, due to the opponent process of color that is a result of the ganglion cells in the back of the eye.</p>\n\n<p>Red/Green is an opponent pair, and Yellow/Blue is an opponent pair, making up four \"unique\" colors (Red, Yellow, Green, Blue). Since Yellow is easily created with red and green light, additive color processes typically omit yellow.</p>\n\n<h2>Subtracting Light</h2>\n\n<p>Reflected surfaces (and transparent film) \"subtract\" light by absorbing it, reflecting (or transmitting) only certain wavelengths. As it turns out, we get the best gamut of colors using \"primaries\" cyan, magenta, and yellow when working with subtractive reflected/translucent colors, as opposed to emitted light colors where we are trying to selectively stimulate each of the three cone types using red, green, and blue. </p>\n\n<p>Also, it is useful to note that cyan is the \"opposite\" of red, magenta \"opposite\" of green and yellow \"opposite\" of blue. </p>\n\n<p>And for the record, in an sRGB monitor, the red is really a red/orange. The green is really a green/yellow, and the blue is more of a violet.</p>\n\n<p>For either additive or subtractive processes, the specific colors chosen are (generally) intended for creating the widest gamut of color, limited by various reasons of economics and practicality.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30622/"
] |
If you could help me with ANY part of this question, I would appreciate it. Thanks.
```
2^0 = 1
2^N = 2^(N-1) + 2^(N-1)
```
1. Convert this definition into an exactly equivalent tree-recursive function called two-to-the-power-of. Describe its asymptotic time complexity and explain why it has this time complexity.
2. Now write a function called tttpo\_rec which computes the exact same thing, but which uses a linear recursive process which has an O(n) time complexity and also uses O(n) space for its pending operations.
3. Now write a function called tttpo\_iter which computes the exact same thing, but which uses a linear iterative process which has an O(n) time complexity and also uses constant space.
4. Now let's say you want to generalize one of the preceding definitions so that it will handle arbitrary integer powers, so that you can compute 2^N, 3^N etc. Write a function called to-the-power-of that takes two arguments and raises one to the power of the other.
Here's the template:
```
;; to-the-power-of: integer integer -> integer
;; This function raises m to the power of n, returning the result.
;; m must be > 0 and n >= 0.
(define (to-the-power-of m n)
...)
(check-expect (to-the-power-of 1 0) 1) ; base case
(check-expect (to-the-power-of 2 3) 8) ; recursive case
(check-expect (to-the-power-of 3 2) 9) ; recursive case
```
We'll add one more restriction: you can't use the \* operator; you can only use the following recursive function to do multiplications:
```
;;; multiply: integer integer -> integer
;; This function multiplies two non-negative integers, returning the result.
;; Its time complexity is O(a).
(define (multiply a b)
...)
```
Write the function, and describe what its time complexity is and why.
|
The hues of magenta, yellow, and cyan are primary for subtractive combination (e.g. paints or inks) rather than additive combination such as light where red, green, and blue are primary.
[Wikipedia has more detail on the whys and wherefores](http://en.wikipedia.org/wiki/Primary_colors).
|
228,424 |
<p>I have the following query:</p>
<pre><code>SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid)
WHERE j.jobid = 123;
</code></pre>
<p>I have the following questions:</p>
<ol>
<li>Is the USING syntax synonymous with ON syntax?</li>
<li>Are these joins evaluated left to right? In other words, does this query say: x = companies JOIN users; y = x JOIN jobs; z = y JOIN useraccounts;</li>
<li>If the answer to question 2 is yes, is it safe to assume that the companies table has companyid, userid and jobid columns?</li>
<li>I don't understand how the WHERE clause can be used to pick rows on the companies table when it is referring to the alias "j"</li>
</ol>
<p>Any help would be appreciated!</p>
|
[
{
"answer_id": 228466,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "<p>SEE <a href=\"http://dev.mysql.com/doc/refman/5.0/en/join.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/join.html</a></p>\n\n<p><em>AND start reading here:</em></p>\n\n<hr>\n\n<p><strong>Join Processing Changes in MySQL 5.0.12</strong></p>\n\n<p>Beginning with MySQL 5.0.12, natural joins and joins with USING, including outer join variants, are processed according to the SQL:2003 standard. The goal was to align the syntax and semantics of MySQL with respect to NATURAL JOIN and JOIN ... USING according to SQL:2003. However, these changes in join processing can result in different output columns for some joins. Also, some queries that appeared to work correctly in older versions must be rewritten to comply with the standard.</p>\n\n<p>These changes have five main aspects:</p>\n\n<ul>\n<li><p>The way that MySQL determines the result columns of NATURAL or USING join operations (and thus the result of the entire FROM clause).</p></li>\n<li><p>Expansion of SELECT * and SELECT tbl_name.* into a list of selected columns.</p></li>\n<li><p>Resolution of column names in NATURAL or USING joins.</p></li>\n<li><p>Transformation of NATURAL or USING joins into JOIN ... ON.</p></li>\n<li><p>Resolution of column names in the ON condition of a JOIN ... ON.</p></li>\n</ul>\n"
},
{
"answer_id": 228468,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 4,
"selected": false,
"text": "<p>I can't answer the bit about the USING syntax. That's weird. I've never seen it before, having always used an ON clause instead.</p>\n\n<p>But what I <em>can</em> tell you is that the order of JOIN operations is determined dynamically by the query optimizer when it constructs its query plan, based on a system of optimization heuristics, some of which are:</p>\n\n<ol>\n<li><p>Is the JOIN performed on a primary key field? If so, this gets high priority in the query plan.</p></li>\n<li><p>Is the JOIN performed on a foreign key field? This also gets high priority.</p></li>\n<li><p>Does an index exist on the joined field? If so, bump the priority.</p></li>\n<li><p>Is a JOIN operation performed on a field in WHERE clause? Can the WHERE clause expression be evaluated by examining the index (rather than by performing a table scan)? This is a <em>major</em> optimization opportunity, so it gets a major priority bump.</p></li>\n<li><p>What is the cardinality of the joined column? Columns with high cardinality give the optimizer more opportunities to discriminate against false matches (those that don't satisfy the WHERE clause or the ON clause), so high-cardinality joins are usually processed before low-cardinality joins.</p></li>\n<li><p>How many actual rows are in the joined table? Joining against a table with only 100 values is going to create less of a data explosion than joining against a table with ten million rows.</p></li>\n</ol>\n\n<p>Anyhow... the point is... there are a LOT of variables that go into the query execution plan. If you want to see how MySQL optimizes its queries, use the EXPLAIN syntax.</p>\n\n<p>And here's a good article to read:</p>\n\n<p><a href=\"http://www.informit.com/articles/article.aspx?p=377652\" rel=\"noreferrer\">http://www.informit.com/articles/article.aspx?p=377652</a></p>\n\n<hr>\n\n<p>ON EDIT:</p>\n\n<p>To answer your 4th question: You aren't querying the \"companies\" table. You're querying the joined cross-product of <strong>ALL</strong> four tables in your FROM and USING clauses.</p>\n\n<p>The \"j.jobid\" alias is just the fully-qualified name of one of the columns in that joined collection of tables.</p>\n"
},
{
"answer_id": 228473,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 0,
"selected": false,
"text": "<p>Im not sure about the ON vs USING part (though this <a href=\"http://www.java2s.com/Tutorial/MySQL/0100__Table-Join/ThekeywordUSINGcanbeusedasareplacementfortheONkeywordduringthetableJoins.htm\" rel=\"nofollow noreferrer\" title=\"website\">website</a> says they are the same)</p>\n\n<p>As for the ordering question, its entirely implementation (and probably query) specific. MYSQL most likely picks an order when compiling the request. If you do want to enforce a particular order you would have to 'nest' your queries:</p>\n\n<pre><code>SELECT c.*\nFROM companies AS c \n JOIN (SELECT * FROM users AS u \n JOIN (SELECT * FROM jobs AS j USING(userid) \n JOIN useraccounts AS us USING(userid) \n WHERE j.jobid = 123)\n )\n</code></pre>\n\n<p>as for part 4: the where clause limits what rows from the jobs table are eligible to be JOINed on. So if there are rows which would join due to the matching userids but don't have the correct jobid then they will be omitted.</p>\n"
},
{
"answer_id": 228517,
"author": "Dave K",
"author_id": 19864,
"author_profile": "https://Stackoverflow.com/users/19864",
"pm_score": 0,
"selected": false,
"text": "<p>1) Using is not exactly the same as on, but it is short hand where both tables have a column with the same name you are joining on... see: <a href=\"http://www.java2s.com/Tutorial/MySQL/0100__Table-Join/ThekeywordUSINGcanbeusedasareplacementfortheONkeywordduringthetableJoins.htm\" rel=\"nofollow noreferrer\">http://www.java2s.com/Tutorial/MySQL/0100__Table-Join/ThekeywordUSINGcanbeusedasareplacementfortheONkeywordduringthetableJoins.htm</a></p>\n\n<p>It is more difficult to read in my opinion, so I'd go spelling out the joins.</p>\n\n<p>3) It is not clear from this query, but I would guess it does not.</p>\n\n<p>2) Assuming you are joining through the other tables (not all directly on companyies) the order in this query does matter... see comparisons below:</p>\n\n<p><strong>Origional:</strong></p>\n\n<pre><code>SELECT c.* \n FROM companies AS c \n JOIN users AS u USING(companyid) \n JOIN jobs AS j USING(userid) \n JOIN useraccounts AS us USING(userid) \nWHERE j.jobid = 123\n</code></pre>\n\n<p><strong>What I think it is likely suggesting:</strong></p>\n\n<pre><code>SELECT c.* \n FROM companies AS c \n JOIN users AS u on u.companyid = c.companyid\n JOIN jobs AS j on j.userid = u.userid\n JOIN useraccounts AS us on us.userid = u.userid \nWHERE j.jobid = 123\n</code></pre>\n\n<p>You could switch you lines joining jobs & usersaccounts here.</p>\n\n<p><strong>What it would look like if everything joined on company:</strong></p>\n\n<pre><code>SELECT c.* \n FROM companies AS c \n JOIN users AS u on u.companyid = c.companyid\n JOIN jobs AS j on j.userid = c.userid\n JOIN useraccounts AS us on us.userid = c.userid\nWHERE j.jobid = 123\n</code></pre>\n\n<p>This doesn't really make logical sense... unless each user has their own company.</p>\n\n<p>4.) The magic of sql is that you can only show certain columns but all of them are their for sorting and filtering...</p>\n\n<p>if you returned</p>\n\n<pre><code>SELECT c.*, j.jobid.... \n</code></pre>\n\n<p>you could clearly see what it was filtering on, but the database server doesn't care if you output a row or not for filtering.</p>\n"
},
{
"answer_id": 228563,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 6,
"selected": true,
"text": "<ol>\n<li><p>USING (fieldname) is a shorthand way of saying ON table1.fieldname = table2.fieldname.</p></li>\n<li><p>SQL doesn't define the 'order' in which JOINS are done because it is not the nature of the language. Obviously an order has to be specified in the statement, but an INNER JOIN can be considered commutative: you can list them in any order and you will get the same results.</p>\n\n<p>That said, when constructing a SELECT ... JOIN, particularly one that includes LEFT JOINs, I've found it makes sense to regard the third JOIN as joining the new table to the results of the first JOIN, the fourth JOIN as joining the results of the second JOIN, and so on.</p>\n\n<p>More rarely, the specified order can influence the behaviour of the query optimizer, due to the way it influences the heuristics.</p></li>\n<li><p>No. The way the query is assembled, it requires that companies and users both have a companyid, jobs has a userid and a jobid and useraccounts has a userid. However, only one of companies <em>or</em> user needs a userid for the JOIN to work.</p></li>\n<li><p>The WHERE clause is filtering the whole result -- i.e. all JOINed columns -- using a column provided by the jobs table.</p></li>\n</ol>\n"
},
{
"answer_id": 750425,
"author": "NickZoic",
"author_id": 90927,
"author_profile": "https://Stackoverflow.com/users/90927",
"pm_score": 2,
"selected": false,
"text": "<p>In MySQL, it's often interesting to ask the query optimizer what it plans to do, with:</p>\n\n<pre><code>EXPLAIN SELECT [...]\n</code></pre>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/using-explain.html\" rel=\"nofollow noreferrer\">\"7.2.1 Optimizing Queries with EXPLAIN\"</a></p>\n"
},
{
"answer_id": 48120937,
"author": "William Entriken",
"author_id": 300224,
"author_profile": "https://Stackoverflow.com/users/300224",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a more detailed answer on <code>JOIN</code> precedence. In your case, the <code>JOIN</code>s are all commutative. Let's try one where they aren't.</p>\n\n<p>Build schema:</p>\n\n<pre><code>CREATE TABLE users (\n name text\n);\n\nCREATE TABLE orders (\n order_id text,\n user_name text\n);\n\nCREATE TABLE shipments (\n order_id text,\n fulfiller text\n);\n</code></pre>\n\n<p>Add data:</p>\n\n<pre><code>INSERT INTO users VALUES ('Bob'), ('Mary');\n\nINSERT INTO orders VALUES ('order1', 'Bob');\n\nINSERT INTO shipments VALUES ('order1', 'Fulfilling Mary');\n</code></pre>\n\n<p>Run query:</p>\n\n<pre><code>SELECT *\n FROM users\n LEFT OUTER JOIN orders\n ON orders.user_name = users.name\n JOIN shipments\n ON shipments.order_id = orders.order_id\n</code></pre>\n\n<p>Result:</p>\n\n<p>Only the Bob row is returned</p>\n\n<p>Analysis:</p>\n\n<p>In this query the <code>LEFT OUTER JOIN</code> was evaluated first and the <code>JOIN</code> was evaluated on the composite result of the <code>LEFT OUTER JOIN</code>.</p>\n\n<p>Second query:</p>\n\n<pre><code>SELECT *\n FROM users\n LEFT OUTER JOIN (\n orders\n JOIN shipments\n ON shipments.order_id = orders.order_id)\n ON orders.user_name = users.name\n</code></pre>\n\n<p>Result:</p>\n\n<p>One row for Bob (with the fulfillment data) and one row for Mary with NULLs for fulfillment data.</p>\n\n<p>Analysis:</p>\n\n<p>The parenthesis changed the evaluation order.</p>\n\n<hr>\n\n<p>Further MySQL documentation is at <a href=\"https://dev.mysql.com/doc/refman/5.5/en/nested-join-optimization.html\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/refman/5.5/en/nested-join-optimization.html</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056/"
] |
I have the following query:
```
SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid)
WHERE j.jobid = 123;
```
I have the following questions:
1. Is the USING syntax synonymous with ON syntax?
2. Are these joins evaluated left to right? In other words, does this query say: x = companies JOIN users; y = x JOIN jobs; z = y JOIN useraccounts;
3. If the answer to question 2 is yes, is it safe to assume that the companies table has companyid, userid and jobid columns?
4. I don't understand how the WHERE clause can be used to pick rows on the companies table when it is referring to the alias "j"
Any help would be appreciated!
|
1. USING (fieldname) is a shorthand way of saying ON table1.fieldname = table2.fieldname.
2. SQL doesn't define the 'order' in which JOINS are done because it is not the nature of the language. Obviously an order has to be specified in the statement, but an INNER JOIN can be considered commutative: you can list them in any order and you will get the same results.
That said, when constructing a SELECT ... JOIN, particularly one that includes LEFT JOINs, I've found it makes sense to regard the third JOIN as joining the new table to the results of the first JOIN, the fourth JOIN as joining the results of the second JOIN, and so on.
More rarely, the specified order can influence the behaviour of the query optimizer, due to the way it influences the heuristics.
3. No. The way the query is assembled, it requires that companies and users both have a companyid, jobs has a userid and a jobid and useraccounts has a userid. However, only one of companies *or* user needs a userid for the JOIN to work.
4. The WHERE clause is filtering the whole result -- i.e. all JOINed columns -- using a column provided by the jobs table.
|
228,441 |
<p>I am working on rails project and I am trying to get exceptions to be logged to the rails log files. I know I can call <code>logger.error $!</code> to get the first line of the exception logged to the file. But, I want to get the entire trace stack logged as well. How do I log the entire trace back of an exception using the default rails logger?</p>
|
[
{
"answer_id": 228467,
"author": "Redbeard",
"author_id": 14977,
"author_profile": "https://Stackoverflow.com/users/14977",
"pm_score": 3,
"selected": false,
"text": "<p><code>logger.error caller.join(\"\\n\")</code> should do the trick.</p>\n"
},
{
"answer_id": 236350,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 6,
"selected": true,
"text": "<pre><code>logger.error $!.backtrace\n</code></pre>\n\n<p>Also, don't forget you can </p>\n\n<pre><code>rescue ErrorType => error_name\n</code></pre>\n\n<p>to give your error a variable name other than the default <code>$!</code>.</p>\n"
},
{
"answer_id": 237846,
"author": "Matt Burke",
"author_id": 29691,
"author_profile": "https://Stackoverflow.com/users/29691",
"pm_score": 4,
"selected": false,
"text": "<p>The way rails does it is</p>\n\n<pre><code>137 logger.fatal(\n138 \"\\n\\n#{exception.class} (#{exception.message}):\\n \" +\n139 clean_backtrace(exception).join(\"\\n \") +\n140 \"\\n\\n\"\n141 )\n\n248 def clean_backtrace(exception)\n249 if backtrace = exception.backtrace\n250 if defined?(RAILS_ROOT)\n251 backtrace.map { |line| line.sub RAILS_ROOT, '' }\n252 else\n253 backtrace\n254 end\n255 end\n256 end\n</code></pre>\n"
},
{
"answer_id": 308239,
"author": "Priit",
"author_id": 22964,
"author_profile": "https://Stackoverflow.com/users/22964",
"pm_score": 2,
"selected": false,
"text": "<p>In Rails, <code>ActionController::Rescue</code> deals with it. In my application controller actions, i'm using method <code>log_error</code> from this module to pretty-format backtrace in logs:</p>\n\n<pre><code>def foo_action\n # break something in here\nrescue\n log_error($!)\n # call firemen\nend\n</code></pre>\n"
},
{
"answer_id": 979388,
"author": "user52804",
"author_id": 52804,
"author_profile": "https://Stackoverflow.com/users/52804",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how I would do it:</p>\n\n<p><a href=\"http://gist.github.com/127708\" rel=\"nofollow noreferrer\">http://gist.github.com/127708</a></p>\n\n<p>Here's the ri documentation for Exception#backtrace:</p>\n\n<p><a href=\"http://gist.github.com/127710\" rel=\"nofollow noreferrer\">http://gist.github.com/127710</a></p>\n\n<p>Note that you could also use Kernel#caller, which gives you the full trace (minus the curent frame) as well.</p>\n\n<p><a href=\"http://gist.github.com/127709\" rel=\"nofollow noreferrer\">http://gist.github.com/127709</a></p>\n\n<p>Also - Note that if you are trying to catch <em>all</em> exceptions, you should rescue from Exception, not RuntimeError.</p>\n"
},
{
"answer_id": 1527404,
"author": "mxgrn",
"author_id": 103160,
"author_profile": "https://Stackoverflow.com/users/103160",
"pm_score": 3,
"selected": false,
"text": "<p>In later versions of Rails, simply uncomment the following line in RAIL_ROOT/config/initializers/backtrace_silencers.rb (or add this file itself if it's not there):</p>\n\n<pre><code># Rails.backtrace_cleaner.remove_silencers!\n</code></pre>\n\n<p>This way you get the full backtrace written to the log on an exception. This works for me in v2.3.4.</p>\n"
},
{
"answer_id": 50532336,
"author": "user3223833",
"author_id": 3223833,
"author_profile": "https://Stackoverflow.com/users/3223833",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use ruby's default variables, like this:</p>\n\n<pre><code>logger.error \"Your error message. Exception message:#{$!} Stacktrace:#{$@}\"\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
I am working on rails project and I am trying to get exceptions to be logged to the rails log files. I know I can call `logger.error $!` to get the first line of the exception logged to the file. But, I want to get the entire trace stack logged as well. How do I log the entire trace back of an exception using the default rails logger?
|
```
logger.error $!.backtrace
```
Also, don't forget you can
```
rescue ErrorType => error_name
```
to give your error a variable name other than the default `$!`.
|
228,476 |
<p>Taking over some code from my predecessor and I found a query that uses the Like operator:</p>
<pre><code>SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';
</code></pre>
<p>Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?</p>
<p>note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.</p>
|
[
{
"answer_id": 228488,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>Simply parameterize your query:</p>\n\n<pre><code>SELECT * FROM suppliers WHERE supplier_name like '%' + @name + '%'\n</code></pre>\n\n<p>Now you can pass your \"name\" variable into the @name parameter and the query will execute without any danger of injection attacks. Even if you pass in something like \"'' OR true --\" it'll still work fine.</p>\n"
},
{
"answer_id": 228490,
"author": "vdhant",
"author_id": 30572,
"author_profile": "https://Stackoverflow.com/users/30572",
"pm_score": -1,
"selected": false,
"text": "<p>Short Anwser:</p>\n\n<p>1) name.Replace(\"'\", \"''\").... Replace any escape characters that your database may have (single quotes being the most common)</p>\n\n<p>2) if you are using a language like .net use Parameterized Queries</p>\n\n<pre><code>sql=\"Insert into Employees (Firstname, Lastname, City, State, Zip, Phone, Email) Values ('\" & frmFirstname.text & \"', '\" & frmLastName & \"', '\" & frmCity & \"', '\" & frmState & \"', '\" & frmZip & \"', '\" & frmPhone & \"', '\" & frmEmail & \"')\"\n</code></pre>\n\n<p>The above gets replaced with the below</p>\n\n<pre><code>Dim MySQL as string = \"Insert into NewEmp (fname, LName, Address, City, State, Postalcode, Phone, Email) Values (@Firstname, @LastName, @Address, @City, @State, @Postalcode, @Phone, @Email)\" \n\nWith cmd.Parameters:\n .Add(New SQLParameter(\"@Firstname\", frmFname.text))\n .Add(New SQLParameter(\"@LastName\", frmLname.text))\n .Add(New SQLParameter(\"@Address\", frmAddress.text))\n .Add(New SQLParameter(\"@City\", frmCity.text))\n .Add(New SQLParameter(\"@state\", frmState.text))\n .Add(New SQLParameter(\"@Postalcode\", frmPostalCode.Text))\n .Add(New SQLParameter(\"@Phone\", frmPhone.text))\n .Add(New SQLParameter(\"@email\", frmemail.text))\nend with\n</code></pre>\n\n<p>3) user Stored procs</p>\n\n<p>4) use Linq to SQL, again if you are using .net</p>\n"
},
{
"answer_id": 228491,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 5,
"selected": true,
"text": "<p>try this: </p>\n\n<pre><code>var query = \"select * from foo where name like @searchterm\";\nusing (var command = new SqlCommand(query, connection))\n{\n command.Parameters.AddWithValue(\"@searchterm\", String.Format(\"%{0}%\", searchTerm));\n var result = command.ExecuteReader();\n}\n</code></pre>\n\n<p>the framework will automatically deal with the quoting issues.</p>\n"
},
{
"answer_id": 47334937,
"author": "Mehmet Recep Yildiz",
"author_id": 2358794,
"author_profile": "https://Stackoverflow.com/users/2358794",
"pm_score": 0,
"selected": false,
"text": "<p>In Entity Framework 6 it could be done like this by Native SQL:</p>\n\n<pre><code>List<Person> peopleList = contex.People.SqlQuery(\n @\"SELECT * FROM [Person].[Person]\n WHERE [FirstName] LIKE N'%' + @p0 + '%' \", \"ab\").ToList();\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>List<Person> peopleList = contex.People.SqlQuery(\n @\"SELECT * FROM [Person].[Person]\n WHERE [FirstName] LIKE N'%' + @name + '%' \",\n new SqlParameter(\"@name\", \"ab\")).ToList();\n</code></pre>\n\n<p>Also, you can just use LINQ to Entities directly:</p>\n\n<pre><code>List<Person> peopleList1 = contex.People.Where(s => s.FirstName.Contains(\"ab\")).ToList();\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
] |
Taking over some code from my predecessor and I found a query that uses the Like operator:
```
SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';
```
Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?
note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.
|
try this:
```
var query = "select * from foo where name like @searchterm";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@searchterm", String.Format("%{0}%", searchTerm));
var result = command.ExecuteReader();
}
```
the framework will automatically deal with the quoting issues.
|
228,477 |
<p>I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?</p>
|
[
{
"answer_id": 228481,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 10,
"selected": true,
"text": "<p>You can use:</p>\n\n<pre><code>System.getProperty(\"os.name\")\n</code></pre>\n\n<p>P.S. You may find this code useful:</p>\n\n<pre><code>class ShowProperties {\n public static void main(String[] args) {\n System.getProperties().list(System.out);\n }\n}\n</code></pre>\n\n<p>All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)</p>\n"
},
{
"answer_id": 228499,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": false,
"text": "<p>Oct. 2008:</p>\n\n<p>I would recommend to cache it in a static variable:</p>\n\n<pre><code>public static final class OsUtils\n{\n private static String OS = null;\n public static String getOsName()\n {\n if(OS == null) { OS = System.getProperty(\"os.name\"); }\n return OS;\n }\n public static boolean isWindows()\n {\n return getOsName().startsWith(\"Windows\");\n }\n\n public static boolean isUnix() // and so on\n}\n</code></pre>\n\n<p>That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.</p>\n\n<hr>\n\n<p>February 2016: 7+ years later:</p>\n\n<p>There is a bug with Windows 10 (which did not exist at the time of the original answer).<br>\nSee \"<a href=\"https://stackoverflow.com/a/31909887/6309\">Java's “os.name” for Windows 10?</a>\"</p>\n"
},
{
"answer_id": 228562,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 3,
"selected": false,
"text": "<p>If you're interested in how an open source project does stuff like this, you can check out the Terracotta class (Os.java) that handles this junk here:</p>\n\n<ul>\n<li><strike><a href=\"http://svn.terracotta.org/svn/tc/dso/trunk/code/base/common/src/com/tc/util/runtime/\" rel=\"noreferrer\">http://svn.terracotta.org/svn/tc/dso/trunk/code/base/common/src/com/tc/util/runtime/</a></strike></li>\n<li><a href=\"http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/\" rel=\"noreferrer\">http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/</a></li>\n</ul>\n\n<p>And you can see a similar class to handle JVM versions (Vm.java and VmVersion.java) here:</p>\n\n<ul>\n<li><a href=\"http://svn.terracotta.org/svn/tc/dso/trunk/common/src/main/java/com/tc/util/runtime/\" rel=\"noreferrer\">http://svn.terracotta.org/svn/tc/dso/trunk/common/src/main/java/com/tc/util/runtime/</a></li>\n</ul>\n"
},
{
"answer_id": 228568,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 3,
"selected": false,
"text": "<p>I find that the <a href=\"https://github.com/tmyroadctfig/swingx/blob/master/swingx-common/src/main/java/org/jdesktop/swingx/util/OS.java\" rel=\"nofollow noreferrer\">OS Utils from Swingx</a> does the job.</p>\n"
},
{
"answer_id": 2917718,
"author": "Leif Carlsen",
"author_id": 233317,
"author_profile": "https://Stackoverflow.com/users/233317",
"pm_score": 8,
"selected": false,
"text": "<p>As indicated in other answers, System.getProperty provides the raw data. However, the <a href=\"http://commons.apache.org/lang/\" rel=\"noreferrer\">Apache Commons Lang component</a> provides a <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html\" rel=\"noreferrer\">wrapper for java.lang.System</a> with handy properties like <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html#IS_OS_WINDOWS\" rel=\"noreferrer\"><code>SystemUtils.IS_OS_WINDOWS</code></a>, much like the aforementioned Swingx OS util.</p>\n"
},
{
"answer_id": 16278800,
"author": "Vishal Chaudhari",
"author_id": 1856449,
"author_profile": "https://Stackoverflow.com/users/1856449",
"pm_score": 3,
"selected": false,
"text": "<pre><code>String osName = System.getProperty(\"os.name\");\nSystem.out.println(\"Operating system \" + osName);\n</code></pre>\n"
},
{
"answer_id": 17506150,
"author": "Nikesh Jauhari",
"author_id": 1964633,
"author_profile": "https://Stackoverflow.com/users/1964633",
"pm_score": 4,
"selected": false,
"text": "<p>A small example of what you're trying to achieve would probably be a <code>class</code> similar to what's underneath:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Locale;\n\npublic class OperatingSystem\n{\n private static String OS = System.getProperty(\"os.name\", \"unknown\").toLowerCase(Locale.ROOT);\n\n public static boolean isWindows()\n {\n return OS.contains(\"win\");\n }\n\n public static boolean isMac()\n {\n return OS.contains(\"mac\");\n }\n\n public static boolean isUnix()\n {\n return OS.contains(\"nux\");\n }\n}\n</code></pre>\n\n<p>This particular implementation is quite reliable and should be universally applicable. Just copy and paste it into your <code>class</code> of choice.</p>\n"
},
{
"answer_id": 18417382,
"author": "Wolfgang Fahl",
"author_id": 1497139,
"author_profile": "https://Stackoverflow.com/users/1497139",
"pm_score": 6,
"selected": false,
"text": "<p>some of the links in the answers above seem to be broken. I have added pointers to current source code in the code below and offer an approach for handling the check with an enum as an answer so that a switch statement can be used when evaluating the result:</p>\n\n<pre><code>OsCheck.OSType ostype=OsCheck.getOperatingSystemType();\nswitch (ostype) {\n case Windows: break;\n case MacOS: break;\n case Linux: break;\n case Other: break;\n}\n</code></pre>\n\n<p>The helper class is:</p>\n\n<pre><code>/**\n * helper class to check the operating system this Java VM runs in\n *\n * please keep the notes below as a pseudo-license\n *\n * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java\n * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java\n * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html\n */\nimport java.util.Locale;\npublic static final class OsCheck {\n /**\n * types of Operating Systems\n */\n public enum OSType {\n Windows, MacOS, Linux, Other\n };\n\n // cached result of OS detection\n protected static OSType detectedOS;\n\n /**\n * detect the operating system from the os.name System property and cache\n * the result\n * \n * @returns - the operating system detected\n */\n public static OSType getOperatingSystemType() {\n if (detectedOS == null) {\n String OS = System.getProperty(\"os.name\", \"generic\").toLowerCase(Locale.ENGLISH);\n if ((OS.indexOf(\"mac\") >= 0) || (OS.indexOf(\"darwin\") >= 0)) {\n detectedOS = OSType.MacOS;\n } else if (OS.indexOf(\"win\") >= 0) {\n detectedOS = OSType.Windows;\n } else if (OS.indexOf(\"nux\") >= 0) {\n detectedOS = OSType.Linux;\n } else {\n detectedOS = OSType.Other;\n }\n }\n return detectedOS;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 22453323,
"author": "TacB0sS",
"author_id": 348189,
"author_profile": "https://Stackoverflow.com/users/348189",
"pm_score": 2,
"selected": false,
"text": "<p>I liked Wolfgang's answer, just because I believe things like that should be consts...</p>\n\n<p>so I've rephrased it a bit for myself, and thought to share it :)</p>\n\n<pre><code>/**\n * types of Operating Systems\n *\n * please keep the note below as a pseudo-license\n *\n * helper class to check the operating system this Java VM runs in\n * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java\n * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java\n * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html\n */\npublic enum OSType {\n MacOS(\"mac\", \"darwin\"),\n Windows(\"win\"),\n Linux(\"nux\"),\n Other(\"generic\");\n\n private static OSType detectedOS;\n\n private final String[] keys;\n\n private OSType(String... keys) {\n this.keys = keys;\n }\n\n private boolean match(String osKey) {\n for (int i = 0; i < keys.length; i++) {\n if (osKey.indexOf(keys[i]) != -1)\n return true;\n }\n return false;\n }\n\n public static OSType getOS_Type() {\n if (detectedOS == null)\n detectedOS = getOperatingSystemType(System.getProperty(\"os.name\", Other.keys[0]).toLowerCase());\n return detectedOS;\n }\n\n private static OSType getOperatingSystemType(String osKey) {\n for (OSType osType : values()) {\n if (osType.match(osKey))\n return osType;\n }\n return Other;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 23512457,
"author": "Kamidu",
"author_id": 3603020,
"author_profile": "https://Stackoverflow.com/users/3603020",
"pm_score": 4,
"selected": false,
"text": "<p>Try this,simple and easy</p>\n\n<pre><code>System.getProperty(\"os.name\");\nSystem.getProperty(\"os.version\");\nSystem.getProperty(\"os.arch\");\n</code></pre>\n"
},
{
"answer_id": 25078556,
"author": "ShinnedHawks",
"author_id": 3068728,
"author_profile": "https://Stackoverflow.com/users/3068728",
"pm_score": 2,
"selected": false,
"text": "<p>This code for displaying all information about the system os type,name , java information and so on.</p>\n\n<pre><code>public static void main(String[] args) {\n // TODO Auto-generated method stub\n Properties pro = System.getProperties();\n for(Object obj : pro.keySet()){\n System.out.println(\" System \"+(String)obj+\" : \"+System.getProperty((String)obj));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 30012452,
"author": "PAA",
"author_id": 2929562,
"author_profile": "https://Stackoverflow.com/users/2929562",
"pm_score": 3,
"selected": false,
"text": "<p>Below code shows the values that you can get from System API, these all things you can get through this API.</p>\n\n<pre><code>public class App {\n public static void main( String[] args ) {\n //Operating system name\n System.out.println(System.getProperty(\"os.name\"));\n\n //Operating system version\n System.out.println(System.getProperty(\"os.version\"));\n\n //Path separator character used in java.class.path\n System.out.println(System.getProperty(\"path.separator\"));\n\n //User working directory\n System.out.println(System.getProperty(\"user.dir\"));\n\n //User home directory\n System.out.println(System.getProperty(\"user.home\"));\n\n //User account name\n System.out.println(System.getProperty(\"user.name\"));\n\n //Operating system architecture\n System.out.println(System.getProperty(\"os.arch\"));\n\n //Sequence used by operating system to separate lines in text files\n System.out.println(System.getProperty(\"line.separator\"));\n\n System.out.println(System.getProperty(\"java.version\")); //JRE version number\n\n System.out.println(System.getProperty(\"java.vendor.url\")); //JRE vendor URL\n\n System.out.println(System.getProperty(\"java.vendor\")); //JRE vendor name\n\n System.out.println(System.getProperty(\"java.home\")); //Installation directory for Java Runtime Environment (JRE)\n\n System.out.println(System.getProperty(\"java.class.path\"));\n\n System.out.println(System.getProperty(\"file.separator\"));\n }\n}\n</code></pre>\n\n<p>Answers:-</p>\n\n<pre><code>Windows 7\n6.1\n;\nC:\\Users\\user\\Documents\\workspace-eclipse\\JavaExample\nC:\\Users\\user\nuser\namd64\n\n\n1.7.0_71\nhttp://java.oracle.com/\nOracle Corporation\nC:\\Program Files\\Java\\jre7\nC:\\Users\\user\\Documents\\workspace-Eclipse\\JavaExample\\target\\classes\n\\\n</code></pre>\n"
},
{
"answer_id": 31547504,
"author": "Memin",
"author_id": 2234161,
"author_profile": "https://Stackoverflow.com/users/2234161",
"pm_score": 5,
"selected": false,
"text": "<p><strong>TL;DR</strong></p>\n<p>For accessing OS use: <code>System.getProperty("os.name")</code>.</p>\n<hr />\n<h2>But WAIT!!!</h2>\n<p>Why not create a utility class, make it reusable! And probably much faster on multiple calls. <strong>Clean, clear, faster!</strong></p>\n<p>Create a Util class for such utility functions. Then create public enums for each operating system type.</p>\n<pre><code>public class Util { \n public enum OS {\n WINDOWS, LINUX, MAC, SOLARIS\n };// Operating systems.\n\n private static OS os = null;\n\n public static OS getOS() {\n if (os == null) {\n String operSys = System.getProperty("os.name").toLowerCase();\n if (operSys.contains("win")) {\n os = OS.WINDOWS;\n } else if (operSys.contains("nix") || operSys.contains("nux")\n || operSys.contains("aix")) {\n os = OS.LINUX;\n } else if (operSys.contains("mac")) {\n os = OS.MAC;\n } else if (operSys.contains("sunos")) {\n os = OS.SOLARIS;\n }\n }\n return os;\n }\n}\n</code></pre>\n<p>Now, you can easily invoke class from any class as follows,(P.S. Since we declared os variable as static, it will consume time only once to identify the system type, then it can be used until your application halts. )</p>\n<pre><code> switch (Util.getOS()) {\n case WINDOWS:\n //do windows stuff\n break;\n case LINUX:\n</code></pre>\n<p>and That is it!</p>\n"
},
{
"answer_id": 34950562,
"author": "Kirill Gamazkov",
"author_id": 1643115,
"author_profile": "https://Stackoverflow.com/users/1643115",
"pm_score": 2,
"selected": false,
"text": "<p>You can just use sun.awt.OSInfo#getOSType() method</p>\n"
},
{
"answer_id": 41174417,
"author": "Ihor Rybak",
"author_id": 5810648,
"author_profile": "https://Stackoverflow.com/users/5810648",
"pm_score": 6,
"selected": false,
"text": "<p>The following JavaFX classes have static methods to determine current OS (isWindows(),isLinux()...):</p>\n\n<ul>\n<li>com.sun.javafx.PlatformUtil </li>\n<li>com.sun.media.jfxmediaimpl.HostUtils</li>\n<li>com.sun.javafx.util.Utils</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>if (PlatformUtil.isWindows()){\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 52531796,
"author": "Nafeez Quraishi",
"author_id": 5916535,
"author_profile": "https://Stackoverflow.com/users/5916535",
"pm_score": 3,
"selected": false,
"text": "<p>I think following can give broader coverage in fewer lines</p>\n\n<pre><code>import org.apache.commons.exec.OS;\n\nif (OS.isFamilyWindows()){\n //load some property\n }\nelse if (OS.isFamilyUnix()){\n //load some other property\n }\n</code></pre>\n\n<p>More details here: <a href=\"https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html\" rel=\"noreferrer\">https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html</a></p>\n"
},
{
"answer_id": 56142476,
"author": "Vladimir Vaschenko",
"author_id": 5300967,
"author_profile": "https://Stackoverflow.com/users/5300967",
"pm_score": 0,
"selected": false,
"text": "<p>In com.sun.jna.Platform class you can find useful static methods like </p>\n\n<pre><code>Platform.isWindows();\nPlatform.is64Bit();\nPlatform.isIntel();\nPlatform.isARM();\n</code></pre>\n\n<p>and much more.</p>\n\n<p>If you use Maven just add dependency</p>\n\n<pre><code><dependency>\n <groupId>net.java.dev.jna</groupId>\n <artifactId>jna</artifactId>\n <version>5.2.0</version>\n</dependency>\n</code></pre>\n\n<p>Otherwise just find jna library jar file (ex. jna-5.2.0.jar) and add it to classpath.</p>\n"
},
{
"answer_id": 56869353,
"author": "itro",
"author_id": 1092450,
"author_profile": "https://Stackoverflow.com/users/1092450",
"pm_score": -1,
"selected": false,
"text": "<p>Just use <code>com.sun.javafx.util.Utils</code> as below.</p>\n\n<pre><code>if ( Utils.isWindows()){\n // LOGIC HERE\n}\n</code></pre>\n\n<p><strong>OR USE</strong> </p>\n\n<pre><code>boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);\n if (isWindows){\n // YOUR LOGIC HERE\n }\n</code></pre>\n"
},
{
"answer_id": 57616565,
"author": "Theikon",
"author_id": 11173058,
"author_profile": "https://Stackoverflow.com/users/11173058",
"pm_score": 3,
"selected": false,
"text": "<p><strong>If you're working in a security sensitive environment, then please read this through.</strong></p>\n<p>Please refrain from ever trusting a property obtained via the <code>System#getProperty(String)</code> subroutine! Actually, almost every property including <code>os.arch</code>, <code>os.name</code>, and <code>os.version</code> isn't readonly as you'd might expect — instead, they're actually quite the opposite.</p>\n<p>First of all, any code with sufficient permission of invoking the <code>System#setProperty(String, String)</code> subroutine can modify the returned literal at will. However, that's not necessarily the primary issue here, as it can be resolved through the use of a so called <code>SecurityManager</code>, as described in greater detail over <a href=\"https://docs.oracle.com/javase/tutorial/essential/environment/security.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>The actual issue is that any user is able to edit these properties when running the <code>JAR</code> in question (through <code>-Dos.name=</code>, <code>-Dos.arch=</code>, etc.). A possible way to avoid tampering with the application parameters is by querying the <code>RuntimeMXBean</code> as shown <a href=\"https://stackoverflow.com/a/1531999/11173058\">here</a>. The following code snippet should provide some insight into how this may be achieved.</p>\n<pre class=\"lang-java prettyprint-override\"><code>RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();\nList<String> arguments = runtimeMxBean.getInputArguments();\n\nfor (String argument : arguments) {\n if (argument.startsWith("-Dos.name") {\n // System.getProperty("os.name") altered\n } else if (argument.startsWith("-Dos.arch") {\n // System.getProperty("os.arch") altered\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67864441,
"author": "Hristo Stoyanov",
"author_id": 3610608,
"author_profile": "https://Stackoverflow.com/users/3610608",
"pm_score": 3,
"selected": false,
"text": "<p>A bit shorter, cleaner (and eagerly computed) version of the top answers:</p>\n<pre><code>switch(OSType.DETECTED){\n...\n}\n</code></pre>\n<p>The helper enum:</p>\n<pre><code>public enum OSType {\n Windows, MacOS, Linux, Other;\n public static final OSType DETECTED;\n static{\n String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);\n if ((OS.contains("mac")) || (OS.contains("darwin"))) {\n DETECTED = OSType.MacOS;\n } else if (OS.contains("win")) {\n DETECTED = OSType.Windows;\n } else if (OS.contains("nux")) {\n DETECTED = OSType.Linux;\n } else {\n DETECTED = OSType.Other;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68681632,
"author": "nima",
"author_id": 536226,
"author_profile": "https://Stackoverflow.com/users/536226",
"pm_score": -1,
"selected": false,
"text": "<p>Since google points "kotlin os name" to this page, here's the Kotlin version of @Memin 's <a href=\"https://stackoverflow.com/a/31547504/536226\">answer</a>:</p>\n<pre><code>private var _osType: OsTypes? = null\nval osType: OsTypes\n get() {\n if (_osType == null) {\n _osType = with(System.getProperty("os.name").lowercase(Locale.getDefault())) {\n if (contains("win"))\n OsTypes.WINDOWS\n else if (listOf("nix", "nux", "aix").any { contains(it) })\n OsTypes.LINUX\n else if (contains("mac"))\n OsTypes.MAC\n else if (contains("sunos"))\n OsTypes.SOLARIS\n else\n OsTypes.OTHER\n }\n }\n return _osType!!\n }\n\nenum class OsTypes {\n WINDOWS, LINUX, MAC, SOLARIS, OTHER\n}\n</code></pre>\n"
},
{
"answer_id": 71930717,
"author": "ShahzadIftikhar",
"author_id": 6690544,
"author_profile": "https://Stackoverflow.com/users/6690544",
"pm_score": -1,
"selected": false,
"text": "<p>For getting OS name, simply use:</p>\n<pre><code>Platform.getOS()\n</code></pre>\n<p>Lets say you want to see if platform is linux:</p>\n<pre><code>if (Platform.getOS().equals(Platform.OS_LINUX)) {\n}\n</code></pre>\n<p>Similarly Platform class have defined constants for others operating system names. Platform class is part of <code>org.eclipse.core.runtime</code> package.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318/"
] |
I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?
|
You can use:
```
System.getProperty("os.name")
```
P.S. You may find this code useful:
```
class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}
```
All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)
|
228,518 |
<p>The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in <b>Python</b>:</p>
<pre><code>R=lambda s:all(a==b for a,b in zip(s,reversed(s)))
</code></pre>
<p>50 characters.</p>
<p>The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.</p>
|
[
{
"answer_id": 228526,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 5,
"selected": false,
"text": "<p>Here's mine; it's written in a domain-specific language I invented, called 'palindrome'.</p>\n\n<pre><code>p\n</code></pre>\n\n<p><strong>Edit:</strong> Less flippant version (i386 asm, AT&T syntax)</p>\n\n<pre><code>xor %eax, %eax\nmov %esi, %edi\n#cld not necessary, assume DF=0 as per x86 ABI\nrepne scasb\nscan:\n dec %edi\n cmpsb\n .byte 0x75, 6 #jnz (short) done\n dec %edi\n cmp %esi, %edi\n .byte 0x72, -9 #jb (short) scan\ninc %eax\ndone:\n</code></pre>\n\n<p>16 bytes, string pointer goes in ESI, result is in EAX.</p>\n"
},
{
"answer_id": 228530,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>My attempt in C (70 chars):</p>\n\n<pre><code>P(char*s){char*e=s+strlen(s)-1;while(s<e&&*s==*e)s++,e--;return s>=e;}\n</code></pre>\n\n<p>[Edit] Now actually working<br>\n[Edit 2] Reduced from 74 to 70 by using default int return</p>\n\n<p>In response to some of the comments: I'm not sure if that preprocessor abuse counts - you could just define the whole thing on the command line and make the function one character.</p>\n"
},
{
"answer_id": 228535,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 5,
"selected": false,
"text": "<p>Another python version that is rather shorter (21 chars):</p>\n\n<pre><code>R=lambda s:s==s[::-1]\n</code></pre>\n"
},
{
"answer_id": 228543,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "<p>Perl (27 chars):</p>\n\n<pre><code>sub p{$_[0]eq reverse$_[0]}\n</code></pre>\n\n<p>Ruby (24 chars):</p>\n\n<pre><code>def p(a)a==a.reverse end\n</code></pre>\n"
},
{
"answer_id": 228678,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": "<p>73 clean, readable, chars written in java</p>\n\n<pre><code>boolean p(String s){return s.equals(\"\"+new StringBuffer(s).reverse());}\n</code></pre>\n\n<p>peace :) </p>\n"
},
{
"answer_id": 228685,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 3,
"selected": false,
"text": "<pre><code>(equal p (reverse p))\n</code></pre>\n\n<p>lisp. 18 characters.</p>\n\n<p>ok, this is a special case. This would work if typed directly into a lisp interpreter and p was already defined.</p>\n\n<p>otherwise, this would be necessary:</p>\n\n<pre><code>(defun g () (equal p (reverse p)))\n</code></pre>\n\n<p>28 characters.</p>\n"
},
{
"answer_id": 228727,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 5,
"selected": false,
"text": "<p>Haskell, <strong>15</strong> chars:</p>\n\n<pre><code>p=ap(==)reverse\n</code></pre>\n\n<p>More readable version, <strong>16</strong> chars:</p>\n\n<pre><code>p x=x==reverse x\n</code></pre>\n"
},
{
"answer_id": 228740,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 2,
"selected": false,
"text": "<p>PHP:</p>\n\n<pre><code>function p($s){return $s==strrev($s);} // 38 chars\n</code></pre>\n\n<p>or, just</p>\n\n<pre><code>$s==strrev($s); // 15 chars\n</code></pre>\n"
},
{
"answer_id": 229562,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "<p>CFScript, 39 characters: </p>\n\n<pre><code>function y(x){return(x is reverse(x));}\n</code></pre>\n\n<p>I was never very good at golf.</p>\n"
},
{
"answer_id": 229608,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "<p>Java:</p>\n\n<pre><code>boolean y(StringBuffer x){return x.equals(x.reverse());}\n</code></pre>\n\n<p>The above doesn't work, oops!</p>\n\n<pre><code>boolean y(StringBuffer x){return x.toString().equals(x.reverse().toString()); }\n</code></pre>\n\n<p>Ew.</p>\n"
},
{
"answer_id": 229610,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Haskell, 28 chars, needs Control.Arrow imported.</p>\n\n<pre><code>p=uncurry(==).(id&&&reverse)\n</code></pre>\n"
},
{
"answer_id": 229626,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "<p>Lua aims more at readability than conciseness, yet does an honest 37 chars:</p>\n\n<pre><code>function p(s)return s==s:reverse()end\n</code></pre>\n\n<p>variant, just for fun (same size):</p>\n\n<pre><code>p=function(s)return s==s:reverse''end\n</code></pre>\n\n<p>The JavaScript version is more verbose (55 chars), because it doesn't has a string reverse function:</p>\n\n<pre><code>function p(s){return s==s.split('').reverse().join('')}\n</code></pre>\n"
},
{
"answer_id": 230113,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 2,
"selected": false,
"text": "<p>Straightforward implementation in C using standard library functions, inspired by the strlen in the other C answer.</p>\n\n<p>Number of characters: 57</p>\n\n<pre><code>p(char*s){char*r=strdup(s);strrev(r);return strcmp(r,s);}\n</code></pre>\n\n<p>Confession: I'm being the bad guy by not freeing r here. My current attempt at being good:</p>\n\n<pre><code>p(char*s){char*r=strdup(s);s[0]=strcmp(strrev(r),s);free(r);return s[0];}\n</code></pre>\n\n<p>brings it to 73 characters; I'm thinking of any ways to do it shorter.</p>\n"
},
{
"answer_id": 230294,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "<p>Without using any library functions (because you should really add in the <code>#include</code> cost as well), here's a C++ version in 96:</p>\n\n<pre><code>int p(char*a,char*b=0,char*c=0){return c?b<a||p(a+1,--b,c)&&*a==*b:b&&*b?p(a,b+1):p(a,b?b:a,b);}\n</code></pre>\n"
},
{
"answer_id": 231080,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>Shell-script (sed + tac + tr):</p>\n\n<pre><code>test \"`echo $1|sed -e 's/\\(.\\)/\\1\\n/g'|tac|tr -d '\\n'`\" == \"$1\"\n</code></pre>\n"
},
{
"answer_id": 231391,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 7,
"selected": true,
"text": "<p>7 characters in J: Not sure if this is the best way, I'm somewhat new to J :)</p>\n\n<pre><code>p=:-:|.\n</code></pre>\n\n<p>explanation: |. reverses the input. -: compares. the operands are implicit.</p>\n\n<pre><code>p 'radar'\n1\n\np 'moose'\n0\n</code></pre>\n"
},
{
"answer_id": 231476,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>Isn't using the reverse function in your language kind of cheating a bit? I mean, looking at the Ruby solution give as</p>\n\n<pre><code>def p(a)a==a.reverse end\n</code></pre>\n\n<p>you could easily rewrite that as</p>\n\n<pre><code>def p(a)a==a.r end\n</code></pre>\n\n<p>and just say that you made an extension method in your code so that \"r\" called reverse. I'd like to see people post solutions that don't contain calls to other functions. Of course, the string length function should be permitted.</p>\n\n<p>Ruby without reverse - 41 characters</p>\n\n<pre><code>def m(a)a==a.split('').inject{|r,l|l+r}end\n</code></pre>\n\n<p>VB.Net - 173 Chars</p>\n\n<pre><code>Function P(ByVal S As String) As Boolean\n For i As Integer = 0 To S.Length - 1\n If S(i) <> S(S.Length - i - 1) Then\n Return False\n End If\n Next\n Return True\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 231639,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 2,
"selected": false,
"text": "<p>C# <strong>Without Reverse Function</strong> 84 chars </p>\n\n<pre><code>int p(char[]s){int i=0,l=s.Length,t=1;while(++i<l)if(s[i]!=s[l-i-1])t&=0;return t;} \n</code></pre>\n\n<p>C# <strong>Without Reverse Function</strong> 86 chars </p>\n\n<pre><code>int p(char[]s){int i=0;int l=s.Length;while(++i<l)if(s[i]!=s[l-i-1])return 0;return 1;}\n</code></pre>\n\n<p>VBScript 41 chars</p>\n\n<pre><code>function p:p=s=strreverse(s):end function\n</code></pre>\n"
},
{
"answer_id": 231685,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 0,
"selected": false,
"text": "<p>Definitely not the smallest, but I still wanted to add a entry:</p>\n\n<pre><code>sub p{return @_==reverse split//;}\n</code></pre>\n\n<p>My perl's rusty tho and this is untested.</p>\n"
},
{
"answer_id": 232360,
"author": "matyr",
"author_id": 15066,
"author_profile": "https://Stackoverflow.com/users/15066",
"pm_score": 2,
"selected": false,
"text": "<p>Groovy 17B:</p>\n\n<blockquote>\n <p><code>p={it==it[-1..0]}</code></p>\n</blockquote>\n\n<p><s>Downside is that it doesn't work with emptry string.</s></p>\n\n<p>On second thought, throwing exception for empty string is reasonable since you can't tell if nothing is palindrome or not.</p>\n"
},
{
"answer_id": 232397,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 4,
"selected": false,
"text": "<p>At the risk of getting down votes, most all of these just call a command <em>reverse</em> of some sort that hides all the real programming logic. </p>\n\n<p>I wonder what the shortest manual way to do this is in each of these languages.</p>\n"
},
{
"answer_id": 232440,
"author": "nyxtom",
"author_id": 19753,
"author_profile": "https://Stackoverflow.com/users/19753",
"pm_score": 2,
"selected": false,
"text": "<p>F# (a lot like the C# example)</p>\n\n<pre><code>let p s=let i=0;let l=s.Length;while(++i<l)if(s[i]!=[l-i-1]) 0; 1;;\n</code></pre>\n"
},
{
"answer_id": 232601,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Josh's Java snippet above will return true every time.</p>\n"
},
{
"answer_id": 232615,
"author": "Steven Dee",
"author_id": 31077,
"author_profile": "https://Stackoverflow.com/users/31077",
"pm_score": 3,
"selected": false,
"text": "<p>Pointless Haskell version (15 chars, though doesn't really work unless you include Control.Arrow and Control.Monad and ignore the monomorphism restriction):</p>\n\n<pre><code>p=ap(==)reverse\n</code></pre>\n"
},
{
"answer_id": 232952,
"author": "Figo",
"author_id": 12661,
"author_profile": "https://Stackoverflow.com/users/12661",
"pm_score": 3,
"selected": false,
"text": "<p>I'll take it a little bit further: full c code, compile and go.</p>\n\n<p>90 characters</p>\n\n<pre><code>main(int n,char**v){char*b,*e;b=e=v[1];while(*++e);for(e--;*b==*e&&b++<e--;);return b>e;}\n</code></pre>\n"
},
{
"answer_id": 233108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Common Lisp, short-and-cheating version (23 chars):</p>\n\n<pre><code>#L(equal !1(reverse !1))\n</code></pre>\n\n<p>#L is a reader macro character implemented by SHARPL-READER in the iterate package. It's basically equivalent to (lambda (!1) ...).</p>\n\n<p>Common Lisp, long version using only primitives (137 including whitespace, compressible down to 108):</p>\n\n<pre><code>(defun p (s)\n (let ((l (1- (length s))))\n (iter (for i from l downto (/ l 2))\n (always (equal (elt s i) (elt s (- l i)))))))\n</code></pre>\n\n<p>Again, it uses iterate, which is basically a cleaner version of the builtin LOOP facility, so I tend to treat it as being in the core language.</p>\n"
},
{
"answer_id": 233872,
"author": "OdeToCode",
"author_id": 17210,
"author_profile": "https://Stackoverflow.com/users/17210",
"pm_score": 4,
"selected": false,
"text": "<p>With C# and LINQ operators:</p>\n\n<pre><code>public bool IsPalindrome(string s)\n{\n return s.Reverse().SequenceEqual(s);\n}\n</code></pre>\n\n<p>If you consider Reverse as cheating, you can do the entire thing with a reduction:</p>\n\n<pre><code>public bool IsPalindrome(string s)\n{\n return s.Aggregate(new StringBuilder(),\n (sb, c) => sb.Insert(0, c),\n (sb) => sb.ToString() == s);\n}\n</code></pre>\n"
},
{
"answer_id": 235777,
"author": "Joe Z",
"author_id": 3696,
"author_profile": "https://Stackoverflow.com/users/3696",
"pm_score": 5,
"selected": false,
"text": "<p>Sadly, I'm unable to get under a thousand words...</p>\n\n<p><img src=\"https://i291.photobucket.com/albums/ll315/underflowx/palindrome.png\" alt=\"alt text\"></p>\n\n<p>(LabVIEW. Yeah, they'll let just about any hobo post here ;)</p>\n"
},
{
"answer_id": 235821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Clojure using 37 characters:</p>\n\n<pre><code>user=> (defn p[s](=(seq s)(reverse(seq s))))\n#'user/p\nuser=> (p \"radar\")\ntrue\nuser=> (p \"moose\")\nfalse\n</code></pre>\n"
},
{
"answer_id": 235864,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 0,
"selected": false,
"text": "<p>C, no libraries, 70 characters:</p>\n\n<pre><code>p(char*a){char*b=a-1;while(*++b);while(a<b&&*a++==*--b);return!(a<b);}\n</code></pre>\n\n<p>As one of the comments on another C solution mentioned, prototypes are completely optional in C, <code>int</code> is assumed everywhere a type would go but isn't mentioned. Has nobody ever programmed in pre-ANSI C?</p>\n\n<p>Edit: shorter and handles empty strings.</p>\n"
},
{
"answer_id": 235870,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "<p>24 characters in Perl.</p>\n\n<pre><code>sub p{$_[0]eq+reverse@_}\n</code></pre>\n"
},
{
"answer_id": 237017,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 2,
"selected": false,
"text": "<p>Inspired by previous post, 69 characters</p>\n\n<pre><code>p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++!=*--b;return!q;}\n</code></pre>\n\n<p>EDIT: Down one char:</p>\n\n<pre><code>p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++%*--b;return!q;}\n</code></pre>\n\n<p>EDIT2: 65 chars:</p>\n\n<pre><code>p(char*a){char*b=a;while(*b)b++;while(*a&&*a++==*--b);return!*a;}\n</code></pre>\n"
},
{
"answer_id": 237420,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>JavaScript: 55 chars</p>\n\n<pre><code>p=function(x){return (x==x.split('').reverse().join())}\n</code></pre>\n\n<p><em>The above won't work because you need to call <code>join</code> with <code>\"\"</code></em></p>\n\n<p>JavaScript: 55 chars</p>\n\n<pre><code>function p(s){return s==s.split(\"\").reverse().join(\"\")}\n</code></pre>\n"
},
{
"answer_id": 237577,
"author": "Skip Head",
"author_id": 23271,
"author_profile": "https://Stackoverflow.com/users/23271",
"pm_score": 0,
"selected": false,
"text": "<p>Java, without using reverse:</p>\n\n<pre><code>boolean p(String s){int i=0,l=s.length();while(i<l){if(s.charAt(i++)!=s.charAt(--l))l=-1;}return l>=0;\n</code></pre>\n"
},
{
"answer_id": 237665,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 0,
"selected": false,
"text": "<p>Standard ML (34 characters and boring):</p>\n\n<pre><code>fun p s=s=implode(rev(explode(s)))\n</code></pre>\n"
},
{
"answer_id": 239501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>C, 68 characters, no libs:</p>\n\n<pre><code>p(char *s){char *e=s;while(*++e);for(;*s==*--e&&s++<e;);return s>e;}\n</code></pre>\n"
},
{
"answer_id": 471849,
"author": "gnovice",
"author_id": 52738,
"author_profile": "https://Stackoverflow.com/users/52738",
"pm_score": 2,
"selected": false,
"text": "<p>Not the shortest, and very after-the-fact, but I couldn't help giving it a try in MATLAB:</p>\n\n<pre><code>R=@(s)all(s==fliplr(s));\n</code></pre>\n\n<p>24 chars.</p>\n"
},
{
"answer_id": 471869,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "<p>may was well give a c++ example which uses the standard library:</p>\n\n<pre><code>bool p(const std::string &s){std::string s2(s);std::reverse(s2);return s==s2;}\n</code></pre>\n\n<p>Thanks to Jon For pointing out that this could be shorter if we make some unnecessary copies. Totalling 67 chars.</p>\n\n<pre><code>bool p(std::string s){std::string x=s;std::reverse(x);return s==x;}\n</code></pre>\n"
},
{
"answer_id": 472245,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Haskell, 36 characters including its own reverse function. (Actually, if you use semicolons to make it a one-liner, and ignore the newline at the end, it'd be 35...)</p>\n\n<pre><code>r[]y=y\nr(a:x)y=r x$a:y\np s=s==r s[]\n</code></pre>\n\n<p>As with other implementations, \"p\" is the palindrome predicate.</p>\n"
},
{
"answer_id": 1483438,
"author": "Daniel",
"author_id": 179741,
"author_profile": "https://Stackoverflow.com/users/179741",
"pm_score": 0,
"selected": false,
"text": "<p>58 characters in Python, without reversing the string:</p>\n\n<pre>r=\"y\"\nfor i in range(len(s)):\n if(s[i]!=s[-i-1]):\n r=\"n\"</pre>\n\n<p>Maybe the for loop could be optimized? Python is new to me...</p>\n"
},
{
"answer_id": 1605617,
"author": "Eric Strom",
"author_id": 189416,
"author_profile": "https://Stackoverflow.com/users/189416",
"pm_score": 2,
"selected": false,
"text": "<p>18 character perl regex</p>\n\n<pre><code>/^(.?|(.)(?1)\\2)$/\n</code></pre>\n"
},
{
"answer_id": 2324017,
"author": "Deadcode",
"author_id": 161468,
"author_profile": "https://Stackoverflow.com/users/161468",
"pm_score": 2,
"selected": false,
"text": "<p>52 characters in C, with the caveat that up to half the string will be overwritten:</p>\n\n<p><code>p(char*s){return!*s||!(s[strlen(s)-1]-=*s)&&p(++s);}</code></p>\n\n<p>Without library calls it's 64 characters:</p>\n\n<p><code>p(char*s){char*e=s;while(*e)++e;return!*s||!(*--e-=*s)&&p(++s);}</code></p>\n"
},
{
"answer_id": 2324146,
"author": "Sean",
"author_id": 182693,
"author_profile": "https://Stackoverflow.com/users/182693",
"pm_score": 1,
"selected": false,
"text": "<p>Perl (21 characters):</p>\n\n<pre><code>sub{\"@_\"eq reverse@_}\n</code></pre>\n\n<p>Hey, the question didn't specify a <i>named</i> subroutine!</p>\n"
},
{
"answer_id": 3539899,
"author": "FishyFingers",
"author_id": 427410,
"author_profile": "https://Stackoverflow.com/users/427410",
"pm_score": 0,
"selected": false,
"text": "<p>javascript recursive version (no reverse junk) </p>\n\n<pre><code>function p(s){l=s.length;return l<2||(s[0]==s[l-1]&&p(s.substr(1,l-2)))}\n</code></pre>\n\n<p>(72 chars)</p>\n\n<p>or implement reverse inside:</p>\n\n<pre><code>p=function(s,y){return y?(s==p(s)):s[1]?(p(s.substr(1))+s[0]):s[0]}\n\np(\"hannah\",1);\n</code></pre>\n\n<p>(67 chars)</p>\n\n<p>or, using no built in functions at all...</p>\n\n<pre><code>p=function(s,y,i){\nreturn i?s[i]?s[i]+p(s,0,i+1):'':y?(s==p(s)):s[1]?(p(p(s,0,1))+s[0]):s[0]\n}\n\np(\"hannah\",1);\n</code></pre>\n\n<p>(92 chars)</p>\n\n<p>shortest I could come up with: (iterative)</p>\n\n<pre><code>function p(s,l){for(c in s){if(s[c]!=s[l-1-c])s=0}return s}\n\np(\"hannah\",6);// (is this cheating?)\n</code></pre>\n\n<p>(59 chars)</p>\n\n<p>looking forward to seeing you do it better in javascript!</p>\n\n<p>(preferably without using any built in functions, especially reverse)</p>\n\n<p>(not really very impressed by the 'return s==s.reverse()' type answers)</p>\n"
},
{
"answer_id": 3886155,
"author": "mob",
"author_id": 168657,
"author_profile": "https://Stackoverflow.com/users/168657",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Golfscript, 5 char</strong></p>\n\n<pre><code>.-1%=\n\n$ echo -n abacaba | ruby golfscript.rb palindrome.gs\n1\n\n$ echo -n deadbeef | ruby golfscript.rb palindrome.gs\n0\n</code></pre>\n"
},
{
"answer_id": 3886306,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 0,
"selected": false,
"text": "<p><strong>F#: 29 chars</strong></p>\n\n<pre><code>let p(s:string)=s=s.Reverse()\n</code></pre>\n\n<p>(assuming System.Linq is imported)</p>\n"
},
{
"answer_id": 3894687,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 0,
"selected": false,
"text": "<p>C# using a <em>recursive lambda</em> function and not using the <code>Reverse</code> function (115 chars):</p>\n\n<pre><code>Func<string,bool>p=null;p=w=>{if(w.Length<2)return true;return w[0]==w[w.Length-1]&&p(w.Substring(1,w.Length-2));};\n</code></pre>\n"
},
{
"answer_id": 3894868,
"author": "Jack",
"author_id": 121747,
"author_profile": "https://Stackoverflow.com/users/121747",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Impossible! language</strong>, assuming that string is passed by using normal args:</p>\n\n<pre><code>;~=\n</code></pre>\n\n<p>3 chars </p>\n"
},
{
"answer_id": 5364731,
"author": "pimvdb",
"author_id": 514749,
"author_profile": "https://Stackoverflow.com/users/514749",
"pm_score": 0,
"selected": false,
"text": "<p>JavaScript, 64 bytes.</p>\n\n<pre><code>function a(x){for(r='',i=x.length;i>0;i--)r+=x[i-1];return x==r}\n</code></pre>\n\n<p>Test case:</p>\n\n<pre><code>a('lolol'); // true\na('haha'); // false\n</code></pre>\n"
},
{
"answer_id": 6005274,
"author": "Denis Mitropolskiy",
"author_id": 272834,
"author_profile": "https://Stackoverflow.com/users/272834",
"pm_score": 1,
"selected": false,
"text": "<p>F#, no LINQ and Reverse method.\nSeq.fold:</p>\n\n<pre><code>let p (s : string) = \n fst(s |> Seq.fold (fun (r, i) c -> (r && c = s.[s.Length - 1 - i], i + 1)) (true, 0))\n</code></pre>\n\n<p>The same, but with Seq.iteri and ref variables instead of Seq.fold:</p>\n\n<pre><code>let p (s : string) = \n let r = ref true\n Seq.iteri (fun i c -> r := (!r && c = s.[s.Length - 1 - i])) s\n !r\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in **Python**:
```
R=lambda s:all(a==b for a,b in zip(s,reversed(s)))
```
50 characters.
The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.
|
7 characters in J: Not sure if this is the best way, I'm somewhat new to J :)
```
p=:-:|.
```
explanation: |. reverses the input. -: compares. the operands are implicit.
```
p 'radar'
1
p 'moose'
0
```
|
228,523 |
<p>Following on from <a href="https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values">this question</a> what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:</p>
<pre><code>bool CharIsHex(char c) {
c = Char.ToLower(c);
return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}
</code></pre>
|
[
{
"answer_id": 228531,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": true,
"text": "<p>From <a href=\"https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values#223854\">my answer</a> to the question you linked to:</p>\n\n<pre><code>bool is_hex_char = (c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F');\n</code></pre>\n"
},
{
"answer_id": 228536,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": false,
"text": "<p>You can write it as an extension method:</p>\n\n<pre><code>public static class Extensions\n{\n public static bool IsHex(this char c)\n {\n return (c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F');\n }\n}\n</code></pre>\n\n<p>This means you can then call it as though it were a member of <code>char</code>.</p>\n\n<pre><code>char c = 'A';\n\nif (c.IsHex())\n{\n Console.WriteLine(\"We have a hex char.\");\n}\n</code></pre>\n"
},
{
"answer_id": 228570,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "<p>What about</p>\n\n<pre><code>bool CharIsHex(char c) {\n c = Char.ToLower(c);\n return Char.IsDigit(c) || (c >= 'a' && c <= 'f');\n}\n</code></pre>\n"
},
{
"answer_id": 228580,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "<p>Note that <code>Char.IsDigit()</code> returns <code>true</code> for many more code points than just the digits in the ASCII range 0x30 to 0x39.</p>\n\n<p>For example the Thai digit characters that return <code>true</code> from Char.IsDigit(): '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'</p>\n\n<p>Also there are the 'Full width' characters that <code>Char.IsDigit()</code> returns true for: <code>0xff10</code> through <code>0xff19</code>. These glyphs look just like the ASCII characters <code>0x30-0x39</code>, so if you're going to accept them you should also probably accept <code>0xff21-0xff26</code> and <code>0xff41-0xff46</code> which look just like 'A'-'F' and 'a'-'f'.</p>\n\n<p>If you're going to support digits that are outside of the ASCII range, your users might expect that you to support glyphs that correspond to Latin 'a'..'f' and 'A'..'F' that exist in other scripts outside of the ASCII range.</p>\n\n<p>Personally, I think I'd stick with something more like:</p>\n\n<pre><code> bool isHexChar = ('0' <= c) && (c <= '9') ||\n ('a' <= c) && (c <= 'f') ||\n ('A' <= c) && (c <= 'F');\n</code></pre>\n\n<p>Which I think would be potentially less surprising to people.</p>\n"
},
{
"answer_id": 228606,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You can use regular expressions in an extension function:</p>\n\n<pre><code>using System.Text.RegularExpressions;\npublic static class Extensions\n{\n public static bool IsHex(this char c)\n {\n\n return (new Regex(\"[A-Fa-f0-9]\").IsMatch(c.ToString()));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27446564,
"author": "Steven Liekens",
"author_id": 1288449,
"author_profile": "https://Stackoverflow.com/users/1288449",
"pm_score": 2,
"selected": false,
"text": "<p>There's one more way to do it, using string comparison.</p>\n\n<pre><code>bool IsHex(char c)\n{\n return \"0123456789ABCDEFabcdef\".IndexOf(c) != -1;\n}\n</code></pre>\n"
},
{
"answer_id": 48183323,
"author": "juFo",
"author_id": 187650,
"author_profile": "https://Stackoverflow.com/users/187650",
"pm_score": 3,
"selected": false,
"text": "<p>Just use a .NET method:</p>\n\n<pre><code>char c = 'a';\nSystem.Uri.IsHexDigit(c);\n</code></pre>\n"
},
{
"answer_id": 72610222,
"author": "Stelio Kontos",
"author_id": 9412456,
"author_profile": "https://Stackoverflow.com/users/9412456",
"pm_score": 0,
"selected": false,
"text": "<p>As of .NET 6.0 / C# 10, the source code for <code>System.Uri.IsHexDigit(char)</code> is (unsurprisingly) still an exact equivalent to the accepted answer from over a decade ago. A nice reminder that simple solutions are often best.</p>\n<p>If, however, you really want to use your own extension method, a concise, modern, and readable version using pattern matching and expression body syntax such as the following would be functionally equivalent.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>// add this to a public static extensions class\npublic static bool IsHexDigit(this char c) => c is >= '0' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F';\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
Following on from [this question](https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values) what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:
```
bool CharIsHex(char c) {
c = Char.ToLower(c);
return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}
```
|
From [my answer](https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values#223854) to the question you linked to:
```
bool is_hex_char = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
```
|
228,532 |
<p>What's the difference between <code>Char.IsDigit()</code> and <code>Char.IsNumber()</code> in C#?</p>
|
[
{
"answer_id": 228538,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 6,
"selected": false,
"text": "<p>I found the answer:</p>\n\n<blockquote>\n <p>Char.IsNumber() determines if a Char\n is of any numeric Unicode category.\n This contrasts with IsDigit, which\n determines if a Char is a radix-10\n digit.</p>\n \n <p>Valid numbers are members of the\n following categories in\n <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.unicodecategory.aspx\" rel=\"noreferrer\" title=\"Decimal digit character, that is, a character in the range 0 through 9. Signified by the Unicode designation "Nd" (number, decimal digit). The value is 8.\">UnicodeCategory</a>:</p>\n \n <ol>\n <li><strong><code>DecimalDigitNumber</code></strong><br>\n Decimal digit character, that is, a character in the range 0 through 9. Signified by the Unicode designation \"Nd\" (number, decimal digit). The value is 8.</li>\n <li><strong><code>LetterNumber</code></strong><br>\n Number represented by a letter, instead of a decimal digit, for example, the Roman numeral for five, which is \"V\". The indicator is signified by the Unicode designation \"Nl\" (number, letter). The value is 9.</li>\n <li><strong><code>OtherNumber</code></strong><br>\n Number that is neither a decimal digit nor a letter number, for example, the fraction ½. The indicator is signified by the Unicode designation \"No\" (number, other). The value is 10.</li>\n </ol>\n</blockquote>\n\n<h2>Conclusion</h2>\n\n<ul>\n<li><strong><code>Char.IsDigit</code></strong>:<br>\nValid digits are members of the <code>DecimalDigitNumber</code> category only.</li>\n<li><strong><code>Char.IsNumber</code></strong>:<br>\nValid numbers are members of the <code>DecimalDigitNumber</code>, <code>LetterNumber</code>, or <code>OtherNumber</code> category.</li>\n</ul>\n"
},
{
"answer_id": 228565,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 8,
"selected": true,
"text": "<p><code>Char.IsDigit()</code> is a subset of <code>Char.IsNumber()</code>.</p>\n\n<p>Some of the characters that are 'numeric' but not digits include 0x00b2 and 0x00b3 which are superscripted 2 and 3 ('²' and '³') and the glyphs that are fractions such as '¼', '½', and '¾'.</p>\n\n<p>Note that there are quite a few characters that <code>IsDigit()</code> returns <code>true</code> for that are not in the ASCII range of 0x30 to 0x39, such as these Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'.</p>\n\n<p>This snippet of code tells you which code points differ:</p>\n\n<pre><code>static private void test()\n{\n for (int i = 0; i <= 0xffff; ++i)\n {\n char c = (char) i;\n\n if (Char.IsDigit( c) != Char.IsNumber( c)) {\n Console.WriteLine( \"Char value {0:x} IsDigit() = {1}, IsNumber() = {2}\", i, Char.IsDigit( c), Char.IsNumber( c));\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36056338,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 6,
"selected": false,
"text": "<p><code>IsNumber(x)</code> will sometimes return <code>true</code> for results average person would not consider to be a number and here is why. </p>\n\n<p>C# groups characters into <code>UnicodeCategory</code> where numbers fall not into a single but 3 different categories:</p>\n\n<ol>\n<li>UnicodeCategory.DecimalDigitNumber</li>\n</ol>\n\n<blockquote>\n <p>Decimal digit character, that is, a character in the range 0 through\n 9. Signified by the Unicode designation \"Nd\" (number, decimal digit). The value is 8.</p>\n</blockquote>\n\n<ol start=\"2\">\n<li>UnicodeCategory.OtherNumber</li>\n</ol>\n\n<blockquote>\n <p>Number that is neither a decimal digit nor a letter number, for\n example, the fraction 1/2. The indicator is signified by the Unicode\n designation \"No\" (number, other). The value is 10.</p>\n</blockquote>\n\n<ol start=\"3\">\n<li>UnicodeCategory.LetterNumber</li>\n</ol>\n\n<blockquote>\n <p>Number represented by a letter, instead of a decimal digit, for\n example, the Roman numeral for five, which is \"V\". The indicator is\n signified by the Unicode designation \"Nl\" (number, letter). The value\n is 9.</p>\n</blockquote>\n\n<p>Anything that falls in to one above will return <code>true</code> for <code>IsNumber()</code>. For is <code>IsDigit()</code> it will only be <code>UnicodeCategory.DecimalDigitNumber</code>.</p>\n\n<p><strong>I wrote this bit of code to indicate which is which:</strong> (Table isn't full due to allowed post size, but you should be able to generate it and it's only for example purposes anyway)</p>\n\n<pre><code> [Test]\n public void IsNumberTest()\n {\n var numberLikes = new[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherNumber, UnicodeCategory.LetterNumber };\n for (var i = 0; i < 0xffff; i++)\n {\n var c = Char.ConvertFromUtf32(i).ToCharArray()[0];\n if (numberLikes.Contains(Char.GetUnicodeCategory(c)))\n {\n File.AppendAllText(\"IsNumberLike.txt\", string.Format(\"{0},{1},{2},&#{3};,{4},{5}\\n\", i, c, Char.GetUnicodeCategory(c), i, Char.IsNumber(c), Char.IsDigit(c)));\n }\n }\n }\n</code></pre>\n\n<p>Result looks following: As you can see there is stuff that one would not expect to be 'number'.</p>\n\n<pre><code>+------+----+--------------------+----------+------+-------+\n| int |symbol| UnicodeCategory | Html |IsNumber|IsDigit|\n+-------+---+--------------------+----------+------+-------+\n| 48 | 0 | DecimalDigitNumber | &#48; | True | True |\n| 49 | 1 | DecimalDigitNumber | &#49; | True | True |\n| 50 | 2 | DecimalDigitNumber | &#50; | True | True |\n| 51 | 3 | DecimalDigitNumber | &#51; | True | True |\n| 52 | 4 | DecimalDigitNumber | &#52; | True | True |\n| 53 | 5 | DecimalDigitNumber | &#53; | True | True |\n| 54 | 6 | DecimalDigitNumber | &#54; | True | True |\n| 55 | 7 | DecimalDigitNumber | &#55; | True | True |\n| 56 | 8 | DecimalDigitNumber | &#56; | True | True |\n| 57 | 9 | DecimalDigitNumber | &#57; | True | True |\n| 178 | ² | OtherNumber | &#178; | True | False |\n| 179 | ³ | OtherNumber | &#179; | True | False |\n| 185 | ¹ | OtherNumber | &#185; | True | False |\n| 188 | ¼ | OtherNumber | &#188; | True | False |\n| 189 | ½ | OtherNumber | &#189; | True | False |\n| 190 | ¾ | OtherNumber | &#190; | True | False |\n| 1632 | ٠ | DecimalDigitNumber | &#1632; | True | True |\n| 1633 | ١ | DecimalDigitNumber | &#1633; | True | True |\n| 1634 | ٢ | DecimalDigitNumber | &#1634; | True | True |\n| 1635 | ٣ | DecimalDigitNumber | &#1635; | True | True |\n| 1636 | ٤ | DecimalDigitNumber | &#1636; | True | True |\n| 1637 | ٥ | DecimalDigitNumber | &#1637; | True | True |\n| 1638 | ٦ | DecimalDigitNumber | &#1638; | True | True |\n| 1639 | ٧ | DecimalDigitNumber | &#1639; | True | True |\n| 1640 | ٨ | DecimalDigitNumber | &#1640; | True | True |\n| 1641 | ٩ | DecimalDigitNumber | &#1641; | True | True |\n| 1776 | ۰ | DecimalDigitNumber | &#1776; | True | True |\n| 1777 | ۱ | DecimalDigitNumber | &#1777; | True | True |\n| 1778 | ۲ | DecimalDigitNumber | &#1778; | True | True |\n| 1779 | ۳ | DecimalDigitNumber | &#1779; | True | True |\n| 1780 | ۴ | DecimalDigitNumber | &#1780; | True | True |\n| 1781 | ۵ | DecimalDigitNumber | &#1781; | True | True |\n| 1782 | ۶ | DecimalDigitNumber | &#1782; | True | True |\n| 1783 | ۷ | DecimalDigitNumber | &#1783; | True | True |\n| 1784 | ۸ | DecimalDigitNumber | &#1784; | True | True |\n| 1785 | ۹ | DecimalDigitNumber | &#1785; | True | True |\n| 1984 | ߀ | DecimalDigitNumber | &#1984; | True | True |\n| 1985 | ߁ | DecimalDigitNumber | &#1985; | True | True |\n| 1986 | ߂ | DecimalDigitNumber | &#1986; | True | True |\n| 1987 | ߃ | DecimalDigitNumber | &#1987; | True | True |\n| 1988 | ߄ | DecimalDigitNumber | &#1988; | True | True |\n| 1989 | ߅ | DecimalDigitNumber | &#1989; | True | True |\n| 1990 | ߆ | DecimalDigitNumber | &#1990; | True | True |\n| 1991 | ߇ | DecimalDigitNumber | &#1991; | True | True |\n| 1992 | ߈ | DecimalDigitNumber | &#1992; | True | True |\n| 1993 | ߉ | DecimalDigitNumber | &#1993; | True | True |\n| 2406 | ० | DecimalDigitNumber | &#2406; | True | True |\n| 2407 | १ | DecimalDigitNumber | &#2407; | True | True |\n| 2408 | २ | DecimalDigitNumber | &#2408; | True | True |\n| 2409 | ३ | DecimalDigitNumber | &#2409; | True | True |\n| 2410 | ४ | DecimalDigitNumber | &#2410; | True | True |\n| 2411 | ५ | DecimalDigitNumber | &#2411; | True | True |\n| 2412 | ६ | DecimalDigitNumber | &#2412; | True | True |\n| 2413 | ७ | DecimalDigitNumber | &#2413; | True | True |\n| 2414 | ८ | DecimalDigitNumber | &#2414; | True | True |\n| 2415 | ९ | DecimalDigitNumber | &#2415; | True | True |\n| 2534 | ০ | DecimalDigitNumber | &#2534; | True | True |\n| 2535 | ১ | DecimalDigitNumber | &#2535; | True | True |\n| 2536 | ২ | DecimalDigitNumber | &#2536; | True | True |\n| 2537 | ৩ | DecimalDigitNumber | &#2537; | True | True |\n| 2538 | ৪ | DecimalDigitNumber | &#2538; | True | True |\n| 2539 | ৫ | DecimalDigitNumber | &#2539; | True | True |\n| 2540 | ৬ | DecimalDigitNumber | &#2540; | True | True |\n| 2541 | ৭ | DecimalDigitNumber | &#2541; | True | True |\n| 2542 | ৮ | DecimalDigitNumber | &#2542; | True | True |\n| 2543 | ৯ | DecimalDigitNumber | &#2543; | True | True |\n| 2548 | ৴ | OtherNumber | &#2548; | True | False |\n| 2549 | ৵ | OtherNumber | &#2549; | True | False |\n| 2550 | ৶ | OtherNumber | &#2550; | True | False |\n| 2551 | ৷ | OtherNumber | &#2551; | True | False |\n| 2552 | ৸ | OtherNumber | &#2552; | True | False |\n| 2553 | ৹ | OtherNumber | &#2553; | True | False |\n| 2662 | ੦ | DecimalDigitNumber | &#2662; | True | True |\n| 2663 | ੧ | DecimalDigitNumber | &#2663; | True | True |\n| 2664 | ੨ | DecimalDigitNumber | &#2664; | True | True |\n| 2665 | ੩ | DecimalDigitNumber | &#2665; | True | True |\n| 2666 | ੪ | DecimalDigitNumber | &#2666; | True | True |\n| 2667 | ੫ | DecimalDigitNumber | &#2667; | True | True |\n| 2668 | ੬ | DecimalDigitNumber | &#2668; | True | True |\n| 2669 | ੭ | DecimalDigitNumber | &#2669; | True | True |\n| 2670 | ੮ | DecimalDigitNumber | &#2670; | True | True |\n| 2671 | ੯ | DecimalDigitNumber | &#2671; | True | True |\n| 2790 | ૦ | DecimalDigitNumber | &#2790; | True | True |\n| 2791 | ૧ | DecimalDigitNumber | &#2791; | True | True |\n| 2792 | ૨ | DecimalDigitNumber | &#2792; | True | True |\n| 2793 | ૩ | DecimalDigitNumber | &#2793; | True | True |\n| 2794 | ૪ | DecimalDigitNumber | &#2794; | True | True |\n| 2795 | ૫ | DecimalDigitNumber | &#2795; | True | True |\n| 2796 | ૬ | DecimalDigitNumber | &#2796; | True | True |\n| 2797 | ૭ | DecimalDigitNumber | &#2797; | True | True |\n| 2798 | ૮ | DecimalDigitNumber | &#2798; | True | True |\n| 2799 | ૯ | DecimalDigitNumber | &#2799; | True | True |\n| 2918 | ୦ | DecimalDigitNumber | &#2918; | True | True |\n| 2919 | ୧ | DecimalDigitNumber | &#2919; | True | True |\n| 2920 | ୨ | DecimalDigitNumber | &#2920; | True | True |\n| 2921 | ୩ | DecimalDigitNumber | &#2921; | True | True |\n| 2922 | ୪ | DecimalDigitNumber | &#2922; | True | True |\n| 2923 | ୫ | DecimalDigitNumber | &#2923; | True | True |\n| 2924 | ୬ | DecimalDigitNumber | &#2924; | True | True |\n| 2925 | ୭ | DecimalDigitNumber | &#2925; | True | True |\n| 2926 | ୮ | DecimalDigitNumber | &#2926; | True | True |\n| 2927 | ୯ | DecimalDigitNumber | &#2927; | True | True |\n| 2930 | ୲ | OtherNumber | &#2930; | True | False |\n| 2931 | ୳ | OtherNumber | &#2931; | True | False |\n| 2932 | ୴ | OtherNumber | &#2932; | True | False |\n| 2933 | ୵ | OtherNumber | &#2933; | True | False |\n| 2934 | ୶ | OtherNumber | &#2934; | True | False |\n| 2935 | ୷ | OtherNumber | &#2935; | True | False |\n| 3046 | ௦ | DecimalDigitNumber | &#3046; | True | True |\n| 3047 | ௧ | DecimalDigitNumber | &#3047; | True | True |\n| 3048 | ௨ | DecimalDigitNumber | &#3048; | True | True |\n| 3049 | ௩ | DecimalDigitNumber | &#3049; | True | True |\n| 3050 | ௪ | DecimalDigitNumber | &#3050; | True | True |\n| 3051 | ௫ | DecimalDigitNumber | &#3051; | True | True |\n| 3052 | ௬ | DecimalDigitNumber | &#3052; | True | True |\n| 3053 | ௭ | DecimalDigitNumber | &#3053; | True | True |\n| 3054 | ௮ | DecimalDigitNumber | &#3054; | True | True |\n| 3055 | ௯ | DecimalDigitNumber | &#3055; | True | True |\n| 3056 | ௰ | OtherNumber | &#3056; | True | False |\n| 3057 | ௱ | OtherNumber | &#3057; | True | False |\n| 3058 | ௲ | OtherNumber | &#3058; | True | False |\n| 3174 | ౦ | DecimalDigitNumber | &#3174; | True | True |\n| 3175 | ౧ | DecimalDigitNumber | &#3175; | True | True |\n| 3176 | ౨ | DecimalDigitNumber | &#3176; | True | True |\n| 3177 | ౩ | DecimalDigitNumber | &#3177; | True | True |\n| 3178 | ౪ | DecimalDigitNumber | &#3178; | True | True |\n| 3179 | ౫ | DecimalDigitNumber | &#3179; | True | True |\n| 3180 | ౬ | DecimalDigitNumber | &#3180; | True | True |\n| 3181 | ౭ | DecimalDigitNumber | &#3181; | True | True |\n| 3182 | ౮ | DecimalDigitNumber | &#3182; | True | True |\n| 3183 | ౯ | DecimalDigitNumber | &#3183; | True | True |\n| 3192 | ౸ | OtherNumber | &#3192; | True | False |\n| 3193 | ౹ | OtherNumber | &#3193; | True | False |\n| 3194 | ౺ | OtherNumber | &#3194; | True | False |\n| 3195 | ౻ | OtherNumber | &#3195; | True | False |\n| 3196 | ౼ | OtherNumber | &#3196; | True | False |\n| 3197 | ౽ | OtherNumber | &#3197; | True | False |\n| 3198 | ౾ | OtherNumber | &#3198; | True | False |\n| 3302 | ೦ | DecimalDigitNumber | &#3302; | True | True |\n| 3303 | ೧ | DecimalDigitNumber | &#3303; | True | True |\n| 3304 | ೨ | DecimalDigitNumber | &#3304; | True | True |\n| 3305 | ೩ | DecimalDigitNumber | &#3305; | True | True |\n| 3306 | ೪ | DecimalDigitNumber | &#3306; | True | True |\n| 3307 | ೫ | DecimalDigitNumber | &#3307; | True | True |\n| 3308 | ೬ | DecimalDigitNumber | &#3308; | True | True |\n| 3309 | ೭ | DecimalDigitNumber | &#3309; | True | True |\n| 3310 | ೮ | DecimalDigitNumber | &#3310; | True | True |\n| 3311 | ೯ | DecimalDigitNumber | &#3311; | True | True |\n| 3430 | ൦ | DecimalDigitNumber | &#3430; | True | True |\n| 3431 | ൧ | DecimalDigitNumber | &#3431; | True | True |\n| 3432 | ൨ | DecimalDigitNumber | &#3432; | True | True |\n| 3433 | ൩ | DecimalDigitNumber | &#3433; | True | True |\n| 3434 | ൪ | DecimalDigitNumber | &#3434; | True | True |\n| 3435 | ൫ | DecimalDigitNumber | &#3435; | True | True |\n| 3436 | ൬ | DecimalDigitNumber | &#3436; | True | True |\n| 3437 | ൭ | DecimalDigitNumber | &#3437; | True | True |\n| 3438 | ൮ | DecimalDigitNumber | &#3438; | True | True |\n| 3439 | ൯ | DecimalDigitNumber | &#3439; | True | True |\n| 3440 | ൰ | OtherNumber | &#3440; | True | False |\n| 3441 | ൱ | OtherNumber | &#3441; | True | False |\n| 3442 | ൲ | OtherNumber | &#3442; | True | False |\n| 3443 | ൳ | OtherNumber | &#3443; | True | False |\n| 3444 | ൴ | OtherNumber | &#3444; | True | False |\n| 3445 | ൵ | OtherNumber | &#3445; | True | False |\n| 3664 | ๐ | DecimalDigitNumber | &#3664; | True | True |\n| 3665 | ๑ | DecimalDigitNumber | &#3665; | True | True |\n| 3666 | ๒ | DecimalDigitNumber | &#3666; | True | True |\n| 3667 | ๓ | DecimalDigitNumber | &#3667; | True | True |\n| 3668 | ๔ | DecimalDigitNumber | &#3668; | True | True |\n| 3669 | ๕ | DecimalDigitNumber | &#3669; | True | True |\n| 3670 | ๖ | DecimalDigitNumber | &#3670; | True | True |\n| 3671 | ๗ | DecimalDigitNumber | &#3671; | True | True |\n| 3672 | ๘ | DecimalDigitNumber | &#3672; | True | True |\n| 3673 | ๙ | DecimalDigitNumber | &#3673; | True | True |\n| 3792 | ໐ | DecimalDigitNumber | &#3792; | True | True |\n| 3793 | ໑ | DecimalDigitNumber | &#3793; | True | True |\n| 3794 | ໒ | DecimalDigitNumber | &#3794; | True | True |\n| 3795 | ໓ | DecimalDigitNumber | &#3795; | True | True |\n| 3796 | ໔ | DecimalDigitNumber | &#3796; | True | True |\n| 3797 | ໕ | DecimalDigitNumber | &#3797; | True | True |\n| 3798 | ໖ | DecimalDigitNumber | &#3798; | True | True |\n| 3799 | ໗ | DecimalDigitNumber | &#3799; | True | True |\n| 3800 | ໘ | DecimalDigitNumber | &#3800; | True | True |\n| 3801 | ໙ | DecimalDigitNumber | &#3801; | True | True |\n| 3872 | ༠ | DecimalDigitNumber | &#3872; | True | True |\n| 3873 | ༡ | DecimalDigitNumber | &#3873; | True | True |\n| 3874 | ༢ | DecimalDigitNumber | &#3874; | True | True |\n| 3875 | ༣ | DecimalDigitNumber | &#3875; | True | True |\n| 3876 | ༤ | DecimalDigitNumber | &#3876; | True | True |\n| 3877 | ༥ | DecimalDigitNumber | &#3877; | True | True |\n| 3878 | ༦ | DecimalDigitNumber | &#3878; | True | True |\n| 3879 | ༧ | DecimalDigitNumber | &#3879; | True | True |\n| 3880 | ༨ | DecimalDigitNumber | &#3880; | True | True |\n| 3881 | ༩ | DecimalDigitNumber | &#3881; | True | True |\n| 3882 | ༪ | OtherNumber | &#3882; | True | False |\n| 3883 | ༫ | OtherNumber | &#3883; | True | False |\n| 3884 | ༬ | OtherNumber | &#3884; | True | False |\n| 3885 | ༭ | OtherNumber | &#3885; | True | False |\n| 3886 | ༮ | OtherNumber | &#3886; | True | False |\n| 3887 | ༯ | OtherNumber | &#3887; | True | False |\n| 3888 | ༰ | OtherNumber | &#3888; | True | False |\n| 3889 | ༱ | OtherNumber | &#3889; | True | False |\n| 3890 | ༲ | OtherNumber | &#3890; | True | False |\n| 3891 | ༳ | OtherNumber | &#3891; | True | False |\n| 4160 | ၀ | DecimalDigitNumber | &#4160; | True | True |\n| 4161 | ၁ | DecimalDigitNumber | &#4161; | True | True |\n| 4162 | ၂ | DecimalDigitNumber | &#4162; | True | True |\n| 4163 | ၃ | DecimalDigitNumber | &#4163; | True | True |\n| 4164 | ၄ | DecimalDigitNumber | &#4164; | True | True |\n| 4165 | ၅ | DecimalDigitNumber | &#4165; | True | True |\n| 4166 | ၆ | DecimalDigitNumber | &#4166; | True | True |\n| 4167 | ၇ | DecimalDigitNumber | &#4167; | True | True |\n| 4168 | ၈ | DecimalDigitNumber | &#4168; | True | True |\n| 4169 | ၉ | DecimalDigitNumber | &#4169; | True | True |\n| 4240 | ႐ | DecimalDigitNumber | &#4240; | True | True |\n| 4241 | ႑ | DecimalDigitNumber | &#4241; | True | True |\n| 4242 | ႒ | DecimalDigitNumber | &#4242; | True | True |\n| 4243 | ႓ | DecimalDigitNumber | &#4243; | True | True |\n| 4244 | ႔ | DecimalDigitNumber | &#4244; | True | True |\n| 4245 | ႕ | DecimalDigitNumber | &#4245; | True | True |\n| 4246 | ႖ | DecimalDigitNumber | &#4246; | True | True |\n| 4247 | ႗ | DecimalDigitNumber | &#4247; | True | True |\n| 4248 | ႘ | DecimalDigitNumber | &#4248; | True | True |\n| 4249 | ႙ | DecimalDigitNumber | &#4249; | True | True |\n| 4969 | ፩ | OtherNumber | &#4969; | True | False |\n| 4970 | ፪ | OtherNumber | &#4970; | True | False |\n| 4971 | ፫ | OtherNumber | &#4971; | True | False |\n| 4972 | ፬ | OtherNumber | &#4972; | True | False |\n| 4973 | ፭ | OtherNumber | &#4973; | True | False |\n| 4974 | ፮ | OtherNumber | &#4974; | True | False |\n| 4975 | ፯ | OtherNumber | &#4975; | True | False |\n| 4976 | ፰ | OtherNumber | &#4976; | True | False |\n| 4977 | ፱ | OtherNumber | &#4977; | True | False |\n| 4978 | ፲ | OtherNumber | &#4978; | True | False |\n| 4979 | ፳ | OtherNumber | &#4979; | True | False |\n| 4980 | ፴ | OtherNumber | &#4980; | True | False |\n| 4981 | ፵ | OtherNumber | &#4981; | True | False |\n| 4982 | ፶ | OtherNumber | &#4982; | True | False |\n| 4983 | ፷ | OtherNumber | &#4983; | True | False |\n| 4984 | ፸ | OtherNumber | &#4984; | True | False |\n| 4985 | ፹ | OtherNumber | &#4985; | True | False |\n| 4986 | ፺ | OtherNumber | &#4986; | True | False |\n| 4987 | ፻ | OtherNumber | &#4987; | True | False |\n| 4988 | ፼ | OtherNumber | &#4988; | True | False |\n| 5870 | ᛮ | LetterNumber | &#5870; | True | False |\n| 5871 | ᛯ | LetterNumber | &#5871; | True | False |\n| 5872 | ᛰ | LetterNumber | &#5872; | True | False |\n| 6112 | ០ | DecimalDigitNumber | &#6112; | True | True |\n| 6113 | ១ | DecimalDigitNumber | &#6113; | True | True |\n| 6114 | ២ | DecimalDigitNumber | &#6114; | True | True |\n| 6115 | ៣ | DecimalDigitNumber | &#6115; | True | True |\n| 6116 | ៤ | DecimalDigitNumber | &#6116; | True | True |\n| 6117 | ៥ | DecimalDigitNumber | &#6117; | True | True |\n| 6118 | ៦ | DecimalDigitNumber | &#6118; | True | True |\n| 6119 | ៧ | DecimalDigitNumber | &#6119; | True | True |\n| 6120 | ៨ | DecimalDigitNumber | &#6120; | True | True |\n| 6121 | ៩ | DecimalDigitNumber | &#6121; | True | True |\n| 6128 | ៰ | OtherNumber | &#6128; | True | False |\n| 6129 | ៱ | OtherNumber | &#6129; | True | False |\n| 6130 | ៲ | OtherNumber | &#6130; | True | False |\n| 6131 | ៳ | OtherNumber | &#6131; | True | False |\n| 6132 | ៴ | OtherNumber | &#6132; | True | False |\n| 6133 | ៵ | OtherNumber | &#6133; | True | False |\n| 6134 | ៶ | OtherNumber | &#6134; | True | False |\n| 6135 | ៷ | OtherNumber | &#6135; | True | False |\n| 6136 | ៸ | OtherNumber | &#6136; | True | False |\n| 6137 | ៹ | OtherNumber | &#6137; | True | False |\n| 6160 | ᠐ | DecimalDigitNumber | &#6160; | True | True |\n| 6161 | ᠑ | DecimalDigitNumber | &#6161; | True | True |\n| 6162 | ᠒ | DecimalDigitNumber | &#6162; | True | True |\n| 6163 | ᠓ | DecimalDigitNumber | &#6163; | True | True |\n| 6164 | ᠔ | DecimalDigitNumber | &#6164; | True | True |\n| 6165 | ᠕ | DecimalDigitNumber | &#6165; | True | True |\n| 6166 | ᠖ | DecimalDigitNumber | &#6166; | True | True |\n| 6167 | ᠗ | DecimalDigitNumber | &#6167; | True | True |\n| 6168 | ᠘ | DecimalDigitNumber | &#6168; | True | True |\n| 6169 | ᠙ | DecimalDigitNumber | &#6169; | True | True |\n| 6470 | ᥆ | DecimalDigitNumber | &#6470; | True | True |\n| 6471 | ᥇ | DecimalDigitNumber | &#6471; | True | True |\n| 6472 | ᥈ | DecimalDigitNumber | &#6472; | True | True |\n| 6473 | ᥉ | DecimalDigitNumber | &#6473; | True | True |\n| 6474 | ᥊ | DecimalDigitNumber | &#6474; | True | True |\n| 6475 | ᥋ | DecimalDigitNumber | &#6475; | True | True |\n| 6476 | ᥌ | DecimalDigitNumber | &#6476; | True | True |\n| 6477 | ᥍ | DecimalDigitNumber | &#6477; | True | True |\n| 6478 | ᥎ | DecimalDigitNumber | &#6478; | True | True |\n| 6479 | ᥏ | DecimalDigitNumber | &#6479; | True | True |\n| 6608 | ᧐ | DecimalDigitNumber | &#6608; | True | True |\n| 6609 | ᧑ | DecimalDigitNumber | &#6609; | True | True |\n| 6610 | ᧒ | DecimalDigitNumber | &#6610; | True | True |\n| 6611 | ᧓ | DecimalDigitNumber | &#6611; | True | True |\n| 6612 | ᧔ | DecimalDigitNumber | &#6612; | True | True |\n| 6613 | ᧕ | DecimalDigitNumber | &#6613; | True | True |\n| 6614 | ᧖ | DecimalDigitNumber | &#6614; | True | True |\n| 6615 | ᧗ | DecimalDigitNumber | &#6615; | True | True |\n| 6616 | ᧘ | DecimalDigitNumber | &#6616; | True | True |\n| 6617 | ᧙ | DecimalDigitNumber | &#6617; | True | True |\n| 6618 | ᧚ | OtherNumber | &#6618; | True | False |\n| 6784 | ᪀ | DecimalDigitNumber | &#6784; | True | True |\n| 6785 | ᪁ | DecimalDigitNumber | &#6785; | True | True |\n| 6786 | ᪂ | DecimalDigitNumber | &#6786; | True | True |\n| 6787 | ᪃ | DecimalDigitNumber | &#6787; | True | True |\n| 6788 | ᪄ | DecimalDigitNumber | &#6788; | True | True |\n| 6789 | ᪅ | DecimalDigitNumber | &#6789; | True | True |\n| 6790 | ᪆ | DecimalDigitNumber | &#6790; | True | True |\n| 6791 | ᪇ | DecimalDigitNumber | &#6791; | True | True |\n| 6792 | ᪈ | DecimalDigitNumber | &#6792; | True | True |\n| 6793 | ᪉ | DecimalDigitNumber | &#6793; | True | True |\n| 6800 | ᪐ | DecimalDigitNumber | &#6800; | True | True |\n| 6801 | ᪑ | DecimalDigitNumber | &#6801; | True | True |\n| 6802 | ᪒ | DecimalDigitNumber | &#6802; | True | True |\n| 6803 | ᪓ | DecimalDigitNumber | &#6803; | True | True |\n| 6804 | ᪔ | DecimalDigitNumber | &#6804; | True | True |\n| 6805 | ᪕ | DecimalDigitNumber | &#6805; | True | True |\n| 6806 | ᪖ | DecimalDigitNumber | &#6806; | True | True |\n| 6807 | ᪗ | DecimalDigitNumber | &#6807; | True | True |\n| 6808 | ᪘ | DecimalDigitNumber | &#6808; | True | True |\n| 6809 | ᪙ | DecimalDigitNumber | &#6809; | True | True |\n| 6992 | ᭐ | DecimalDigitNumber | &#6992; | True | True |\n| 6993 | ᭑ | DecimalDigitNumber | &#6993; | True | True |\n| 6994 | ᭒ | DecimalDigitNumber | &#6994; | True | True |\n| 6995 | ᭓ | DecimalDigitNumber | &#6995; | True | True |\n| 6996 | ᭔ | DecimalDigitNumber | &#6996; | True | True |\n| 6997 | ᭕ | DecimalDigitNumber | &#6997; | True | True |\n| 6998 | ᭖ | DecimalDigitNumber | &#6998; | True | True |\n| 6999 | ᭗ | DecimalDigitNumber | &#6999; | True | True |\n| 7000 | ᭘ | DecimalDigitNumber | &#7000; | True | True |\n| 7001 | ᭙ | DecimalDigitNumber | &#7001; | True | True |\n| 7088 | ᮰ | DecimalDigitNumber | &#7088; | True | True |\n| 7089 | ᮱ | DecimalDigitNumber | &#7089; | True | True |\n| 7090 | ᮲ | DecimalDigitNumber | &#7090; | True | True |\n| 7091 | ᮳ | DecimalDigitNumber | &#7091; | True | True |\n| 7092 | ᮴ | DecimalDigitNumber | &#7092; | True | True |\n| 7093 | ᮵ | DecimalDigitNumber | &#7093; | True | True |\n| 7094 | ᮶ | DecimalDigitNumber | &#7094; | True | True |\n| 7095 | ᮷ | DecimalDigitNumber | &#7095; | True | True |\n| 7096 | ᮸ | DecimalDigitNumber | &#7096; | True | True |\n| 7097 | ᮹ | DecimalDigitNumber | &#7097; | True | True |\n| 7232 | ᱀ | DecimalDigitNumber | &#7232; | True | True |\n| 7233 | ᱁ | DecimalDigitNumber | &#7233; | True | True |\n| 7234 | ᱂ | DecimalDigitNumber | &#7234; | True | True |\n| 7235 | ᱃ | DecimalDigitNumber | &#7235; | True | True |\n| 7236 | ᱄ | DecimalDigitNumber | &#7236; | True | True |\n| 7237 | ᱅ | DecimalDigitNumber | &#7237; | True | True |\n| 7238 | ᱆ | DecimalDigitNumber | &#7238; | True | True |\n| 7239 | ᱇ | DecimalDigitNumber | &#7239; | True | True |\n| 8304 | ⁰ | OtherNumber | &#8304; | True | False |\n| 8308 | ⁴ | OtherNumber | &#8308; | True | False |\n| 8309 | ⁵ | OtherNumber | &#8309; | True | False |\n| 8310 | ⁶ | OtherNumber | &#8310; | True | False |\n| 8311 | ⁷ | OtherNumber | &#8311; | True | False |\n| 8312 | ⁸ | OtherNumber | &#8312; | True | False |\n| 8313 | ⁹ | OtherNumber | &#8313; | True | False |\n| 8320 | ₀ | OtherNumber | &#8320; | True | False |\n| 8321 | ₁ | OtherNumber | &#8321; | True | False |\n| 8322 | ₂ | OtherNumber | &#8322; | True | False |\n| 8323 | ₃ | OtherNumber | &#8323; | True | False |\n| 8324 | ₄ | OtherNumber | &#8324; | True | False |\n| 8325 | ₅ | OtherNumber | &#8325; | True | False |\n| 8326 | ₆ | OtherNumber | &#8326; | True | False |\n| 8327 | ₇ | OtherNumber | &#8327; | True | False |\n| 8328 | ₈ | OtherNumber | &#8328; | True | False |\n| 8329 | ₉ | OtherNumber | &#8329; | True | False |\n| 8528 | ⅐ | OtherNumber | &#8528; | True | False |\n| 8529 | ⅑ | OtherNumber | &#8529; | True | False |\n| 8530 | ⅒ | OtherNumber | &#8530; | True | False |\n| 8531 | ⅓ | OtherNumber | &#8531; | True | False |\n| 8532 | ⅔ | OtherNumber | &#8532; | True | False |\n| 8533 | ⅕ | OtherNumber | &#8533; | True | False |\n| 8534 | ⅖ | OtherNumber | &#8534; | True | False |\n| 8535 | ⅗ | OtherNumber | &#8535; | True | False |\n| 8536 | ⅘ | OtherNumber | &#8536; | True | False |\n| 8537 | ⅙ | OtherNumber | &#8537; | True | False |\n| 8538 | ⅚ | OtherNumber | &#8538; | True | False |\n| 8539 | ⅛ | OtherNumber | &#8539; | True | False |\n| 8540 | ⅜ | OtherNumber | &#8540; | True | False |\n| 8541 | ⅝ | OtherNumber | &#8541; | True | False |\n| 8542 | ⅞ | OtherNumber | &#8542; | True | False |\n| 8543 | ⅟ | OtherNumber | &#8543; | True | False |\n| 8544 | Ⅰ | LetterNumber | &#8544; | True | False |\n| 8545 | Ⅱ | LetterNumber | &#8545; | True | False |\n| 8546 | Ⅲ | LetterNumber | &#8546; | True | False |\n| 8547 | Ⅳ | LetterNumber | &#8547; | True | False |\n| 8548 | Ⅴ | LetterNumber | &#8548; | True | False |\n| 8549 | Ⅵ | LetterNumber | &#8549; | True | False |\n| 8550 | Ⅶ | LetterNumber | &#8550; | True | False |\n| 8551 | Ⅷ | LetterNumber | &#8551; | True | False |\n| 8552 | Ⅸ | LetterNumber | &#8552; | True | False |\n| 8553 | Ⅹ | LetterNumber | &#8553; | True | False |\n| 8554 | Ⅺ | LetterNumber | &#8554; | True | False |\n| 8555 | Ⅻ | LetterNumber | &#8555; | True | False |\n| 8556 | Ⅼ | LetterNumber | &#8556; | True | False |\n| 8557 | Ⅽ | LetterNumber | &#8557; | True | False |\n| 8558 | Ⅾ | LetterNumber | &#8558; | True | False |\n| 8559 | Ⅿ | LetterNumber | &#8559; | True | False |\n| 8560 | ⅰ | LetterNumber | &#8560; | True | False |\n| 8561 | ⅱ | LetterNumber | &#8561; | True | False |\n| 8562 | ⅲ | LetterNumber | &#8562; | True | False |\n| 8563 | ⅳ | LetterNumber | &#8563; | True | False |\n| 8564 | ⅴ | LetterNumber | &#8564; | True | False |\n| 8565 | ⅵ | LetterNumber | &#8565; | True | False |\n| 8566 | ⅶ | LetterNumber | &#8566; | True | False |\n| 8567 | ⅷ | LetterNumber | &#8567; | True | False |\n| 8568 | ⅸ | LetterNumber | &#8568; | True | False |\n| 8569 | ⅹ | LetterNumber | &#8569; | True | False |\n| 8570 | ⅺ | LetterNumber | &#8570; | True | False |\n| 8571 | ⅻ | LetterNumber | &#8571; | True | False |\n| 8572 | ⅼ | LetterNumber | &#8572; | True | False |\n| 8573 | ⅽ | LetterNumber | &#8573; | True | False |\n| 8574 | ⅾ | LetterNumber | &#8574; | True | False |\n| 8575 | ⅿ | LetterNumber | &#8575; | True | False |\n| 8576 | ↀ | LetterNumber | &#8576; | True | False |\n| 8577 | ↁ | LetterNumber | &#8577; | True | False |\n| 8578 | ↂ | LetterNumber | &#8578; | True | False |\n| 8581 | ↅ | LetterNumber | &#8581; | True | False |\n+-------+---+--------------------+----------+------+-------+\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
What's the difference between `Char.IsDigit()` and `Char.IsNumber()` in C#?
|
`Char.IsDigit()` is a subset of `Char.IsNumber()`.
Some of the characters that are 'numeric' but not digits include 0x00b2 and 0x00b3 which are superscripted 2 and 3 ('²' and '³') and the glyphs that are fractions such as '¼', '½', and '¾'.
Note that there are quite a few characters that `IsDigit()` returns `true` for that are not in the ASCII range of 0x30 to 0x39, such as these Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'.
This snippet of code tells you which code points differ:
```
static private void test()
{
for (int i = 0; i <= 0xffff; ++i)
{
char c = (char) i;
if (Char.IsDigit( c) != Char.IsNumber( c)) {
Console.WriteLine( "Char value {0:x} IsDigit() = {1}, IsNumber() = {2}", i, Char.IsDigit( c), Char.IsNumber( c));
}
}
}
```
|
228,544 |
<p>If I want to check for the null string I would do</p>
<pre><code>[ -z $mystr ]
</code></pre>
<p>but what if I want to check whether the variable has been defined at all? Or is there no distinction in Bash scripting?</p>
|
[
{
"answer_id": 228552,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": false,
"text": "<pre><code>~> if [ -z $FOO ]; then echo \"EMPTY\"; fi\nEMPTY\n~> FOO=\"\"\n~> if [ -z $FOO ]; then echo \"EMPTY\"; fi\nEMPTY\n~> FOO=\"a\"\n~> if [ -z $FOO ]; then echo \"EMPTY\"; fi\n~> \n</code></pre>\n\n<p>-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed <a href=\"http://wooledge.org:8000/BashFAQ/083\" rel=\"noreferrer\">here</a> or, with clearer explanations, <a href=\"http://bash-hackers.org/wiki/doku.php/syntax/pe#use_a_default_value\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.</p>\n\n<p>Alternate word:</p>\n\n<pre><code>~$ unset FOO\n~$ if test ${FOO+defined}; then echo \"DEFINED\"; fi\n~$ FOO=\"\"\n~$ if test ${FOO+defined}; then echo \"DEFINED\"; fi\nDEFINED\n</code></pre>\n\n<p>Default value:</p>\n\n<pre><code>~$ FOO=\"\"\n~$ if test \"${FOO-default value}\" ; then echo \"UNDEFINED\"; fi\n~$ unset FOO\n~$ if test \"${FOO-default value}\" ; then echo \"UNDEFINED\"; fi\nUNDEFINED\n</code></pre>\n\n<p>Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.</p>\n"
},
{
"answer_id": 228561,
"author": "Aditya Mukherji",
"author_id": 25990,
"author_profile": "https://Stackoverflow.com/users/25990",
"pm_score": -1,
"selected": false,
"text": "<p>Call <em><a href=\"https://ss64.com/bash/set.html\" rel=\"nofollow noreferrer\">set</a></em> without any arguments... it outputs all the defined variables.</p>\n<p>The last ones on the list would be the ones defined in your script.</p>\n<p>So you could pipe its output to something that could figure out what things are defined and what’s not.</p>\n"
},
{
"answer_id": 230593,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 8,
"selected": true,
"text": "<p>I think the answer you are after is implied (if not stated) by <a href=\"https://stackoverflow.com/users/5190/vinko-vrsalovic\">Vinko</a>'s <a href=\"https://stackoverflow.com/a/228552/15168\">answer</a>, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:</p>\n<pre><code>if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi\nif [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi\n</code></pre>\n<p>You probably can combine the two tests on the second line into one with:</p>\n<pre><code>if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi\n</code></pre>\n<p>However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '<code>-a</code>' and do recommend using separate simple tests combined with <code>&&</code>. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).</p>\n<p>You can find the details of these, and other related <a href=\"https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion\" rel=\"nofollow noreferrer\">shell parameter expansions</a>, the <a href=\"https://www.gnu.org/software/bash/manual/bash.html#index-_005b\" rel=\"nofollow noreferrer\"><code>test</code> or <code>[</code></a> command and <a href=\"https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions\" rel=\"nofollow noreferrer\">conditional expressions</a> in the Bash manual.</p>\n<hr>\n<p>I was recently asked by email about this answer with the question:</p>\n<blockquote>\n<p>You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion</p>\n<pre><code>if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi\n</code></pre>\n<p>Wouldn't this accomplish the same?</p>\n<pre><code>if [ -z "${VAR}" ]; then echo "VAR is not set at all"; fi\n</code></pre>\n</blockquote>\n<p>Fair question - the answer is 'No, your simpler alternative does not do the same thing'.</p>\n<p>Suppose I write this before your test:</p>\n<pre><code>VAR=\n</code></pre>\n<p>Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:</p>\n<pre><code>(\nunset VAR\nif [ -z "${VAR+xxx}" ]; then echo "JL:1 VAR is not set at all"; fi\nif [ -z "${VAR}" ]; then echo "MP:1 VAR is not set at all"; fi\nVAR=\nif [ -z "${VAR+xxx}" ]; then echo "JL:2 VAR is not set at all"; fi\nif [ -z "${VAR}" ]; then echo "MP:2 VAR is not set at all"; fi\n)\n</code></pre>\n<p>The output is:</p>\n<pre>\nJL:1 VAR is not set at all\nMP:1 VAR is not set at all\nMP:2 VAR is not set at all\n</pre>\n<p>In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the <code>${VAR=value}</code> and <code>${VAR:=value}</code> notations make. Ditto for <code>${VAR-value}</code> and <code>${VAR:-value}</code>, and <code>${VAR+value}</code> and <code>${VAR:+value}</code>, and so on.</p>\n<hr>\n<p>As <a href=\"https://stackoverflow.com/users/14731/gili\">Gili</a> points out in his <a href=\"https://stackoverflow.com/a/20003892\">answer</a>, if you run <code>bash</code> with the <code>set -o nounset</code> option, then the basic answer above fails with <code>unbound variable</code>. It is easily remedied:</p>\n<pre><code>if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi\nif [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi\n</code></pre>\n<p>Or you could cancel the <code>set -o nounset</code> option with <code>set +u</code> (<code>set -u</code> being equivalent to <code>set -o nounset</code>).</p>\n"
},
{
"answer_id": 7617214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Advanced Bash scripting guide, 10.2. Parameter Substitution:</p>\n<ul>\n<li>${var+blahblah}: if var is defined, 'blahblah' is substituted for the\nexpression, else null is substituted</li>\n<li>${var-blahblah}: if var is defined, it is itself substituted, else\n'blahblah' is substituted</li>\n<li>${var?blahblah}: if var is defined, it is substituted, else the\nfunction exists with 'blahblah' as an error message.</li>\n</ul>\n<br/>\n<p>To base your program logic on whether the variable $mystr is defined or not, you can do the following:</p>\n<pre><code>isdefined=0\n${mystr+ export isdefined=1}\n</code></pre>\n<p>Now, if isdefined=0 then the variable was undefined, and if isdefined=1 the variable was defined.</p>\n<p>This way of checking variables is better than the previous answers, because it is more elegant, readable, and if your Bash shell was configured to error on the use of undefined variables <code>(set -u)</code>, the script will terminate prematurely.</p>\n<p>Other useful stuff:</p>\n<p>To have a default value of 7 assigned to $mystr if it was undefined, and leave it intact otherwise:</p>\n<pre><code>mystr=${mystr- 7}\n</code></pre>\n<p>To print an error message and exit the function if the variable is undefined:</p>\n<pre><code>: ${mystr? not defined}\n</code></pre>\n<p>Beware here that I used ':' so as not to have the contents of $mystr executed as a command in case it is defined.</p>\n"
},
{
"answer_id": 7617451,
"author": "Swiss",
"author_id": 84955,
"author_profile": "https://Stackoverflow.com/users/84955",
"pm_score": 0,
"selected": false,
"text": "<p>Here is what I think is a much clearer way to check if a variable is defined:</p>\n\n<pre><code>var_defined() {\n local var_name=$1\n set | grep \"^${var_name}=\" 1>/dev/null\n return $?\n}\n</code></pre>\n\n<p>Use it as follows:</p>\n\n<pre><code>if var_defined foo; then\n echo \"foo is defined\"\nelse\n echo \"foo is not defined\"\nfi\n</code></pre>\n"
},
{
"answer_id": 9898583,
"author": "Aaron Davies",
"author_id": 428843,
"author_profile": "https://Stackoverflow.com/users/428843",
"pm_score": 1,
"selected": false,
"text": "<p>Another option: the <a href=\"http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html\" rel=\"nofollow noreferrer\">"list array indices" expansion</a>:</p>\n<pre><code>$ unset foo\n$ foo=\n$ echo ${!foo[*]}\n0\n\n$ foo=bar\n$ echo ${!foo[*]}\n0\n\n$ foo=(bar baz)\n$ echo ${!foo[*]}\n0 1\n</code></pre>\n<p>The only time this expands to the empty string is when <code>foo</code> is unset, so you can check it with the string conditional:</p>\n<pre><code>$ unset foo\n$ [[ ${!foo[*]} ]]; echo $?\n1\n\n$ foo=\n$ [[ ${!foo[*]} ]]; echo $?\n0\n\n$ foo=bar\n$ [[ ${!foo[*]} ]]; echo $?\n0\n\n$ foo=(bar baz)\n$ [[ ${!foo[*]} ]]; echo $?\n0\n</code></pre>\n<p>should be available in any Bash version 3.0 or greater.</p>\n"
},
{
"answer_id": 10965292,
"author": "k107",
"author_id": 594496,
"author_profile": "https://Stackoverflow.com/users/594496",
"pm_score": 4,
"selected": false,
"text": "<p>A summary of tests.</p>\n\n<pre><code>[ -n \"$var\" ] && echo \"var is set and not empty\"\n[ -z \"$var\" ] && echo \"var is unset or empty\"\n[ \"${var+x}\" = \"x\" ] && echo \"var is set\" # may or may not be empty\n[ -n \"${var+x}\" ] && echo \"var is set\" # may or may not be empty\n[ -z \"${var+x}\" ] && echo \"var is unset\"\n[ -z \"${var-x}\" ] && echo \"var is set and empty\"\n</code></pre>\n"
},
{
"answer_id": 11593841,
"author": "Sacrilicious",
"author_id": 743638,
"author_profile": "https://Stackoverflow.com/users/743638",
"pm_score": 1,
"selected": false,
"text": "<p>Not to <a href=\"https://en.wikipedia.org/wiki/Law_of_triviality\" rel=\"nofollow noreferrer\">shed this bike</a> even further, but wanted to add</p>\n<pre class=\"lang-none prettyprint-override\"><code>shopt -s -o nounset\n</code></pre>\n<p>is something you could add to the top of a script, which will error if variables aren't <em>declared</em> anywhere in the script.</p>\n<p>The message you'd see is <em>unbound variable</em>, but as others mention, it won't catch an empty string or null value.</p>\n<p>To make sure any individual value isn't empty, we can test a variable as it's expanded with <code>${mystr:?}</code>, also known as dollar sign expansion, which would error with <code>parameter null or not set</code>.</p>\n"
},
{
"answer_id": 16946889,
"author": "Felix Leipold",
"author_id": 500571,
"author_profile": "https://Stackoverflow.com/users/500571",
"pm_score": 3,
"selected": false,
"text": "<p>The explicit way to check for a variable being defined would be:</p>\n\n<pre><code>[ -v mystr ]\n</code></pre>\n"
},
{
"answer_id": 20003892,
"author": "Gili",
"author_id": 14731,
"author_profile": "https://Stackoverflow.com/users/14731",
"pm_score": 3,
"selected": false,
"text": "<p><em><a href=\"https://stackoverflow.com/questions/7832080/test-if-a-variable-is-set-in-bash-when-using-set-o-nounset/9824943#9824943\">Test if a variable is set in bash when using "set -o nounset"</a></em> contains a better answer (one that is more readable and works with <code>set -o nounset</code> enabled). It works roughly like this:</p>\n<pre><code>if [ -n "${VAR-}" ]; then\n echo "VAR is set and is not empty"\nelif [ "${VAR+DEFINED_BUT_EMPTY}" = "DEFINED_BUT_EMPTY" ]; then\n echo "VAR is set, but empty"\nelse\n echo "VAR is not set"\nfi\n</code></pre>\n"
},
{
"answer_id": 34028846,
"author": "funroll",
"author_id": 878969,
"author_profile": "https://Stackoverflow.com/users/878969",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://www.gnu.org/software/bash/manual/bash.html\" rel=\"nofollow noreferrer\" title=\"Bash Reference Manual on gnu.org\">Bash Reference Manual</a> is an authoritative source of information about Bash.</p>\n<p>Here's an example of testing a variable to see if it exists:</p>\n<pre><code>if [ -z "$PS1" ]; then\n echo This shell is not interactive\nelse\n echo This shell is interactive\nfi\n</code></pre>\n<p>(From <a href=\"https://www.gnu.org/software/bash/manual/bash.html#Is-this-Shell-Interactive_003f\" rel=\"nofollow noreferrer\" title=\"Link to the specific section in the manual\">section 6.3.2</a>.)</p>\n<p>Note that the whitespace after the open <code>[</code> and before the <code>]</code> is <em>not optional</em>.</p>\n<hr />\n<p><strong>Tips for <a href=\"https://en.wikipedia.org/wiki/Vim_%28text_editor%29\" rel=\"nofollow noreferrer\">Vim</a> users</strong></p>\n<p>I had a script that had several declarations as follows:</p>\n<pre><code>export VARIABLE_NAME="$SOME_OTHER_VARIABLE/path-part"\n</code></pre>\n<p>But I wanted them to defer to any existing values. So I rewrote them to look like this:</p>\n<pre><code>if [ -z "$VARIABLE_NAME" ]; then\n export VARIABLE_NAME="$SOME_OTHER_VARIABLE/path-part"\nfi\n</code></pre>\n<p>I was able to automate this in Vim using a quick regex:</p>\n<pre><code>s/\\vexport ([A-Z_]+)\\=("[^"]+")\\n/if [ -z "$\\1" ]; then\\r export \\1=\\2\\rfi\\r/gc\n</code></pre>\n<p>This can be applied by selecting the relevant lines visually, then typing <code>:</code>. The command bar pre-populates with <code>:'<,'></code>. Paste the above command and hit <kbd>Enter</kbd>.</p>\n<hr />\n<p>It was tested on this version of Vim:</p>\n<pre><code>VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 22 2015 15:38:58)\nCompiled by [email protected]\n</code></pre>\n<p>Windows users may want different line endings.</p>\n"
},
{
"answer_id": 59073821,
"author": "nfleury",
"author_id": 5074477,
"author_profile": "https://Stackoverflow.com/users/5074477",
"pm_score": 0,
"selected": false,
"text": "<p>A shorter version to test an undefined variable can simply be:</p>\n<pre><code>test -z ${mystr} && echo "mystr is not defined"\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30636/"
] |
If I want to check for the null string I would do
```
[ -z $mystr ]
```
but what if I want to check whether the variable has been defined at all? Or is there no distinction in Bash scripting?
|
I think the answer you are after is implied (if not stated) by [Vinko](https://stackoverflow.com/users/5190/vinko-vrsalovic)'s [answer](https://stackoverflow.com/a/228552/15168), though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:
```
if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi
```
You probably can combine the two tests on the second line into one with:
```
if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi
```
However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '`-a`' and do recommend using separate simple tests combined with `&&`. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).
You can find the details of these, and other related [shell parameter expansions](https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion), the [`test` or `[`](https://www.gnu.org/software/bash/manual/bash.html#index-_005b) command and [conditional expressions](https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions) in the Bash manual.
---
I was recently asked by email about this answer with the question:
>
> You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion
>
>
>
> ```
> if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi
>
> ```
>
> Wouldn't this accomplish the same?
>
>
>
> ```
> if [ -z "${VAR}" ]; then echo "VAR is not set at all"; fi
>
> ```
>
>
Fair question - the answer is 'No, your simpler alternative does not do the same thing'.
Suppose I write this before your test:
```
VAR=
```
Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:
```
(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo "JL:1 VAR is not set at all"; fi
if [ -z "${VAR}" ]; then echo "MP:1 VAR is not set at all"; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo "JL:2 VAR is not set at all"; fi
if [ -z "${VAR}" ]; then echo "MP:2 VAR is not set at all"; fi
)
```
The output is:
```
JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all
```
In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the `${VAR=value}` and `${VAR:=value}` notations make. Ditto for `${VAR-value}` and `${VAR:-value}`, and `${VAR+value}` and `${VAR:+value}`, and so on.
---
As [Gili](https://stackoverflow.com/users/14731/gili) points out in his [answer](https://stackoverflow.com/a/20003892), if you run `bash` with the `set -o nounset` option, then the basic answer above fails with `unbound variable`. It is easily remedied:
```
if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi
```
Or you could cancel the `set -o nounset` option with `set +u` (`set -u` being equivalent to `set -o nounset`).
|
228,545 |
<p>A legacy backend requires the email body with a .tif document, no tif and it fails. So i need to generate a blank .tif, is there a fast way to do this with ghostscript? </p>
<hr>
<p>edit: make once in project installation use when i need it.</p>
|
[
{
"answer_id": 228579,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 0,
"selected": false,
"text": "<p>Couldn't you make your blank .tif file once and then attach the same file every time it is needed?</p>\n"
},
{
"answer_id": 228764,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>Might be something here: <a href=\"http://tolstoy.newcastle.edu.au/R/e2/help/07/01/8435.html\" rel=\"nofollow noreferrer\">Re: [R] Making TIFF images with rtiff</a></p>\n"
},
{
"answer_id": 229044,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "<p>The following line will produce a 1 pixel Tiff file (340 bytes). That's the smallest Tiff file I could get.</p>\n\n<pre><code>gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffpack -g1x1 -sOutputFile=small.tif -c newpath 0 0 moveto 1 1 lineto closepath stroke showpage quit\n</code></pre>\n\n<p>Actually, you can even reduce the command to:</p>\n\n<pre><code>gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffpack -g1x1 -sOutputFile=small.tif -c showpage quit\n</code></pre>\n\n<p>without size gain, alas.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
A legacy backend requires the email body with a .tif document, no tif and it fails. So i need to generate a blank .tif, is there a fast way to do this with ghostscript?
---
edit: make once in project installation use when i need it.
|
The following line will produce a 1 pixel Tiff file (340 bytes). That's the smallest Tiff file I could get.
```
gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffpack -g1x1 -sOutputFile=small.tif -c newpath 0 0 moveto 1 1 lineto closepath stroke showpage quit
```
Actually, you can even reduce the command to:
```
gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffpack -g1x1 -sOutputFile=small.tif -c showpage quit
```
without size gain, alas.
|
228,549 |
<p>I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of</p>
<pre><code>function editRecord()
{
var gridView = document.getElementById("<%= GridView.ClientID %>");
var id = // somehow get the id here ???
window.open("edit.aspx?id=" + id);
}
</code></pre>
<p>The question is how do I retrieve the selected records ID in javascript?</p>
|
[
{
"answer_id": 228556,
"author": "Dave K",
"author_id": 19864,
"author_profile": "https://Stackoverflow.com/users/19864",
"pm_score": 1,
"selected": false,
"text": "<p>1) change your javascript function to use a parameter</p>\n\n<pre><code>function editRecord(clientId)\n{ ....\n</code></pre>\n\n<p>2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple </p>\n\n<pre><code><input type=\"button\" onclick=\"editRecord(your-rows-client-id-goes-here)\" />\n</code></pre>\n"
},
{
"answer_id": 228569,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 1,
"selected": false,
"text": "<p>Based off of your comments to @DaveK's response, in javascript you can set the id of a hidden field to the clientId of the selected row when the user selects it. Then have your editRecord function use the value set on the hidden form field.</p>\n"
},
{
"answer_id": 228616,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 4,
"selected": true,
"text": "<p>I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:</p>\n\n<pre><code><asp:TemplateField ShowHeader=\"False\">\n <ItemTemplate>\n <asp:HiddenField ID=\"hdID\" runat=\"server\" Value='<%# Eval(\"JobID\") %>' />\n </ItemTemplate>\n</asp:TemplateField>\n<asp:TemplateField Visible=\"False\">\n <ItemTemplate>\n <asp:LinkButton ID=\"lnkSelect\" runat=\"server\" CommandName=\"select\" Text=\"Select\" />\n </ItemTemplate>\n</asp:TemplateField>\n</code></pre>\n\n<p>Then on the OnRowDataBind have code to set the selected row</p>\n\n<pre><code>protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n // Click to highlight row\n Control lnkSelect = e.Row.FindControl(\"lnkSelect\");\n if (lnkSelect != null)\n {\n StringBuilder click = new StringBuilder();\n click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));\n click.AppendLine(String.Format(\"onGridViewRowSelected('{0}')\", e.Row.RowIndex));\n e.Row.Attributes.Add(\"onclick\", click.ToString());\n }\n } \n}\n</code></pre>\n\n<p>And then in the Javascript I have code like this</p>\n\n<pre><code><script type=\"text/javascript\">\n\nvar selectedRowIndex = null;\n\nfunction onGridViewRowSelected(rowIndex)\n{ \n selectedRowIndex = rowIndex;\n}\n\nfunction editItem()\n{ \n if (selectedRowIndex == null) return;\n\n var gridView = document.getElementById('<%= GridView1.ClientID %>'); \n var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0]; \n var hidID = cell.childNodes[0]; \n window.open('JobTypeEdit.aspx?id=' + hidID.value);\n}\n\n</script> \n</code></pre>\n\n<p>Works a treat :-)</p>\n"
},
{
"answer_id": 8904692,
"author": "Brent",
"author_id": 1022710,
"author_profile": "https://Stackoverflow.com/users/1022710",
"pm_score": 0,
"selected": false,
"text": "<p>one could avoid javascript altogether, by setting anchor tags pre-populated with the query string for each row (although this will effect your table layout, it will need only one click rather than 2 from the user) </p>\n\n<p>insert in the gridview template:</p>\n\n<pre><code><asp:HyperLink runat=\"server\" ID=\"editLink\" Target=\"_blank\"\n NavigateURL='<%# Eval(\"JobID\",\"edit.aspx?id={0}\") %>'> \n Edit..\n</asp:HyperLink>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of
```
function editRecord()
{
var gridView = document.getElementById("<%= GridView.ClientID %>");
var id = // somehow get the id here ???
window.open("edit.aspx?id=" + id);
}
```
The question is how do I retrieve the selected records ID in javascript?
|
I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:
```
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
```
Then on the OnRowDataBind have code to set the selected row
```
protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Click to highlight row
Control lnkSelect = e.Row.FindControl("lnkSelect");
if (lnkSelect != null)
{
StringBuilder click = new StringBuilder();
click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));
click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex));
e.Row.Attributes.Add("onclick", click.ToString());
}
}
}
```
And then in the Javascript I have code like this
```
<script type="text/javascript">
var selectedRowIndex = null;
function onGridViewRowSelected(rowIndex)
{
selectedRowIndex = rowIndex;
}
function editItem()
{
if (selectedRowIndex == null) return;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0];
var hidID = cell.childNodes[0];
window.open('JobTypeEdit.aspx?id=' + hidID.value);
}
</script>
```
Works a treat :-)
|
228,559 |
<p>currently i obtain the below result from the following C# line of code when in es-MX Culture</p>
<pre><code> Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = new
CultureInfo("es-mx");
<span><%=DateTime.Now.ToLongDateString()%></span>
</code></pre>
<h1>miércoles, 22 de octubre de 2008</h1>
<p>i would like to obtain the following</p>
<h1>Miércoles, 22 de Octubre de 2008</h1>
<p>do i need to Build my own culture?</p>
|
[
{
"answer_id": 228582,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "<p>The pattern of LongDate for Spanish (Mexico) is</p>\n\n<blockquote>\n <p><code>dddd, dd' de 'MMMM' de 'yyyy</code></p>\n</blockquote>\n\n<p>according to <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.longdatepattern.aspx\" rel=\"nofollow noreferrer\">Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern</a>. I guess you just have to manually convert the initial letters of the day and month to uppercase or you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx\" rel=\"nofollow noreferrer\">Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase</a> and then replace \"De\" with \"de\".</p>\n"
},
{
"answer_id": 228597,
"author": "jaircazarin-old-account",
"author_id": 20915,
"author_profile": "https://Stackoverflow.com/users/20915",
"pm_score": 4,
"selected": true,
"text": "<p>You don't need to build your own culture. You only need to change the property DateTimeFormat.DayNames and DateTimeFormat.MonthNames in the current culture.</p>\n\n<p>i.e.</p>\n\n<pre><code> string[] newNames = { \"Lunes\", \"Martes\", \"Miercoles\", \"Jueves\", \"Viernes\", \"Sabado\", \"Domingo\" };\n Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = newNames;\n</code></pre>\n\n<p>However, it's weird that en-US show months and days with the first uppercase letter and for mx-ES not.</p>\n\n<p>Hope it helps!.</p>\n"
},
{
"answer_id": 228649,
"author": "Oscar Cabrero",
"author_id": 14440,
"author_profile": "https://Stackoverflow.com/users/14440",
"pm_score": 0,
"selected": false,
"text": "<p>first two Solutions works fine but what if we would like to extend this to any culture so i came up with this approach i change the current culture date time arrays into TitleCase</p>\n\n<pre><code>private void SetDateTimeFormatNames()\n {\n\n Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = ConvertoToTitleCase(Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames);\n Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames = ConvertoToTitleCase(Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames);\n\n }\n\nprivate string[] ConvertoToTitleCase(string[] arrayToConvert)\n {\n for (int i = 0; i < arrayToConvert.Length; i++)\n {\n arrayToConvert[i] = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(arrayToConvert[i]);\n }\n\n return arrayToConvert;\n }\n</code></pre>\n\n<p>how can this be improved with out the Loop?</p>\n"
},
{
"answer_id": 2542616,
"author": "xavier",
"author_id": 304756,
"author_profile": "https://Stackoverflow.com/users/304756",
"pm_score": 2,
"selected": false,
"text": "<p>a little late but this work for me!</p>\n\n<pre><code> public static string GetFecha()\n {\n System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(\"es-EC\");\n System.Threading.Thread.CurrentThread.CurrentCulture = culture;\n\n // maldita sea!\n string strDate = culture.TextInfo.ToTitleCase(DateTime.Now.ToLongDateString());\n\n return strDate.Replace(\"De\", \"de\");\n\n\n }\n</code></pre>\n"
},
{
"answer_id": 70626777,
"author": "Márcio Souza Júnior",
"author_id": 2083581,
"author_profile": "https://Stackoverflow.com/users/2083581",
"pm_score": 1,
"selected": false,
"text": "<p>The custom long date format string for the invariant culture is "dddd, dd MMMM yyyy", so you can use <code>string.Format</code> and a method to handle uppercase:</p>\n<pre><code>private string GetDateFormated(DateTime date)\n{\n return string.Format("{0}, {1} {2} {3}",\n ToTitleCase(date.ToString("dddd")),\n date.ToString("dd"),\n ToTitleCase(date.ToString("MMMM")),\n date.ToString("yyyy"));\n}\n\nprivate string ToTitleCase(string input)\n{\n return input[0].ToString().ToUpper() + input.Substring(1);\n}\n</code></pre>\n<p>Reference: <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#LongDate\" rel=\"nofollow noreferrer\">The long date ("D") format specifier</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14440/"
] |
currently i obtain the below result from the following C# line of code when in es-MX Culture
```
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = new
CultureInfo("es-mx");
<span><%=DateTime.Now.ToLongDateString()%></span>
```
miércoles, 22 de octubre de 2008
================================
i would like to obtain the following
Miércoles, 22 de Octubre de 2008
================================
do i need to Build my own culture?
|
You don't need to build your own culture. You only need to change the property DateTimeFormat.DayNames and DateTimeFormat.MonthNames in the current culture.
i.e.
```
string[] newNames = { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo" };
Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = newNames;
```
However, it's weird that en-US show months and days with the first uppercase letter and for mx-ES not.
Hope it helps!.
|
228,567 |
<p>I have a section of makefile that has this sort of structure:</p>
<pre><code>
bob:
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
bobit:
@echo "before"
@make bob
@echo "after"
</code></pre>
<p>I'm simplifying greatly here, all the echo's are actually non trivial blocks of commands and there is more conditional stuff, but this captures the essence of my problem.</p>
<p>For technical reasons I don't want to get into right now, I need to get rid of that submake, but because the echo's represent nontrivial amounts of code I don't want to just copy and past the body of bob in place of the submake.</p>
<p>Ideally what I'd like to do is something like this</p>
<pre><code>
define BOB_BODY
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
endef
bob:
$(BOB_BODY)
bobit:
@echo "before"
$(BOB_BODY)
@echo "after"
</code></pre>
<p>Unfortunately the conditionals seem to be shafting me, they produce "ifdef: Command not found" errors, I tried getting around this with various combinations of eval and call, but can't seem to figure out a way to get it to work.</p>
<p>How do I make this work? and is it even the right way to approach the problem?</p>
|
[
{
"answer_id": 233014,
"author": "Gordon Wrigley",
"author_id": 10471,
"author_profile": "https://Stackoverflow.com/users/10471",
"pm_score": 3,
"selected": true,
"text": "<p>The way I have fixed this is to use bash conditionals instead, which actually makes a certain amount of sense since we are playing with commands and not make rules.</p>\n\n<p>So my ideal solution from above becomes something like\n<pre><code>\ndefine BOB_BODY\n @if [[ -n \"$(DEBUG)\" ]]; then \\\n echo running; \\\n fi;\n @echo chug chug chug\n @if [[ -n \"$(DEBUG)\" ]]; then \\\n echo done; \\\n fi\nendef</p>\n\n<p>bob:\n $(BOB_BODY)</p>\n\n<p>bobit:\n @echo \"before\"\n $(BOB_BODY)\n @echo \"after\"\n</pre></code></p>\n"
},
{
"answer_id": 7667551,
"author": "pmod",
"author_id": 356838,
"author_profile": "https://Stackoverflow.com/users/356838",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply change the order of ifdef/define:</p>\n\n<pre><code>ifdef DEBUG\n define BOB_BODY \n @echo running\n @echo chug chug chug\n @echo done\n endef\nelse \n define BOB_BODY \n @echo chug chug chug\n endef\nendif\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<pre><code>define CHUG\n @echo chug chug chug\nendef\n\nifdef DEBUG\n define BOB_BODY \n @echo running\n $(CHUG)\n @echo done\n endef\nelse \n define BOB_BODY \n $(CHUG)\n endef\nendif\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10471/"
] |
I have a section of makefile that has this sort of structure:
```
bob:
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
bobit:
@echo "before"
@make bob
@echo "after"
```
I'm simplifying greatly here, all the echo's are actually non trivial blocks of commands and there is more conditional stuff, but this captures the essence of my problem.
For technical reasons I don't want to get into right now, I need to get rid of that submake, but because the echo's represent nontrivial amounts of code I don't want to just copy and past the body of bob in place of the submake.
Ideally what I'd like to do is something like this
```
define BOB_BODY
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
endef
bob:
$(BOB_BODY)
bobit:
@echo "before"
$(BOB_BODY)
@echo "after"
```
Unfortunately the conditionals seem to be shafting me, they produce "ifdef: Command not found" errors, I tried getting around this with various combinations of eval and call, but can't seem to figure out a way to get it to work.
How do I make this work? and is it even the right way to approach the problem?
|
The way I have fixed this is to use bash conditionals instead, which actually makes a certain amount of sense since we are playing with commands and not make rules.
So my ideal solution from above becomes something like
```
define BOB_BODY
@if [[ -n "$(DEBUG)" ]]; then \
echo running; \
fi;
@echo chug chug chug
@if [[ -n "$(DEBUG)" ]]; then \
echo done; \
fi
endef
```
bob:
$(BOB\_BODY)
bobit:
@echo "before"
$(BOB\_BODY)
@echo "after"
|
228,590 |
<p>A couple of the options are:</p>
<pre><code>$connection = {my db connection/object};
function PassedIn($connection) { ... }
function PassedByReference(&$connection) { ... }
function UsingGlobal() {
global $connection;
...
}
</code></pre>
<p>So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.</p>
<p>I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.</p>
<p>The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.</p>
|
[
{
"answer_id": 228596,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "<p>None of the above.</p>\n\n<p>All the <code>mysql</code> functions take the database connection argument <em>optionally</em>. If you leave that argument out, the last connection by mysql_connect() is assumed.</p>\n"
},
{
"answer_id": 228652,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 1,
"selected": false,
"text": "<p>My advice is to avoid global in the bulk of the code - it's dangerous, hard to track and will bite you.</p>\n\n<p>The way that I'd do this is to have a function called getDB() which can either be at class level by way of a constructor injection or static within a common class.</p>\n\n<p>So the code becomes</p>\n\n<pre><code>class SomeClass {\n protected $dbc;\n\n public function __construct($db) {\n $this->dbc = $db;\n }\n\n public function getDB() {\n return $this->dbc;\n }\n\n function read_something() {\n $db = getDB();\n $db->query();\n }\n}\n</code></pre>\n\n<p>or using a common shared class.</p>\n\n<pre><code>function read_something() {\n $db = System::getDB();\n $db->query();\n}\n</code></pre>\n\n<p>No matter how much elegant system design you do, there are always a few items that are necessarily global in scope (such as DB, Session, Config), and I prefer to keep these as static methods in my <em>System</em> class.</p>\n\n<p>Having each class require a connection via the constructor is the best way of doing this, by best I mean most reliable and isolated.</p>\n\n<p>However be aware that using a common shared class to do this can impact on the ability to isolate fully the objects using it and also the ability to perform unit tests on these objects.</p>\n"
},
{
"answer_id": 228660,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "<p>Try designing your code in an object-oriented fashion. Methods that use the database should be grouped in a class, and the class instance should contain the database connection as a class variable. That way the database connection is available to the functions that need it, but it's not global.</p>\n\n<pre><code>class MyClass {\n protected $_db;\n\n public function __construct($db)\n {\n $this->_db = $db;\n }\n\n public function doSomething()\n {\n $this->_db->query(...);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 228663,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function usingFunc() {\n $connection = getConnection();\n ...\n}\n\nfunction getConnection() {\n static $connectionObject = null;\n if ($connectionObject == null) {\n $connectionObject = connectFoo(\"whatever\",\"connection\",\"method\",\"you\",\"choose\");\n }\n return $connectionObject;\n}\n</code></pre>\n\n<p>This way, the static $connectionObject is preserved between getConnection calls.</p>\n"
},
{
"answer_id": 228715,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 3,
"selected": true,
"text": "<p>I use a Singleton ResourceManager class to handle stuff like DB connections and config settings through a whole app:</p>\n\n<pre><code>class ResourceManager {\n private static $DB;\n private static $Config;\n\n public static function get($resource, $options = false) {\n if (property_exists('ResourceManager', $resource)) {\n if (empty(self::$$resource)) {\n self::_init_resource($resource, $options);\n }\n if (!empty(self::$$resource)) {\n return self::$$resource;\n }\n }\n return null;\n }\n\n private static function _init_resource($resource, $options = null) {\n if ($resource == 'DB') {\n $dsn = 'mysql:host=localhost';\n $username = 'my_username';\n $password = 'p4ssw0rd';\n try {\n self::$DB = new PDO($dsn, $username, $password);\n } catch (PDOException $e) {\n echo 'Connection failed: ' . $e->getMessage();\n }\n } elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {\n self::$$resource = new $resource($options);\n }\n }\n}\n</code></pre>\n\n<p>And then in functions / objects / where ever:</p>\n\n<pre><code>function doDBThingy() {\n $db = ResourceManager::get('DB');\n if ($db) {\n $stmt = $db->prepare('SELECT * FROM `table`');\n etc...\n }\n}\n</code></pre>\n\n<p>I use it to store messages, error messages and warnings, as well as global variables. There's an interesting question <a href=\"https://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton\">here</a> on when to actually use this type of class.</p>\n"
},
{
"answer_id": 229383,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "<p>I see that a lot of people have suggested some kind of static variable.</p>\n\n<p>Essentially, there is very little difference between a global variable and a static variable. Except for the syntax, they have exactly the same characteristics. As such, you are gaining nothing at all, by replacing a global variable with a static variable. In most examples, there is a level of decoupling in that the static variable isn't referred directly, but rather through a static method (Eg. a singleton or static registry). While slightly better, this still has the problems of a global scope. If you ever need to use more than one database connection in your application, you're screwed. If you ever want to know which parts of your code has side-effects, you need to manually inspect the implementation. That's not stuff that will make or break your application, but it will make it harder to maintain.</p>\n\n<p>I propose that you chose between one of:</p>\n\n<ul>\n<li><p>Pass the instance as arguments to the functions that needs it. This is by far the simplest, and it has all the benefits of narrow scope, but it can get rather unwieldy. It is also a source for introducing dependencies, since some parts of your code may end up becoming a middleman. If that happens, go on to ..</p></li>\n<li><p>Put the instance in the scope of the object, which has the method that needs it. Eg. if the method <code>Foo->doStuff()</code> needs a database connection, pass it in <code>Foo</code>'s constructor and set it as a protected instance variable on <code>Foo</code>. You can still end up with some of the problems of passing in the method, but it's generally less of a problem with unwieldy constructors, than with methods. If your application gets big enough, you can use a dependency injection container to automate this.</p></li>\n</ul>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
A couple of the options are:
```
$connection = {my db connection/object};
function PassedIn($connection) { ... }
function PassedByReference(&$connection) { ... }
function UsingGlobal() {
global $connection;
...
}
```
So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.
I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.
The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.
|
I use a Singleton ResourceManager class to handle stuff like DB connections and config settings through a whole app:
```
class ResourceManager {
private static $DB;
private static $Config;
public static function get($resource, $options = false) {
if (property_exists('ResourceManager', $resource)) {
if (empty(self::$$resource)) {
self::_init_resource($resource, $options);
}
if (!empty(self::$$resource)) {
return self::$$resource;
}
}
return null;
}
private static function _init_resource($resource, $options = null) {
if ($resource == 'DB') {
$dsn = 'mysql:host=localhost';
$username = 'my_username';
$password = 'p4ssw0rd';
try {
self::$DB = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
} elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {
self::$$resource = new $resource($options);
}
}
}
```
And then in functions / objects / where ever:
```
function doDBThingy() {
$db = ResourceManager::get('DB');
if ($db) {
$stmt = $db->prepare('SELECT * FROM `table`');
etc...
}
}
```
I use it to store messages, error messages and warnings, as well as global variables. There's an interesting question [here](https://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton) on when to actually use this type of class.
|
228,595 |
<p>I have an ADO.Net Data Service that I am using to do a data import. There are a number of entities that are linked to by most entities. To do that during import I create those entities first, save them and then use .SetLink(EntityImport, "NavigationProperty", CreatedEntity). Now the first issue that I ran into was that the context did not always know about CreatedEntity (this is due to each of the entities being imported independently and a creation of a context as each item is created - I'd like to retain this functionality - i.e. I'm trying to avoid "just use one context" as the answer). </p>
<p>So I have a .AddToCreatedEntityType(CreatedEntity) before attempting to call SetLink. This of course works for the first time, but on the second pass I get the error message "the context is already tracking the entity". </p>
<p>Is there a way to check if the context is already tracking the entity (context.Contains(CreatedEntity) isn't yet implemented)? I was thinking about attempting a try catch and just avoiding the error, but that seems to create a new CreatedEntity each pass. It is looking like I need to use a LINQ to Data Services to get that CreatedEntity each time, but that seems innefficient - any suggestions?</p>
|
[
{
"answer_id": 228800,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 3,
"selected": false,
"text": "<p>I think you should look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx\" rel=\"nofollow noreferrer\">EntityState</a> property of your entity.</p>\n\n<p>Only if it is of the value EntityState.Detached than you have to add it to your context.</p>\n\n<p>Do not forget the following remark:</p>\n\n<blockquote>\n <p>This enumeration has a FlagsAttribute\n attribute that allows a bitwise\n combination of its member values.</p>\n</blockquote>\n\n<p>I would create a extension method:</p>\n\n<pre><code>public static class EntityObjectExtensions\n{\n public static Boolean IsTracked(this EntityObject self)\n {\n return (self.EntityState & EntityState.Detached) != EntityState.Detached;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 277103,
"author": "James_2195",
"author_id": 36086,
"author_profile": "https://Stackoverflow.com/users/36086",
"pm_score": 2,
"selected": false,
"text": "<p>When trying to check whether the context was tracking the entity that I wanted to update (or add) I was pretty disapointed when I found that the context.Entites.Contains(currentItem) didn't work.</p>\n\n<p>I got around it using:</p>\n\n<pre><code>if (context.Entities.Where(entities => entities.Entity == currentItem).Any())\n{\n this.service.UpdateObject(currentItem); \n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25719/"
] |
I have an ADO.Net Data Service that I am using to do a data import. There are a number of entities that are linked to by most entities. To do that during import I create those entities first, save them and then use .SetLink(EntityImport, "NavigationProperty", CreatedEntity). Now the first issue that I ran into was that the context did not always know about CreatedEntity (this is due to each of the entities being imported independently and a creation of a context as each item is created - I'd like to retain this functionality - i.e. I'm trying to avoid "just use one context" as the answer).
So I have a .AddToCreatedEntityType(CreatedEntity) before attempting to call SetLink. This of course works for the first time, but on the second pass I get the error message "the context is already tracking the entity".
Is there a way to check if the context is already tracking the entity (context.Contains(CreatedEntity) isn't yet implemented)? I was thinking about attempting a try catch and just avoiding the error, but that seems to create a new CreatedEntity each pass. It is looking like I need to use a LINQ to Data Services to get that CreatedEntity each time, but that seems innefficient - any suggestions?
|
I think you should look at the [EntityState](http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx) property of your entity.
Only if it is of the value EntityState.Detached than you have to add it to your context.
Do not forget the following remark:
>
> This enumeration has a FlagsAttribute
> attribute that allows a bitwise
> combination of its member values.
>
>
>
I would create a extension method:
```
public static class EntityObjectExtensions
{
public static Boolean IsTracked(this EntityObject self)
{
return (self.EntityState & EntityState.Detached) != EntityState.Detached;
}
}
```
|
228,614 |
<p>This is a bit of a lazyweb question but you get the rep so :-)</p>
<p>I have a Java class that returns instances of itself to allow chaining
(e.g. ClassObject.doStuff().doStuff())</p>
<p>For instance:</p>
<pre><code>public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
</code></pre>
<p>I would like to extend this class. Is there a way, perhaps using generics, to extend this class without having to overwrite each method signature?</p>
<p>E.g. not:</p>
<pre><code>public class ChainerExtender extends Chainer
{
public ChainerExtender doStuff()
{
super.doStuff();
return this;
}
}
</code></pre>
<p>I have tried:</p>
<pre><code>public class Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return (A)this;
}
}
public class ChainerExtender extends Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return super.doStuff();
}
}
</code></pre>
<p>But this didn't work giving the error:</p>
<pre><code>type parameters of <A>A cannot be determined;
no unique maximal instance exists for type variable A with upper bounds A,Chainer
</code></pre>
<p>Am I forced to have class declarations like:</p>
<pre><code>public class Chainer<T extends Chainer<T>> {}
public class ChainerExtender extends Chainer<ChainerExtender>
</code></pre>
<p>As per <a href="https://stackoverflow.com/questions/153994/generic-type-args-which-specificy-the-extending-class">this question</a>?</p>
|
[
{
"answer_id": 228632,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>Could you just post a complete example leading to the error message you see ?</p>\n\n<p>I just compiled and execute the following without a hitch:</p>\n\n<pre><code>public class Test {\n\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n ChainerExtender c = new ChainerExtender();\n c.doStuff().doStuff();\n }\n\n public static class Chainer\n {\n public <A extends Chainer> A doStuff()\n {\n /* Do stuff ... */\n System.out.println(\"Chainer\");\n return (A)this;\n }\n }\n\n public static class ChainerExtender extends Chainer\n {\n /** \n * @see test.Test.Chainer#doStuff()\n */\n @Override\n public <A extends Chainer> A doStuff()\n {\n System.out.println(\"ChainerExtender\");\n return super.doStuff();\n }\n }\n\n}\n</code></pre>\n\n<p>Gives:</p>\n\n<pre><code>ChainerExtender\nChainer\nChainerExtender\nChainer\n</code></pre>\n\n<p>I have have misunderstood this issue, please downvote and comment.</p>\n"
},
{
"answer_id": 228657,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<p>Why not have them all return an interface? You'd have to define all of the possible chained methods in the interface and provide \"null\" implementations in the base class, but you'd be able to chain to your heart's content.</p>\n\n<pre><code>public interface IChainer\n{\n IChainer doStuff();\n IChainer doSomethingElse();\n}\n\npublic class Chainer implements IChainer\n{\n public IChainer doStuff()\n {\n // really do something\n return this;\n }\n\n public IChainer doSomethingElse()\n {\n return this; // do nothing\n }\n}\n\npublic class ChainerExtender extends Chainer\n{\n // simply inherits implementation for doStuff()\n\n public override IChainer doSomethingElse()\n {\n // really do something\n return this;\n }\n}\n</code></pre>\n\n<p>Note: I may have some syntax issues above. I've been programming mostly in C# for the last few years. Hopefully, you get the idea.</p>\n"
},
{
"answer_id": 228867,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 1,
"selected": false,
"text": "<p>I think that the simple answer is \"no you can't\". I can see how this might be useful but I feel that this use of inheritance screams \"unexpected consequences\" at me. It's only a matter of time before someone decides to add a bit of extra functionality in a subclass, as opposed to just doing a <code>super.doStuff()</code> and the control flow is going to be extremely difficult to follow. </p>\n\n<p>One possible solution is for your chainers (if they are using the <strong>builder</strong> pattern) to return new instances of different builder classes instead of <code>this</code>. See what Stephen Colebourne has done with the date-creation builders in <a href=\"http://www.threeten.org/\" rel=\"nofollow noreferrer\">JSR 310</a> which is quite clever from an API perspective, although clunky to write.</p>\n"
},
{
"answer_id": 229744,
"author": "user21714",
"author_id": 21714,
"author_profile": "https://Stackoverflow.com/users/21714",
"pm_score": 1,
"selected": false,
"text": "<p>It's been awhile since I've done any Java generics.</p>\n\n<p>What about :</p>\n\n<pre>\n\n<T>\npublic class Chainer \n{\n public T doStuf()\n {\n }\n\n}\n\npublic class ChainerDerived : extends Chainer<ChainerDerived>\n{\n public ChainerDerived doStuf()\n {\n }\n}\n\n</pre>\n\n<p>I've mostly been doing C++ lately and this kind of stuff is just par for the course. Do Java generics support this type of structure?</p>\n\n<p>I hope I understood your question.</p>\n"
},
{
"answer_id": 229907,
"author": "bhavanki",
"author_id": 24184,
"author_profile": "https://Stackoverflow.com/users/24184",
"pm_score": 2,
"selected": false,
"text": "<p>I got it to work this way. It uses a class literal to signal what type to cast to at runtime (see section 8 of <a href=\"http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf\" rel=\"nofollow noreferrer\">Gilad Bracha's Generics Tutorial</a>).</p>\n\n<pre>\npublic class Chainer {\n public <T extends Chainer> T doStuff (Class<T> foo) {\n /* do stuff */\n return foo.cast (this);\n }\n}\n\npublic class ChainerExtender extends Chainer {\n public <T extends ChainerExtender> doOtherStuff (Class<T> foo) {\n /* do other stuff */\n return foo.cast (this);\n }\n}\n</pre>\n\n<p>So calls look like this:</p>\n\n<pre>\nChainer c1 = new Chainer();\nc1 = c1.doStuff (c1.getClass());\n// ...\nChainerExtender ce1 = new ChainerExtender();\nce1 = ce1.doStuff (ce1.getClass()).doOtherStuff (ce1.getClass());\n</pre>\n\n<p>One downside to this technique is that, if you have a <code>Chainer</code> reference, you have to explicitly check if it's actually a <code>ChainerExtender</code> object before calling <code>doOtherStuff</code> on it. This makes sense, though, since trying to call the method on a <code>Chainer</code> object at runtime would yield an error.</p>\n"
},
{
"answer_id": 256693,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 4,
"selected": true,
"text": "<p>Have you tried the straight-forward</p>\n\n<pre><code>public class Chainer\n{\n public Chainer doStuff()\n {\n /* Do stuff ... */\n return this;\n }\n}\n\npublic class ChainerExtender extends Chainer\n{\n @Override\n public ChainerExtender doStuff()\n {\n /* Do stuff ... */\n super.doStuff();\n return this;\n }\n}\n</code></pre>\n\n<p>With Java 5, you can declare overriding methods to have co-variant return types, which means just what this says: a subclass can have an overriding method signature with a more specific return type.</p>\n"
},
{
"answer_id": 279033,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Notice that \"super.<A>doStuff()\" would compile <em>and</em> work. It hints generics about the type you are expecting.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
This is a bit of a lazyweb question but you get the rep so :-)
I have a Java class that returns instances of itself to allow chaining
(e.g. ClassObject.doStuff().doStuff())
For instance:
```
public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
```
I would like to extend this class. Is there a way, perhaps using generics, to extend this class without having to overwrite each method signature?
E.g. not:
```
public class ChainerExtender extends Chainer
{
public ChainerExtender doStuff()
{
super.doStuff();
return this;
}
}
```
I have tried:
```
public class Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return (A)this;
}
}
public class ChainerExtender extends Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return super.doStuff();
}
}
```
But this didn't work giving the error:
```
type parameters of <A>A cannot be determined;
no unique maximal instance exists for type variable A with upper bounds A,Chainer
```
Am I forced to have class declarations like:
```
public class Chainer<T extends Chainer<T>> {}
public class ChainerExtender extends Chainer<ChainerExtender>
```
As per [this question](https://stackoverflow.com/questions/153994/generic-type-args-which-specificy-the-extending-class)?
|
Have you tried the straight-forward
```
public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
public class ChainerExtender extends Chainer
{
@Override
public ChainerExtender doStuff()
{
/* Do stuff ... */
super.doStuff();
return this;
}
}
```
With Java 5, you can declare overriding methods to have co-variant return types, which means just what this says: a subclass can have an overriding method signature with a more specific return type.
|
228,623 |
<p>This may be a simple fix - but I'm trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0:</p>
<pre><code> private long sum(Node<T> thisNode)
{
if (thisNode.Left == null && thisNode.Right == null)
return 0;
if (node.Right == null)
return sum(thisNode.Left);
if (node.Left == null)
return sum(thisNode.Right);
return sum(thisNode.Left) + sum(thisNode.Right);
}
</code></pre>
<p>Within my Node class I have Data which stores Size and Name in their given properties. I'm just trying to sum the entire size. Any suggestions or ideas?</p>
|
[
{
"answer_id": 228631,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you meant </p>\n\n<pre><code> if (thisNode.Left == null && thisNode.Right == null)\n return thisNode.Size;\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 228641,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "<p>It's because you're returning zero when you reach a leaf node. You should be returning the size stored in that leaf node.</p>\n\n<p>In addition, if your non-leaf nodes also have a size, you'll need to process them as well thus:</p>\n\n<pre><code>private long sum(Node<T> thisNode)\n{\n if (thisNode.Left == null && thisNode.Right == null)\n return thisNode.Size;\n if (node.Right == null)\n return thisNode.Size + sum(thisNode.Left);\n if (node.Left == null) \n return thisNode.Size + sum(thisNode.Right);\n return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);\n}\n</code></pre>\n\n<p>If your non-leaf nodes don't have size, use:</p>\n\n<pre><code>private long sum(Node<T> thisNode)\n{\n if (thisNode.Left == null && thisNode.Right == null)\n return thisNode.Size;\n if (node.Right == null)\n return sum(thisNode.Left);\n if (node.Left == null) \n return sum(thisNode.Right);\n return sum(thisNode.Left) + sum(thisNode.Right);\n}\n</code></pre>\n\n<p>A more elegant version of the first one is:</p>\n\n<pre><code>private long sum(Node<T> thisNode)\n{\n if (thisNode == null)\n return 0;\n return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);\n}\n</code></pre>\n"
},
{
"answer_id": 228643,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 1,
"selected": false,
"text": "<p>How about</p>\n\n<pre><code>private long Sum(Node<T> thisNode)\n{\n if( thisNode == null )\n return 0;\n\n return thisNode.Size + Sum(thisNode.Left) + Sum(thisNode.Right);\n}\n</code></pre>\n\n<p>If the size property isn't on the node itself, what about this?</p>\n\n<pre><code> public class Node<T>\n {\n public T Data;\n public Node<T> Left;\n public Node<T> Right;\n\n public static void ForEach(Node<T> root, Action<T> action)\n {\n action(root.Data);\n\n if (root.Left != null)\n ForEach(root.Left, action);\n if (root.Right != null)\n ForEach(root.Right, action);\n }\n }\n\n public interface IHasSize\n {\n long Size { get; }\n }\n\n public static long SumSize<T>(Node<T> root) where T : IHasSize\n {\n long sum = 0;\n Node<T>.ForEach(root, delegate(T item)\n {\n sum += item.Size;\n });\n return sum;\n }\n</code></pre>\n"
},
{
"answer_id": 228645,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code> private long sum(Node<T> thisNode)\n {\n if (thisNode == null)\n return 0;\n return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);\n }\n</code></pre>\n\n<p>The only \"value\" that the original code ever returns is 0 - that's why the result is always 0.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30649/"
] |
This may be a simple fix - but I'm trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0:
```
private long sum(Node<T> thisNode)
{
if (thisNode.Left == null && thisNode.Right == null)
return 0;
if (node.Right == null)
return sum(thisNode.Left);
if (node.Left == null)
return sum(thisNode.Right);
return sum(thisNode.Left) + sum(thisNode.Right);
}
```
Within my Node class I have Data which stores Size and Name in their given properties. I'm just trying to sum the entire size. Any suggestions or ideas?
|
It's because you're returning zero when you reach a leaf node. You should be returning the size stored in that leaf node.
In addition, if your non-leaf nodes also have a size, you'll need to process them as well thus:
```
private long sum(Node<T> thisNode)
{
if (thisNode.Left == null && thisNode.Right == null)
return thisNode.Size;
if (node.Right == null)
return thisNode.Size + sum(thisNode.Left);
if (node.Left == null)
return thisNode.Size + sum(thisNode.Right);
return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);
}
```
If your non-leaf nodes don't have size, use:
```
private long sum(Node<T> thisNode)
{
if (thisNode.Left == null && thisNode.Right == null)
return thisNode.Size;
if (node.Right == null)
return sum(thisNode.Left);
if (node.Left == null)
return sum(thisNode.Right);
return sum(thisNode.Left) + sum(thisNode.Right);
}
```
A more elegant version of the first one is:
```
private long sum(Node<T> thisNode)
{
if (thisNode == null)
return 0;
return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);
}
```
|
228,642 |
<p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p>
<p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p>
<pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
</code></pre>
<p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p>
<p>So my question is twofold:</p>
<ol>
<li>Am I missing something?</li>
<li>Is there a python debugger that would indeed let me do this?</li>
</ol>
<p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
|
[
{
"answer_id": 228653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>And I've answered my own question! It's the \"debug\" command in pydb:</p>\n\n<pre><code>~> cat -n /tmp/test_python.py\n 1 #!/usr/local/bin/python\n 2\n 3 def foo():\n 4 print \"hi\"\n 5 print \"bye\"\n 6\n 7 exit(0)\n 8\n\n~> pydb /tmp/test_python.py\n(/tmp/test_python.py:7): <module>\n7 exit(0)\n\n\n(Pydb) debug foo()\nENTERING RECURSIVE DEBUGGER\n------------------------Call level 11\n(/tmp/test_python.py:3): foo\n3 def foo():\n\n((Pydb)) s\n(/tmp/test_python.py:4): foo\n4 print \"hi\"\n\n((Pydb)) s\nhi\n(/tmp/test_python.py:5): foo\n5 print \"bye\"\n\n\n((Pydb)) s\nbye\n------------------------Return from level 11 (<type 'NoneType'>)\n----------------------Return from level 10 (<type 'NoneType'>)\nLEAVING RECURSIVE DEBUGGER\n(/tmp/test_python.py:7): <module>\n</code></pre>\n"
},
{
"answer_id": 228662,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": "<p>There is a python debugger that is part of the core distribution of python called 'pdb'. I rarely use it myself, but find it useful sometimes.</p>\n\n<p>Given this program:</p>\n\n<pre><code>def foo():\n a = 0\n print \"hi\"\n\n a += 1\n\n print \"bye\"\n\nfoo()\n</code></pre>\n\n<p>Here is a session debugging it:</p>\n\n<pre><code>$ python /usr/lib/python2.5/pdb.py /var/tmp/pdbtest.py ~\n> /var/tmp/pdbtest.py(2)<module>()\n-> def foo():\n(Pdb) s\n> /var/tmp/pdbtest.py(10)<module>()\n-> foo()\n(Pdb) s\n--Call--\n> /var/tmp/pdbtest.py(2)foo()\n-> def foo():\n(Pdb) s\n> /var/tmp/pdbtest.py(3)foo()\n-> a = 0\n(Pdb) s\n> /var/tmp/pdbtest.py(4)foo()\n-> print \"hi\"\n(Pdb) print a\n0\n(Pdb) s\nhi\n> /var/tmp/pdbtest.py(6)foo()\n-> a += 1\n(Pdb) s\n> /var/tmp/pdbtest.py(8)foo()\n-> print \"bye\"\n(Pdb) print a\n1\n(Pdb) s\nbye\n--Return--\n> /var/tmp/pdbtest.py(8)foo()->None\n-> print \"bye\"\n(Pdb) s\n--Return--\n> /var/tmp/pdbtest.py(10)<module>()->None\n-> foo()\n(Pdb) s\n</code></pre>\n"
},
{
"answer_id": 229311,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 2,
"selected": false,
"text": "<p>For interactive work on code I'm developing, I usually find it more efficient to set a programmatic \"break point\" in the code itself with <code>pdb.set_trace</code>. This makes it easir to break on the program's state deep in a a loop, too: <code>if <state>: pdb.set_trace()</code></p>\n"
},
{
"answer_id": 229380,
"author": "Simon",
"author_id": 22404,
"author_profile": "https://Stackoverflow.com/users/22404",
"pm_score": 5,
"selected": false,
"text": "<p>You can interactively debug a function with pdb as well, provided the script you want to debug does not exit() at the end:</p>\n\n<pre><code>$ cat test.py\n#!/usr/bin/python\n\ndef foo(f, g):\n h = f+g\n print h\n return 2*f\n</code></pre>\n\n<p>To debug, start an interactive python session and import pdb:</p>\n\n<pre><code>$ python\nPython 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) \n[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import pdb\n>>> import test\n>>> pdb.runcall(test.foo, 1, 2)\n> /Users/simon/Desktop/test.py(4)foo()\n-> h = f+g\n(Pdb) n\n> /Users/simon/Desktop/test.py(5)foo()\n-> print h\n(Pdb) \n</code></pre>\n\n<p>The pdb module comes with python and is documented in the modules docs at <a href=\"http://docs.python.org/modindex.html\" rel=\"noreferrer\">http://docs.python.org/modindex.html</a></p>\n"
},
{
"answer_id": 230561,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": false,
"text": "<p>If you're more familiar with a GUI debugger, there's winpdb ('win' in this case does not refer to Windows). I actually use it on Linux.</p>\n\n<p>On debian/ubuntu:</p>\n\n<pre><code>sudo aptitude install winpdb\n</code></pre>\n\n<p>Then just put this in your code where you want it to break:</p>\n\n<pre><code>import rpdb2; rpdb2.start_embedded_debugger_interactive_password()\n</code></pre>\n\n<p>Then start winpdb and attach to your running script.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Python is quite cool, but unfortunately, its debugger is not as good as perl -d.
One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:
```
# NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
```
This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).
So my question is twofold:
1. Am I missing something?
2. Is there a python debugger that would indeed let me do this?
Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.
|
And I've answered my own question! It's the "debug" command in pydb:
```
~> cat -n /tmp/test_python.py
1 #!/usr/local/bin/python
2
3 def foo():
4 print "hi"
5 print "bye"
6
7 exit(0)
8
~> pydb /tmp/test_python.py
(/tmp/test_python.py:7): <module>
7 exit(0)
(Pydb) debug foo()
ENTERING RECURSIVE DEBUGGER
------------------------Call level 11
(/tmp/test_python.py:3): foo
3 def foo():
((Pydb)) s
(/tmp/test_python.py:4): foo
4 print "hi"
((Pydb)) s
hi
(/tmp/test_python.py:5): foo
5 print "bye"
((Pydb)) s
bye
------------------------Return from level 11 (<type 'NoneType'>)
----------------------Return from level 10 (<type 'NoneType'>)
LEAVING RECURSIVE DEBUGGER
(/tmp/test_python.py:7): <module>
```
|
228,648 |
<p>I'm new to ruby and I'm playing around with the IRB.</p>
<p>I found that I can list methods of an object using the ".methods" method, and that self.methods sort of give me what I want (similar to Python's dir(<strong>builtins</strong>)?), but how can I find the methods of a library/module I've loaded via include and require?</p>
<pre><code>irb(main):036:0* self.methods
=> ["irb_pop_binding", "inspect", "taguri", "irb_chws", "clone", "irb_pushws", "public_methods", "taguri=", "irb_pwws",
"public", "display", "irb_require", "irb_exit", "instance_variable_defined?", "irb_cb", "equal?", "freeze", "irb_context
", "irb_pop_workspace", "irb_cwb", "irb_jobs", "irb_bindings", "methods", "irb_current_working_workspace", "respond_to?"
, "irb_popb", "irb_cws", "fg", "pushws", "conf", "dup", "cwws", "instance_variables", "source", "cb", "kill", "help", "_
_id__", "method", "eql?", "irb_pwb", "id", "bindings", "send", "singleton_methods", "popb", "irb_kill", "chws", "taint",
"irb_push_binding", "instance_variable_get", "frozen?", "irb_source", "pwws", "private", "instance_of?", "__send__", "i
rb_workspaces", "to_a", "irb_quit", "to_yaml_style", "irb_popws", "irb_change_workspace", "jobs", "type", "install_alias
_method", "irb_push_workspace", "require_gem", "object_id", "instance_eval", "protected_methods", "irb_print_working_wor
kspace", "irb_load", "require", "==", "cws", "===", "irb_pushb", "instance_variable_set", "irb_current_working_binding",
"extend", "kind_of?", "context", "gem", "to_yaml_properties", "quit", "popws", "irb", "to_s", "to_yaml", "irb_fg", "cla
ss", "hash", "private_methods", "=~", "tainted?", "include", "irb_cwws", "irb_change_binding", "irb_help", "untaint", "n
il?", "pushb", "exit", "irb_print_working_binding", "is_a?", "workspaces"]
irb(main):037:0>
</code></pre>
<p>I'm used to python, where I use the dir() function to accomplish the same thing:</p>
<pre><code>>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
</code></pre>
|
[
{
"answer_id": 228903,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can pass the .methods messages to the library/module even before loading it, to see all the available methods. Doing <code>self.methods</code> just returns all the methods that the Object object contains. You can see this by doing <code>self.class</code>. So let's say you want to see all the methods in the File module. You simply do <code>File.methods</code> and you'll get a list of all the methods that exist in the File module. This, perhaps, isn't what you want, but it should be somewhat helpful.</p>\n"
},
{
"answer_id": 228907,
"author": "Osseta",
"author_id": 30584,
"author_profile": "https://Stackoverflow.com/users/30584",
"pm_score": 2,
"selected": false,
"text": "<p>To access all object instances in ruby you use ObjectSpace</p>\n\n<p><a href=\"http://www.ruby-doc.org/core-1.8.7/classes/ObjectSpace.html#M000928\" rel=\"nofollow noreferrer\">http://www.ruby-doc.org/core-1.8.7/classes/ObjectSpace.html#M000928</a></p>\n\n<p>However, this is considered slow (even for ruby), and may not be enabled in some interpreters (e.g. jRuby can disable ObjectSpace as it is much faster relying in the jvm for gc without needing to track this stuff in jRuby).</p>\n"
},
{
"answer_id": 228911,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://www.ruby-doc.org/core-1.8.7/classes/ObjectSpace.html#M000928\" rel=\"noreferrer\">ObjectSpace.each_object</a> could be what you are looking for.</p>\n\n<p>To get a list of included modules you could use <a href=\"http://www.ruby-doc.org/core/classes/Module.html#M001697\" rel=\"noreferrer\">Module.included_modules</a>.</p>\n\n<p>You can also check if an object responds to a method on a case-by-case basis using <a href=\"http://ruby-doc.org/core/classes/Object.html#M000333\" rel=\"noreferrer\">object.respond_to?</a>.</p>\n"
},
{
"answer_id": 232272,
"author": "two-bit-fool",
"author_id": 23899,
"author_profile": "https://Stackoverflow.com/users/23899",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>dir()</code> method is <a href=\"http://www.python.org/doc/2.5.2/lib/built-in-funcs.html\" rel=\"noreferrer\">not clearly defined</a>...</p>\n\n<blockquote>\n <p><strong>Note:</strong> Because <code>dir()</code> is supplied\n primarily as a convenience for use at\n an interactive prompt, it tries to\n supply an interesting set of names\n more than it tries to supply a\n rigorously or consistently defined set\n of names, and its detailed behavior\n may change across releases.</p>\n</blockquote>\n\n<p>...but we can create a close approximation in Ruby. Let's make a method that will return a sorted list of all methods added to our scope by included modules. We can get a list of the modules that have been included by using the <code>included_modules</code> method.</p>\n\n<p>Like <code>dir()</code>, we want to ignore the \"default\" methods (like <code>print</code>), and we also want to focus on the \"interesting\" set of names. So, we will ignore methods in <code>Kernel</code>, and we will only return methods that were defined directly in the modules, ignoring inherited methods. We can accomplish the later by passing <code>false</code> into the <code>methods()</code> method. Putting it all together we get...</p>\n\n<pre><code>def included_methods(object=self)\n object = object.class if object.class != Class\n modules = (object.included_modules-[Kernel])\n modules.collect{ |mod| mod.methods(false)}.flatten.sort\nend\n</code></pre>\n\n<p>You can pass it a class, an object, or nothing (it defaults to the current scope). Let's try it out...</p>\n\n<pre><code>irb(main):006:0> included_methods\n=> []\nirb(main):007:0> include Math\n=> Object\nirb(main):008:0> included_methods\n=> [\"acos\", \"acosh\", \"asin\", \"asinh\", \"atan\", \"atan2\", \"atanh\", \"cos\", \"cosh\", \"erf\", \"erfc\", \"exp\", \"frexp\", \"hypot\", \"ldexp\", \"log\", \"log10\", \"sin\", \"sinh\", \"sqrt\", \"tan\", \"tanh\"]\n</code></pre>\n\n<hr>\n\n<p><code>dir()</code> also includes locally defined variables, and that's an easy one. Just call...</p>\n\n<pre><code>local_variables\n</code></pre>\n\n<p>...unfortunately, we can't just add the <code>local_variables</code> call to <code>included_methods</code> because it would give us the variables that are local to the <code>included_methods</code> method, and that wouldn't be very useful. So, if you want local variables included with the included_methods, just call...</p>\n\n<pre><code> (included_methods + local_variables).sort\n</code></pre>\n"
},
{
"answer_id": 235996,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 6,
"selected": false,
"text": "<p>I'm not entirely sure of what you mean by the 'current objects'. You can iterate over ObjectSpace, as has been mentioned already. But here are a few other methods.</p>\n\n<pre><code>local_variables\ninstance_variables\nglobal_variables\n\nclass_variables\nconstants\n</code></pre>\n\n<p>There's one gotcha. They must be called at the right scopes. So right in IRB, or in an object instance or at class scope (so everywhere, basically) you can call the first 3.</p>\n\n<pre><code>local_variables #=> [\"_\"]\nfoo = \"bar\"\nlocal_variables #=> [\"_\", \"foo\"]\n# Note: the _ variable in IRB contains the last value evaluated\n_ #=> \"bar\"\n\ninstance_variables #=> []\n@inst_var = 42\ninstance_variables #=> [\"@inst_var\"]\n\nglobal_variables #=> [\"$-d\", \"$\\\"\", \"$$\", \"$<\", \"$_\", ...]\n$\" #=> [\"e2mmap.rb\", \"irb/init.rb\", \"irb/workspace.rb\", ...]\n</code></pre>\n\n<p>But umm, what if you want your program to actually evaluate them without needing you to type them manyally? The trick is eval.</p>\n\n<pre><code>eval \"@inst_var\" #=> 42\nglobal_variables.each do |v|\n puts eval(v)\nend\n</code></pre>\n\n<p>The last 2 of the 5 mentioned at the beginning must be evaluated at the module level (a class is a descendant of a module, so that works).</p>\n\n<pre><code>Object.class_variables #=> []\nObject.constants #=> [\"IO\", \"Duration\", \"UNIXserver\", \"Binding\", ...]\n\nclass MyClass\n A_CONST = 'pshh'\n class InnerClass\n end\n def initialize\n @@meh = \"class_var\"\n end\nend\n\nMyClass.constants #=> [\"A_CONST\", \"InnerClass\"]\nMyClass.class_variables #=> []\nmc = MyClass.new\nMyClass.class_variables #=> [\"@@meh\"]\nMyClass.class_eval \"@@meh\" #=> \"class_var\"\n</code></pre>\n\n<p>Here's are a few more tricks to explore in different directions</p>\n\n<pre><code>\"\".class #=> String\n\"\".class.ancestors #=> [String, Enumerable, Comparable, ...]\nString.ancestors #=> [String, Enumerable, Comparable, ...]\n\ndef trace\n return caller\nend\ntrace #=> [\"(irb):67:in `irb_binding'\", \"/System/Library/Frameworks/Ruby...\", ...]\n</code></pre>\n"
},
{
"answer_id": 4132930,
"author": "Tomtt",
"author_id": 501795,
"author_profile": "https://Stackoverflow.com/users/501795",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a gem for that:</p>\n\n<pre><code>$ gem install method_info\n$ rvm use 1.8.7 # (1.8.6 works but can be very slow for an object with a lot of methods)\n$ irb\n> require 'method_info'\n> 5.method_info\n::: Fixnum :::\n%, &, *, **, +, -, -@, /, <, <<, <=, <=>, ==, >, >=, >>, [], ^, abs,\ndiv, divmod, even?, fdiv, id2name, modulo, odd?, power!, quo, rdiv,\nrpower, size, to_f, to_s, to_sym, zero?, |, ~\n::: Integer :::\nceil, chr, denominator, downto, floor, gcd, gcdlcm, integer?, lcm,\nnext, numerator, ord, pred, round, succ, taguri, taguri=, times, to_i,\nto_int, to_r, to_yaml, truncate, upto\n::: Precision :::\nprec, prec_f, prec_i\n::: Numeric :::\n+@, coerce, eql?, nonzero?, pretty_print, pretty_print_cycle,\nremainder, singleton_method_added, step\n::: Comparable :::\nbetween?\n::: Object :::\nclone, to_yaml_properties, to_yaml_style, what?\n::: MethodInfo::ObjectMethod :::\nmethod_info\n::: Kernel :::\n===, =~, __clone__, __id__, __send__, class, display, dup, enum_for,\nequal?, extend, freeze, frozen?, hash, id, inspect, instance_eval,\ninstance_exec, instance_of?, instance_variable_defined?,\ninstance_variable_get, instance_variable_set, instance_variables,\nis_a?, kind_of?, method, methods, nil?, object_id, pretty_inspect,\nprivate_methods, protected_methods, public_methods, respond_to?, ri,\nsend, singleton_methods, taint, tainted?, tap, to_a, to_enum, type,\nuntaint\n => nil\n</code></pre>\n\n<p>I am working on an improvement of passing options and settings defaults, but for now I would suggest you add the following to your .irbrc file:</p>\n\n<pre><code>require 'method_info'\nMethodInfo::OptionHandler.default_options = {\n :ancestors_to_exclude => [Object],\n :enable_colors => true\n}\n</code></pre>\n\n<p>This enables colours and hides the methods that every object has, since you're usually not interested in those.</p>\n"
},
{
"answer_id": 38624205,
"author": "MarioR",
"author_id": 6647036,
"author_profile": "https://Stackoverflow.com/users/6647036",
"pm_score": 2,
"selected": false,
"text": "<p>What about:</p>\n\n<pre><code>Object.constants.select{|x| eval(x.to_s).class == Class}\n</code></pre>\n\n<p>That lists available classes for me. I am not ruby expert and I was being dropped at a ruby console with no idea of what classes were at hand. That one liner was a start.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24718/"
] |
I'm new to ruby and I'm playing around with the IRB.
I found that I can list methods of an object using the ".methods" method, and that self.methods sort of give me what I want (similar to Python's dir(**builtins**)?), but how can I find the methods of a library/module I've loaded via include and require?
```
irb(main):036:0* self.methods
=> ["irb_pop_binding", "inspect", "taguri", "irb_chws", "clone", "irb_pushws", "public_methods", "taguri=", "irb_pwws",
"public", "display", "irb_require", "irb_exit", "instance_variable_defined?", "irb_cb", "equal?", "freeze", "irb_context
", "irb_pop_workspace", "irb_cwb", "irb_jobs", "irb_bindings", "methods", "irb_current_working_workspace", "respond_to?"
, "irb_popb", "irb_cws", "fg", "pushws", "conf", "dup", "cwws", "instance_variables", "source", "cb", "kill", "help", "_
_id__", "method", "eql?", "irb_pwb", "id", "bindings", "send", "singleton_methods", "popb", "irb_kill", "chws", "taint",
"irb_push_binding", "instance_variable_get", "frozen?", "irb_source", "pwws", "private", "instance_of?", "__send__", "i
rb_workspaces", "to_a", "irb_quit", "to_yaml_style", "irb_popws", "irb_change_workspace", "jobs", "type", "install_alias
_method", "irb_push_workspace", "require_gem", "object_id", "instance_eval", "protected_methods", "irb_print_working_wor
kspace", "irb_load", "require", "==", "cws", "===", "irb_pushb", "instance_variable_set", "irb_current_working_binding",
"extend", "kind_of?", "context", "gem", "to_yaml_properties", "quit", "popws", "irb", "to_s", "to_yaml", "irb_fg", "cla
ss", "hash", "private_methods", "=~", "tainted?", "include", "irb_cwws", "irb_change_binding", "irb_help", "untaint", "n
il?", "pushb", "exit", "irb_print_working_binding", "is_a?", "workspaces"]
irb(main):037:0>
```
I'm used to python, where I use the dir() function to accomplish the same thing:
```
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
```
|
[ObjectSpace.each\_object](http://www.ruby-doc.org/core-1.8.7/classes/ObjectSpace.html#M000928) could be what you are looking for.
To get a list of included modules you could use [Module.included\_modules](http://www.ruby-doc.org/core/classes/Module.html#M001697).
You can also check if an object responds to a method on a case-by-case basis using [object.respond\_to?](http://ruby-doc.org/core/classes/Object.html#M000333).
|
228,680 |
<p>How does one import CSV files via Excel VBA in a set, in groups or in multiple individual files, rather than one at a time?</p>
|
[
{
"answer_id": 228717,
"author": "jdecuyper",
"author_id": 296,
"author_profile": "https://Stackoverflow.com/users/296",
"pm_score": 0,
"selected": false,
"text": "<p>You could write a simple console application to parse a batch of csv files and save them to excel files.<br />\nNot the easiest solution but it could be an option.</p>\n"
},
{
"answer_id": 228973,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 1,
"selected": false,
"text": "<p>This will get a file into a one dimensional array quickly</p>\n\n<pre><code>Open \"myfile.csv\" For Input As 1\nDim Txt As String\nTxt = Input(LOF(1), 1)\nClose #1\nDim V As Variant\nV = Split(Txt, \",\")\n</code></pre>\n\n<p>Then V contains all the items in a single column, NB first item is V(0)</p>\n"
},
{
"answer_id": 231640,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "<p>I am a bit puzzled in that most versions of Excel will open .csv files with out any problems.</p>\n\n<pre><code>strPath = \"C:\\Docs\\\"\nstrFile = Dir(strPath & \"*.csv\")\n\nDo While strFile <> \"\"\n Workbooks.Open Filename:=strPath & strFile\n ActiveWorkbook.SaveAs Filename:=strPath & Mid(strFile, 1, InStr(strFile, \".\") - 1) _\n & \"Conv.xls\", FileFormat:=xlNormal\n\n strFile = Dir\nLoop\n</code></pre>\n"
},
{
"answer_id": 235692,
"author": "Jon Fournier",
"author_id": 5106,
"author_profile": "https://Stackoverflow.com/users/5106",
"pm_score": 0,
"selected": false,
"text": "<p>you can also use workbooks.opentext</p>\n"
},
{
"answer_id": 245649,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>The idea I had originally was as follows. Given this data</p>\n\n<pre><code>Dog Names,Dog Ages,Collar Size\nWoof,3,4\nBowser,2,5\nRuffy,4.5,6\nAngel,1,7\nDemon,7,8\nDog,9,2\n</code></pre>\n\n<p>create three global arrays, called <code>Dog_Names</code>, <code>Dog_Ages</code> and <code>Collar_Size</code> and populate them with the data in the CSV file.</p>\n\n<p>This bit of VBScript does that job and displays the results. Remove the comment mark from the <code>wscript.echo</code> in the <code>x</code> subroutine to see it all happen.</p>\n\n<pre><code>Option Explicit\n\nDim FSO\nSet FSO = CreateObject( \"Scripting.FileSystemObject\" )\n\nDim oStream\nDim sData\nDim aData\n\nSet oStream = fso.OpenTextFile(\"data.csv\")\nsData = oStream.ReadAll\naData = Split( sData, vbNewLine )\n\nDim sLine\nsLine = aData(0)\n\nDim aContent\naContent = Split( sLine, \",\" )\n\nDim aNames()\nDim nArrayCount\nnArrayCount = UBound( aContent )\nReDim aNames( nArrayCount )\n\nDim i\n\nFor i = 0 To nArrayCount\n aNames(i) = Replace( aContent( i ), \" \", \"_\" )\n x \"dim \" & aNames(i) & \"()\"\nNext\n\nFor j = 0 To nArrayCount\n x \"redim \" & aNames(j) & \"( \" & UBound( aData ) - 1 & \" )\"\nNext\n\nDim j\nDim actual\nactual = 0\n\nFor i = 1 To UBound( aData )\n sLine = aData( i )\n If sLine <> vbnullstring Then\n actual = actual + 1\n aContent = Split( sLine, \",\" )\n For j = 0 To nArrayCount\n x aNames(j) & \"(\" & i - 1 & \")=\" & Chr(34) & aContent(j) & Chr(34)\n Next\n End If\nNext\n\nFor j = 0 To nArrayCount\n x \"redim preserve \" & aNames(j) & \"(\" & actual - 1 & \")\"\nNext\n\nFor i = 0 To actual - 1\n For j = 0 To nArrayCount\n x \"wscript.echo aNames(\" & j & \"),\" & aNames(j) & \"(\" & i & \")\"\n Next\nNext\n\nSub x( s )\n 'wscript.echo s\n executeglobal s\nEnd Sub\n</code></pre>\n\n<p>The result looks like this</p>\n\n<pre><code>>cscript \"C:\\Documents and Settings\\Bruce\\Desktop\\datathing.vbs\"\nDog_Names Woof\nDog_Ages 3\nCollar_Size 4\nDog_Names Bowser\nDog_Ages 2\nCollar_Size 5\nDog_Names Ruffy\nDog_Ages 4.5\nCollar_Size 6\nDog_Names Angel\nDog_Ages 1\nCollar_Size 7\nDog_Names Demon\nDog_Ages 7\nCollar_Size 8\nDog_Names Dog\nDog_Ages 9\nCollar_Size 2\n>Exit code: 0 Time: 0.338\n</code></pre>\n"
},
{
"answer_id": 6384945,
"author": "njt",
"author_id": 803119,
"author_profile": "https://Stackoverflow.com/users/803119",
"pm_score": 1,
"selected": false,
"text": "<p>This is another way that avoids the recalc you get when opening a csv file in Excel.</p>\n\n<p>Add a blank sheet to your workbook and add the following code the sheet's object</p>\n\n<pre><code>Function getCsv(fn)\n Dim d, scrup As Boolean\n scrup = Application.ScreenUpdating\n Application.ScreenUpdating = False\n With Me.QueryTables.Add( _\n Connection:=\"TEXT;\" & fn, _\n Destination:=Me.Range(\"A1\") _\n )\n .Name = \"data\"\n .FieldNames = True\n .RowNumbers = False\n .FillAdjacentFormulas = False\n .PreserveFormatting = True\n .RefreshStyle = xlOverwriteCells\n .SavePassword = False\n .SaveData = True\n .AdjustColumnWidth = False\n .TextFilePromptOnRefresh = False\n .TextFilePlatform = 850\n .TextFileStartRow = 1\n .TextFileParseType = xlDelimited\n .TextFileTextQualifier = xlTextQualifierDoubleQuote\n .TextFileCommaDelimiter = True\n .Refresh BackgroundQuery:=False\n End With\n\n d = Me.Names(1).RefersToRange.Value\n\n Me.Names(1).Delete\n Me.UsedRange.Rows.Delete\n\n Application.ScreenUpdating = scrup\n getCsv = d\nEnd Function\n</code></pre>\n\n<p>You might also want to hide the sheet, so that no one accidentally uses it.\nThen you can use like this</p>\n\n<pre><code>dim d\nd = getCsv(\"C:\\temp\\some.csv\")\n</code></pre>\n\n<p>One thing that slightly concerns me is that the Name gets incremented each time you use the function (e.g. data_1, data_2, ...), so there might be a stability issue if these names get saved somewhere.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How does one import CSV files via Excel VBA in a set, in groups or in multiple individual files, rather than one at a time?
|
I am a bit puzzled in that most versions of Excel will open .csv files with out any problems.
```
strPath = "C:\Docs\"
strFile = Dir(strPath & "*.csv")
Do While strFile <> ""
Workbooks.Open Filename:=strPath & strFile
ActiveWorkbook.SaveAs Filename:=strPath & Mid(strFile, 1, InStr(strFile, ".") - 1) _
& "Conv.xls", FileFormat:=xlNormal
strFile = Dir
Loop
```
|
228,684 |
<p>If I have a source.c file with a struct:</p>
<pre><code>struct a {
int i;
struct b {
int j;
}
};
</code></pre>
<p>How can this struct be used in another file (i.e. <code>func.c</code>)?</p>
<p>Should I create a new header file, declare the struct there and include that header in <code>func.c</code>?</p>
<p>Or should I define the whole struct in a header file and include that in both <code>source.c</code> and <code>func.c</code>? How can the struct be declared <code>extern</code> in both files?</p>
<p>Should I <code>typedef</code> it? If so, how?</p>
|
[
{
"answer_id": 228689,
"author": "fmsf",
"author_id": 26004,
"author_profile": "https://Stackoverflow.com/users/26004",
"pm_score": 3,
"selected": false,
"text": "<p>a.h:</p>\n\n<pre><code>#ifndef A_H\n#define A_H\n\nstruct a { \n int i;\n struct b {\n int j;\n }\n};\n\n#endif\n</code></pre>\n\n<p>there you go, now you just need to include a.h to the files where you want to use this structure.</p>\n"
},
{
"answer_id": 228691,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": "<p>For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.</p>\n\n<p>The <code>extern</code> declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as <code>extern</code> in a header file like:</p>\n\n<pre><code>extern struct a myAValue;\n</code></pre>\n\n<p>Then, in <em>one</em> source file, define the actual variable:</p>\n\n<pre><code>struct a myAValue;\n</code></pre>\n\n<p>If you forget to do this or accidentally define it in two source files, the linker will let you know about this.</p>\n"
},
{
"answer_id": 228757,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": false,
"text": "<h3>if this structure is to be used by some other file func.c how to do it?</h3>\n<p>When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.</p>\n<p>The right way is putting it in an header file, and include this header file whenever needed.</p>\n<h3>shall we open a new header file and declare the structure there and include that header in the func.c?</h3>\n<p>This is the solution I like more, because it makes the code highly modular. I would code your struct as:</p>\n<pre><code>#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME\n#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME\n\nstruct a\n{ \n int i;\n struct b\n {\n int j;\n }\n};\n\n#endif\n</code></pre>\n<p>I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").</p>\n<p>And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.</p>\n<p>If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:</p>\n<pre><code>struct a ;\n</code></pre>\n<p>Will be enough, and it decreases coupling.</p>\n<h3>or can we define the total structure in header file and include that in both source.c and func.c?</h3>\n<p>This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.</p>\n<p>In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.</p>\n<h3>then how to declare that structure as extern in both the files. ?</h3>\n<p>I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post <a href=\"https://stackoverflow.com/questions/228684/how-to-declare-a-structure-in-a-header-that-is-to-be-used-by-multiple-files-in-c#228691\">How to declare a structure in a header that is to be used by multiple files in c?</a>.</p>\n<h3>shall we typedef it then how?</h3>\n<ul>\n<li>If you are using C++, don't.</li>\n<li>If you are using C, you should.</li>\n</ul>\n<p>The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:</p>\n<pre><code>struct MyStruct ; /* Forward declaration */\n\nstruct MyStruct\n{\n /* etc. */\n} ;\n\nvoid doSomething(struct MyStruct * p) /* parameter */\n{\n struct MyStruct a ; /* variable */\n /* etc */\n}\n</code></pre>\n<p>While a typedef will enable you to write it without the struct keyword.</p>\n<pre><code>struct MyStructTag ; /* Forward declaration */\n\ntypedef struct MyStructTag\n{\n /* etc. */\n} MyStruct ;\n\nvoid doSomething(MyStruct * p) /* parameter */\n{\n MyStruct a ; /* variable */\n /* etc */\n}\n</code></pre>\n<p>It is <strong>important</strong> you still keep a name for the struct. Writing:</p>\n<pre><code>typedef struct\n{\n /* etc. */\n} MyStruct ;\n</code></pre>\n<p>will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:</p>\n<pre><code>typedef struct MyStructTag\n{\n /* etc. */\n} MyStruct ;\n</code></pre>\n<p>Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)</p>\n<h3>Edit:</h3>\n<p>Corrected wrong assumption about C99 struct declaration, as rightfully remarked by <a href=\"https://stackoverflow.com/users/15168/jonathan-leffler\">Jonathan Leffler</a>.</p>\n<h3>Edit 2018-06-01:</h3>\n<p><a href=\"https://stackoverflow.com/users/1471119/craig-barnes\">Craig Barnes</a> reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.</p>\n<p>Indeed, the code above could well be written as:</p>\n<pre><code>typedef struct MyStruct\n{\n /* etc. */\n} MyStruct ;\n</code></pre>\n<p>IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:</p>\n<pre><code>// C++ explicit declaration by the user\nstruct MyStruct\n{\n /* etc. */\n} ;\n// C++ standard then implicitly adds the following line\ntypedef MyStruct MyStruct;\n</code></pre>\n<p>Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use <a href=\"https://stackoverflow.com/questions/3793952/\">C separate "namespaces" for structs and other symbols</a>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
If I have a source.c file with a struct:
```
struct a {
int i;
struct b {
int j;
}
};
```
How can this struct be used in another file (i.e. `func.c`)?
Should I create a new header file, declare the struct there and include that header in `func.c`?
Or should I define the whole struct in a header file and include that in both `source.c` and `func.c`? How can the struct be declared `extern` in both files?
Should I `typedef` it? If so, how?
|
### if this structure is to be used by some other file func.c how to do it?
When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.
The right way is putting it in an header file, and include this header file whenever needed.
### shall we open a new header file and declare the structure there and include that header in the func.c?
This is the solution I like more, because it makes the code highly modular. I would code your struct as:
```
#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME
struct a
{
int i;
struct b
{
int j;
}
};
#endif
```
I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").
And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.
If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:
```
struct a ;
```
Will be enough, and it decreases coupling.
### or can we define the total structure in header file and include that in both source.c and func.c?
This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.
In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.
### then how to declare that structure as extern in both the files. ?
I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post [How to declare a structure in a header that is to be used by multiple files in c?](https://stackoverflow.com/questions/228684/how-to-declare-a-structure-in-a-header-that-is-to-be-used-by-multiple-files-in-c#228691).
### shall we typedef it then how?
* If you are using C++, don't.
* If you are using C, you should.
The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:
```
struct MyStruct ; /* Forward declaration */
struct MyStruct
{
/* etc. */
} ;
void doSomething(struct MyStruct * p) /* parameter */
{
struct MyStruct a ; /* variable */
/* etc */
}
```
While a typedef will enable you to write it without the struct keyword.
```
struct MyStructTag ; /* Forward declaration */
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
void doSomething(MyStruct * p) /* parameter */
{
MyStruct a ; /* variable */
/* etc */
}
```
It is **important** you still keep a name for the struct. Writing:
```
typedef struct
{
/* etc. */
} MyStruct ;
```
will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:
```
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
```
Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)
### Edit:
Corrected wrong assumption about C99 struct declaration, as rightfully remarked by [Jonathan Leffler](https://stackoverflow.com/users/15168/jonathan-leffler).
### Edit 2018-06-01:
[Craig Barnes](https://stackoverflow.com/users/1471119/craig-barnes) reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.
Indeed, the code above could well be written as:
```
typedef struct MyStruct
{
/* etc. */
} MyStruct ;
```
IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:
```
// C++ explicit declaration by the user
struct MyStruct
{
/* etc. */
} ;
// C++ standard then implicitly adds the following line
typedef MyStruct MyStruct;
```
Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use [C separate "namespaces" for structs and other symbols](https://stackoverflow.com/questions/3793952/).
|
228,702 |
<p>Say I have the classic 4-byte signed integer, and I want something like</p>
<pre><code>print hex(-1)
</code></pre>
<p>to give me something like</p>
<blockquote>
<p>0xffffffff</p>
</blockquote>
<p>In reality, the above gives me <code>-0x1</code>. I'm dawdling about in some lower level language, and python commandline is quick n easy.</p>
<p>So.. is there a way to do it?</p>
|
[
{
"answer_id": 228708,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 6,
"selected": true,
"text": "<p>This will do the trick:</p>\n<pre><code>>>> print(hex (-1 & 0xffffffff))\n0xffffffff\n</code></pre>\n<p>or, a variant that always returns fixed size (there may well be a better way to do this):</p>\n<pre><code>>>> def hex3(n):\n... return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]\n...\n>>> print hex3(-1)\n0xffffffff\n>>> print hex3(17)\n0x00000011\n</code></pre>\n<p>Or, avoiding the hex() altogether, thanks to Ignacio and bobince:</p>\n<pre><code>def hex2(n):\n return "0x%x"%(n&0xffffffff)\n\ndef hex3(n):\n return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]\n</code></pre>\n"
},
{
"answer_id": 228785,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 2,
"selected": false,
"text": "<p>Try this function:</p>\n\n<pre><code>'%#4x' % (-1 & 0xffffffff)\n</code></pre>\n"
},
{
"answer_id": 39483945,
"author": "Sai Gautam",
"author_id": 4499207,
"author_profile": "https://Stackoverflow.com/users/4499207",
"pm_score": 2,
"selected": false,
"text": "<p>Use</p>\n<pre class=\"lang-py prettyprint-override\"><code>"0x{:04x}".format((int(my_num) & 0xFFFF), '04x')\n</code></pre>\n<p>where <code>my_num</code> is the required number.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23648/"
] |
Say I have the classic 4-byte signed integer, and I want something like
```
print hex(-1)
```
to give me something like
>
> 0xffffffff
>
>
>
In reality, the above gives me `-0x1`. I'm dawdling about in some lower level language, and python commandline is quick n easy.
So.. is there a way to do it?
|
This will do the trick:
```
>>> print(hex (-1 & 0xffffffff))
0xffffffff
```
or, a variant that always returns fixed size (there may well be a better way to do this):
```
>>> def hex3(n):
... return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x00000011
```
Or, avoiding the hex() altogether, thanks to Ignacio and bobince:
```
def hex2(n):
return "0x%x"%(n&0xffffffff)
def hex3(n):
return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]
```
|
228,705 |
<p>I know I'm gonna get down votes, but I have to make sure if this is logical or not.</p>
<p>I have three tables A, B, C. B is a table used to make a many-many relationship between A and C. But the thing is that A and C are also related directly in a 1-many relationship</p>
<p>A customer added the following requirement:</p>
<p>Obtain the information from the Table B inner joining with A and C, and in the same query relate A and C in a one-many relationship</p>
<p>Something like:</p>
<p><a href="http://img247.imageshack.us/img247/7371/74492374sa4.png" rel="nofollow noreferrer">alt text http://img247.imageshack.us/img247/7371/74492374sa4.png</a></p>
<p>I tried doing the query but always got 0 rows back. The customer insists that I can accomplish the requirement, but I doubt it. Any comments?</p>
<p>PS. I didn't have a more descriptive title, any ideas?</p>
<p>UPDATE:
Thanks to rcar, In some cases this can be logical, in order to have a history of all the classes a student has taken (supposing the student can only take one class at a time)</p>
<p>UPDATE:
There is a table for Contacts, a table with the Information of each Contact, and the Relationship table. To get the information of a Contact I have to make a 1:1 relationship with Information, and each contact can have like and an address book with; this is why the many-many relationship is implemented.</p>
<p>The full idea is to obtain the contact's name and his address book.
Now that I got the customer's idea... I'm having trouble with the query, basically I am trying to use the query that jdecuyper wrote, but as he warns, I get no data back</p>
|
[
{
"answer_id": 228739,
"author": "jdecuyper",
"author_id": 296,
"author_profile": "https://Stackoverflow.com/users/296",
"pm_score": 1,
"selected": false,
"text": "<p>It doesn't seem to make sense. A query like: </p>\n\n<pre><code>SELECT * FROM relAC RAC\n INNER JOIN tableA A ON A.id_class = RAC.id_class \n INNER JOIN tableC C ON C.id_class = RAC.id_class \n WHERE A.id_class = B.id_class\n</code></pre>\n\n<p>could generate a set of data but inconsistent. Or maybe we are missing some important part of the information about the content and the relationships of those 3 tables. </p>\n"
},
{
"answer_id": 228742,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 3,
"selected": false,
"text": "<p>This is a doable scenario. You can join a table twice in a query, usually assigning it a different alias to keep things straight.</p>\n\n<p>For example:</p>\n\n<pre><code>SELECT s.name AS \"student name\", c1.className AS \"student class\", c2.className as \"class list\"\nFROM s\nJOIN many_to_many mtm ON s.id_student = mtm.id_student\nJOIN c c1 ON s.id_class = c1.id_class\nJOIN c c2 ON mtm.id_class = c2.id_class\n</code></pre>\n\n<p>This will give you a list of all students' names and \"hardcoded\" classes with all their classes from the many_to_many table.</p>\n\n<p>That said, this schema doesn't make logical sense. From what I can gather, you want students to be able to have multiple classes, so the many_to_many table should be where you'd want to find the classes associated with a student. If the id_class entries used in table s are distinct from those in many_to_many (e.g., if s.id_class refers to, say, homeroom class assignments that only appear in that table while many_to_many.id_class refers to classes for credit and excludes homeroom classes), you're going to be better off splitting c into two tables instead.</p>\n\n<p>If that's not the case, I have a hard time understanding why you'd want one class hardwired to the s table.</p>\n\n<p>EDIT: Just saw your comment that this was a made-up schema to give an example. In other cases, this could be a sensible way to do things. For example, if you wanted to keep track of company locations, you might have a Company table, a Locations table, and a Countries table. The Company table might have a 1-many link to Countries where you would keep track of a company's headquarters country, but a many-to-many link through Locations where you keep track of every place the company has a store.</p>\n\n<p>If you can give real information as to what the schema really represents for your client, it might be easier for us to figure out whether it's logical in this case or not.</p>\n"
},
{
"answer_id": 228744,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps it's a lack of caffeine, but I can't conceive of a legitimate reason for wanting to do this. In the example you gave, you've got students, classes and a table which relates the two. If you think about what you want the query to do, in plain English, surely it has to be driven by either the <code>student</code> table or the <code>class</code> table. i.e. </p>\n\n<ul>\n<li>select all the classes which are attended by student 1245235</li>\n<li>select all the students which attend class 101</li>\n</ul>\n\n<p>Can you explain the requirement better? If not, tell your customer to suck it up. Having a relationship between Students and Classes directly (A and C), seems like pure madness, you've already got table B which does that...</p>\n"
},
{
"answer_id": 229199,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 2,
"selected": false,
"text": "<p>Bear in mind that the one-to-many relationship can be represented through the many-to-many, most simply by adding a field there to indicate the type of relationship. Then you could have one \"current\" record and any number of \"history\" ones.</p>\n\n<p>Was the customer \"requirement\" phrased as given, by the way? I think I'd be looking to redefine my relationship with them if so: they should be telling me \"what\" they want (ideally what, in business domain language, their problem is) and leaving the \"how\" to me. If they know exactly how the thing should be implemented, then I'd be inclined to open the source code in an editor and leave them to it!</p>\n"
},
{
"answer_id": 229246,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 0,
"selected": false,
"text": "<p>I personally never heard a requirement from a customer that would sound like:</p>\n\n<blockquote>\n <p>Obtain the information from the Table\n B inner joining with A and C, and in\n the same query relate A and C in a\n one-many relationship</p>\n</blockquote>\n\n<p>It looks like that it is what you translated the requirement to. \nCould you specify the requirement in plain English, as what results your customer wants to get?</p>\n"
},
{
"answer_id": 231081,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "<p>I'm supposing that s.id_class indicates the student's current class, as opposed to classes she has taken in the past. </p>\n\n<p>The solution shown by rcar works, but it repeats the c1.className on every row.</p>\n\n<p>Here's an alternative that doesn't repeat information and it uses one fewer join. You can use an expression to compare s.id_class to the current c.id_class matched via the mtm table.</p>\n\n<pre><code>SELECT s.name, c.className, (s.id_class = c.id_class) AS is_current\nFROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student)\n JOIN c ON (c.id_class = mtm.id_class);\n</code></pre>\n\n<p>So is_current will be 1 (true) on one row, and 0 (false) on all the other rows. Or you can output something more informative using a <code>CASE</code> construct:</p>\n\n<pre><code>SELECT s.name, c.className, \n CASE WHEN s.id_class = c.id_class THEN 'current' ELSE 'past' END AS is_current\nFROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student)\n JOIN c ON (c.id_class = mtm.id_class);\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23146/"
] |
I know I'm gonna get down votes, but I have to make sure if this is logical or not.
I have three tables A, B, C. B is a table used to make a many-many relationship between A and C. But the thing is that A and C are also related directly in a 1-many relationship
A customer added the following requirement:
Obtain the information from the Table B inner joining with A and C, and in the same query relate A and C in a one-many relationship
Something like:
[alt text http://img247.imageshack.us/img247/7371/74492374sa4.png](http://img247.imageshack.us/img247/7371/74492374sa4.png)
I tried doing the query but always got 0 rows back. The customer insists that I can accomplish the requirement, but I doubt it. Any comments?
PS. I didn't have a more descriptive title, any ideas?
UPDATE:
Thanks to rcar, In some cases this can be logical, in order to have a history of all the classes a student has taken (supposing the student can only take one class at a time)
UPDATE:
There is a table for Contacts, a table with the Information of each Contact, and the Relationship table. To get the information of a Contact I have to make a 1:1 relationship with Information, and each contact can have like and an address book with; this is why the many-many relationship is implemented.
The full idea is to obtain the contact's name and his address book.
Now that I got the customer's idea... I'm having trouble with the query, basically I am trying to use the query that jdecuyper wrote, but as he warns, I get no data back
|
I'm supposing that s.id\_class indicates the student's current class, as opposed to classes she has taken in the past.
The solution shown by rcar works, but it repeats the c1.className on every row.
Here's an alternative that doesn't repeat information and it uses one fewer join. You can use an expression to compare s.id\_class to the current c.id\_class matched via the mtm table.
```
SELECT s.name, c.className, (s.id_class = c.id_class) AS is_current
FROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student)
JOIN c ON (c.id_class = mtm.id_class);
```
So is\_current will be 1 (true) on one row, and 0 (false) on all the other rows. Or you can output something more informative using a `CASE` construct:
```
SELECT s.name, c.className,
CASE WHEN s.id_class = c.id_class THEN 'current' ELSE 'past' END AS is_current
FROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student)
JOIN c ON (c.id_class = mtm.id_class);
```
|
228,724 |
<p>Im creating a report using crystal report in vb.net.</p>
<p>The report contained a crosstab which I have 3 data:
1. Dealer - row field
2. Month - column
3. Quantity Sales - summarize field</p>
<p>How can I arrange this by ascending order based on the
Quantity Sales - summarize field?</p>
<p>thanks</p>
|
[
{
"answer_id": 234541,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on how you're working with it, you can adjust the input to order the data ascending.</p>\n\n<blockquote>\n<pre><code>SELECT customer, sum(amountdue) AS total FROM invoices \nGROUP BY customer\nORDER BY total ASC\n</code></pre>\n</blockquote>\n\n<p>If you're doing in a way that you can't change that information, could you provide a little more insight?</p>\n"
},
{
"answer_id": 234568,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 0,
"selected": false,
"text": "<p>Note that other Business Objects products order on the total of a summary field when sorting a cross tab by it's values. I forget how CR does it exactly.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Im creating a report using crystal report in vb.net.
The report contained a crosstab which I have 3 data:
1. Dealer - row field
2. Month - column
3. Quantity Sales - summarize field
How can I arrange this by ascending order based on the
Quantity Sales - summarize field?
thanks
|
Depending on how you're working with it, you can adjust the input to order the data ascending.
>
>
> ```
> SELECT customer, sum(amountdue) AS total FROM invoices
> GROUP BY customer
> ORDER BY total ASC
>
> ```
>
>
If you're doing in a way that you can't change that information, could you provide a little more insight?
|
228,726 |
<p>The coding is done using VS2008
There are two divs in my page namely "dvLeftContent" and "dvRightContent".
I cannot statically set the height of the pages since "dvRightContent" have variable heights on various pages (Master Pages are used here)
Is there a client side function(javascript or jquery) that takes the height of the right div and assigns it to left div?</p>
|
[
{
"answer_id": 234541,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on how you're working with it, you can adjust the input to order the data ascending.</p>\n\n<blockquote>\n<pre><code>SELECT customer, sum(amountdue) AS total FROM invoices \nGROUP BY customer\nORDER BY total ASC\n</code></pre>\n</blockquote>\n\n<p>If you're doing in a way that you can't change that information, could you provide a little more insight?</p>\n"
},
{
"answer_id": 234568,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 0,
"selected": false,
"text": "<p>Note that other Business Objects products order on the total of a summary field when sorting a cross tab by it's values. I forget how CR does it exactly.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17447/"
] |
The coding is done using VS2008
There are two divs in my page namely "dvLeftContent" and "dvRightContent".
I cannot statically set the height of the pages since "dvRightContent" have variable heights on various pages (Master Pages are used here)
Is there a client side function(javascript or jquery) that takes the height of the right div and assigns it to left div?
|
Depending on how you're working with it, you can adjust the input to order the data ascending.
>
>
> ```
> SELECT customer, sum(amountdue) AS total FROM invoices
> GROUP BY customer
> ORDER BY total ASC
>
> ```
>
>
If you're doing in a way that you can't change that information, could you provide a little more insight?
|
228,730 |
<p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
|
[
{
"answer_id": 228734,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this?</p>\n\n<pre><code>for letter in range(ord('a'), ord('z') + 1):\n print chr(letter) + \":\", lowertext.count(chr(letter))\n</code></pre>\n"
},
{
"answer_id": 228762,
"author": "Matthew Trevor",
"author_id": 11265,
"author_profile": "https://Stackoverflow.com/users/11265",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>the question is how to make\n allTheLetters equal to said letters\n without something like allTheLetters =\n \"abcdefg...xyz\"</p>\n</blockquote>\n\n<p>That's actually provided by the string module, it's not like you have to manually type it yourself ;)</p>\n\n<pre><code>import string\n\nallTheLetters = string.ascii_lowercase\n\ndef alphCount(text):\n lowerText = text.lower()\n for letter in allTheLetters: \n print letter + \":\", lowertext.count(letter)\n</code></pre>\n"
},
{
"answer_id": 228766,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "<p>Do you mean using:</p>\n\n<pre><code>import string\nstring.ascii_lowercase\n</code></pre>\n\n<p>then,</p>\n\n<pre><code>counters = dict()\nfor letter in string.ascii_lowercase:\n counters[letter] = lowertext.count(letter)\n</code></pre>\n\n<p>All lowercase letters are accounted for, missing counters will have zero value.</p>\n\n<p>using generators:</p>\n\n<pre><code>counters = \n dict( (letter,lowertext.count(letter)) for letter in string.ascii_lowercase )\n</code></pre>\n"
},
{
"answer_id": 228790,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": "<p>If you just want to do a frequency count of a string, try this:</p>\n\n<pre><code>s = 'hi there'\nf = {}\n\nfor c in s:\n f[c] = f.get(c, 0) + 1\n\nprint f\n</code></pre>\n"
},
{
"answer_id": 228845,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 2,
"selected": false,
"text": "<p>Main question is \"iterate through the alphabet\":</p>\n\n<pre><code>import string\nfor c in string.lowercase:\n print c\n</code></pre>\n\n<p>How get letter frequencies with some efficiency and without counting non-letter characters:</p>\n\n<pre><code>import string\n\nsample = \"Hello there, this is a test!\"\nletter_freq = dict((c,0) for c in string.lowercase)\n\nfor c in [c for c in sample.lower() if c.isalpha()]:\n letter_freq[c] += 1\n\nprint letter_freq\n</code></pre>\n"
},
{
"answer_id": 228850,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 7,
"selected": true,
"text": "<p>The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).</p>\n\n<p>You can use string.lowercase, as other posters have suggested:</p>\n\n<pre><code>import string\nallTheLetters = string.lowercase\n</code></pre>\n\n<p>To do things the way you're \"used to\", treating letters as numbers, you can use the \"ord\" and \"chr\" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:</p>\n\n<pre><code>def getAllTheLetters(begin='a', end='z'):\n beginNum = ord(begin)\n endNum = ord(end)\n for number in xrange(beginNum, endNum+1):\n yield chr(number)\n</code></pre>\n\n<p>You can tell it does the right thing because this code prints <code>True</code>:</p>\n\n<pre><code>import string\nprint ''.join(getAllTheLetters()) == string.lowercase\n</code></pre>\n\n<p>But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:</p>\n\n<pre><code>from collections import defaultdict \ndef letterOccurrances(string):\n frequencies = defaultdict(lambda: 0)\n for character in string:\n frequencies[character.lower()] += 1\n return frequencies\n</code></pre>\n\n<p>Use like so:</p>\n\n<pre><code>occs = letterOccurrances(\"Hello, world!\")\nprint occs['l']\nprint occs['h']\n</code></pre>\n\n<p>This will print '3' and '1' respectively.</p>\n\n<p>Note that this works for unicode as well:</p>\n\n<pre><code># -*- coding: utf-8 -*-\noccs = letterOccurrances(u\"héĺĺó, ẃóŕĺd!\")\nprint occs[u'l']\nprint occs[u'ĺ']\n</code></pre>\n\n<p>If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.</p>\n\n<p>To implement your original function (print the counts of each letter in alphabetical order) in terms of this:</p>\n\n<pre><code>def alphCount(text):\n for character, count in sorted(letterOccurrances(text).iteritems()):\n print \"%s: %s\" % (character, count)\n\nalphCount(\"hello, world!\")\n</code></pre>\n"
},
{
"answer_id": 8659737,
"author": "Kimvais",
"author_id": 180174,
"author_profile": "https://Stackoverflow.com/users/180174",
"pm_score": 2,
"selected": false,
"text": "<p>For counting objects, the <em>obvious</em> solution is the <a href=\"http://docs.python.org/dev/library/collections.html#collections.Counter\" rel=\"nofollow\">Counter</a></p>\n\n<pre><code>from collections import Counter\nimport string\n\nc = Counter()\nfor letter in text.lower():\n c[letter] += 1\n\nfor letter in string.lowercase:\n print(\"%s: %d\" % (letter, c[letter]))\n</code></pre>\n"
},
{
"answer_id": 10820994,
"author": "masnun",
"author_id": 301107,
"author_profile": "https://Stackoverflow.com/users/301107",
"pm_score": -1,
"selected": false,
"text": "<p>This is what I do:</p>\n\n<pre><code>import string\nfor x in list(string.lowercase):\n print x\n</code></pre>\n"
},
{
"answer_id": 14206285,
"author": "user1956583",
"author_id": 1956583,
"author_profile": "https://Stackoverflow.com/users/1956583",
"pm_score": 0,
"selected": false,
"text": "<p>How about this, to use letters, figures and punctuation (all usable to form a Django key):</p>\n\n<pre><code>import random\nimport string\n\nchars = string.letters + string.digits + string.punctuation\nchars_len = len(chars)\nn = 40\n\nprint(''.join([chars[random.randint(0, chars_len)] for i in range(n)]))\n</code></pre>\n\n<p>Example result: coOL:V!D+P,&S*hzbO{a0_6]2!{4|OIbVuAbq0:</p>\n"
},
{
"answer_id": 15001537,
"author": "guest",
"author_id": 2095294,
"author_profile": "https://Stackoverflow.com/users/2095294",
"pm_score": 0,
"selected": false,
"text": "<p>Just use:</p>\n\n<pre><code>import string\nstring.lowercase \nstring.uppercase\n</code></pre>\n\n<p>or</p>\n\n<pre><code>string.letters[:26] \nstring.letters[26:]\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?
This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.
```
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
```
|
The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).
You can use string.lowercase, as other posters have suggested:
```
import string
allTheLetters = string.lowercase
```
To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:
```
def getAllTheLetters(begin='a', end='z'):
beginNum = ord(begin)
endNum = ord(end)
for number in xrange(beginNum, endNum+1):
yield chr(number)
```
You can tell it does the right thing because this code prints `True`:
```
import string
print ''.join(getAllTheLetters()) == string.lowercase
```
But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:
```
from collections import defaultdict
def letterOccurrances(string):
frequencies = defaultdict(lambda: 0)
for character in string:
frequencies[character.lower()] += 1
return frequencies
```
Use like so:
```
occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']
```
This will print '3' and '1' respectively.
Note that this works for unicode as well:
```
# -*- coding: utf-8 -*-
occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!")
print occs[u'l']
print occs[u'ĺ']
```
If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.
To implement your original function (print the counts of each letter in alphabetical order) in terms of this:
```
def alphCount(text):
for character, count in sorted(letterOccurrances(text).iteritems()):
print "%s: %s" % (character, count)
alphCount("hello, world!")
```
|
228,775 |
<p>I'm trying to do some async stuff in a webservice method. Let say I have the following API call: <a href="http://www.example.com/api.asmx" rel="nofollow noreferrer">http://www.example.com/api.asmx</a></p>
<p>and the method is called <em>GetProducts()</em>.</p>
<p>I this GetProducts methods, I do some stuff (eg. get data from database) then just before i return the result, I want to do some async stuff (eg. send me an email).</p>
<p>So this is what I did.</p>
<pre><code>[WebMethod(Description = "Bal blah blah.")]
public IList<Product> GetProducts()
{
// Blah blah blah ..
// Get data from DB .. hi DB!
// var myData = .......
// Moar clbuttic blahs :) (yes, google for clbuttic if you don't know what that is)
// Ok .. now send me an email for no particular reason, but to prove that async stuff works.
var myObject = new MyObject();
myObject.SendDataAsync();
// Ok, now return the result.
return myData;
}
}
public class TrackingCode
{
public void SendDataAsync()
{
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += BackgroundWorker_DoWork;
backgroundWorker.RunWorkerAsync();
//System.Threading.Thread.Sleep(1000 * 20);
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
SendEmail();
}
}
</code></pre>
<p>Now, when I run this code the email is never sent. If I uncomment out the Thread.Sleep .. then the email is sent.</p>
<p>So ... why is it that the background worker thread is torn down? is it dependant on the parent thread? Is this the wrong way I should be doing background or forked threading, in asp.net web apps?</p>
|
[
{
"answer_id": 228798,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<p><code>BackgroundWorker</code> is useful when you need to synchronize back to (for example) a UI* thread, eg for affinity reasons. In this case, it would seem that simply using <code>ThreadPool</code> would be more than adequate (and much simpler). If you have high volumes, then a producer/consumer queue may allow better throttling (so you don't drown in threads) - but I suspect <code>ThreadPool</code> will be fine here...</p>\n\n<pre><code>public void SendDataAsync()\n{\n ThreadPool.QueueUserWorkItem(delegate\n {\n SendEmail();\n });\n}\n</code></pre>\n\n<p>Also - I'm not quite sure what you want to achieve by sleeping? This will just tie up a thread (not using CPU, but doing no good either). Care to elaborate? It <em>looks</em> like you are pausing your actual web page (i.e. the Sleep happens on the web-page thread, not the e-mail thread). What are you trying to do here?</p>\n\n<p>*=actually, it will use whatever sync-context is in place</p>\n"
},
{
"answer_id": 228830,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 0,
"selected": false,
"text": "<p>It may torn down because after 20 seconds, that BackgroundWorker instance may be garbage collected because it has no references (gone out of scope).</p>\n"
},
{
"answer_id": 241708,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>Re producer/consumer; basically - it is just worth keeping <em>some</em> kind of throttle. At the simplest level, a <code>Semaphore</code> could be used (along with the regular <code>ThreadPool</code>) to limit things to a known amount of work (to avoid saturating the thread pool); but a producer/consumer queue would probably be more efficient and managed.</p>\n\n<p>Jon Skeet has such a queue <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/\" rel=\"nofollow noreferrer\">here</a> (<code>CustomThreadPool</code>). I could probably write some notes about it if you wanted.</p>\n\n<p>That said: if you are calling off to an external web-site, it is quite likely that you will have a lot of waits on network IO / completion ports; as such, you can have a slightly higher number of threads... obviously (by contrast) if the work was CPU-bound, there is no point having more threads than you have CPU cores.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
I'm trying to do some async stuff in a webservice method. Let say I have the following API call: <http://www.example.com/api.asmx>
and the method is called *GetProducts()*.
I this GetProducts methods, I do some stuff (eg. get data from database) then just before i return the result, I want to do some async stuff (eg. send me an email).
So this is what I did.
```
[WebMethod(Description = "Bal blah blah.")]
public IList<Product> GetProducts()
{
// Blah blah blah ..
// Get data from DB .. hi DB!
// var myData = .......
// Moar clbuttic blahs :) (yes, google for clbuttic if you don't know what that is)
// Ok .. now send me an email for no particular reason, but to prove that async stuff works.
var myObject = new MyObject();
myObject.SendDataAsync();
// Ok, now return the result.
return myData;
}
}
public class TrackingCode
{
public void SendDataAsync()
{
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += BackgroundWorker_DoWork;
backgroundWorker.RunWorkerAsync();
//System.Threading.Thread.Sleep(1000 * 20);
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
SendEmail();
}
}
```
Now, when I run this code the email is never sent. If I uncomment out the Thread.Sleep .. then the email is sent.
So ... why is it that the background worker thread is torn down? is it dependant on the parent thread? Is this the wrong way I should be doing background or forked threading, in asp.net web apps?
|
`BackgroundWorker` is useful when you need to synchronize back to (for example) a UI\* thread, eg for affinity reasons. In this case, it would seem that simply using `ThreadPool` would be more than adequate (and much simpler). If you have high volumes, then a producer/consumer queue may allow better throttling (so you don't drown in threads) - but I suspect `ThreadPool` will be fine here...
```
public void SendDataAsync()
{
ThreadPool.QueueUserWorkItem(delegate
{
SendEmail();
});
}
```
Also - I'm not quite sure what you want to achieve by sleeping? This will just tie up a thread (not using CPU, but doing no good either). Care to elaborate? It *looks* like you are pausing your actual web page (i.e. the Sleep happens on the web-page thread, not the e-mail thread). What are you trying to do here?
\*=actually, it will use whatever sync-context is in place
|
228,782 |
<p>How should I manage tables that refer to site 'events'. i.e. certain activities a user has done on a website that I use for tracking. I want to be able to do all kinds of datamining and correlation between different activities of users and what they have done.</p>
<p>Today alone I added 107,000 rows to my SiteEvent table. I dont think this is sustainable!</p>
<p>The database is SQL Server. I'm mainly referring to best practice activites with respect to managing large amounts of data. </p>
<p>For instance :</p>
<ul>
<li>Should I keep these tables in a database all of their own? If i need to join with other tables this could be a problem. Currently I just have one database with everything in.</li>
<li>How ought I to purge old records. I want to ensure my db file doesnt keep growing.</li>
<li>Best practices for backing up and truncating logs</li>
<li>Will adding additional indexes dramatically increase the size of the DB with so many records?</li>
<li>Any other things i need to so in SQL Server that might come back to bite me later?</li>
</ul>
<p>FYI: these are the tables</p>
<pre><code>CREATE TABLE [dbo].[SiteEvent](
[SiteEventId] [int] IDENTITY(1,1) NOT NULL,
[SiteEventTypeId] [int] NOT NULL,
[SiteVisitId] [int] NOT NULL,
[SiteId] [int] NOT NULL,
[Date] [datetime] NULL,
[Data] [varchar](255) NULL,
[Data2] [varchar](255) NULL,
[Duration] [int] NULL,
[StageSize] [varchar](10) NULL,
</code></pre>
<p>and</p>
<pre><code>CREATE TABLE [dbo].[SiteVisit](
[SiteVisitId] [int] IDENTITY(1,1) NOT NULL,
[SiteUserId] [int] NULL,
[ClientGUID] [uniqueidentifier] ROWGUIDCOL NULL CONSTRAINT [DF_SiteVisit_ClientGUID] DEFAULT (newid()),
[ServerGUID] [uniqueidentifier] NULL,
[UserGUID] [uniqueidentifier] NULL,
[SiteId] [int] NOT NULL,
[EntryURL] [varchar](100) NULL,
[CampaignId] [varchar](50) NULL,
[Date] [datetime] NOT NULL,
[Cookie] [varchar](50) NULL,
[UserAgent] [varchar](255) NULL,
[Platform] [int] NULL,
[Referer] [varchar](255) NULL,
[RegisteredReferer] [int] NULL,
[FlashVersion] [varchar](20) NULL,
[SiteURL] [varchar](100) NULL,
[Email] [varchar](50) NULL,
[FlexSWZVersion] [varchar](20) NULL,
[HostAddress] [varchar](20) NULL,
[HostName] [varchar](100) NULL,
[InitialStageSize] [varchar](20) NULL,
[OrderId] [varchar](50) NULL,
[ScreenResolution] [varchar](50) NULL,
[TotalTimeOnSite] [int] NULL,
[CumulativeVisitCount] [int] NULL CONSTRAINT [DF_SiteVisit_CumulativeVisitCount] DEFAULT ((0)),
[ContentActivatedTime] [int] NULL CONSTRAINT [DF_SiteVisit_ContentActivatedTime] DEFAULT ((0)),
[ContentCompleteTime] [int] NULL,
[MasterVersion] [int] NULL CONSTRAINT [DF_SiteVisit_MasterVersion] DEFAULT ((0)),
</code></pre>
|
[
{
"answer_id": 228791,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 0,
"selected": false,
"text": "<p>Re-thinking the problem might be just what the doctor ordered. Can 100k records per day really be that useful? Seems like information overload to me. Maybe start by reducing the granularity of your usage tracking?</p>\n"
},
{
"answer_id": 228891,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 0,
"selected": false,
"text": "<p>In terms of re-thinking the problem, you might explore one of the many web statistics packages out there. There are only a few fields in your sample table that are not part of an out-of-the-box implementation of WebTrends or Google Analytics or many others. The other items in your table can be set up as well, but take a bit more thought and some research into which package will meet all of your needs. Most of the off the shelf stuff can deal with campaign tracking, etc. these days.</p>\n\n<p>One other option would be to offload the common stuff to a standard web-stats package and then parse this back into SQL Server with your custom data out-of-band. </p>\n\n<p>I don't know how much other data you have, but if the 107K+ records a day represents the bulk of it, you might end up spending your time dealing with keeping your web stats working rather than your applications actual functionality.</p>\n"
},
{
"answer_id": 228916,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 0,
"selected": false,
"text": "<p>I would keep them in the same database, unless you can safely purge / store old records for OLAP querying and then keep the primary database for OLTP purposes.</p>\n\n<p>Make sure you set a large initial size for the database and set a large autogrow value, and ensure you don't run out of disk space. 107k records a day <strong>is</strong> going to take up space no matter how you store it.</p>\n\n<p>As for backups, that's completely dependent on your requirements. A weekly full, daily diff and one/two hour diff should work fine as long as the IO subsystem can cope with it.</p>\n\n<p>Additional indexes will take up space, but again, it depends on which columns you add. If you have 10^6 rows and you add a nonclustered index it'll take up 10^6 * 4 * 2. That's 10^6 for the actual indexed column, and an additional 4 bytes for the primary key as well, for each index entry. So for each 1 million records, a nonclustered index on an int column will take up roughly 8MBs.</p>\n\n<p>When the table grows, you can add servers and do horizontal partitioning on the table so you spread out the data on multiple servers.</p>\n\n<p>As for the IO, which is probably going to be the largest hurdle, make sure you have enough spindles to handle the load, preferably with indexes being on their own diskset/LUN and the actual data on their own set of disks/LUN.</p>\n"
},
{
"answer_id": 230393,
"author": "KCorax",
"author_id": 354645,
"author_profile": "https://Stackoverflow.com/users/354645",
"pm_score": 1,
"selected": false,
"text": "<p>Personally I would keep absolutely keep the log records outside the main database. The performance of your application would take a huge hit by having to constantly do writes.</p>\n\n<p>I think the way to go is to create a secondary database on a different machine, publish a SOAP api that is irrelevant to the underlying DB Schema and have the application report to that. I'd also suggest that maybe-write semantics (don't wait for confirmation response) could do for you, if you can risk loosing some of this information.</p>\n\n<p>On the secondary DB you can have your API calls trigger some sort of database pruning or detach/backup/recreate maintenance procedure. If you need a log then you shouldn't give up on the possibility of it being useful in the future.</p>\n\n<p>If you need some sort of analysis service on that, the best way to go is SQL Server. Otherwise MySQL or PostGREs will do the job much cheaper.</p>\n"
},
{
"answer_id": 231314,
"author": "Maitus",
"author_id": 21253,
"author_profile": "https://Stackoverflow.com/users/21253",
"pm_score": 2,
"selected": false,
"text": "<p>You said two things that are in conflict with each other.</p>\n\n<ol>\n<li>I want to be able to do all kinds of datamining and correlation between different activities of users and what they have done.</li>\n<li>I want to ensure my db file doesnt keep growing.</li>\n</ol>\n\n<p>I am also a big fan of data mining, but you need data to mine. In my mind, create a scalable database design and plan for it to grow TREMENDOUSLY. Then, go grab all the data you can. Then, finally, you will be able to do all the cool data mining you are dreaming about.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24727/"
] |
How should I manage tables that refer to site 'events'. i.e. certain activities a user has done on a website that I use for tracking. I want to be able to do all kinds of datamining and correlation between different activities of users and what they have done.
Today alone I added 107,000 rows to my SiteEvent table. I dont think this is sustainable!
The database is SQL Server. I'm mainly referring to best practice activites with respect to managing large amounts of data.
For instance :
* Should I keep these tables in a database all of their own? If i need to join with other tables this could be a problem. Currently I just have one database with everything in.
* How ought I to purge old records. I want to ensure my db file doesnt keep growing.
* Best practices for backing up and truncating logs
* Will adding additional indexes dramatically increase the size of the DB with so many records?
* Any other things i need to so in SQL Server that might come back to bite me later?
FYI: these are the tables
```
CREATE TABLE [dbo].[SiteEvent](
[SiteEventId] [int] IDENTITY(1,1) NOT NULL,
[SiteEventTypeId] [int] NOT NULL,
[SiteVisitId] [int] NOT NULL,
[SiteId] [int] NOT NULL,
[Date] [datetime] NULL,
[Data] [varchar](255) NULL,
[Data2] [varchar](255) NULL,
[Duration] [int] NULL,
[StageSize] [varchar](10) NULL,
```
and
```
CREATE TABLE [dbo].[SiteVisit](
[SiteVisitId] [int] IDENTITY(1,1) NOT NULL,
[SiteUserId] [int] NULL,
[ClientGUID] [uniqueidentifier] ROWGUIDCOL NULL CONSTRAINT [DF_SiteVisit_ClientGUID] DEFAULT (newid()),
[ServerGUID] [uniqueidentifier] NULL,
[UserGUID] [uniqueidentifier] NULL,
[SiteId] [int] NOT NULL,
[EntryURL] [varchar](100) NULL,
[CampaignId] [varchar](50) NULL,
[Date] [datetime] NOT NULL,
[Cookie] [varchar](50) NULL,
[UserAgent] [varchar](255) NULL,
[Platform] [int] NULL,
[Referer] [varchar](255) NULL,
[RegisteredReferer] [int] NULL,
[FlashVersion] [varchar](20) NULL,
[SiteURL] [varchar](100) NULL,
[Email] [varchar](50) NULL,
[FlexSWZVersion] [varchar](20) NULL,
[HostAddress] [varchar](20) NULL,
[HostName] [varchar](100) NULL,
[InitialStageSize] [varchar](20) NULL,
[OrderId] [varchar](50) NULL,
[ScreenResolution] [varchar](50) NULL,
[TotalTimeOnSite] [int] NULL,
[CumulativeVisitCount] [int] NULL CONSTRAINT [DF_SiteVisit_CumulativeVisitCount] DEFAULT ((0)),
[ContentActivatedTime] [int] NULL CONSTRAINT [DF_SiteVisit_ContentActivatedTime] DEFAULT ((0)),
[ContentCompleteTime] [int] NULL,
[MasterVersion] [int] NULL CONSTRAINT [DF_SiteVisit_MasterVersion] DEFAULT ((0)),
```
|
You said two things that are in conflict with each other.
1. I want to be able to do all kinds of datamining and correlation between different activities of users and what they have done.
2. I want to ensure my db file doesnt keep growing.
I am also a big fan of data mining, but you need data to mine. In my mind, create a scalable database design and plan for it to grow TREMENDOUSLY. Then, go grab all the data you can. Then, finally, you will be able to do all the cool data mining you are dreaming about.
|
228,795 |
<p>If I have the following code (this was written in .NET)</p>
<pre><code>double i = 0.1 + 0.1 + 0.1;
</code></pre>
<p>Why doesn't <code>i</code> equal <code>0.3</code>?<br>
Any ideas?</p>
|
[
{
"answer_id": 228799,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 1,
"selected": false,
"text": "<p>The precision of floating point arithmetic cannot be guaranteed.</p>\n"
},
{
"answer_id": 228802,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>You need to read up on floating point numbers. Many decimal numbers don't have an exact representation in binary so they won't be an exact match.</p>\n\n<p>That's why in comparisons, you tend to see:</p>\n\n<pre><code>if (abs(a-b) < epsilon) { ...\n</code></pre>\n\n<p>where epsilon is a small value such as 0.00000001, depending on the accuracy required.</p>\n"
},
{
"answer_id": 228805,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": 2,
"selected": false,
"text": "<p>Double is a 64-bit floating point data type. It stores decimals as approximate values. If you need exact values, use the Decimal data type which is a <a href=\"http://en.wikipedia.org/wiki/Binary-coded_decimal\" rel=\"nofollow noreferrer\">Binary Coded Decimal</a> data type.</p>\n"
},
{
"answer_id": 228806,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "<p>Equality with floating point numbers is often not used because there is always an issue with the representation.\nNormally we compare the difference between two floats and if it is smaller than a certain value (for example 0.0000001) it is considdered equal.</p>\n"
},
{
"answer_id": 228808,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 1,
"selected": false,
"text": "<p>Double calculation is not exact. You have two solution:</p>\n\n<ul>\n<li>Use the <code>Decimal</code> type which is exact</li>\n<li>compare abs(i - 0.3) < espilon</li>\n</ul>\n"
},
{
"answer_id": 228828,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>Jon Skeet has a very good walkthrough of this <a href=\"http://www.yoda.arachsys.com/csharp/floatingpoint.html\" rel=\"nofollow noreferrer\">here</a>, and the same for <code>decimal</code> <a href=\"http://www.yoda.arachsys.com/csharp/decimal.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 228846,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at this thread:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/177506/why-do-i-see-a-double-variable-initialized-to-some-value-like-214-as-2139999961\">Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
If I have the following code (this was written in .NET)
```
double i = 0.1 + 0.1 + 0.1;
```
Why doesn't `i` equal `0.3`?
Any ideas?
|
You need to read up on floating point numbers. Many decimal numbers don't have an exact representation in binary so they won't be an exact match.
That's why in comparisons, you tend to see:
```
if (abs(a-b) < epsilon) { ...
```
where epsilon is a small value such as 0.00000001, depending on the accuracy required.
|
228,796 |
<p>I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less.</p>
<p>If I pass in a char-array of characters from <strong>0</strong> to <strong>J</strong>, and set length to 5, I want results like <em>00000, 00001, 00002... HJJJJ, IJJJJJ, JJJJJ</em>.</p>
<p>Here is the base, please help me expand:</p>
<pre><code>protected void Main()
{
char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
BruteForce(chars, 5);
}
private void BruteForce(char[] chars, int length)
{
// for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
// (when passed in length is 5)
// TODO: Implement code...
}
</code></pre>
|
[
{
"answer_id": 228815,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "<p>Google for permutations.</p>\n\n<p>If however you are just dealing with that 'hex' range, just do the following:</p>\n\n<pre><code>for (int i = 0; i < (1 << 24); i++)\n string s = i.ToString(\"X6\");\n</code></pre>\n"
},
{
"answer_id": 228825,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>This isn't <em>quite</em> a duplicate of <a href=\"https://stackoverflow.com/questions/207889/recursion-instead-of-multi-loops\">\"recursion instead of multi-loops\"</a> but it's pretty close. I'll write up a solution if this doesn't help you.</p>\n\n<p>EDIT: Here's a non-recursive solution. The recursive one is slightly harder to return an <code>IEnumerable<string></code> from, but returning an iterator gives a nice interface IMO :)</p>\n\n<pre><code>private static IEnumerable<string> GetAllMatches(char[] chars, int length)\n{\n int[] indexes = new int[length];\n char[] current = new char[length];\n for (int i=0; i < length; i++)\n {\n current[i] = chars[0];\n }\n do\n {\n yield return new string(current);\n }\n while (Increment(indexes, current, chars));\n}\n\nprivate static bool Increment(int[] indexes, char[] current, char[] chars)\n{\n int position = indexes.Length-1;\n\n while (position >= 0)\n {\n indexes[position]++;\n if (indexes[position] < chars.Length)\n {\n current[position] = chars[indexes[position]];\n return true;\n }\n indexes[position] = 0;\n current[position] = chars[0];\n position--;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 231533,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 0,
"selected": false,
"text": "<p>Below is a class I've used before for this exact purpose... as the name suggests, it essential counts in different Bases based on the number of characters in the character set provided. Hope it's useful...</p>\n\n<pre><code>public class BaseNCounter\n{\n public char[] CharSet { get; set; }\n public int Power { get; set; }\n\n public BaseNCounter() { }\n\n public IEnumerable<string> Count() {\n long max = (long)Math.Pow((double)this.CharSet.Length, (double)this.Power);\n long[] counts = new long[this.Power];\n for(long i = 0; i < max; i++)\n yield return IncrementArray(ref counts, i);\n }\n\n public string IncrementArray(ref long[] counts, long count) {\n long temp = count;\n for (int i = this.Power - 1; i >= 0 ; i--) {\n long pow = (long)Math.Pow(this.CharSet.Length, i);\n counts[i] = temp / pow;\n temp = temp % pow;\n }\n\n StringBuilder sb = new StringBuilder();\n foreach (int c in counts) sb.Insert(0, this.CharSet[c]);\n return sb.ToString();\n }\n}\n</code></pre>\n\n<p>Heres a couple of usage scenarios in a console app.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n BaseNCounter c = new BaseNCounter() { \n CharSet = new char [] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }, \n Power = 2};\n\n foreach(string cc in c.Count())\n Console.Write(\"{0} ,\", cc);\n Console.WriteLine(\"\");\n\n BaseNCounter c2 = new BaseNCounter()\n {\n CharSet = new char[] { 'x', 'q', 'r', '9'},\n Power = 3\n };\n foreach (string cc in c2.Count())\n Console.Write(\"{0} ,\", cc);\n Console.Read();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1393146,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 2,
"selected": true,
"text": "<p>This is one of the solutions I've found. I like the compactness and separation of it:</p>\n\n<pre><code>private static char[] characters =\n new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };\n\n// length: The length of the string created by bruteforce\npublic static void PerformBruteForce(int length) {\n int charactersLength = characters.Length;\n int[] odometer = new int[length];\n long size = (long)Math.Pow(charactersLength, length);\n\n for (int i = 0; i < size; i++) {\n WriteBruteForce(odometer, characters);\n int position = 0;\n do {\n odometer[position] += 1;\n odometer[position] %= charactersLength;\n } while (odometer[position++] == 0 && position < length);\n }\n}\n\nprivate static void WriteBruteForce(int[] odometer, char[] characters) {\n // Print backwards\n for (int i = odometer.Length - 1; i >= 0; i--) {\n Console.Write(characters[odometer[i]]);\n }\n Console.WriteLine();\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] |
I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less.
If I pass in a char-array of characters from **0** to **J**, and set length to 5, I want results like *00000, 00001, 00002... HJJJJ, IJJJJJ, JJJJJ*.
Here is the base, please help me expand:
```
protected void Main()
{
char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
BruteForce(chars, 5);
}
private void BruteForce(char[] chars, int length)
{
// for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
// (when passed in length is 5)
// TODO: Implement code...
}
```
|
This is one of the solutions I've found. I like the compactness and separation of it:
```
private static char[] characters =
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
// length: The length of the string created by bruteforce
public static void PerformBruteForce(int length) {
int charactersLength = characters.Length;
int[] odometer = new int[length];
long size = (long)Math.Pow(charactersLength, length);
for (int i = 0; i < size; i++) {
WriteBruteForce(odometer, characters);
int position = 0;
do {
odometer[position] += 1;
odometer[position] %= charactersLength;
} while (odometer[position++] == 0 && position < length);
}
}
private static void WriteBruteForce(int[] odometer, char[] characters) {
// Print backwards
for (int i = odometer.Length - 1; i >= 0; i--) {
Console.Write(characters[odometer[i]]);
}
Console.WriteLine();
}
```
|
228,811 |
<p>I'm interested in using Functional MetaPost on Mac OS X:</p>
<p><a href="http://cryp.to/funcmp/" rel="nofollow noreferrer">http://cryp.to/funcmp/</a></p>
<p>I'm looking for a tutorial like:</p>
<p><a href="http://haskell.org/haskellwiki/Haskell_in_5_steps" rel="nofollow noreferrer">http://haskell.org/haskellwiki/Haskell_in_5_steps</a></p>
<p>but for a trivial FuncMP example, i.e. using GHC, I can compile something simple such as:</p>
<pre><code>import FMP
myPicture = text "blah"
main = generate "foo" 1 myPicture
</code></pre>
<p>but I can't figure out how to view this foo.1.mp output. (It gives a runtime error about not finding 'virmp'; my MetaPost binary is 'mpost'; I can't figure out how to override this Parameter or what my .FunMP file is or should be doing...) I can run mpost on that but the output (foo.1.1) is what, PostScript? EPS? How do I use this? (I imagine I just need a simple LaTeX file with an EPS figure in it or something...)</p>
<p>Preferably, I'd like to generate output (.ps or .pdf that I can view) so I an actually get somewhere <em>with Functional MetaPost</em>, learning it, playing with it, not banging my head against paths and binaries and shell commands.</p>
|
[
{
"answer_id": 238456,
"author": "ja.",
"author_id": 15467,
"author_profile": "https://Stackoverflow.com/users/15467",
"pm_score": 2,
"selected": false,
"text": "<p>the output of mpost is eps, which you can view in ghostview...</p>\n"
},
{
"answer_id": 238925,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 2,
"selected": true,
"text": "<p>@ja: This is true (EPS should be mpost's output) but there are a few problems here:</p>\n\n<ol>\n<li><p>ghostview uses X11 and is ugly (especially on a Mac) to the point of being difficult to use.</p></li>\n<li><p>I need smooth anti-aliased graphics, specifically PDF so I can import the graphics into Photoshop when I'm done---the on screen results matter!</p></li>\n<li><p>In the end, I'm not the only one <a href=\"http://www.haskell.org/pipermail/haskell-cafe/2008-October/049776.html\" rel=\"nofollow noreferrer\">having trouble with Functional Metapost's non-standard Metapost output</a>.</p></li>\n</ol>\n\n<p>My solution is to try something else:</p>\n\n<ul>\n<li><a href=\"http://asymptote.sourceforge.net/\" rel=\"nofollow noreferrer\">Asymptote</a> ... \"a powerful descriptive vector graphics language that provides a mathematical coordinate-based framework for technical drawings. Labels and equations are typeset with LaTeX, for overall document consistency, yielding the same high-quality level of typesetting that LaTeX provides for scientific text. By default it produces PostScript output, but it can also generate any format that the ImageMagick package can produce.\"</li>\n<li>It looks really impressive and improves on Metapost in many ways (true floating point, full 3D!) and the programming language looks fairly modern and well thought out (first class functions, Pythonic/Java-ish syntax).</li>\n</ul>\n\n<p>Wow! This is so cool. Asymptote delivers (once you get it installed... the problems are all on the FOSS packages/X11/texlive/macports and especially lazwutil side...)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
] |
I'm interested in using Functional MetaPost on Mac OS X:
<http://cryp.to/funcmp/>
I'm looking for a tutorial like:
<http://haskell.org/haskellwiki/Haskell_in_5_steps>
but for a trivial FuncMP example, i.e. using GHC, I can compile something simple such as:
```
import FMP
myPicture = text "blah"
main = generate "foo" 1 myPicture
```
but I can't figure out how to view this foo.1.mp output. (It gives a runtime error about not finding 'virmp'; my MetaPost binary is 'mpost'; I can't figure out how to override this Parameter or what my .FunMP file is or should be doing...) I can run mpost on that but the output (foo.1.1) is what, PostScript? EPS? How do I use this? (I imagine I just need a simple LaTeX file with an EPS figure in it or something...)
Preferably, I'd like to generate output (.ps or .pdf that I can view) so I an actually get somewhere *with Functional MetaPost*, learning it, playing with it, not banging my head against paths and binaries and shell commands.
|
@ja: This is true (EPS should be mpost's output) but there are a few problems here:
1. ghostview uses X11 and is ugly (especially on a Mac) to the point of being difficult to use.
2. I need smooth anti-aliased graphics, specifically PDF so I can import the graphics into Photoshop when I'm done---the on screen results matter!
3. In the end, I'm not the only one [having trouble with Functional Metapost's non-standard Metapost output](http://www.haskell.org/pipermail/haskell-cafe/2008-October/049776.html).
My solution is to try something else:
* [Asymptote](http://asymptote.sourceforge.net/) ... "a powerful descriptive vector graphics language that provides a mathematical coordinate-based framework for technical drawings. Labels and equations are typeset with LaTeX, for overall document consistency, yielding the same high-quality level of typesetting that LaTeX provides for scientific text. By default it produces PostScript output, but it can also generate any format that the ImageMagick package can produce."
* It looks really impressive and improves on Metapost in many ways (true floating point, full 3D!) and the programming language looks fairly modern and well thought out (first class functions, Pythonic/Java-ish syntax).
Wow! This is so cool. Asymptote delivers (once you get it installed... the problems are all on the FOSS packages/X11/texlive/macports and especially lazwutil side...)
|
228,835 |
<p>what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?</p>
|
[
{
"answer_id": 228879,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 7,
"selected": true,
"text": "<p>When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of \"language\" files:</p>\n\n<ul>\n<li>lang.en.js</li>\n<li>lang.it.js</li>\n<li>lang.fr.js</li>\n</ul>\n\n<p>Each of the files declares an object which is basically just a map from key word to language phrase:</p>\n\n<pre><code>// lang.en.js\nlang = {\n greeting : \"Hello\"\n};\n\n// lang.fr.js\nlang = {\n greeting : \"Bonjour\"\n};\n</code></pre>\n\n<p>Dynamically load one of those files and then all you need to do is reference the key from your map:</p>\n\n<pre><code>document.onload = function() {\n alert(lang.greeting);\n};\n</code></pre>\n\n<p>There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your \"dictionary\" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc.</p>\n\n<pre><code>var l = new Language('en');\nl.get('greeting');\n</code></pre>\n"
},
{
"answer_id": 228917,
"author": "Berzemus",
"author_id": 2452,
"author_profile": "https://Stackoverflow.com/users/2452",
"pm_score": 3,
"selected": false,
"text": "<p>Just found a nice article about i18n in javascript:<br>\n<a href=\"http://24ways.org/2007/javascript-internationalisation\" rel=\"noreferrer\">http://24ways.org/2007/javascript-internationalisation</a></p>\n\n<p>Although a simple google search with i18n + javascript reveals plenty of alternatives. </p>\n\n<p>In the end, it depends on how <em>deep</em> you want it to be. For a couple of languages, a single file is enough.</p>\n\n<p>You could use a framework like <a href=\"http://jquery.com/\" rel=\"noreferrer\">Jquery</a>, use a span to identify the text (with a class) and then use the id of each span to find the corresponding text in the chosen language.<br>\n1 Line of Jquery, done.</p>\n"
},
{
"answer_id": 229575,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 6,
"selected": false,
"text": "<p>There are a few things you need to keep in mind when designing multilanguage support:</p>\n<p>1 - Separate code from data (i.e. don't hard-code strings right into your functions)</p>\n<p>2 - create a formatting hook function to deal with localization differences. Allowing formattable strings (<strong>"{0}"</strong>) is better than concatenating (<strong>"Welcome to" + value</strong>), for a lot of reasons:</p>\n<ul>\n<li>in some languages, a number is formatted like 1.234.678,00 instead of 1,234,567.00</li>\n<li>pluralization is often not as simple as appending an "s" at the end of the singular</li>\n<li>grammar rules are different and can affect the order of things so you should allow dynamic data to be appended after the translation hook: for example, <strong>"Welcome to {0}"</strong> turns into <strong>"{0} he youkoso"</strong> in japanese (this happens in pretty much every language, mind you).</li>\n</ul>\n<p>3 - Make sure that you can actually format strings <strong>after</strong> the translation hook runs, so you can reuse keys.</p>\n<p>4 - <strong>Do not, under any circunstance, hook database outputs to the translator utility</strong>. If you have multilingual data, create separate tables / rows in your database. I've seen people get this no-brainer wrong fairly often (usually for countries and states/provinces in forms).</p>\n<p>5 - Create explicit coding practices rules for creating keys. The formatter utility function (which will look something like <strong>translate("hello world")</strong> will take a key as a parameter, and keys with slight variations make maintainance very annoying. For instance, you might end up with three keys in the following example: "enter you name", "enter your name:", "enter your name: ". Choose one format (e.g. no colon, trimmed) and catch discrepancies in code reviews. Don't do this filtering programmatically, as it can trigger false positives.</p>\n<p>6 - Be mindful that HTML markup could potentially be needed in the translation table (e.g. if you need to bold a word in a sentence, or have footnote medical references). Test for this extensively.</p>\n<p>7 - There are several ways of importing language strings. Ideally, you should have multiple versions of a language.lang.js file, switch between them with server side code, and reference the file from the bottom of the HTML file. Pulling the file via AJAX is also an alternative, but could introduce delays. Merging language.js into your main code file is not advisable, since you lose the benefits of file caching.</p>\n<p>8 - <strong>Test with your target languages.</strong> This sounds silly, but I've seen a serious bug once because the programmer didn't bother to check for the existence of "é" in the key.</p>\n"
},
{
"answer_id": 233167,
"author": "Bertrand Gorge",
"author_id": 30955,
"author_profile": "https://Stackoverflow.com/users/30955",
"pm_score": 1,
"selected": false,
"text": "<p>You should look into what has been done in classic JS components - take things like Dojo, Ext, FCKEditor, TinyMCE, etc. You'll find lots of good ideas.</p>\n\n<p>Usually it ends up being some kind of attributes you set on tags, and then you replace the content of the tag with the translation found in your translation file, based on the value of the attribute.</p>\n\n<p>One thing to keep in mind, is the evolution of the language set (when your code evolves, will you need to retranslate the whole thing or not). We keep the translations in PO Files (Gnu Gettext), and we have a script that transforms the PO File into ready to use JS Files.</p>\n\n<p>In addition:</p>\n\n<ul>\n<li>Always use UTF-8 - this sounds silly, but if you are not in utf-8 from start (HTML head + JS encoding), you'll be bust quickly.</li>\n<li>Use the english string as a key to your translations - this way you won't end up with things like: lang.Greeting = 'Hello world' - but lang['Hello world'] = 'Hello world';</li>\n</ul>\n"
},
{
"answer_id": 24832259,
"author": "Nail",
"author_id": 943535,
"author_profile": "https://Stackoverflow.com/users/943535",
"pm_score": 4,
"selected": false,
"text": "<pre><code>function Language(lang)\n{\n var __construct = function() {\n if (eval('typeof ' + lang) == 'undefined')\n {\n lang = \"en\";\n }\n return;\n }()\n\n this.getStr = function(str, defaultStr) {\n var retStr = eval('eval(lang).' + str);\n if (typeof retStr != 'undefined')\n {\n return retStr;\n } else {\n if (typeof defaultStr != 'undefined')\n {\n return defaultStr;\n } else {\n return eval('en.' + str);\n }\n }\n }\n}\n</code></pre>\n\n<p>After adding this to your page, you can work with it like this:</p>\n\n<pre><code>var en = {\n SelPlace:\"Select this place?\",\n Save:\"Saved.\"\n};\n\nvar tr = {\n SelPlace:\"Burayı seçmek istiyor musunuz?\"\n};\n\nvar translator = new Language(\"en\");\nalert(translator.getStr(\"SelPlace\")); // result: Select this place?\nalert(translator.getStr(\"Save\")); // result: Saved.\nalert(translator.getStr(\"DFKASFASDFJK\", \"Default string for non-existent string\")); // result: Default string for non-existent string\n\nvar translator = new Language(\"tr\");\nalert(translator.getStr(\"SelPlace\")); // result: Burayı seçmek istiyor musunuz?\nalert(translator.getStr(\"Save\")); // result: Saved. (because it doesn't exist in this language, borrowed from english as default)\nalert(translator.getStr(\"DFKASFASDFJK\", \"Default string for non-existent string\")); // result: Default string for non-existent string\n</code></pre>\n\n<p>If you call the class with a language that you haven't defined, English(<strong>en</strong>) will be selected.</p>\n"
},
{
"answer_id": 30191493,
"author": "Tzach",
"author_id": 1795244,
"author_profile": "https://Stackoverflow.com/users/1795244",
"pm_score": 3,
"selected": false,
"text": "<p>After reading the great answers by nickf and Leo, I created the following CommonJS style language.js to manage all my strings (and optionally, <a href=\"https://mustache.github.io/\" rel=\"nofollow\">Mustache</a> to format them):</p>\n\n<pre><code>var Mustache = require('mustache');\n\nvar LANGUAGE = {\n general: {\n welcome: \"Welcome {{name}}!\"\n }\n};\n\nfunction _get_string(key) {\n var parts = key.split('.');\n var result = LANGUAGE, i;\n for (i = 0; i < parts.length; ++i) {\n result = result[parts[i]];\n }\n return result;\n}\n\nmodule.exports = function(key, params) {\n var str = _get_string(key);\n if (!params || _.isEmpty(params)) {\n return str;\n }\n return Mustache.render(str, params);\n};\n</code></pre>\n\n<p>And this is how I get a string:</p>\n\n<pre><code>var L = require('language');\nvar the_string = L('general.welcome', {name='Joe'});\n</code></pre>\n"
},
{
"answer_id": 44169714,
"author": "Grigory Kislin",
"author_id": 548473,
"author_profile": "https://Stackoverflow.com/users/548473",
"pm_score": 0,
"selected": false,
"text": "<p>For Spring bundles and JavaScript there are simple solution: generate i18n array in template (e.g. JSP) and use it in JavaScript:</p>\n\n<p>JSP:</p>\n\n<pre><code><html>\n<script type=\"text/javascript\">\n var i18n = [];\n <c:forEach var='key' items='<%=new String[]{\"common.deleted\",\"common.saved\",\"common.enabled\",\"common.disabled\",\"...}%>'>\n i18n['${key}'] = '<spring:message code=\"${key}\"/>';\n </c:forEach>\n</script>\n</html>\n</code></pre>\n\n<p>And in JS:</p>\n\n<pre><code>alert(i18n[\"common.deleted\"]);\n</code></pre>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/6218970/resolving-springmessages-in-javascript-for-i18n-internationalization\">Resolving spring:messages in javascript for i18n internationalization</a></p>\n"
},
{
"answer_id": 57882370,
"author": "Amirhossein",
"author_id": 11258674,
"author_profile": "https://Stackoverflow.com/users/11258674",
"pm_score": 2,
"selected": false,
"text": "<p>This way you can use one js code for multi language by multi word :</p>\n\n<pre><code>var strings = new Object();\n\nif(navigator.browserLanguage){\n lang = navigator.browserLanguage;\n}else{\n lang = navigator.language;\n}\n\nlang = lang.substr(0,2).toLowerCase();\n\n\n\nif(lang=='fa'){/////////////////////////////Persian////////////////////////////////////////////////////\n\n\n strings[\"Contents\"] = \"فهرست\";\n strings[\"Index\"] = \"شاخص\";\n strings[\"Search\"] = \"جستجو\";\n strings[\"Bookmark\"] = \"ذخیره\";\n\n strings[\"Loading the data for search...\"] = \"در حال جسنجوی متن...\";\n strings[\"Type in the word(s) to search for:\"] = \"لغت مد نظر خود را اینجا تایپ کنید:\";\n strings[\"Search title only\"] = \"جستجو بر اساس عنوان\";\n strings[\"Search previous results\"] = \"جستجو در نتایج قبلی\";\n strings[\"Display\"] = \"نمایش\";\n strings[\"No topics found!\"] = \"موردی یافت نشد!\";\n\n strings[\"Type in the keyword to find:\"] = \"کلیدواژه برای یافتن تایپ کنید\";\n\n strings[\"Show all\"] = \"نمایش همه\";\n strings[\"Hide all\"] = \"پنهان کردن\";\n strings[\"Previous\"] = \"قبلی\";\n strings[\"Next\"] = \"بعدی\";\n\n strings[\"Loading table of contents...\"] = \"در حال بارگزاری جدول فهرست...\";\n\n strings[\"Topics:\"] = \"عنوان ها\";\n strings[\"Current topic:\"] = \"عنوان جاری:\";\n strings[\"Remove\"] = \"پاک کردن\";\n strings[\"Add\"] = \"افزودن\";\n\n}else{//////////////////////////////////////English///////////////////////////////////////////////////\n\nstrings[\"Contents\"] = \"Contents\";\nstrings[\"Index\"] = \"Index\";\nstrings[\"Search\"] = \"Search\";\nstrings[\"Bookmark\"] = \"Bookmark\";\n\nstrings[\"Loading the data for search...\"] = \"Loading the data for search...\";\nstrings[\"Type in the word(s) to search for:\"] = \"Type in the word(s) to search for:\";\nstrings[\"Search title only\"] = \"Search title only\";\nstrings[\"Search previous results\"] = \"Search previous results\";\nstrings[\"Display\"] = \"Display\";\nstrings[\"No topics found!\"] = \"No topics found!\";\n\nstrings[\"Type in the keyword to find:\"] = \"Type in the keyword to find:\";\n\nstrings[\"Show all\"] = \"Show all\";\nstrings[\"Hide all\"] = \"Hide all\";\nstrings[\"Previous\"] = \"Previous\";\nstrings[\"Next\"] = \"Next\";\n\nstrings[\"Loading table of contents...\"] = \"Loading table of contents...\";\n\nstrings[\"Topics:\"] = \"Topics:\";\nstrings[\"Current topic:\"] = \"Current topic:\";\nstrings[\"Remove\"] = \"Remove\";\nstrings[\"Add\"] = \"Add\";\n\n}\n</code></pre>\n\n<p>you can add another lang in this code and set objects on your html code.\nI used Persian For Farsi language and English, you can use any type language just create copy of this part of code by If-Else statement.</p>\n"
},
{
"answer_id": 61810072,
"author": "Benjamin Sloutsky",
"author_id": 13401529,
"author_profile": "https://Stackoverflow.com/users/13401529",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a google translator:</p>\n\n<pre><code><div id=\"google_translate_element\" style = \"float: left; margin-left: 10px;\"></div>\n\n<script type=\"text/javascript\">\nfunction googleTranslateElementInit() {\n new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');\n}\n</script>\n\n<script type=\"text/javascript\" src=\"//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit\"></script>\n\n</div><input type = \"text\" style = \"display: inline; margin-left: 8%;\" class = \"sear\" placeholder = \"Search people...\"><button class = \"bar\">&#128270;</button>\n</code></pre>\n"
},
{
"answer_id": 66312038,
"author": "amirrezasalari",
"author_id": 14659697,
"author_profile": "https://Stackoverflow.com/users/14659697",
"pm_score": 1,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Language {\n constructor(lang) {\n var __construct = function (){\n if (eval('typeof ' + lang) == 'undefined'){\n lang = \"en\";\n }\n return;\n };\n this.getStr = function (str){\n var retStr = eval('eval(lang).' + str);\n if (typeof retStr != 'undefined'){\n return retStr;\n } else {\n return str;\n }\n };\n }\n}\n\nvar en = {\n Save:\"Saved.\"\n};\n\nvar fa = {\n Save:\"ذخیره\"\n};\n\nvar translator = new Language(\"fa\");\nconsole.log(translator.getStr(\"Save\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3214/"
] |
what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?
|
When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files:
* lang.en.js
* lang.it.js
* lang.fr.js
Each of the files declares an object which is basically just a map from key word to language phrase:
```
// lang.en.js
lang = {
greeting : "Hello"
};
// lang.fr.js
lang = {
greeting : "Bonjour"
};
```
Dynamically load one of those files and then all you need to do is reference the key from your map:
```
document.onload = function() {
alert(lang.greeting);
};
```
There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your "dictionary" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc.
```
var l = new Language('en');
l.get('greeting');
```
|
228,863 |
<p>I am considering creating some JSP-tags that will always give the same output. For example:</p>
<pre><code><foo:bar>baz</foo:bar>
</code></pre>
<p>Will always output:</p>
<pre><code><div class="bar">baz</div>
</code></pre>
<p>Is there any way to get a JSP-tag to behave just like static output in the generated servlet?</p>
<p>For example:</p>
<pre><code>out.write("<div class=\"bar\">");
...
out.write("</div>");
</code></pre>
<p>in stead of</p>
<pre><code>x.y.z.foo.BarTag _jspx_th_foo_bar_0 = new x.y.z.foo.BarTag();
_jspx_th_foo_bar_0.setPageContext(pageContext);
_jspx_th_foo_bar_0.setParent(null);
_jspxTagObjects.push(_jspx_th_foo_bar_0);
int _jspx_eval_foo_bar_0 = _jspx_th_foo_bar_0.doStartTag();
etc...
etc...
etc...
</code></pre>
<h2>Background</h2>
<p>I'm worried about performance. I haven't tested this yet, but it looks like the generated servlet does a lot for something very simple, and performance is very important.</p>
<p>But if the servlet behaves as if the output was written directly in the JSP, the cost in production will be zero.</p>
<p>I see a few advantages by doing this. I can change the static HTML or even change to something more dynamic, without editing every portlet. In our setup it's easy to change a tag, but very time-consuming to change every JSP that uses a specific element.</p>
<p>This also means I can force developers to not write something like</p>
<pre><code><div class="bar" style="whatever">...</div>
</code></pre>
<p>There is even more advantages, but if it costs performance on the production servers, it's probably not worth it.</p>
|
[
{
"answer_id": 228872,
"author": "abahgat",
"author_id": 27565,
"author_profile": "https://Stackoverflow.com/users/27565",
"pm_score": 0,
"selected": false,
"text": "<p>I was wondering... why not use just a plain old <strong>include</strong>?</p>\n"
},
{
"answer_id": 228952,
"author": "Jonas K",
"author_id": 26609,
"author_profile": "https://Stackoverflow.com/users/26609",
"pm_score": 2,
"selected": false,
"text": "<p>I am quite certain the performance hit will be negligeble considering the code you just showed. </p>\n"
},
{
"answer_id": 239624,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 2,
"selected": true,
"text": "<p>I made a performance-test. There is very little difference in performace, so that is no problem.</p>\n\n<h2>How I made the test</h2>\n\n<p>I created 500 individual tags (programmatically) in one of our tag libraries. (So it is wrapped in a jar etc.)\nThey all look like this, with the number as the only difference:</p>\n\n<pre><code>package XX.XX.XX.XX\n\nimport java.io.IOException;\n\nimport javax.servlet.jsp.JspException;\nimport javax.servlet.jsp.tagext.TagSupport;\n\npublic class Test0001Tag extends TagSupport {\n\n public Test0001Tag() {\n }\n\n public int doStartTag() throws JspException {\n\n try {\n pageContext.getOut().print(\"<div class=\\\"Test0001\\\">\");\n } catch (IOException e) {\n throw new JspException(e);\n }\n return EVAL_BODY_INCLUDE;\n }\n\n public int doEndTag() throws JspException {\n try {\n pageContext.getOut().print(\"</div>\");\n } catch (IOException e) {\n throw new JspException(e);\n }\n return EVAL_PAGE;\n }\n\n public void release() {\n super.release();\n }\n}\n</code></pre>\n\n<p>And then 500 entries in the TLD like this:</p>\n\n<pre><code><tag>\n <name>test0001</name>\n <tagclass>XX.XX.XX.XX.Test0001Tag</tagclass>\n <bodycontent>JSP</bodycontent> \n</tag>\n</code></pre>\n\n<p>Then I grabbed a JSP with a little code in it, and made two copies: One with static HTML, and one with tags.</p>\n\n<p>The one with static HTML:</p>\n\n<pre><code><!-- \n<%long start = System.currentTimeMillis();%>\n<% for (int i = 0; i < 1000; i++) { %>\n<div class=\"Test0001\">X</div>\n<div class=\"Test0002\">X</div>\n<div class=\"Test0003\">X</div>\n...\n<div class=\"Test0498\">X</div>\n<div class=\"Test0499\">X</div>\n<div class=\"Test0500\">X</div>\n<% } %>\n<%System.out.println(System.currentTimeMillis()-start);%>\n -->\n</code></pre>\n\n<p>The one with tags:</p>\n\n<pre><code><!-- \n<%long start = System.currentTimeMillis();%>\n<% for (int i = 0; i < 1000; i++) { %>\n<bddesign:test0001>X</bddesign:test0001>\n<bddesign:test0002>X</bddesign:test0002>\n<bddesign:test0003>X</bddesign:test0003>\n...\n<bddesign:test0498>X</bddesign:test0498>\n<bddesign:test0499>X</bddesign:test0499>\n<bddesign:test0500>X</bddesign:test0500>\n<% } %>\n<%System.out.println(System.currentTimeMillis()-start);%>\n -->\n</code></pre>\n\n<p>The loop was introduced because both came out with zero milliseconds. (Unfortunately I run Windows at work, so I don't get much precision here.)\nThe fact that 500 tags didn't make a measure-able delay could be answer enough, but I wanted more, even if the repetition may allow for some optimization.</p>\n\n<p>The result for 500 000 tags:</p>\n\n<ul>\n<li>JSP-tags: 15-19 seconds</li>\n<li>HTML-tags: 12-16 seconds</li>\n</ul>\n\n<p>So there is a difference, but I think it's insignificant compared to everything else going on from the user clicks to the answer is rendered on the screen.</p>\n\n<h2>Other thoughts</h2>\n\n<p>As far as I know the granularity in Windows is about 15-16 milliseconds. So \"0 milliseconds\" actually means \"<16 milliseconds\". A delay of less than 16/500 milliseconds pr. tag is quite acceptable.</p>\n\n<p>I tried with 1000 tags, but the JSP-compiler was very unhappy with that. I reduced to 500 tags because the alternative was to change the setup which would invalidate my results.</p>\n\n<p>I made the generated HTML a HTML-comment, because the browser is on the same physical machine as the test-server, and I was afraid that the browser would take too much CPU-time rendering, even with a dual-core CPU. The easy solution was to comment the HTML.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28683/"
] |
I am considering creating some JSP-tags that will always give the same output. For example:
```
<foo:bar>baz</foo:bar>
```
Will always output:
```
<div class="bar">baz</div>
```
Is there any way to get a JSP-tag to behave just like static output in the generated servlet?
For example:
```
out.write("<div class=\"bar\">");
...
out.write("</div>");
```
in stead of
```
x.y.z.foo.BarTag _jspx_th_foo_bar_0 = new x.y.z.foo.BarTag();
_jspx_th_foo_bar_0.setPageContext(pageContext);
_jspx_th_foo_bar_0.setParent(null);
_jspxTagObjects.push(_jspx_th_foo_bar_0);
int _jspx_eval_foo_bar_0 = _jspx_th_foo_bar_0.doStartTag();
etc...
etc...
etc...
```
Background
----------
I'm worried about performance. I haven't tested this yet, but it looks like the generated servlet does a lot for something very simple, and performance is very important.
But if the servlet behaves as if the output was written directly in the JSP, the cost in production will be zero.
I see a few advantages by doing this. I can change the static HTML or even change to something more dynamic, without editing every portlet. In our setup it's easy to change a tag, but very time-consuming to change every JSP that uses a specific element.
This also means I can force developers to not write something like
```
<div class="bar" style="whatever">...</div>
```
There is even more advantages, but if it costs performance on the production servers, it's probably not worth it.
|
I made a performance-test. There is very little difference in performace, so that is no problem.
How I made the test
-------------------
I created 500 individual tags (programmatically) in one of our tag libraries. (So it is wrapped in a jar etc.)
They all look like this, with the number as the only difference:
```
package XX.XX.XX.XX
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Test0001Tag extends TagSupport {
public Test0001Tag() {
}
public int doStartTag() throws JspException {
try {
pageContext.getOut().print("<div class=\"Test0001\">");
} catch (IOException e) {
throw new JspException(e);
}
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException {
try {
pageContext.getOut().print("</div>");
} catch (IOException e) {
throw new JspException(e);
}
return EVAL_PAGE;
}
public void release() {
super.release();
}
}
```
And then 500 entries in the TLD like this:
```
<tag>
<name>test0001</name>
<tagclass>XX.XX.XX.XX.Test0001Tag</tagclass>
<bodycontent>JSP</bodycontent>
</tag>
```
Then I grabbed a JSP with a little code in it, and made two copies: One with static HTML, and one with tags.
The one with static HTML:
```
<!--
<%long start = System.currentTimeMillis();%>
<% for (int i = 0; i < 1000; i++) { %>
<div class="Test0001">X</div>
<div class="Test0002">X</div>
<div class="Test0003">X</div>
...
<div class="Test0498">X</div>
<div class="Test0499">X</div>
<div class="Test0500">X</div>
<% } %>
<%System.out.println(System.currentTimeMillis()-start);%>
-->
```
The one with tags:
```
<!--
<%long start = System.currentTimeMillis();%>
<% for (int i = 0; i < 1000; i++) { %>
<bddesign:test0001>X</bddesign:test0001>
<bddesign:test0002>X</bddesign:test0002>
<bddesign:test0003>X</bddesign:test0003>
...
<bddesign:test0498>X</bddesign:test0498>
<bddesign:test0499>X</bddesign:test0499>
<bddesign:test0500>X</bddesign:test0500>
<% } %>
<%System.out.println(System.currentTimeMillis()-start);%>
-->
```
The loop was introduced because both came out with zero milliseconds. (Unfortunately I run Windows at work, so I don't get much precision here.)
The fact that 500 tags didn't make a measure-able delay could be answer enough, but I wanted more, even if the repetition may allow for some optimization.
The result for 500 000 tags:
* JSP-tags: 15-19 seconds
* HTML-tags: 12-16 seconds
So there is a difference, but I think it's insignificant compared to everything else going on from the user clicks to the answer is rendered on the screen.
Other thoughts
--------------
As far as I know the granularity in Windows is about 15-16 milliseconds. So "0 milliseconds" actually means "<16 milliseconds". A delay of less than 16/500 milliseconds pr. tag is quite acceptable.
I tried with 1000 tags, but the JSP-compiler was very unhappy with that. I reduced to 500 tags because the alternative was to change the setup which would invalidate my results.
I made the generated HTML a HTML-comment, because the browser is on the same physical machine as the test-server, and I was afraid that the browser would take too much CPU-time rendering, even with a dual-core CPU. The easy solution was to comment the HTML.
|
228,875 |
<p>I have data coming from the database in the form of a <code>DataSet</code>. I then set it as the <code>DataSource</code> of a grid control before doing a <code>DataBind()</code>. I want to sort the <code>DataSet</code>/<code>DataTable</code> on one column. The column is to complex to sort in the database but I was hoping I could sort it like I would sort a generic list i.e. using a deligate.</p>
<p>Is this possible or do I have to transfer it to a different data structure?</p>
<p><strong>Edit</strong> I can't get any of these answer to work for me, I think because I am using <strong>.Net 2.0.</strong></p>
|
[
{
"answer_id": 228886,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>I think <a href=\"http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx\" rel=\"nofollow noreferrer\">DataView.Sort</a> property would help. You can access it through <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview.aspx\" rel=\"nofollow noreferrer\">DataTable.DefaultView</a>.</p>\n"
},
{
"answer_id": 228890,
"author": "Toby",
"author_id": 291137,
"author_profile": "https://Stackoverflow.com/users/291137",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't mind losing paging/sorting on the control you can use something like:</p>\n\n<pre><code>var dt = new DataTable();\ngvWhatever.DataSource = dt.Select().ToList().Sort();\n</code></pre>\n\n<p>And that sort will take IComparables etc as per the overloads so you can sort however you like.</p>\n"
},
{
"answer_id": 228892,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>Because of how DataTable (and DataView) sorting works, you can't use the delegate approach directly. One workaround is to add a column to the data-table that represents the order, and set the value (per row) based on the desired sequence. You can then add a Sort to the view on this new column. For example (using LINQ to do the sort, just for brevity):</p>\n\n<pre><code>var sorted = table.Rows.Cast<DataRow>().OrderBy(row => your code);\nint sequence = 0;\nforeach(var row in sorted)\n{\n row[\"sequence\"] = sequence++;\n}\n</code></pre>\n\n<p>(if you have a typed data-set, then I don't think you need the Cast step, or you would use your typed DataRow subclass)</p>\n\n<p>[edit to include 2.0]</p>\n\n<p>In 2.0 (i.e. without LINQ etc) you could use a <code>List<T></code> to do the sort - a bit more long-winded, but:</p>\n\n<pre><code> List<DataRow> sorted = new List<DataRow>();\n foreach(DataRow row in table.Rows)\n {\n sorted.Add(row);\n }\n sorted.Sort(delegate(DataRow x, DataRow y) { your code });\n int sequence = 0;\n foreach(DataRow row in sorted)\n {\n row[\"sequence\"] = sequence++;\n }\n</code></pre>\n\n<p>(again, substitute DataRow if you are using a typed data-set)</p>\n"
},
{
"answer_id": 229368,
"author": "AlePani",
"author_id": 24276,
"author_profile": "https://Stackoverflow.com/users/24276",
"pm_score": 0,
"selected": false,
"text": "<p>You can sort the Database in memory , but I don't know what \"too complex to sort in the database\" would be. If I were you I would try to get it sorted in the database, use Views, Redundancy Indexes, complex SQL statements, it's probably going to be faster than sorting a large Dataset in memory, with the added advantage that it keeps the sort for other kind of clients ( e.g. Web Services, etc)</p>\n"
},
{
"answer_id": 229445,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 0,
"selected": false,
"text": "<p>Why is the column <em>to complex to sort in the database</em>? It suppose the complexity of the sort will be the same in the database or in the framework, unless of course it's a computed column, and even in that case I'm guessing that sorting in the DB is still faster.</p>\n\n<p>However, as John said, you can change the sorting at the form level via DataView.Sort property. I would recommend doing this if the too much time consuming, and it that case it would be useful to cache the results.</p>\n"
},
{
"answer_id": 760330,
"author": "0100110010101",
"author_id": 88702,
"author_profile": "https://Stackoverflow.com/users/88702",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it by </p>\n\n<pre><code>myTableName.DefaultView.Sort = \"MyFieldName DESC\";\n</code></pre>\n"
},
{
"answer_id": 3935404,
"author": "Irina",
"author_id": 476020,
"author_profile": "https://Stackoverflow.com/users/476020",
"pm_score": 1,
"selected": false,
"text": "<pre><code>protected void grdResult_Sorting(object sender, GridViewSortEventArgs e)\n {\n DataTable dt = ((DataTable)Session[\"myDatatable\"]);\n grdResult.DataSource = dt;\n DataTable dataTable = grdResult.DataSource as DataTable;\n\n //Code added to fix issue with sorting for Date datatype fields\n if (dataTable != null)\n { \n\n DataView dataView = new DataView(dataTable);\n for (int i = 0; i < dataView.Table.Rows.Count; i++)\n {\n try\n {\n dataView.Table.Rows[i][\"RESP_DUE_DT\"] = common.FormatDateWithYYYYMMDD(Convert.ToDateTime(dataView.Table.Rows[i][\"RESP_DUE_DT\"]));\n dataView.Table.Rows[i][\"RECD_DT\"] = common.FormatDateWithYYYYMMDD(Convert.ToDateTime(dataView.Table.Rows[i][\"RECD_DT\"]));\n }\n catch (Exception ex)\n {\n\n }\n }\n\n dataView.Sort = \"[\" + e.SortExpression + \"]\" + \" \" + GetSortDirection(e.SortExpression);\n\n for (int i = 0; i < dataView.Table.Rows.Count; i++)\n {\n try\n {\n dataView.AllowEdit = true;\n dataView[i].BeginEdit();\n dataView[i][\"RESP_DUE_DT\"] = common.FormatDateFromStringYYYYMMDD(dataView[i][\"RESP_DUE_DT\"].ToString());\n dataView[i][\"RECD_DT\"] = common.FormatDateFromStringYYYYMMDD(dataView[i][\"RECD_DT\"].ToString());\n }\n catch (Exception ex)\n {\n\n }\n }\n //End code added to fix the issue with sorting for Date data type fields\n\n\n grdResult.DataSource = dataView;\n grdResult.DataBind();\n\n\n }\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
I have data coming from the database in the form of a `DataSet`. I then set it as the `DataSource` of a grid control before doing a `DataBind()`. I want to sort the `DataSet`/`DataTable` on one column. The column is to complex to sort in the database but I was hoping I could sort it like I would sort a generic list i.e. using a deligate.
Is this possible or do I have to transfer it to a different data structure?
**Edit** I can't get any of these answer to work for me, I think because I am using **.Net 2.0.**
|
Because of how DataTable (and DataView) sorting works, you can't use the delegate approach directly. One workaround is to add a column to the data-table that represents the order, and set the value (per row) based on the desired sequence. You can then add a Sort to the view on this new column. For example (using LINQ to do the sort, just for brevity):
```
var sorted = table.Rows.Cast<DataRow>().OrderBy(row => your code);
int sequence = 0;
foreach(var row in sorted)
{
row["sequence"] = sequence++;
}
```
(if you have a typed data-set, then I don't think you need the Cast step, or you would use your typed DataRow subclass)
[edit to include 2.0]
In 2.0 (i.e. without LINQ etc) you could use a `List<T>` to do the sort - a bit more long-winded, but:
```
List<DataRow> sorted = new List<DataRow>();
foreach(DataRow row in table.Rows)
{
sorted.Add(row);
}
sorted.Sort(delegate(DataRow x, DataRow y) { your code });
int sequence = 0;
foreach(DataRow row in sorted)
{
row["sequence"] = sequence++;
}
```
(again, substitute DataRow if you are using a typed data-set)
|
228,912 |
<p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
|
[
{
"answer_id": 228961,
"author": "Blauohr",
"author_id": 22176,
"author_profile": "https://Stackoverflow.com/users/22176",
"pm_score": 2,
"selected": false,
"text": "<p>have You tried this ? :</p>\n\n<pre><code>for item in self.inventory_names:\n t = (item,)\n self.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", t)\n self.cursor.close()\n</code></pre>\n\n<p>cursor.execute() expects a sequence (list,tuple) as second parameter. (-> ddaa )</p>\n"
},
{
"answer_id": 228981,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 8,
"selected": true,
"text": "<p>The <code>Cursor.execute()</code> method expects a sequence as second parameter. You are supplying a string which happens to be 8 characters long.</p>\n\n<p>Use the following form instead:</p>\n\n<pre><code>self.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", [item])\n</code></pre>\n\n<p>Python library reference: sqlite3 <a href=\"https://docs.python.org/2/library/sqlite3.html#cursor-objects\" rel=\"noreferrer\">Cursor Objects</a>.</p>\n"
},
{
"answer_id": 597198,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>I have spent half a day trying to figure out why something like this would give me an error:</p>\n\n<pre><code>cursor.execute(\"SELECT * from ? WHERE name = ?\", (table_name, name))\n</code></pre>\n\n<p>only to find out that table names <em>cannot be parametrized</em>. Hope this will help other people save some time.</p>\n"
},
{
"answer_id": 2238193,
"author": "kjikaqawej",
"author_id": 270416,
"author_profile": "https://Stackoverflow.com/users/270416",
"pm_score": 1,
"selected": false,
"text": "<p>Quoting (is that what the parens mean?) the ? with parens seems to work for me. I kept trying with (literally) '?' but I kept getting</p>\n\n<blockquote>\n <p>ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.</p>\n</blockquote>\n\n<p>When I did:</p>\n\n<blockquote>\n <p>SELECT fact FROM factoids WHERE key LIKE (?)</p>\n</blockquote>\n\n<p>instead of:</p>\n\n<blockquote>\n <p>SELECT fact FROM factoids WHERE key LIKE '?'</p>\n</blockquote>\n\n<p>It worked.</p>\n\n<p>Is this some python 2.6 thing?</p>\n"
},
{
"answer_id": 3346710,
"author": "JBE",
"author_id": 403743,
"author_profile": "https://Stackoverflow.com/users/403743",
"pm_score": -1,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>execute(\"select fact from factoids where key like ?\", \"%%s%\" % val)\n</code></pre>\n\n<p>You don't wrap anything around the <code>?</code> at all, Python sqlite will correctly convert it into a quoted entity.</p>\n"
},
{
"answer_id": 7305758,
"author": "jgtumusiime",
"author_id": 820591,
"author_profile": "https://Stackoverflow.com/users/820591",
"pm_score": 5,
"selected": false,
"text": "<p>The argument of <code>cursor.execute</code> that represents the values you need inserted in the database should be a tuple (sequence). However consider this example and see what's happening:</p>\n\n<pre><code>>>> ('jason')\n'jason'\n\n>>> ('jason',)\n('jason',)\n</code></pre>\n\n<p>The first example evaluates to a string instead; so the correct way of representing single valued tuple is as in the second evaluation. Anyhow, the code below to fix your error.</p>\n\n<pre><code>self.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", (item,))\n</code></pre>\n\n<p>Also giving the <code>cursor.execute</code> value arguments as strings,(which is what you are doing) results in the first evaluation in the example and results into the error you are getting.</p>\n"
},
{
"answer_id": 23729861,
"author": "Joey Nelson",
"author_id": 2600246,
"author_profile": "https://Stackoverflow.com/users/2600246",
"pm_score": 0,
"selected": false,
"text": "<p>each element of items has to be a tuple.\nassuming names looks something like this:</p>\n\n<pre><code>names = ['Joe', 'Bob', 'Mary']\n</code></pre>\n\n<p>you should do the following:</p>\n\n<pre><code>for item in self.inventory_names:\nself.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", (item, ))\n</code></pre>\n\n<p>by using (item, ) you are making it a tuple instead of a string.</p>\n"
},
{
"answer_id": 51570095,
"author": "Mike T",
"author_id": 327026,
"author_profile": "https://Stackoverflow.com/users/327026",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"https://docs.python.org/3/library/sqlite3.html\" rel=\"nofollow noreferrer\"><code>sqlite3</code></a> module supports <em>two</em> kinds of placeholders for parameters:</p>\n<h1>qmark style</h1>\n<p>Use one or more <code>?</code> to mark the position of each parameter, and supply a list or tuple of parameters. E.g.:</p>\n<pre><code>curs.execute("SELECT weight FROM Equipment WHERE name = ? AND price = ?",\n ['lead', 24])\n</code></pre>\n<h1>named style</h1>\n<p>Use <code>:par</code> placeholders for each named parameter, and supply a dict. E.g.:</p>\n<pre><code>curs.execute("SELECT weight FROM Equipment WHERE name = :name AND price = :price",\n {name: 'lead', price: 24})\n</code></pre>\n<p>Advantages of named style parameters is that you don't need to worry about the order of parameters, and each <code>:par</code> can be used multiple times in large/complex SQL queries.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.
I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:
```
for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
```
I get the error:
>
> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.
>
>
>
I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.
```
cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
```
However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:
```
for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
```
I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?
|
The `Cursor.execute()` method expects a sequence as second parameter. You are supplying a string which happens to be 8 characters long.
Use the following form instead:
```
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item])
```
Python library reference: sqlite3 [Cursor Objects](https://docs.python.org/2/library/sqlite3.html#cursor-objects).
|
228,926 |
<p>How do you find out the local time of the user browsing your website in ASP.NET? </p>
|
[
{
"answer_id": 228968,
"author": "Albert",
"author_id": 24065,
"author_profile": "https://Stackoverflow.com/users/24065",
"pm_score": 1,
"selected": false,
"text": "<p>You have to use JavaScript in the client side that will get the local time and pass that value to server side. You can pass it using querystring, hidden fields or even AJAX magic.</p>\n"
},
{
"answer_id": 229020,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 4,
"selected": true,
"text": "<p>Create a hidden input control to get the value back at the server on the next page postback. It will need to be populated it in the onload event for the page with the value of a new Date object created in JavaScript. You will want to create a JavaScript function to do this and add that to the page using RegisterClientScriptBlock.</p>\n\n<p>Something like this;</p>\n\n<pre><code>function setNow(hiddenInputId)\n{\n var now = new Date();\n var input = document.getElementById(hiddenInputId);\n\n if(input) input.value = now.toString();\n}\n</code></pre>\n\n<p>Then create a call to the function passing the ClientId of the hidden input and then add that piece of script to the page using RegisterStartupScript so that it runs on page load.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16628/"
] |
How do you find out the local time of the user browsing your website in ASP.NET?
|
Create a hidden input control to get the value back at the server on the next page postback. It will need to be populated it in the onload event for the page with the value of a new Date object created in JavaScript. You will want to create a JavaScript function to do this and add that to the page using RegisterClientScriptBlock.
Something like this;
```
function setNow(hiddenInputId)
{
var now = new Date();
var input = document.getElementById(hiddenInputId);
if(input) input.value = now.toString();
}
```
Then create a call to the function passing the ClientId of the hidden input and then add that piece of script to the page using RegisterStartupScript so that it runs on page load.
|
228,931 |
<p>I'm using this code, to make a request to a given URL:</p>
<pre><code>private static string GetWebRequestContent(string url)
{
string sid = String.Empty;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.KeepAlive = false;
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
sid = sr.ReadToEnd().Trim();
}
}
return sid;
}
</code></pre>
<p>I'm using it to test the stickyness of a Work Load Balancer, with 3 servers behind it. They all have a static HTM file called sid.htm, where the server's Server ID is written.</p>
<p>For URL's with HTTP this works fine. But with HTTPS it doesn't work. I get this exception:</p>
<blockquote>
<p>The request was aborted: Could not create SSL/TLS secure channel.</p>
</blockquote>
<p>At the moment, I have only 2 servers behind the WLB and one on its own with a public IP behind a firewall. HTTPS requests works fine if I hit the stand-alone server - but when I hit the WLB I get the above error.</p>
<p>One thing: In order to switch between hitting the single server, and the WLB I use my hosts file. The DNS records for my domain points to the single server at the moment. So I put a record in my hosts file to hit the WLB. This shouldn't be causing problems...</p>
<p><strong>My question</strong>: Which SSL credentials/certificates does the HttpWebRequest use? If it uses 40 bit DES or 56 bit DES, that's the reason, because those are disabled in the WLB. But those certificates haven't been used in browsers since IE3 and Netscape 1 and 2.</p>
|
[
{
"answer_id": 228954,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 4,
"selected": true,
"text": "<p>It works perfectly in my browser.</p>\n\n<p>I found the solution 1 minute after i posted the question:</p>\n\n<pre><code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;\n</code></pre>\n\n<p>And that means the HttpWebRequest was using TLS 1.0 - I don't know, but I assume that is 40 bit DES or 56 bit DES, which is disabled in the WLB.</p>\n"
},
{
"answer_id": 228980,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 0,
"selected": false,
"text": "<p>There is smothing you might want to consider with the load balancer. The ones we use forward the HTTPS secure traffic to the servers behind it on an insecure HTTP connection. The connection between the load balancer and the browser is still secure but there is no need for the over head of the secure protocol between the balancer and the web servers.</p>\n\n<p>We wanted to detect a secure connection on our web servers but initially never saw an HTTPS connection. That's when we realised the traffic behind the balancer was all insecure. Made sense once we knew. </p>\n\n<p>What we do now is forward all secure traffic coming into the balancer (port 443) to port 81 (altenative HTTP) and then forwarded all normal HTTP traffic (ports 80 & 81) to port 80. Then we can check the port on the web server and know 80 is insecure and 81 is secure traffic between browser and balancer despite the fact its all HTTP at the web server.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2972/"
] |
I'm using this code, to make a request to a given URL:
```
private static string GetWebRequestContent(string url)
{
string sid = String.Empty;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.KeepAlive = false;
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
sid = sr.ReadToEnd().Trim();
}
}
return sid;
}
```
I'm using it to test the stickyness of a Work Load Balancer, with 3 servers behind it. They all have a static HTM file called sid.htm, where the server's Server ID is written.
For URL's with HTTP this works fine. But with HTTPS it doesn't work. I get this exception:
>
> The request was aborted: Could not create SSL/TLS secure channel.
>
>
>
At the moment, I have only 2 servers behind the WLB and one on its own with a public IP behind a firewall. HTTPS requests works fine if I hit the stand-alone server - but when I hit the WLB I get the above error.
One thing: In order to switch between hitting the single server, and the WLB I use my hosts file. The DNS records for my domain points to the single server at the moment. So I put a record in my hosts file to hit the WLB. This shouldn't be causing problems...
**My question**: Which SSL credentials/certificates does the HttpWebRequest use? If it uses 40 bit DES or 56 bit DES, that's the reason, because those are disabled in the WLB. But those certificates haven't been used in browsers since IE3 and Netscape 1 and 2.
|
It works perfectly in my browser.
I found the solution 1 minute after i posted the question:
```
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
```
And that means the HttpWebRequest was using TLS 1.0 - I don't know, but I assume that is 40 bit DES or 56 bit DES, which is disabled in the WLB.
|
228,945 |
<p>I find System.Monitor very confusing, although I understand threading, locks, deadlocks, race conditions, dining philosophers and all that jazz. Normally I use a ManualResetEvent() to do inter-thread co-ordination, but I know that that's a heavyweight kernel object, and that System.Monitor (Enter/Pulse, etc.) is much more efficient. I've Googled and Googled but cannot find a sensible example.</p>
<p>I would be most grateful if the SO crew could explain this potentially wonderful construct to me :-)</p>
|
[
{
"answer_id": 228983,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>Here's a very simple example; the call to <code>Wait</code> releases the lock (allowing <code>Worker</code> to obtain it) and adds the <code>Main</code> thread to the lock-object's pending queue. <code>Worker</code> then obtains the lock, and calls <code>Pulse</code>: this moves the <code>Main</code> thread into the lock-object's ready queue. When <code>Worker</code> <em>releases</em> the lock, <code>Main</code> can resume work.</p>\n\n<p>Note that <code>lock(obj) {...}</code> is just compiler-candy for <code>Monitor.Enter</code>/<code>Monitor.Exit</code> in a try/finally block.</p>\n\n<p>[edit: I changed the sample to move <code>lock(sync)</code> earlier, to avoid the (unlikely) risk of a missed Pulse] </p>\n\n<pre><code> static void Main()\n {\n object sync = new object();\n lock (sync)\n {\n ThreadPool.QueueUserWorkItem(Worker, sync);\n Console.WriteLine(\"Main sleeping\");\n\n // wait for the worker to tell us it is ready\n Monitor.Wait(sync);\n Console.WriteLine(\"Main woke up!\");\n }\n Console.WriteLine(\"Press any key...\");\n Console.ReadKey();\n }\n static void Worker(object sync)\n {\n Console.WriteLine(\"Worker started; about to sleep\");\n Thread.Sleep(5000);\n Console.WriteLine(\"Worker about pulse\");\n lock (sync)\n { // notify Main that we did something interesting\n Monitor.Pulse(sync);\n Console.WriteLine(\"Worker pulsed; about to release lock\");\n }\n Console.WriteLine(\"Worker all done\");\n }\n</code></pre>\n"
},
{
"answer_id": 228996,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>See if <a href=\"http://pobox.com/~skeet/csharp/threads/deadlocks.shtml\" rel=\"nofollow noreferrer\">this part of my threading article</a> helps... (the second half of that page). It implements a producer/consumer queue: when the producer produces something in the queue (and finds it was empty - as an optimisation), it pulses the monitor to wake up any waiting threads. When a consumer tries to consume from the queue but finds it empty, it waits for a pulse before trying again.</p>\n\n<p>Alternatively, <a href=\"http://www.albahari.com/threading/part4.aspx#_Wait_and_Pulse\" rel=\"nofollow noreferrer\">Joe Albahari's threading tutorial</a> has a section on Wait/Pulse too.</p>\n\n<p>It's quite similar to the WaitHandle stuff you're used to - although frankly I find it easier to get my head round than WaitHandles, mostly because it's so similar to the Java wait/notify that I \"grew up\" with :)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25462/"
] |
I find System.Monitor very confusing, although I understand threading, locks, deadlocks, race conditions, dining philosophers and all that jazz. Normally I use a ManualResetEvent() to do inter-thread co-ordination, but I know that that's a heavyweight kernel object, and that System.Monitor (Enter/Pulse, etc.) is much more efficient. I've Googled and Googled but cannot find a sensible example.
I would be most grateful if the SO crew could explain this potentially wonderful construct to me :-)
|
Here's a very simple example; the call to `Wait` releases the lock (allowing `Worker` to obtain it) and adds the `Main` thread to the lock-object's pending queue. `Worker` then obtains the lock, and calls `Pulse`: this moves the `Main` thread into the lock-object's ready queue. When `Worker` *releases* the lock, `Main` can resume work.
Note that `lock(obj) {...}` is just compiler-candy for `Monitor.Enter`/`Monitor.Exit` in a try/finally block.
[edit: I changed the sample to move `lock(sync)` earlier, to avoid the (unlikely) risk of a missed Pulse]
```
static void Main()
{
object sync = new object();
lock (sync)
{
ThreadPool.QueueUserWorkItem(Worker, sync);
Console.WriteLine("Main sleeping");
// wait for the worker to tell us it is ready
Monitor.Wait(sync);
Console.WriteLine("Main woke up!");
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static void Worker(object sync)
{
Console.WriteLine("Worker started; about to sleep");
Thread.Sleep(5000);
Console.WriteLine("Worker about pulse");
lock (sync)
{ // notify Main that we did something interesting
Monitor.Pulse(sync);
Console.WriteLine("Worker pulsed; about to release lock");
}
Console.WriteLine("Worker all done");
}
```
|
228,969 |
<p>I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.</p>
<p>How do we fix this?</p>
<p>Error details below:</p>
<pre><code>Server Error in '/XXX' Application.
--------------------------------------------------------------------------------
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
</code></pre>
|
[
{
"answer_id": 229041,
"author": "Norbert B.",
"author_id": 2605840,
"author_profile": "https://Stackoverflow.com/users/2605840",
"pm_score": 8,
"selected": true,
"text": "<p>The problem is that ASP.NET does not get to know about this extra or removed listitem.\nYou got an number of options (listed below):</p>\n\n<ul>\n<li>Disable eventvalidation (bad idea, because you lose a little of security that come with very little cost).</li>\n<li>Use ASP.NET Ajax UpdatePanel. (Put the listbox in the Updatepanel and trigger a update, if you add or remove listbox. This way viewstate and related fields get updates and eventvalidation will pass.)</li>\n<li>Forget client-side and use the classic postback and add or remove the listitems server-side.</li>\n</ul>\n\n<p>I hope this helps. </p>\n"
},
{
"answer_id": 245512,
"author": "Andy C.",
"author_id": 28541,
"author_profile": "https://Stackoverflow.com/users/28541",
"pm_score": 5,
"selected": false,
"text": "<p>You are really going to want to do 2 or 3, don't disable event validation.</p>\n\n<p>There are two main problems with adding items to an asp:listbox client side.</p>\n\n<ul>\n<li><p>The first is that it interferes with event validation. What came back to the server is not what it sent down.</p></li>\n<li><p>The second is that even if you disable event validation, when your page gets posted back the items in the listbox will be rebuilt from the viewstate, so any changes you made on the client are lost. The reason for this is that a asp.net does not expect the contents of a listbox to be modified on the client, it only expects a selection to be made, so it discards any changes you might have made.</p></li>\n</ul>\n\n<p>The best option is most likely to use an update panel as has been recommended. Another option, if you really need to do this client side, is to use a plain old <code><select></code> instead of an <code><asp:ListBox></code>, and to keep your list of items in a hidden field. When the page renders on the client you can populate it from a split of your text field contents. </p>\n\n<p>Then, when you are ready to post it, you repopulate the hidden field's contents from your modified <code><select></code>. Then, of course, you have to split that again on the server and do something with your items, since your select is empty now that it's back on the server.</p>\n\n<p>All in all it's a pretty cumbersome solution that I would not really recommend, but if you really have to do client-side modifications of a listBox, it does work. I would really recommend you look into an updatePanel before going this route, however.</p>\n"
},
{
"answer_id": 275724,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I had an experience with DataGrid. One of it's columns was \"Select\" button. When I was clicking \"Select\" button of any row I had received this error message:</p>\n\n<blockquote>\n <p>\"Invalid postback or callback argument. Event validation is enabled using in configuration or\n <%@ Page EnableEventValidation=\"true\" %> in a page. For security purposes, this feature verifies that arguments to postback or\n callback events originate from the server control that originally rendered them. If the data is valid and expected, use the\n ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.\"</p>\n</blockquote>\n\n<p>I changed several codes, and finally I succeeded. My experience route:</p>\n\n<p>1) I changed page attribute to <code>EnableEventValidation=\"false\"</code>. <strong><em>But it didn't work.</em></strong> (not only is this dangerous\n for security reason, my event handler wasn't called: <code>void Grid_SelectedIndexChanged(object sender, EventArgs e)</code></p>\n\n<p>2) I implemented <code>ClientScript.RegisterForEventValidation</code> in Render method. <strong><em>But it didn't work.</em></strong></p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\n foreach (DataGridItem item in this.Grid.Items)\n {\n Page.ClientScript.RegisterForEventValidation(item.UniqueID);\n foreach (TableCell cell in (item as TableRow).Cells)\n {\n Page.ClientScript.RegisterForEventValidation(cell.UniqueID);\n foreach (System.Web.UI.Control control in cell.Controls)\n {\n if (control is Button)\n Page.ClientScript.RegisterForEventValidation(control.UniqueID);\n }\n }\n }\n}\n</code></pre>\n\n<p>3) I changed my button type in grid column from <code>PushButton</code> to <code>LinkButton</code>. <strong><em>It worked!</em></strong> (\"ButtonType=\"LinkButton\"). I think if you can change your button to other controls like \"LinkButton\" in other cases, it would work properly.</p>\n"
},
{
"answer_id": 360809,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>If you fill the DropdownList through client side script then clear the list before submit the form back to server; then ASP.NET will not complain and the security will be still on.</p>\n\n<p>And to get the data selected from the DDL, you can attach an \"OnChange\" event to the DDL to collect the value in a hidden Input or in a textbox with Style=\"display: none;\"</p>\n"
},
{
"answer_id": 384507,
"author": "netseng",
"author_id": 32718,
"author_profile": "https://Stackoverflow.com/users/32718",
"pm_score": 2,
"selected": false,
"text": "<p>Ajax <strong>UpdatePanel</strong> makes it, and I think it's the <strong>easiest</strong> way, ignoring the <strong>Ajax postback</strong> overhead.</p>\n"
},
{
"answer_id": 563497,
"author": "brian welch",
"author_id": 12516,
"author_profile": "https://Stackoverflow.com/users/12516",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>3: I changed my button type in grid\n column from \"PushButton\" to\n \"LinkButton\". It worked!\n (\"ButtonType=\"LinkButton\") I think if\n you can change your button to other\n controls like \"LinkButton\" in other\n cases, it would work properly.</p>\n</blockquote>\n\n<p>I wish I could vote you up, Amir (alas my rep is too low.) I was just having this problem and changing this worked like a champ on my gridview. Just a little aside, I think the valid code is: ButtonType=\"Link\"</p>\n\n<p>I suspect this is because when you click 'edit', your edit changes to 'update' and 'cancel' which then change back to 'edit' on submit. And these shifting controls make .net uneasy.</p>\n"
},
{
"answer_id": 783784,
"author": "Boog",
"author_id": 16492,
"author_profile": "https://Stackoverflow.com/users/16492",
"pm_score": 0,
"selected": false,
"text": "<p>I worked around this exact error by not adding the ListBox to a parent Page/Control Controls collection. Because I really didn't need any server-side functionality out of it. I just wanted to use it to output the HTML for a custom server control, which I did in the OnRender event handler myself. I hoped that using the control would save me from writing to the response my own html.</p>\n\n<p>This solution probably won't work for most, but it keeps ASP.NET from performing the ValidateEvent against the control, because the control doesn't retain in memory between postbacks.</p>\n\n<p>Also, my error was specifically caused by the selected list item being an item that wasn't in the listbox the previous postback. Incase that helps anyone.</p>\n"
},
{
"answer_id": 824726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In this case add id to the button in RowDataBound of the grid. It will solve your problem.</p>\n"
},
{
"answer_id": 1506432,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>When I added the id on ItemDataBound then it did not give me the error, but it was not giving me the command name. It was returning command name empty. Then I added command name as well while ItemDataBound. Then it resolved the same problem. Thanks Nilesh, great suggestion. It Worked :)</p>\n"
},
{
"answer_id": 1762943,
"author": "Umar Farooq Khawaja",
"author_id": 151742,
"author_profile": "https://Stackoverflow.com/users/151742",
"pm_score": 4,
"selected": false,
"text": "<p>I had the same problem with a Repeater because I had a web-page with a Repeater control in a web-site which had EnableEventValidation switched on. It wasn't good. I was getting invalid postback related exceptions.</p>\n\n<p>What worked for me was to set EnableViewState=\"false\" for the Repeater. The advantages are that it is simpler to use, as simple as switching event validation off for the web-site or web-page, but the scope is a lot less than switching event validation off for either.</p>\n"
},
{
"answer_id": 2054526,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A simple solution for this problem is to use the <strong>IsPostBack</strong> check on your page load. That will solve this problem.</p>\n"
},
{
"answer_id": 2401684,
"author": "Razia",
"author_id": 288816,
"author_profile": "https://Stackoverflow.com/users/288816",
"pm_score": 1,
"selected": false,
"text": "<p>I was using datalist and I was getting the same error for my push button. I just use IsPostBack to check and fill my controls and the problem is solved! Great!!!</p>\n"
},
{
"answer_id": 3346940,
"author": "cem",
"author_id": 403774,
"author_profile": "https://Stackoverflow.com/users/403774",
"pm_score": 1,
"selected": false,
"text": "<p>Four minutes ago I received the same error. Then I have researched during one half hour like you. In all forums they are generally saying \"add page enableEvent..=false or true\". Any solution proposed didn't resolved my problems until I found it. The problem is unfortunately an ASP.NET button. I removed it two seconds ago. I tried to replace with \"imagebutton\", but it was also unacceptable (because it gave the same error).</p>\n\n<p>Finally I have replaced with <code>LinkButton</code>. it seems to be working!</p>\n"
},
{
"answer_id": 3758957,
"author": "Jeff Pang",
"author_id": 453722,
"author_profile": "https://Stackoverflow.com/users/453722",
"pm_score": 8,
"selected": false,
"text": "<p>Do you have code in your Page_Load events? if yes, then perhaps adding the following will help.</p>\n<pre><code>if (!Page.IsPostBack)\n{ //do something }\n</code></pre>\n<p>This error is thrown when you click on your command and the Page_load is being ran again, in a normal life cycle it would be\nPage_Load -> Click on Command -> Page_Load (again) -> Process ItemCommand Event</p>\n"
},
{
"answer_id": 3776581,
"author": "batsuuri",
"author_id": 455948,
"author_profile": "https://Stackoverflow.com/users/455948",
"pm_score": -1,
"selected": false,
"text": "<p>Check you data of binded your controls. Some invalid data corrupt ValidateEvent.</p>\n"
},
{
"answer_id": 3937787,
"author": "Murad Dodhiya",
"author_id": 476330,
"author_profile": "https://Stackoverflow.com/users/476330",
"pm_score": 1,
"selected": false,
"text": "<p>What worked for me is moving the following code from page_load to page_prerender:</p>\n\n<pre><code>lstMain.DataBind();\nImage img = (Image)lstMain.Items[0].FindControl(\"imgMain\");\n\n// Define the name and type of the client scripts on the page.\nString csname1 = \"PopupScript\";\nType cstype = this.GetType();\n\n// Get a ClientScriptManager reference from the Page class.\nClientScriptManager cs = Page.ClientScript;\n\n// Check to see if the startup script is already registered.\nif (!cs.IsStartupScriptRegistered(cstype, csname1))\n{\n cs.RegisterStartupScript(cstype, csname1, \"<script language=javascript> p=\\\"\" + img.ClientID + \"\\\"</script>\");\n}\n</code></pre>\n"
},
{
"answer_id": 4178314,
"author": "pamelo",
"author_id": 484265,
"author_profile": "https://Stackoverflow.com/users/484265",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar issue, but I was not using ASP.Net 1.1 nor updating a control via javascript.\nMy problem only happened on Firefox and not on IE (!).</p>\n\n<p>I added options to a DropDownList on the PreRender event like this:</p>\n\n<pre><code>DropDownList DD = (DropDownList)F.FindControl(\"DDlista\");\nHiddenField HF = (HiddenField)F.FindControl(\"HFlista\");\nstring[] opcoes = HF.value.Split('\\n');\nforeach (string opcao in opcoes) DD.Items.Add(opcao);\n</code></pre>\n\n<p>My \"HF\" (hiddenfield) had the options separated by the newline, like this:</p>\n\n<pre><code>HF.value = \"option 1\\n\\roption 2\\n\\roption 3\";\n</code></pre>\n\n<p>The problem was that the HTML page was broken (I mean had newlines) on the options of the \"select\" that represented the DropDown.</p>\n\n<p>So I resolved my my problem adding one line:</p>\n\n<pre><code>DropDownList DD = (DropDownList)F.FindControl(\"DDlista\");\nHiddenField HF = (HiddenField)F.FindControl(\"HFlista\");\nstring dados = HF.Value.Replace(\"\\r\", \"\");\nstring[] opcoes = dados.Split('\\n');\nforeach (string opcao in opcoes) DD.Items.Add(opcao);\n</code></pre>\n\n<p>Hope this help someone.</p>\n"
},
{
"answer_id": 5033280,
"author": "Tushar",
"author_id": 621947,
"author_profile": "https://Stackoverflow.com/users/621947",
"pm_score": 2,
"selected": false,
"text": "<p>We ran into this same issue when we were converting our regular ASPX pages to Content pages. </p>\n\n<p>The page with this issue had a <code></form></code> tag within one of the Content sections, thus two form end tags were rendered at run time which caused this issue. Removing the extra form end tag from the page resolved this issue.</p>\n"
},
{
"answer_id": 5055843,
"author": "ali joodie",
"author_id": 625067,
"author_profile": "https://Stackoverflow.com/users/625067",
"pm_score": 2,
"selected": false,
"text": "<p>if you change <code>UseSubmitBehavior=\"True\"</code> to <code>UseSubmitBehavior=\"False\"</code> your problem will be solved</p>\n\n<pre><code><asp:Button ID=\"BtnDis\" runat=\"server\" CommandName=\"BtnDis\" CommandArgument='<%#Eval(\"Id\")%>' Text=\"Discription\" CausesValidation=\"True\" UseSubmitBehavior=\"False\" />\n</code></pre>\n"
},
{
"answer_id": 5144268,
"author": "Mike C.",
"author_id": 637966,
"author_profile": "https://Stackoverflow.com/users/637966",
"pm_score": 3,
"selected": false,
"text": "<p>One other way not mentioned here is to subclass ListBox</p>\n\n<p>Ie. </p>\n\n<pre><code>public class ListBoxNoEventValidation : ListBox \n{\n}\n</code></pre>\n\n<p>ClientEventValidation keys off the attribute System.Web.UI.SupportsEventValidation if you subclass it, unless you explicitly add it back in, it will never call the validation routine. That works with any control, and is the only way I've found to \"disable\" it on a control by control basis (Ie, not page level).</p>\n"
},
{
"answer_id": 5744178,
"author": "Swathi",
"author_id": 718933,
"author_profile": "https://Stackoverflow.com/users/718933",
"pm_score": 3,
"selected": false,
"text": "<p>I implemented a nested grid view and i faced the same problem .I have used LinkButton instead of image button like this:</p>\n\n<p>before i had a column like this:</p>\n\n<pre><code><asp:TemplateField ItemStyle-Width=\"9\">\n <ItemTemplate>\n <asp:ImageButton ID=\"ImgBtn\" ImageUrl=\"Include/images/gridplus.gif\" CommandName=\"Expand\"\n runat=\"server\" />\n </ItemTemplate>\n</asp:TemplateField>\n</code></pre>\n\n<p>I have replaced like this.</p>\n\n<pre><code><asp:TemplateField>\n<ItemTemplate>\n <asp:LinkButton CommandName=\"Expand\" ID=\"lnkBtn\" runat=\"server\" ><asp:Image ID=\"Img\" runat=\"server\" ImageUrl=\"~/Images/app/plus.gif\" /></asp:LinkButton>\n </ItemTemplate>\n</asp:TemplateField> \n</code></pre>\n"
},
{
"answer_id": 5883678,
"author": "devo882",
"author_id": 738013,
"author_profile": "https://Stackoverflow.com/users/738013",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using Ajax update panel. Add <code><Triggers></code> tag and inside it trigger the Button or control causing the postBack using <code><asp:PostBackTrigger .../></code></p>\n"
},
{
"answer_id": 6344010,
"author": "Programista",
"author_id": 287815,
"author_profile": "https://Stackoverflow.com/users/287815",
"pm_score": 1,
"selected": false,
"text": "<p>Best option to do is use hidden field and do not disable event validation, also change every listbox, dropdownlist to select with runat server attribute</p>\n"
},
{
"answer_id": 6953748,
"author": "Niket",
"author_id": 880215,
"author_profile": "https://Stackoverflow.com/users/880215",
"pm_score": 2,
"selected": false,
"text": "<p>I've had the same problem, what I did:</p>\n\n<p>Just added a condition <code>if(!IsPostBack)</code> and it works fine :)</p>\n"
},
{
"answer_id": 7750203,
"author": "Josh",
"author_id": 960978,
"author_profile": "https://Stackoverflow.com/users/960978",
"pm_score": 4,
"selected": false,
"text": "<p>I had the same problem when modifying a ListBox using JavaScript on the client. It occurs when you add new items to the ListBox from the client that were not there when the page was rendered. </p>\n\n<p>The fix that I found is to inform the event validation system of all the possible valid items that can be added from the client. You do this by overriding Page.Render and calling Page.ClientScript.RegisterForEventValidation for each value that your JavaScript could add to the list box:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>protected override void Render(HtmlTextWriter writer)\n{\n foreach (string val in allPossibleListBoxValues)\n {\n Page.ClientScript.RegisterForEventValidation(myListBox.UniqueID, val);\n }\n base.Render(writer);\n}\n</code></pre>\n\n<p>This can be kind of a pain if you have a large number of potentially valid values for the list box. In my case I was moving items between two ListBoxes - one that that has all the possible values and another that is initially empty but gets filled in with a subset of the values from the first one in JavaScript when the user clicks a button. In this case you just need to iterate through the items in the first ListBoxand register each one with the second list box:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>protected override void Render(HtmlTextWriter writer)\n{\n foreach (ListItem i in listBoxAll.Items)\n {\n Page.ClientScript.RegisterForEventValidation(listBoxSelected.UniqueID, i.Value);\n }\n base.Render(writer);\n}\n</code></pre>\n"
},
{
"answer_id": 7853928,
"author": "tmck2",
"author_id": 990558,
"author_profile": "https://Stackoverflow.com/users/990558",
"pm_score": 2,
"selected": false,
"text": "<p>I know that this is a super-old post. Assuming that you are calling into your application, here is an idea that has worked for me:</p>\n\n<ol>\n<li>Implement the ICallbackEventHandler on your page</li>\n<li>Call ClientScriptManager.GetCallbackEventReference to call your server side code</li>\n<li>As the error message states, you could then call ClientScriptManager.RegisterForEventValidation</li>\n</ol>\n\n<p>If you don't need total control, you could use an update panel which would do this for you.</p>\n"
},
{
"answer_id": 13949590,
"author": "CraigS",
"author_id": 1363554,
"author_profile": "https://Stackoverflow.com/users/1363554",
"pm_score": 1,
"selected": false,
"text": "<p>If you know up front the data that could be populated, you can use the ClientScriptManager to resolve this issue. I had this issue when dynamically populating a drop down box using javascript on a previous user selection.</p>\n\n<p>Here is some example code for overriding the render method (in VB and C#) and declaring a potential value for the dropdownlist ddCar.</p>\n\n<p>In VB:</p>\n\n<pre><code>Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)\n\n Dim ClientScript As ClientScriptManager = Page.ClientScript\n\n ClientScript.RegisterForEventValidation(\"ddCar\", \"Mercedes\")\n\n MyBase.Render(writer)\nEnd Sub\n</code></pre>\n\n<p>or a slight variation in C# could be:</p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\n Page.ClientScript.RegisterForEventValidation(\"ddCar\", \"Mercedes\");\n base.Render(writer);\n}\n</code></pre>\n\n<p>For newbies: This should go in the code behind file (.vb or .cs) or if used in the aspx file you can wrap in <code><script></code> tags.</p>\n"
},
{
"answer_id": 15714437,
"author": "yilee",
"author_id": 2156481,
"author_profile": "https://Stackoverflow.com/users/2156481",
"pm_score": 3,
"selected": false,
"text": "<p>(1) EnableEventValidation=\"false\"...................It does not work for me.</p>\n\n<p>(2) ClientScript.RegisterForEventValidation....It does not work for me.</p>\n\n<p><strong>Solution 1:</strong></p>\n\n<p>Change Button/ImageButton to LinkButton in GridView. It works. (But I like ImageButton)</p>\n\n<p>Research: Button/ImageButton and LinkButton use different methods to postback</p>\n\n<p><strong>Original article:</strong></p>\n\n<p><a href=\"http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx\">http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx</a></p>\n\n<p><strong>Solution 2:</strong></p>\n\n<p>In OnInit() , enter the code something like this to set unique ID for Button/ImageButton :</p>\n\n<pre><code>protected override void OnInit(EventArgs e) {\n foreach (GridViewRow grdRw in gvEvent.Rows) {\n\n Button deleteButton = (Button)grdRw.Cells[2].Controls[1];\n\n deleteButton.ID = \"btnDelete_\" + grdRw.RowIndex.ToString(); \n }\n}\n</code></pre>\n\n<p><strong>Original Article:</strong> </p>\n\n<p><a href=\"http://www.c-sharpcorner.com/Forums/Thread/35301/\">http://www.c-sharpcorner.com/Forums/Thread/35301/</a></p>\n"
},
{
"answer_id": 19320006,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This was the reason why I was getting it:</p>\n\n<p>I had an ASP:ListBox. Initially it was hidden. At client side I would populate it via AJAX with options. The user chose one option. Then when clicking the Submit button, the Server would get all funny about the ListBox, since it did not remember it having any options.</p>\n\n<p>So what I did is to make sure I clear all the list options before submitting the form back to the server. That way the server did not complain since the list went to the client empty and it came back empty.</p>\n\n<p>Sorted!!!</p>\n"
},
{
"answer_id": 19816890,
"author": "Nick B",
"author_id": 2961257,
"author_profile": "https://Stackoverflow.com/users/2961257",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem, two list boxes and two buttons.</p>\n\n<p>The data in the list boxes was being loaded from a database and you could move items between boxes by clicking the buttons.</p>\n\n<p>I was getting an invalid postback.</p>\n\n<p>turns out that it was the data had carriage return line feeds in it which you cannot see when displayed in the list box.</p>\n\n<p>worked fine in every browser except IE 10 and IE 11.</p>\n\n<p>Remove the carriage return line feeds and all works fine.</p>\n"
},
{
"answer_id": 20786904,
"author": "Balaji Selvarajan",
"author_id": 3135882,
"author_profile": "https://Stackoverflow.com/users/3135882",
"pm_score": 2,
"selected": false,
"text": "<p>This error will show without postback</p>\n\n<p>Add code: </p>\n\n<pre><code>If(!IsPostBack){\n\n //do something\n\n}\n</code></pre>\n"
},
{
"answer_id": 28993051,
"author": "markiyanm",
"author_id": 456605,
"author_profile": "https://Stackoverflow.com/users/456605",
"pm_score": 0,
"selected": false,
"text": "<p>FYI I had the same issue with that error message and it was that I had 2 form tags on the same page. There was one in the Master page and one in the page itself. Soon as I removed the second form tag pair the problem went away.</p>\n"
},
{
"answer_id": 31187805,
"author": "Andre RB",
"author_id": 2944964,
"author_profile": "https://Stackoverflow.com/users/2944964",
"pm_score": 1,
"selected": false,
"text": "<p>As Nick B said and that worked for me you have to remove line breaks in some cases. Take a look at the code:</p>\n\n<p>-Wrong way:</p>\n\n<pre><code><asp:DropDownList ID=\"DropDownList1\" runat=\"server\">\n <asp:ListItem Selected=\"True\">\n Item 1</asp:ListItem>\n <asp:ListItem>\n Item 2</asp:ListItem>\n <asp:ListItem>\n Item 3</asp:ListItem>\n</asp:DropDownList>\n</code></pre>\n\n<p>-Right way:</p>\n\n<pre><code><asp:DropDownList ID=\"DropDownList1\" runat=\"server\">\n <asp:ListItem Selected=\"True\">Item 1</asp:ListItem>\n <asp:ListItem>Item 2</asp:ListItem>\n <asp:ListItem>Item 3</asp:ListItem>\n</asp:DropDownList>\n</code></pre>\n\n<p>It only ocurred for me in IE10+</p>\n"
},
{
"answer_id": 32064413,
"author": "user3690871",
"author_id": 3690871,
"author_profile": "https://Stackoverflow.com/users/3690871",
"pm_score": 3,
"selected": false,
"text": "<p>you try something like that,in your .aspx page</p>\n\n\n\n<p>add </p>\n\n<blockquote>\n <p>EnableEventValidation=\"false\"</p>\n</blockquote>\n\n<p>you feel free to ask any question!</p>\n"
},
{
"answer_id": 36181804,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": "<p>After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0. </p>\n\n<p>This caused the app pool to give up and reply with the exception noted in the question. </p>\n"
},
{
"answer_id": 36724438,
"author": "biggles",
"author_id": 5579080,
"author_profile": "https://Stackoverflow.com/users/5579080",
"pm_score": 4,
"selected": false,
"text": "<p>None of the above worked for me. After more digging I realized I had overlooked 2 forms applied on the page which was causing the issue.</p>\n\n<pre><code><body>\n<form id=\"form1\" runat=\"server\">\n<div>\n <form action=\"#\" method=\"post\" class=\"form\" role=\"form\">\n <div>\n ...\n <asp:Button ID=\"submitButton\" runat=\"server\"\n </div>\n</div>\n</body>\n</code></pre>\n\n<p>Be aware that recently ASP.NET has started considering iframes within a form tag which contains a form tag in the iframe document itself a nested frame. I had to move the iframe out of the form tag to avoid this error.</p>\n"
},
{
"answer_id": 42356691,
"author": "Sudhakar Rao",
"author_id": 2798049,
"author_profile": "https://Stackoverflow.com/users/2798049",
"pm_score": 0,
"selected": false,
"text": "<p>The following example shows how to test the value of the IsPostBack property when the page is loaded in order to determine whether the page is being rendered for the first time or is responding to a postback. If the page is being rendered for the first time, the code calls the Page.Validate method.\nThe page markup (not shown) contains RequiredFieldValidator controls that display asterisks if no entry is made for a required input field. Calling Page.Validate causes the asterisks to be displayed immediately when the page is rendered, instead of waiting until the user clicks the Submit button. After a postback, you do not have to call Page.Validate, because that method is called as part of the Page life cycle. </p>\n\n<pre><code> private void Page_Load()\n {\n if (!IsPostBack)\n { \n }\n }\n</code></pre>\n"
},
{
"answer_id": 49427870,
"author": "Akhil Singh",
"author_id": 7528842,
"author_profile": "https://Stackoverflow.com/users/7528842",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using gridview and not bind gridview at pageload inside !ispostback then this error occur when you click on edit and delete row in gridview . </p>\n\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n bindGridview();\n }\n</code></pre>\n"
},
{
"answer_id": 51951356,
"author": "Zolfaghari",
"author_id": 2155778,
"author_profile": "https://Stackoverflow.com/users/2155778",
"pm_score": 0,
"selected": false,
"text": "<p>My problem was solved when cancel event at end of grid event at server side.</p>\n\n<pre><code>protected void grdEducation_RowEditing(object sender, GridViewEditEventArgs e)\n{\n // do your processing ...\n\n // at end<br />\n e.Cancel = true;\n}\n</code></pre>\n"
},
{
"answer_id": 56668980,
"author": "Marisol Gutiérrez",
"author_id": 8656365,
"author_profile": "https://Stackoverflow.com/users/8656365",
"pm_score": 1,
"selected": false,
"text": "<p>For us the problem was happening randomly only in the production environment. The RegisterForEventValidation did nothing for us.</p>\n\n<p>Finally, we figured out that the web farm in which the asp.net app was running, two IIS servers had different .net versions installed. So it appears they had different rules for encrypting the asp.net validation hash. Updating them solved most of the problem. </p>\n\n<p>Also, we configured the machineKey(compatibilityMode) (the same in both servers), httpRuntime(targetFramework), ValidationSettings:UnobtrusiveValidationMode, pages(renderAllHiddenFieldsAtTopOfForm) in the web.config of both servers.</p>\n\n<p>We used this site to generate the key <a href=\"https://www.allkeysgenerator.com/Random/ASP-Net-MachineKey-Generator.aspx\" rel=\"nofollow noreferrer\">https://www.allkeysgenerator.com/Random/ASP-Net-MachineKey-Generator.aspx</a></p>\n\n<p>We spent a lot of time solving this, I hope this helps somebody.</p>\n\n<pre><code><appSettings>\n <add key=\"ValidationSettings:UnobtrusiveValidationMode\" value=\"None\" />\n...\n</appSettings>\n<system.web>\n <machineKey compatibilityMode=\"Framework45\" decryptionKey=\"somekey\" validationKey=\"otherkey\" validation=\"SHA1\" decryption=\"AES />\n <pages [...] controlRenderingCompatibilityVersion=\"4.0\" enableEventValidation=\"true\" renderAllHiddenFieldsAtTopOfForm=\"true\" />\n <httpRuntime [...] requestValidationMode=\"2.0\" targetFramework=\"4.5\" />\n...\n</system.web>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.
How do we fix this?
Error details below:
```
Server Error in '/XXX' Application.
--------------------------------------------------------------------------------
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
```
|
The problem is that ASP.NET does not get to know about this extra or removed listitem.
You got an number of options (listed below):
* Disable eventvalidation (bad idea, because you lose a little of security that come with very little cost).
* Use ASP.NET Ajax UpdatePanel. (Put the listbox in the Updatepanel and trigger a update, if you add or remove listbox. This way viewstate and related fields get updates and eventvalidation will pass.)
* Forget client-side and use the classic postback and add or remove the listitems server-side.
I hope this helps.
|
228,978 |
<p>I have this Perl script with many defined constants of configuration files. For example:</p>
<pre><code>use constant {
LOG_DIR => "/var/log/",
LOG_FILENAME => "/var/log/file1.log",
LOG4PERL_CONF_FILE => "/etc/app1/log4perl.conf",
CONF_FILE1 => "/etc/app1/config1.xml",
CONF_FILE2 => "/etc/app1/config2.xml",
CONF_FILE3 => "/etc/app1/config3.xml",
CONF_FILE4 => "/etc/app1/config4.xml",
CONF_FILE5 => "/etc/app1/config5.xml",
};
</code></pre>
<p>I want to reduce duplication of "/etc/app1" and "/var/log" , but using variables does not work. Also using previously defined constants does not work in the same "use constant block". For example:</p>
<pre><code>use constant {
LOG_DIR => "/var/log/",
FILE_FILENAME => LOG_DIR . "file1.log"
};
</code></pre>
<p>does not work.</p>
<p>Using separate "use constant" blocks does workaround this problem, but that adds a lot of unneeded code.</p>
<p>What is the correct way to do this?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 228991,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "<p>That's not going to work, sadly. The reason for this is that you are using functions ('constants') before they are defined. You evaluate them before the call to <code>constant->import</code>.</p>\n\n<p>Using variables doesn't work because use statements are evaluated at compile time. Assigning to variables is only done at runtime, so they won't be defined yet.</p>\n\n<p>The only solution I can give is to split it into multiple <code>use constant</code> statements. In this case, two statements will do (one for <code>LOG_DIR</code> and <code>CONF_DIR</code>, another for the rest).</p>\n"
},
{
"answer_id": 229061,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 4,
"selected": true,
"text": "<p>I'd probably write it like this:</p>\n\n<pre><code>use Readonly;\n\nReadonly my $LOG_DIR => \"/var/log\";\nReadonly my $LOG_FILENAME => \"$LOG_DIR/file1.log\";\nReadonly my $ETC => '/etc/app1';\nReadonly my $LOG4PERL_CONF_FILE => \"$ETC/log4perl.con\";\n\n# hash because we don't have an index '0'\nReadonly my %CONF_FILES => map { $_ => \"$ETC/config$_.xml\" } 1 .. 5;\n</code></pre>\n\n<p>However, that's still a lot of code, but it does remove the duplication and that's a win.</p>\n\n<p>Why are your logfiles numeric? If they start with 0, an array is a better choice than a hash. If they're named, they're more descriptive.</p>\n"
},
{
"answer_id": 229550,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Using separate \"use constant\" blocks\n does workaround this problem, but that\n adds a lot of unneeded code.</p>\n</blockquote>\n\n<p>Does it really?</p>\n\n<pre><code>use constant BASE_PATH => \"/etc/app1\";\n\nuse constant {\n LOG4PERL_CONF_FILE => BASE_PATH . \"/log4perl.conf\",\n CONF_FILE1 => BASE_PATH . \"/config1.xml\",\n CONF_FILE2 => BASE_PATH . \"/config2.xml\",\n CONF_FILE3 => BASE_PATH . \"/config3.xml\",\n CONF_FILE4 => BASE_PATH . \"/config4.xml\",\n CONF_FILE5 => BASE_PATH . \"/config5.xml\",\n};\n</code></pre>\n\n<p>I don't see a lot of problems with this. You have specified the base path in one point only, thereby respecting the DRY principle. If you assign BASE_PATH with an environment variable:</p>\n\n<pre><code>use constant BASE_PATH => $ENV{MY_BASE_PATH} || \"/etc/app1\";\n</code></pre>\n\n<p>... you then have a cheap way of reconfiguring your constant without having to edit your code. What's there to not like about this?</p>\n\n<p>If you really want to cut down the repetitive \"BASE_PATH . \" concatenation, you could add a bit of machinery to install the constants yourself and factor that away:</p>\n\n<pre><code>use strict;\nuse warnings;\n\nuse constant BASE_PATH => $ENV{MY_PATH} || '/etc/apps';\n\nBEGIN {\n my %conf = (\n FILE1 => \"/config1.xml\",\n FILE2 => \"/config2.xml\",\n );\n\n for my $constant (keys %conf) {\n no strict 'refs';\n *{__PACKAGE__ . \"::CONF_$constant\"}\n = sub () {BASE_PATH . \"$conf{$constant}\"};\n }\n}\n\nprint \"Config is \", CONF_FILE1, \".\\n\";\n</code></pre>\n\n<p>But at this point I think the balance has swung away from Correct to Nasty :) For a start, you can no longer grep for CONF_FILE1 and see where it is defined.</p>\n"
},
{
"answer_id": 230051,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "<pre><code>use constant +{\n map { sprintf $_, '/var/log' } (\n LOG_DIR => \"%s/\",\n LOG_FILENAME => \"%s/file1.log\",\n ),\n map { sprintf $_, '/etc/app1' } (\n LOG4PERL_CONF_FILE => \"%s/log4perl.conf\",\n CONF_FILE1 => \"%s/config1.xml\",\n CONF_FILE2 => \"%s/config2.xml\",\n CONF_FILE3 => \"%s/config3.xml\",\n CONF_FILE4 => \"%s/config4.xml\",\n CONF_FILE5 => \"%s/config5.xml\",\n ),\n};\n</code></pre>\n"
},
{
"answer_id": 241296,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on what you are doing, you might not want constants at all. Mostly, I write stuff that other people use to get their stuff done, so I solve this problem in a way that gives other programmers flexibility. I make these things into methods:</p>\n\n<pre><code> sub base_log_dir { '...' }\n\n sub get_log_file\n {\n my( $self, $number ) = @_;\n\n my $log_file = catfile( \n $self->base_log_dir, \n sprintf \"foo%03d\", $number\n );\n }\n</code></pre>\n\n<p>By doing it this way, I can easily extend or override things. </p>\n\n<p>Doing this loses the value of constant folding though, so you have to think about how important that is to you.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
I have this Perl script with many defined constants of configuration files. For example:
```
use constant {
LOG_DIR => "/var/log/",
LOG_FILENAME => "/var/log/file1.log",
LOG4PERL_CONF_FILE => "/etc/app1/log4perl.conf",
CONF_FILE1 => "/etc/app1/config1.xml",
CONF_FILE2 => "/etc/app1/config2.xml",
CONF_FILE3 => "/etc/app1/config3.xml",
CONF_FILE4 => "/etc/app1/config4.xml",
CONF_FILE5 => "/etc/app1/config5.xml",
};
```
I want to reduce duplication of "/etc/app1" and "/var/log" , but using variables does not work. Also using previously defined constants does not work in the same "use constant block". For example:
```
use constant {
LOG_DIR => "/var/log/",
FILE_FILENAME => LOG_DIR . "file1.log"
};
```
does not work.
Using separate "use constant" blocks does workaround this problem, but that adds a lot of unneeded code.
What is the correct way to do this?
Thank you.
|
I'd probably write it like this:
```
use Readonly;
Readonly my $LOG_DIR => "/var/log";
Readonly my $LOG_FILENAME => "$LOG_DIR/file1.log";
Readonly my $ETC => '/etc/app1';
Readonly my $LOG4PERL_CONF_FILE => "$ETC/log4perl.con";
# hash because we don't have an index '0'
Readonly my %CONF_FILES => map { $_ => "$ETC/config$_.xml" } 1 .. 5;
```
However, that's still a lot of code, but it does remove the duplication and that's a win.
Why are your logfiles numeric? If they start with 0, an array is a better choice than a hash. If they're named, they're more descriptive.
|
228,985 |
<p>I'm trying to get tags working in my rails application and want to use acts_as_taggable. Firstly I followed the instructions I found in Rails Recipies (a free sample bit online) that used the acts_as_taggable plugin. However, I then found <a href="http://taggable.rubyforge.org/" rel="nofollow noreferrer">this site</a> which seems to have a gem for acts_as_taggable which is more advanced (has options for related tags etc).</p>
<p>I've tried to follow the instructions there to install it, but I keep getting errors.</p>
<p>Firstly I installed the gem as normal (<code>gem install acts_as_taggable</code>) and then I tried various ways to get rails to recognise and load the gem. The <code>require_gem</code> listed on the site didn't work (I assume that is an old command that has been removed) and neither did a straight <code>require</code> (although that has worked for my bluecloth gem).</p>
<p>I've then tried using <code>config.gem 'acts_as_taggable'</code> but that keeps telling me that I haven't got acts_as_taggable installed and asks me to run <code>rake gems:install</code>. No matter how many times I run that it still gives the error!</p>
<p>The result of the <code>gem query -l -n acts_as_taggable</code> lists acts_as_taggable as an installed local gem.</p>
<p>I've tried running <code>gem check</code> and that doesn't show any problems.</p>
<p>The response I get when I try to require it from the console is:</p>
<pre><code>MissingSourceFile: no such file to load -- acts_as_taggable
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `ge
m_original_require'
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `re
quire'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:510:in `require'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:355:in `new_constants_in'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:510:in `require'
from (irb):1
</code></pre>
<p>It looks like for some reason it can't find it. Any ideas why?</p>
|
[
{
"answer_id": 229017,
"author": "glenatron",
"author_id": 15394,
"author_profile": "https://Stackoverflow.com/users/15394",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried running something like \"gem query -l -n <em>taggable</em>\" to check whether it has installed correctly into your local gem repository?</p>\n\n<p>If it has you could use some of the built in checks against it - <a href=\"http://www.rubygems.org/read/chapter/10\" rel=\"nofollow noreferrer\">Gem is good for this</a> - to make sure it installed as it is supposed to.</p>\n\n<p>That would be my first avenue to explore.</p>\n"
},
{
"answer_id": 241923,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 3,
"selected": true,
"text": "<p>You could also try <a href=\"http://agilewebdevelopment.com/plugins/acts_as_taggable_on_steroids\" rel=\"nofollow noreferrer\">acts_as_taggable_on_steroids</a>:</p>\n\n<blockquote>\n <p>This plugin is based on acts_as_taggable by DHH but includes extras such as tests, smarter tag assignment, and tag cloud calculations.</p>\n</blockquote>\n\n<p>I've used it recently. Aside from some performance issues, it works very well and, unlike <a href=\"http://taggable.rubyforge.org/\" rel=\"nofollow noreferrer\">taggable</a>, is under active maintenance.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912/"
] |
I'm trying to get tags working in my rails application and want to use acts\_as\_taggable. Firstly I followed the instructions I found in Rails Recipies (a free sample bit online) that used the acts\_as\_taggable plugin. However, I then found [this site](http://taggable.rubyforge.org/) which seems to have a gem for acts\_as\_taggable which is more advanced (has options for related tags etc).
I've tried to follow the instructions there to install it, but I keep getting errors.
Firstly I installed the gem as normal (`gem install acts_as_taggable`) and then I tried various ways to get rails to recognise and load the gem. The `require_gem` listed on the site didn't work (I assume that is an old command that has been removed) and neither did a straight `require` (although that has worked for my bluecloth gem).
I've then tried using `config.gem 'acts_as_taggable'` but that keeps telling me that I haven't got acts\_as\_taggable installed and asks me to run `rake gems:install`. No matter how many times I run that it still gives the error!
The result of the `gem query -l -n acts_as_taggable` lists acts\_as\_taggable as an installed local gem.
I've tried running `gem check` and that doesn't show any problems.
The response I get when I try to require it from the console is:
```
MissingSourceFile: no such file to load -- acts_as_taggable
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `ge
m_original_require'
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `re
quire'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:510:in `require'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:355:in `new_constants_in'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:510:in `require'
from (irb):1
```
It looks like for some reason it can't find it. Any ideas why?
|
You could also try [acts\_as\_taggable\_on\_steroids](http://agilewebdevelopment.com/plugins/acts_as_taggable_on_steroids):
>
> This plugin is based on acts\_as\_taggable by DHH but includes extras such as tests, smarter tag assignment, and tag cloud calculations.
>
>
>
I've used it recently. Aside from some performance issues, it works very well and, unlike [taggable](http://taggable.rubyforge.org/), is under active maintenance.
|
228,987 |
<p>We try to convert from string to <code>Byte[]</code> using the following Java code:</p>
<pre><code>String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16");
</code></pre>
<p>We get a byte array of length 22 bytes, we are not sure where this padding comes from.
How do I get an array of length 20?</p>
|
[
{
"answer_id": 228998,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 5,
"selected": false,
"text": "<p>May be the first two bytes are the <a href=\"http://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"nofollow noreferrer\">Byte Order Mark</a>. It specifies the order of bytes in each 16-bit word used in the encoding.</p>\n"
},
{
"answer_id": 229005,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 3,
"selected": false,
"text": "<p>Try printing out the bytes in hex to see where the extra 2 bytes are added - are they at the start or end?</p>\n\n<p>I'm picking that you'll find a <a href=\"http://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"noreferrer\">byte order marker</a> at the start (0xFEFF) - this allows anyone consuming (receiving) the byte array to recognise whether the encoding is little-endian or big-endian.</p>\n"
},
{
"answer_id": 229006,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/228987/convert-string-to-byte-in-java#228998\">Alexander's answer</a> explains why it's there, but not how to get rid of it. You simply need to specify the endianness you want in the encoding name:</p>\n\n<pre><code>String source = \"0123456789\";\nbyte[] byteArray = source.getBytes(\"UTF-16LE\"); // Or UTF-16BE\n</code></pre>\n"
},
{
"answer_id": 229029,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 3,
"selected": false,
"text": "<p>UTF has a byte order marker at the beginning that tells that this stream is encoded in a particular format. As the other users have pointed out, the <br>\n1st byte is 0XFE<br>\n2nd byte is 0XFF<br>\nthe remaining bytes are <br>\n0<br>\n48<br>\n0<br>\n49<br>\n0<br>\n50<br>\n0<br>\n51<br>\n0<br>\n52<br>\n0<br>\n53<br>\n0<br>\n54<br>\n0<br>\n55<br>\n0<br>\n56<br>\n0<br>\n57<br></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30704/"
] |
We try to convert from string to `Byte[]` using the following Java code:
```
String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16");
```
We get a byte array of length 22 bytes, we are not sure where this padding comes from.
How do I get an array of length 20?
|
[Alexander's answer](https://stackoverflow.com/questions/228987/convert-string-to-byte-in-java#228998) explains why it's there, but not how to get rid of it. You simply need to specify the endianness you want in the encoding name:
```
String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16LE"); // Or UTF-16BE
```
|
229,007 |
<p>I am running the free version of Helicon ISAPI Rewrite on IIS and have several sites running through the same set of rewrite rules. Up 'til now this has been fine as all the rules have applied to all the sites. I have recently added a new site which I don't want to run through all the rules. Is there any way to make requests to this site break out of the rule set after it's executed its own rules.</p>
<p>I've tried the following with no luck; all requests to mysite.com result in a 404. I guess what I'm looking for is a rule that does nothing and is marked as the last rule to execute [L].</p>
<pre><code>## New site rule for mysite.com only
RewriteCond Host: (?:www\.)?mysite\.com
RewriteRule /content([\w/]*) /content.aspx?page=$1 [L]
## Break out of processing for all other requests to mysite.com
RewriteCond Host: (?:www\.)?mysite\.com
RewriteRule (.*) - [L]
## Rules for all other sites
RewriteRule ^/([^\.\?]+)/?(\?.*)?$ /$1.aspx$2 [L]
...
</code></pre>
|
[
{
"answer_id": 229026,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 2,
"selected": false,
"text": "<p>Rewrite it to itself?</p>\n\n<pre><code>RewriteCond Host: (?:www\\.)?mysite\\.com\nRewriteRule ^(.*)$ $1 [QSA,L]\n</code></pre>\n"
},
{
"answer_id": 229523,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 5,
"selected": true,
"text": "<p>I've done something similar, to stop mod_rewrite on a WebDAV folder: </p>\n\n<pre><code># stop processing if we're in the webdav folder\nRewriteCond %{REQUEST_URI} ^/webdav [NC]\nRewriteRule .* - [L]\n</code></pre>\n\n<p>That should work for your purposes too. If not or if you are interested in additional references, see this previous question: <a href=\"https://stackoverflow.com/questions/163302/\">How do I ignore a directory in mod_rewrite?</a></p>\n"
},
{
"answer_id": 1128867,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know ISAPI Rewrite syntax, but on <a href=\"http://iirf.codeplex.com\" rel=\"nofollow noreferrer\">IIRF</a>, the \"break out\" rule is like this: </p>\n\n<pre><code>## Break out of processing for all other requests to mysite.com\nRewriteCond %{SERVER_NAME} ^(?:www\\.)?mysite\\.com$\nRewriteRule (.*) - [L]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>## Break out of processing for all other requests to mysite.com\nRewriteCond %{HTTP_HOST} ^(?:www\\.)?mysite\\.com$\nRewriteRule (.*) - [L]\n</code></pre>\n\n<p>In each case the rule says \"don't rewrite (and don't process any more rules)\" and it applies when the hostname used is mysite.com or www.mysite.com. The [L] flag is the part that says \"don't process any more rules\" and the - replacement is the part that says \"don't rewrite\". </p>\n"
},
{
"answer_id": 47487534,
"author": "Frank N",
"author_id": 444255,
"author_profile": "https://Stackoverflow.com/users/444255",
"pm_score": 3,
"selected": false,
"text": "<h2><code>RewriteRule ^ - [END]</code></h2>\n\n<ul>\n<li><code>.</code> would be incorrect, since it requires at least 1 char</li>\n<li><code>.*</code> <em>could</em> be less efficient IMHO</li>\n<li>L is worse than END, as it allows for additional rounds, also on internal redirects. Only END truly stops. → <a href=\"https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_l\" rel=\"noreferrer\"><strong>Details</strong></a></li>\n</ul>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2179408/"
] |
I am running the free version of Helicon ISAPI Rewrite on IIS and have several sites running through the same set of rewrite rules. Up 'til now this has been fine as all the rules have applied to all the sites. I have recently added a new site which I don't want to run through all the rules. Is there any way to make requests to this site break out of the rule set after it's executed its own rules.
I've tried the following with no luck; all requests to mysite.com result in a 404. I guess what I'm looking for is a rule that does nothing and is marked as the last rule to execute [L].
```
## New site rule for mysite.com only
RewriteCond Host: (?:www\.)?mysite\.com
RewriteRule /content([\w/]*) /content.aspx?page=$1 [L]
## Break out of processing for all other requests to mysite.com
RewriteCond Host: (?:www\.)?mysite\.com
RewriteRule (.*) - [L]
## Rules for all other sites
RewriteRule ^/([^\.\?]+)/?(\?.*)?$ /$1.aspx$2 [L]
...
```
|
I've done something similar, to stop mod\_rewrite on a WebDAV folder:
```
# stop processing if we're in the webdav folder
RewriteCond %{REQUEST_URI} ^/webdav [NC]
RewriteRule .* - [L]
```
That should work for your purposes too. If not or if you are interested in additional references, see this previous question: [How do I ignore a directory in mod\_rewrite?](https://stackoverflow.com/questions/163302/)
|
229,009 |
<p>Is there a way I can access (for printout) a list of sub + module to arbitrary depth of sub-calls preceding a current position in a Perl script?</p>
<p>I need to make changes to some Perl modules (.pm's). The workflow is initiated from a web-page thru a cgi-script, passing input through several modules/objects ending in the module where I need to use the data. Somewhere along the line the data got changed and I need to find out where.</p>
|
[
{
"answer_id": 229030,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 7,
"selected": true,
"text": "<p>You can use <a href=\"http://search.cpan.org/dist/Devel-StackTrace/\" rel=\"noreferrer\">Devel::StackTrace</a>.</p>\n\n<pre><code>use Devel::StackTrace;\nmy $trace = Devel::StackTrace->new;\nprint $trace->as_string; # like carp\n</code></pre>\n\n<p>It behaves like Carp's trace, but you can get more control over the frames.</p>\n\n<p>The one problem is that references are stringified and if a referenced value changes, you won't see it. However, you could whip up some stuff with <a href=\"http://search.cpan.org/dist/PadWalker/\" rel=\"noreferrer\">PadWalker</a> to print out the full data (it would be huge, though).</p>\n"
},
{
"answer_id": 229035,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://perldoc.perl.org/functions/caller.html\" rel=\"noreferrer\">caller</a> can do that, though you may want even more information than that.</p>\n"
},
{
"answer_id": 229151,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 4,
"selected": false,
"text": "<p>There's also <code>Carp::confess</code> and <code>Carp::cluck</code>.</p>\n"
},
{
"answer_id": 231863,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 4,
"selected": false,
"text": "<p><code>Carp::longmess</code> will do what you want, and it's standard.</p>\n\n<pre><code>use Carp qw<longmess>;\nuse Data::Dumper;\nsub A { &B; }\nsub B { &C; }\nsub C { &D; }\nsub D { &E; }\n\nsub E { \n # Uncomment below if you want to see the place in E\n # local $Carp::CarpLevel = -1; \n my $mess = longmess();\n print Dumper( $mess );\n}\n\nA();\n__END__\n$VAR1 = ' at - line 14\n main::D called at - line 12\n main::C called at - line 10\n main::B called at - line 8\n main::A() called at - line 23\n';\n</code></pre>\n\n<p>I came up with this sub (Now with optional blessin' action!)</p>\n\n<pre><code>my $stack_frame_re = qr{\n ^ # Beginning of line\n \\s* # Any number of spaces\n ( [\\w:]+ ) # Package + sub\n (?: [(] ( .*? ) [)] )? # Anything between two parens\n \\s+ # At least one space\n called [ ] at # \"called\" followed by a single space\n \\s+ ( \\S+ ) \\s+ # Spaces surrounding at least one non-space character\n line [ ] (\\d+) # line designation\n}x;\n\nsub get_stack {\n my @lines = split /\\s*\\n\\s*/, longmess;\n shift @lines;\n my @frames\n = map { \n my ( $sub_name, $arg_str, $file, $line ) = /$stack_frame_re/;\n my $ref = { sub_name => $sub_name\n , args => [ map { s/^'//; s/'$//; $_ } \n split /\\s*,\\s*/, $arg_str \n ]\n , file => $file\n , line => $line \n };\n bless $ref, $_[0] if @_;\n $ref\n } \n @lines\n ;\n return wantarray ? @frames : \\@frames;\n}\n</code></pre>\n"
},
{
"answer_id": 24822871,
"author": "user2291758",
"author_id": 2291758,
"author_profile": "https://Stackoverflow.com/users/2291758",
"pm_score": 2,
"selected": false,
"text": "<p>One that is more pretty: <a href=\"https://metacpan.org/pod/Devel::PrettyTrace\" rel=\"nofollow\" title=\"Devel::PrettyTrace\">Devel::PrettyTrace</a></p>\n\n<pre><code>use Devel::PrettyTrace;\nbt;\n</code></pre>\n"
},
{
"answer_id": 39011773,
"author": "Thariama",
"author_id": 346063,
"author_profile": "https://Stackoverflow.com/users/346063",
"pm_score": 5,
"selected": false,
"text": "<p>This code works <strong>without any additional modules</strong>.\nJust include it where needed.</p>\n\n<pre><code>my $i = 1;\nprint STDERR \"Stack Trace:\\n\";\nwhile ( (my @call_details = (caller($i++))) ){\n print STDERR $call_details[1].\":\".$call_details[2].\" in function \".$call_details[3].\"\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 56596630,
"author": "x-yuri",
"author_id": 52499,
"author_profile": "https://Stackoverflow.com/users/52499",
"pm_score": 2,
"selected": false,
"text": "<p>In case you can't use (or would like to avoid) non-core modules, here's a simple subroutine I came up with:</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nsub printstack {\n my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash);\n my $i = 1;\n my @r;\n while (@r = caller($i)) {\n ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) = @r;\n print \"$filename:$line $subroutine\\n\";\n $i++;\n }\n}\n\nsub i {\n printstack();\n}\n\nsub h {\n i;\n}\n\nsub g {\n h;\n}\n\ng;\n</code></pre>\n\n<p>It produces output like as follows:</p>\n\n<pre><code>/root/_/1.pl:21 main::i\n/root/_/1.pl:25 main::h\n/root/_/1.pl:28 main::g\n</code></pre>\n\n<p>Or a oneliner:</p>\n\n<pre><code>for (my $i = 0; my @r = caller($i); $i++) { print \"$r[1]:$r[2] $r[3]\\n\"; }\n</code></pre>\n\n<p>You can find documentation on caller <a href=\"https://perldoc.perl.org/functions/caller.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 59791844,
"author": "Pablo Bianchi",
"author_id": 4970442,
"author_profile": "https://Stackoverflow.com/users/4970442",
"pm_score": 2,
"selected": false,
"text": "<p>Moving <a href=\"https://stackoverflow.com/questions/229009/how-can-i-get-a-call-stack-listing-in-perl#comment87243409_229030\">my comment</a> to an answer:</p>\n\n<ol>\n<li><p>Install <a href=\"https://metacpan.org/pod/Devel::Confess\" rel=\"nofollow noreferrer\">Devel::Confess</a> the <a href=\"https://cpan.metacpan.org/modules/INSTALL.html\" rel=\"nofollow noreferrer\">right way</a></p>\n\n<pre><code>cpanm Devel::Confess\n</code></pre></li>\n<li><p>Run with</p>\n\n<pre><code>perl -d:Confess myscript.pl\n</code></pre></li>\n</ol>\n\n<p>On errors, this will show the whole call stack list.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
] |
Is there a way I can access (for printout) a list of sub + module to arbitrary depth of sub-calls preceding a current position in a Perl script?
I need to make changes to some Perl modules (.pm's). The workflow is initiated from a web-page thru a cgi-script, passing input through several modules/objects ending in the module where I need to use the data. Somewhere along the line the data got changed and I need to find out where.
|
You can use [Devel::StackTrace](http://search.cpan.org/dist/Devel-StackTrace/).
```
use Devel::StackTrace;
my $trace = Devel::StackTrace->new;
print $trace->as_string; # like carp
```
It behaves like Carp's trace, but you can get more control over the frames.
The one problem is that references are stringified and if a referenced value changes, you won't see it. However, you could whip up some stuff with [PadWalker](http://search.cpan.org/dist/PadWalker/) to print out the full data (it would be huge, though).
|
229,010 |
<pre><code>$("#dvMyDIV").bind("resize", function(){
alert("Resized");
});
</code></pre>
<p>or</p>
<pre><code>$("#dvMyDIV").resize(function(){
alert("Resized");
});
</code></pre>
<p>The questions</p>
<ol>
<li>Why is this not working at FireFox, Chrome and Safari?</li>
<li>Can this be considered a jQuery bug since the resize is not handled for other browsers?</li>
<li>Could the only workaround be calling a SetTimeout function checking the clientHeight and clientWidth?</li>
<li>Any workarounds using jQuery?</li>
</ol>
|
[
{
"answer_id": 229028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>I believe the JavaScript resize event only applies to frames or windows, not to DIVs.</p>\n\n<p>e.g. see <a href=\"http://devguru.com/technologies/javascript/10929.asp\" rel=\"noreferrer\">this page</a>:</p>\n\n<blockquote>\n <p>The onResize even handler is use to execute specified code whenever a user or script resizes a window or frame. This allows you to query the size and position of window elements, dynamically reset SRC properties etc. </p>\n</blockquote>\n\n<p>So if you want to detect when the window is resized, in jQuery you should probably use <code>$(window).resize(function() { });</code></p>\n\n<p><b>Edit:</b> if you want to watch the size of a DIV, it depends on what your intention is. If you're resizing with JavaScript then you could implement a method to perform the resize and have that handle calling any other resize code.</p>\n\n<p>Otherwise, if you're just watching for the DIV to resize when someone resizes the window, wouldn't it just work to attach the resize listener to the window and then check if the DIV had been resized (i.e. store the old values of width / height and check them on resize)?</p>\n\n<p>Finally, you could consider using <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch\" rel=\"noreferrer\">watch</a> on the width / height properties, although I don't know whether this is fully browser-compatible (think this might be Mozilla-only). I did find <a href=\"http://www.west-wind.com/Weblog/posts/453942.aspx\" rel=\"noreferrer\">this jQuery plugin</a> which looks like it might do the same thing though (with some slight modification).</p>\n"
},
{
"answer_id": 229054,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 0,
"selected": false,
"text": "<p>Why do you expect #dvMyDIV to be resized? Is maybe resizing of that element a result of something else, maybe the window being resized? If so, try</p>\n\n<pre><code>$(window).resize(function(){alert(\"Resized\");});\n</code></pre>\n"
},
{
"answer_id": 229139,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 0,
"selected": false,
"text": "<p>I might suggest something like this:</p>\n\n<p>1) on page load, get width of your div and put it in a global variable</p>\n\n<p>2) on execution of whatever operation directly or implicitly resizes that div (which I assume is a javascript-driven event) check the new width against the old width and update the global value with the new width.</p>\n"
},
{
"answer_id": 229182,
"author": "Matt Goddard",
"author_id": 5185,
"author_profile": "https://Stackoverflow.com/users/5185",
"pm_score": 1,
"selected": false,
"text": "<p>Are you trying to set myDiv to a specific size?</p>\n\n<p>Try the JavaScript code below. I used it for resizing a div which holds a flash object based upon a height being returned from the flash file and it seemed to work okay for me.</p>\n\n<pre><code>function setMovieHeight(value) {\n var height = Number(value) + 50;\ndocument.getElementById(\"video\").height = height;\n}\n</code></pre>\n\n<p>the jQuery equivilent should be:</p>\n\n<pre><code>function setHeight(value) {\n var height = number(value) + 50;\n $('#MyDiv').attr('height') = height;\n}\n</code></pre>\n\n<p>resize does only seem to apply to the windows object.</p>\n"
},
{
"answer_id": 2366373,
"author": "Chad",
"author_id": 284732,
"author_profile": "https://Stackoverflow.com/users/284732",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a much more refined and a live example that does a lot of resize math all based on the window resize event. Works brilliantly in ff 3.6, safari 4.0.4, and chrome. It is a little chunky in ff 3.5. So thus it should work in mozilla and webkit across the boards. I avoid the other BROWSER, because I really do not like it, and the code is so much cleaner without having to consider it. I realize that I will have to get over that, I swallow it when I have to with and IE surcharge. </p>\n\n<p>ANYWAY the link:</p>\n\n<p><a href=\"http://fridaydev.com/bookmap/proport3.html\" rel=\"nofollow noreferrer\">http://fridaydev.com/bookmap/proport3.html</a></p>\n"
},
{
"answer_id": 3704537,
"author": "BoBoDev",
"author_id": 441851,
"author_profile": "https://Stackoverflow.com/users/441851",
"pm_score": 1,
"selected": false,
"text": "<p>It is not the question WHY? It is Demanded, as in, we WANT to monitor a DIV when it is resized. </p>\n\n<p>For obvious example, jQuery UI, resizable. Yeah, user resized a div by mouse drag, now what? Maybe the content inside is resized and we want to know about it. And should we have all the code in a giant melting pot within the original reszing code? I don't think so.</p>\n\n<p>Another speedy browser that does nothing, sigh.</p>\n"
},
{
"answer_id": 4894469,
"author": "Ludmil Tinkov",
"author_id": 519553,
"author_profile": "https://Stackoverflow.com/users/519553",
"pm_score": 0,
"selected": false,
"text": "<p>With MSIE everything works just fine. With Firefox, I guess you'll have to resort to some oblique techniques such as storing the element's original width/height in custom properties and using <code>$(elem).bind('DOMAttrModified', func)</code>. Then in the func() callback, check if the new width/height differ from the ones you stored previously, take the respective resize action and store them again for the next event callback. Note that this approach works for Firefox only. I haven't been able to find a decent workaround for Chrome, Safari and Opera yet. Maybe using window.setInterval() would do but... sounds too slopy... event the thought of it makes me kinda sick :(</p>\n"
},
{
"answer_id": 7902130,
"author": "Aamir Afridi",
"author_id": 569751,
"author_profile": "https://Stackoverflow.com/users/569751",
"pm_score": 3,
"selected": false,
"text": "<p>There is a benalman plugin for that :)</p>\n\n<p><a href=\"http://benalman.com/projects/jquery-resize-plugin/\">http://benalman.com/projects/jquery-resize-plugin/</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17447/"
] |
```
$("#dvMyDIV").bind("resize", function(){
alert("Resized");
});
```
or
```
$("#dvMyDIV").resize(function(){
alert("Resized");
});
```
The questions
1. Why is this not working at FireFox, Chrome and Safari?
2. Can this be considered a jQuery bug since the resize is not handled for other browsers?
3. Could the only workaround be calling a SetTimeout function checking the clientHeight and clientWidth?
4. Any workarounds using jQuery?
|
I believe the JavaScript resize event only applies to frames or windows, not to DIVs.
e.g. see [this page](http://devguru.com/technologies/javascript/10929.asp):
>
> The onResize even handler is use to execute specified code whenever a user or script resizes a window or frame. This allows you to query the size and position of window elements, dynamically reset SRC properties etc.
>
>
>
So if you want to detect when the window is resized, in jQuery you should probably use `$(window).resize(function() { });`
**Edit:** if you want to watch the size of a DIV, it depends on what your intention is. If you're resizing with JavaScript then you could implement a method to perform the resize and have that handle calling any other resize code.
Otherwise, if you're just watching for the DIV to resize when someone resizes the window, wouldn't it just work to attach the resize listener to the window and then check if the DIV had been resized (i.e. store the old values of width / height and check them on resize)?
Finally, you could consider using [watch](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch) on the width / height properties, although I don't know whether this is fully browser-compatible (think this might be Mozilla-only). I did find [this jQuery plugin](http://www.west-wind.com/Weblog/posts/453942.aspx) which looks like it might do the same thing though (with some slight modification).
|
229,012 |
<p>How can I convert a relative path to an absolute path in C on Unix?
Is there a convenient system function for this?</p>
<p>On Windows there is a <code>GetFullPathName</code> function that does the job, but I didn't find something similar on Unix...</p>
|
[
{
"answer_id": 229038,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 7,
"selected": true,
"text": "<p>Use <a href=\"http://www.opengroup.org/onlinepubs/000095399/functions/realpath.html\" rel=\"noreferrer\">realpath()</a>.</p>\n\n<blockquote>\n <p>The <code>realpath()</code> function shall derive,\n from the pathname pointed to by\n <code>file_name</code>, an absolute pathname that\n names the same file, whose resolution\n does not involve '<code>.</code>', '<code>..</code>', or\n symbolic links. The generated pathname\n shall be stored as a null-terminated\n string, up to a maximum of <code>{PATH_MAX}</code>\n bytes, in the buffer pointed to by\n <code>resolved_name</code>.</p>\n \n <p>If <code>resolved_name</code> is a null pointer,\n the behavior of <code>realpath()</code> is\n implementation-defined.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>The following example generates an\n absolute pathname for the file\n identified by the symlinkpath\n argument. The generated pathname is\n stored in the actualpath array.</p>\n</blockquote>\n\n<pre><code>#include <stdlib.h>\n...\nchar *symlinkpath = \"/tmp/symlink/file\";\nchar actualpath [PATH_MAX+1];\nchar *ptr;\n\n\nptr = realpath(symlinkpath, actualpath);\n</code></pre>\n"
},
{
"answer_id": 41212150,
"author": "PADYMKO",
"author_id": 6003870,
"author_profile": "https://Stackoverflow.com/users/6003870",
"pm_score": 0,
"selected": false,
"text": "<p>Also try \"getcwd\"</p>\n\n<pre><code>#include <unistd.h>\n\nchar cwd[100000];\ngetcwd(cwd, sizeof(cwd));\nstd::cout << \"Absolute path: \"<< cwd << \"/\" << __FILE__ << std::endl;\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Absolute path: /media/setivolkylany/WorkDisk/Programming/Sources/MichailFlenov/main.cpp\n</code></pre>\n\n<p>Testing environment:</p>\n\n<pre><code>setivolkylany@localhost$/ lsb_release -a\nNo LSB modules are available.\nDistributor ID: Debian\nDescription: Debian GNU/Linux 8.6 (jessie)\nRelease: 8.6\nCodename: jessie\nsetivolkylany@localhost$/ uname -a\nLinux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux\nsetivolkylany@localhost$/ g++ --version\ng++ (Debian 4.9.2-10) 4.9.2\nCopyright (C) 2014 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n</code></pre>\n"
},
{
"answer_id": 53808693,
"author": "Scott Yang",
"author_id": 4751658,
"author_profile": "https://Stackoverflow.com/users/4751658",
"pm_score": 3,
"selected": false,
"text": "<p>Try <code>realpath()</code> in <code>stdlib.h</code></p>\n\n<pre><code>char filename[] = \"../../../../data/000000.jpg\";\nchar* path = realpath(filename, NULL);\nif(path == NULL){\n printf(\"cannot find file with name[%s]\\n\", filename);\n} else{\n printf(\"path[%s]\\n\", path);\n free(path);\n}\n</code></pre>\n"
},
{
"answer_id": 54970463,
"author": "Julius",
"author_id": 10674275,
"author_profile": "https://Stackoverflow.com/users/10674275",
"pm_score": 2,
"selected": false,
"text": "<p>There is also a small path library <a href=\"https://github.com/likle/cwalk\" rel=\"nofollow noreferrer\">cwalk</a> which works cross-platform. It has <a href=\"https://likle.github.io/cwalk/reference/cwk_path_get_absolute.html\" rel=\"nofollow noreferrer\">cwk_path_get_absolute</a> to do that:</p>\n\n<pre><code>#include <cwalk.h>\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n char buffer[FILENAME_MAX];\n\n cwk_path_get_absolute(\"/hello/there\", \"./world\", buffer, sizeof(buffer));\n printf(\"The absolute path is: %s\", buffer);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>The absolute path is: /hello/there/world\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9280/"
] |
How can I convert a relative path to an absolute path in C on Unix?
Is there a convenient system function for this?
On Windows there is a `GetFullPathName` function that does the job, but I didn't find something similar on Unix...
|
Use [realpath()](http://www.opengroup.org/onlinepubs/000095399/functions/realpath.html).
>
> The `realpath()` function shall derive,
> from the pathname pointed to by
> `file_name`, an absolute pathname that
> names the same file, whose resolution
> does not involve '`.`', '`..`', or
> symbolic links. The generated pathname
> shall be stored as a null-terminated
> string, up to a maximum of `{PATH_MAX}`
> bytes, in the buffer pointed to by
> `resolved_name`.
>
>
> If `resolved_name` is a null pointer,
> the behavior of `realpath()` is
> implementation-defined.
>
>
>
---
>
> The following example generates an
> absolute pathname for the file
> identified by the symlinkpath
> argument. The generated pathname is
> stored in the actualpath array.
>
>
>
```
#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;
ptr = realpath(symlinkpath, actualpath);
```
|
229,021 |
<p>We want to show a hint for a JList that the user can select multiple items with the platform dependent key for multiselect. </p>
<p>However I have not found any way to show the OS X COMMAND symbol in a JLabel, which means the symbol that's printed on the apple keyboard on the command key, also called apple key.</p>
<p>Here's a picture of the symbol I want to display on OS X. <a href="https://i.stack.imgur.com/VKGb4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VKGb4.png" alt="COMMAND SYMBOL"></a><br>
<sub>(source: <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Command_key.svg/120px-Command_key.svg.png" rel="nofollow noreferrer">wikimedia.org</a>)</sub> </p>
<p>Also I do want to have it platform independent.</p>
<p>I.e. something like </p>
<pre><code>component.add( new JList() , BorderLayout.CENTER );
component.add( new JLabel( MessageFormat.format("With {0} you can "
+ "select multiple items",
KeyStroke.getKeyStroke( ... , ... ) ) ) , BorderLayout.SOUTH );
</code></pre>
<p>Where instead of the <em>{0}</em> there should appear above seen symbol...</p>
<p>Does any one of you guys know how to do this? I know it must be possible somehow since in the JMenuItems there is the symbol...</p>
<p>My own (non graphical solutions) looks like this:</p>
<pre><code>add( new JLabel( MessageFormat.format(
"With {0} you can select multiple items" ,
System.getProperty( "mrj.version" ) != null ? "COMMAND" : "CTRL" ) ) ,
BorderLayout.SOUTH );
</code></pre>
|
[
{
"answer_id": 232786,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 0,
"selected": false,
"text": "<p>Your solution looks perfect. I assume you intend to factor out the hint code so you reuse it.</p>\n\n<pre><code>add( new JLabel( MessageFormat.format(\n \"With {0} you can select multiple items\", \n getMetaKeyHint(),\n BorderLayout.SOUTH );\n\npublic String getMetaKeyHint() {\n return System.getProperty( \"mrj.version\" ) != null ? \"COMMAND\" : \"CTRL\" );\n}\n</code></pre>\n"
},
{
"answer_id": 233062,
"author": "Dan",
"author_id": 9774,
"author_profile": "https://Stackoverflow.com/users/9774",
"pm_score": 0,
"selected": false,
"text": "<p>I use the following code to check for the system and load accordingly</p>\n\n<pre><code>(System.getProperty(\"os.name\").toUpperCase(Locale.US).indexOf(\"MAC OS X\") == 0 )\n</code></pre>\n"
},
{
"answer_id": 236642,
"author": "banjollity",
"author_id": 29620,
"author_profile": "https://Stackoverflow.com/users/29620",
"pm_score": 3,
"selected": true,
"text": "<p>The symbol in question is avaiable through Unicode, and the HTML character sets. All you need to do is make your JLabel display HTML by starting its text string with <html> and then include the character code.</p>\n\n<pre><code>JLabel label = new JLabel( \"<html>&#8984; is the Apple command symbol.\" );\n</code></pre>\n\n<p>This will work on a Mac, but I've no idea what it'll do on other platforms, although you do seem to have that covered off.</p>\n"
},
{
"answer_id": 236771,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>As David points out, you can use the Unicode escape sequence <code>\\u2318</code> although it must be displayed with a font supporting it.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16193/"
] |
We want to show a hint for a JList that the user can select multiple items with the platform dependent key for multiselect.
However I have not found any way to show the OS X COMMAND symbol in a JLabel, which means the symbol that's printed on the apple keyboard on the command key, also called apple key.
Here's a picture of the symbol I want to display on OS X. [](https://i.stack.imgur.com/VKGb4.png)
(source: [wikimedia.org](https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Command_key.svg/120px-Command_key.svg.png))
Also I do want to have it platform independent.
I.e. something like
```
component.add( new JList() , BorderLayout.CENTER );
component.add( new JLabel( MessageFormat.format("With {0} you can "
+ "select multiple items",
KeyStroke.getKeyStroke( ... , ... ) ) ) , BorderLayout.SOUTH );
```
Where instead of the *{0}* there should appear above seen symbol...
Does any one of you guys know how to do this? I know it must be possible somehow since in the JMenuItems there is the symbol...
My own (non graphical solutions) looks like this:
```
add( new JLabel( MessageFormat.format(
"With {0} you can select multiple items" ,
System.getProperty( "mrj.version" ) != null ? "COMMAND" : "CTRL" ) ) ,
BorderLayout.SOUTH );
```
|
The symbol in question is avaiable through Unicode, and the HTML character sets. All you need to do is make your JLabel display HTML by starting its text string with <html> and then include the character code.
```
JLabel label = new JLabel( "<html>⌘ is the Apple command symbol." );
```
This will work on a Mac, but I've no idea what it'll do on other platforms, although you do seem to have that covered off.
|
229,031 |
<p>I need to test a web form that takes a file upload.
The filesize in each upload will be about 10 MB.
I want to test if the server can handle over 100 simultaneous uploads, and still remain
responsive for the rest of the site.</p>
<p>Repeated form submissions from our office will be limited by our local DSL line.
The server is offsite with higher bandwidth.</p>
<p>Answers based on experience would be great, but any suggestions are welcome.</p>
|
[
{
"answer_id": 229051,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "<p>I would perhaps guide you towards using cURL and submitting just random stuff (like, read 10MB out of <code>/dev/urandom</code> and encode it into base32), through a POST-request and manually fabricate the body to be a file upload (it's not rocket science).</p>\n\n<p>Fork that script 100 times, perhaps over a few servers. Just make sure that sysadmins don't think you are doing a DDoS, or something :)</p>\n\n<p>Unfortunately, this answer remains a bit vague, but hopefully it helps you by nudging you in the right track.</p>\n\n<p><strong>Continued as per Liam's comment:</strong><br/>\nIf the server receiving the uploads is not in the same LAN as the clients connecting to it, it would be better to get as remote nodes as possible for stress testing, if only to simulate behavior as authentic as possible. But if you don't have access to computers outside the local LAN, the local LAN is always better than nothing.</p>\n\n<p>Stress testing from inside the same hardware would be not a good idea, as you would do double load on the server: Figuring out the random data, packing it, sending it through the TCP/IP stack (although probably not over Ethernet), and <em>only then</em> can the server do its magic. If the sending part is outsourced, you get double (taken with an arbitrary sized grain of salt) performance by the receiving end.</p>\n"
},
{
"answer_id": 229056,
"author": "Midhat",
"author_id": 9425,
"author_profile": "https://Stackoverflow.com/users/9425",
"pm_score": 0,
"selected": false,
"text": "<p>Automate <a href=\"http://selenium-rc.openqa.org/\" rel=\"nofollow noreferrer\">Selenium RC</a> using your favorite language. Start 100 Threads of Selenium,each typing a path of the file in the input and clicking submit.</p>\n\n<p>You could generate 100 sequentially named files to make looping over them easyily, or just use the same file over and over again</p>\n"
},
{
"answer_id": 323983,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 4,
"selected": true,
"text": "<p>Use the <a href=\"http://httpd.apache.org/docs/2.0/programs/ab.html\" rel=\"noreferrer\">ab (ApacheBench)</a> command-line tool that is bundled with Apache\n(I have just discovered this great little tool). Unlike cURL or wget,\nApacheBench was designed for performing stress tests on web servers (any type of web server!).\nIt generates plenty statistics too. The following command will send a\nHTTP POST request including the file <code>test.jpg</code> to <code>http://localhost/</code>\n100 times, with up to 4 concurrent requests.</p>\n\n<pre><code>ab -n 100 -c 4 -p test.jpg http://localhost/\n</code></pre>\n\n<p>It produces output like this:</p>\n\n<pre><code>Server Software: \nServer Hostname: localhost\nServer Port: 80\n\nDocument Path: /\nDocument Length: 0 bytes\n\nConcurrency Level: 4\nTime taken for tests: 0.78125 seconds\nComplete requests: 100\nFailed requests: 0\nWrite errors: 0\nNon-2xx responses: 100\nTotal transferred: 2600 bytes\nHTML transferred: 0 bytes\nRequests per second: 1280.00 [#/sec] (mean)\nTime per request: 3.125 [ms] (mean)\nTime per request: 0.781 [ms] (mean, across all concurrent requests)\nTransfer rate: 25.60 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 2.6 0 15\nProcessing: 0 2 5.5 0 15\nWaiting: 0 1 4.8 0 15\nTotal: 0 2 6.0 0 15\n\nPercentage of the requests served within a certain time (ms)\n 50% 0\n 66% 0\n 75% 0\n 80% 0\n 90% 15\n 95% 15\n 98% 15\n 99% 15\n 100% 15 (longest request)\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18333/"
] |
I need to test a web form that takes a file upload.
The filesize in each upload will be about 10 MB.
I want to test if the server can handle over 100 simultaneous uploads, and still remain
responsive for the rest of the site.
Repeated form submissions from our office will be limited by our local DSL line.
The server is offsite with higher bandwidth.
Answers based on experience would be great, but any suggestions are welcome.
|
Use the [ab (ApacheBench)](http://httpd.apache.org/docs/2.0/programs/ab.html) command-line tool that is bundled with Apache
(I have just discovered this great little tool). Unlike cURL or wget,
ApacheBench was designed for performing stress tests on web servers (any type of web server!).
It generates plenty statistics too. The following command will send a
HTTP POST request including the file `test.jpg` to `http://localhost/`
100 times, with up to 4 concurrent requests.
```
ab -n 100 -c 4 -p test.jpg http://localhost/
```
It produces output like this:
```
Server Software:
Server Hostname: localhost
Server Port: 80
Document Path: /
Document Length: 0 bytes
Concurrency Level: 4
Time taken for tests: 0.78125 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Non-2xx responses: 100
Total transferred: 2600 bytes
HTML transferred: 0 bytes
Requests per second: 1280.00 [#/sec] (mean)
Time per request: 3.125 [ms] (mean)
Time per request: 0.781 [ms] (mean, across all concurrent requests)
Transfer rate: 25.60 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 2.6 0 15
Processing: 0 2 5.5 0 15
Waiting: 0 1 4.8 0 15
Total: 0 2 6.0 0 15
Percentage of the requests served within a certain time (ms)
50% 0
66% 0
75% 0
80% 0
90% 15
95% 15
98% 15
99% 15
100% 15 (longest request)
```
|
229,058 |
<p>When using something like <code>object.methods.sort.to_yaml</code> I'd like to have irb interpret the \n characters rather than print them. </p>
<p>I currently get the following output:</p>
<pre><code>--- \n- "&"\n- "*"\n- +\n- "-"\n- "<<"\n- <=>\n ...
</code></pre>
<p>What I'd like is something similar to this:</p>
<pre><code>---
- "&"
- "*"
- +
- "-"
- "<<"
- <=>
</code></pre>
<p>Is this possible? Is there another method I can be calling which will interpret the string perhaps?</p>
|
[
{
"answer_id": 229064,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 0,
"selected": false,
"text": "<p>That's just irb -- I don't think you can control the <code>return</code> formatting.</p>\n\n<p>You can still use <code>print</code> or <code>puts</code> to display it as you want.</p>\n"
},
{
"answer_id": 229065,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "<p>Prefix your output with <code>puts</code>:</p>\n\n<pre><code>> puts object.methods.sort.to_yaml\n--- \n - \"&\"\n - \"*\"\n - +\n - \"-\"\n - \"<<\"\n - <=>\n => nil\n</code></pre>\n"
},
{
"answer_id": 229148,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 1,
"selected": false,
"text": "<p>Another option is to start irb with the noinspect option: </p>\n\n<pre><code>C:\\>irb --noinspect\nirb(main):001:0> Object.methods.to_yaml\n=> ---\n- instance_method\n- yaml_tag_read_class\n.....\n- constants\n- is_a?\n\nirb(main):002:0>\n</code></pre>\n"
},
{
"answer_id": 238354,
"author": "slothbear",
"author_id": 2464,
"author_profile": "https://Stackoverflow.com/users/2464",
"pm_score": 1,
"selected": false,
"text": "<p>The Ruby <em>yaml</em> library includes the \"<strong>y</strong>\" command, which takes care of both the yamlizing and the formatting:</p>\n\n<pre><code>y object.methods.sort\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17453/"
] |
When using something like `object.methods.sort.to_yaml` I'd like to have irb interpret the \n characters rather than print them.
I currently get the following output:
```
--- \n- "&"\n- "*"\n- +\n- "-"\n- "<<"\n- <=>\n ...
```
What I'd like is something similar to this:
```
---
- "&"
- "*"
- +
- "-"
- "<<"
- <=>
```
Is this possible? Is there another method I can be calling which will interpret the string perhaps?
|
Prefix your output with `puts`:
```
> puts object.methods.sort.to_yaml
---
- "&"
- "*"
- +
- "-"
- "<<"
- <=>
=> nil
```
|
229,071 |
<p>how to show all values of a particular field in a text box ???
ie. for eg. when u run the SP, u'll be getting 3 rows. and i want to show the (eg.empname)
in a textbox each value separated by a comma.
(ram, john, sita). </p>
|
[
{
"answer_id": 229282,
"author": "CaRDiaK",
"author_id": 15628,
"author_profile": "https://Stackoverflow.com/users/15628",
"pm_score": 1,
"selected": false,
"text": "<p>I had this problem the other day. If you are using SQL 2005 you can use the CROSS APPLY function.</p>\n\n<p>Here is a sample; </p>\n\n<pre><code>Structure; \nID TYPE TEXT\n1 1 Ram\n2 1 Jon\n3 2 Sita\n4 2 Joe\n\n\nExpecteed Output;\nID TYPE TEXT\n1 1 Ram, Jon\n2 2 Sita, Joe\n\nQuery; \nSELECT t.TYPE,LEFT(tl.txtlist,LEN(tl.txtlist)-1)\nFROM(SELECT DISTINCT TYPE FROM Table)t\nCROSS APPLY (SELECT TEXT + ','\n FROM Table\n WHERE TYPE=t.TYPE\n FOR XML PATH(''))tl(txtlist)\n</code></pre>\n\n<p>Hope this helps :) </p>\n\n<p>Remember you'll need to select this as something in your sp, then bind that to the textbox on your report. Good luck! </p>\n"
},
{
"answer_id": 325154,
"author": "Mike Shepard",
"author_id": 36429,
"author_profile": "https://Stackoverflow.com/users/36429",
"pm_score": 0,
"selected": false,
"text": "<p>In 2005 the cross apply looks like a good solution (haven't used it myself). I have usually solved this by creating a UDF that concatenates the values by looping through a cursor.</p>\n"
},
{
"answer_id": 345101,
"author": "jerryhung",
"author_id": 37568,
"author_profile": "https://Stackoverflow.com/users/37568",
"pm_score": 0,
"selected": false,
"text": "<p>The question should be \"How to concatenate rows\"\n<a href=\"http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-single-row.html\" rel=\"nofollow noreferrer\">http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-single-row.html</a></p>\n\n<p>CROSS APPLY works\nor FOR XML are good alternatives vs a cursor</p>\n\n<pre><code>SELECT \nCustomerID, \nSalesOrderIDs = REPLACE( \n ( \n SELECT \n SalesOrderID AS [data()] \n FROM \n Sales.SalesOrderHeader soh \n WHERE \n soh.CustomerID = c.CustomerID \n ORDER BY \n SalesOrderID \n FOR XML PATH ('') \n ), ' ', ',') \n</code></pre>\n\n<p>FROM \n Sales.Customer c \nORDER BY \n CustomerID</p>\n\n<p>You could use a Number/Tally table as well </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29867/"
] |
how to show all values of a particular field in a text box ???
ie. for eg. when u run the SP, u'll be getting 3 rows. and i want to show the (eg.empname)
in a textbox each value separated by a comma.
(ram, john, sita).
|
I had this problem the other day. If you are using SQL 2005 you can use the CROSS APPLY function.
Here is a sample;
```
Structure;
ID TYPE TEXT
1 1 Ram
2 1 Jon
3 2 Sita
4 2 Joe
Expecteed Output;
ID TYPE TEXT
1 1 Ram, Jon
2 2 Sita, Joe
Query;
SELECT t.TYPE,LEFT(tl.txtlist,LEN(tl.txtlist)-1)
FROM(SELECT DISTINCT TYPE FROM Table)t
CROSS APPLY (SELECT TEXT + ','
FROM Table
WHERE TYPE=t.TYPE
FOR XML PATH(''))tl(txtlist)
```
Hope this helps :)
Remember you'll need to select this as something in your sp, then bind that to the textbox on your report. Good luck!
|
229,078 |
<p>The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.</p>
<p>Any help would be much appreciated.</p>
<pre><code>function validate_phone($phone)
{
$phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";
$phonevalid = 0;
if (ereg($phoneregexp, $phone))
{
$phonevalid = 1;
}else{
$phonevalid = 0;
}
}
</code></pre>
|
[
{
"answer_id": 229089,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": true,
"text": "<p>If this is PHP, then the regex must be enclosed in quotes. <del>Furthermore, what's <code>preg</code>? Did you mean <code>preg_match</code>?</del></p>\n\n<p>Another thing. PHP knows boolean values. The canonical solution would rather look like this:</p>\n\n<pre><code>return preg_match($regex, $phone) !== 0;\n</code></pre>\n\n<p>EDIT: Or, using <code>ereg</code>:</p>\n\n<pre><code>return ereg($regex, $phone) !== FALSE;\n</code></pre>\n\n<p>(Here, the explicit test against <code>FALSE</code> isn't strictly necessary but since <code>ereg</code> returns a number upon success I feel safer coercing the value into a <code>bool</code>).</p>\n"
},
{
"answer_id": 229095,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 2,
"selected": false,
"text": "<p>Hmm well the code you pasted isn't quite valid, I fixed it up by adding the missing quotes, missing delimiters, and changed preg to preg_match. I didn't get the warning.</p>\n\n<p><strong>Edit</strong>: after seeing the other comment, you meant \"ereg\" not \"preg\"... that gives the warning. Try using <code>preg_match()</code> instead ;)</p>\n\n<pre><code><?php\nfunction validate_phone($phone) {\n $phoneregexp ='/^(\\+[1-9][0-9]*(\\([0-9]*\\)|-[0-9]*-))?[0]?[1-9][0-9\\- ]*$/';\n\n $phonevalid = 0;\n\n if (preg_match($phoneregexp, $phone)) {\n $phonevalid = 1;\n } else {\n $phonevalid = 0;\n }\n}\nvalidate_phone(\"123456\");\n?>\n</code></pre>\n"
},
{
"answer_id": 229098,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 0,
"selected": false,
"text": "<p>Just to provide some reference material please read</p>\n\n<ul>\n<li><a href=\"http://de.php.net/manual/en/book.pcre.php\" rel=\"nofollow noreferrer\">Regular Expressions (Perl-Compatible)</a></li>\n<li><a href=\"http://de.php.net/manual/en/function.preg-match.php\" rel=\"nofollow noreferrer\">preg_match()</a></li>\n</ul>\n\n<p>or if you'd like to stick with the POSIX regexp:</p>\n\n<ul>\n<li><a href=\"http://de.php.net/manual/en/book.regex.php\" rel=\"nofollow noreferrer\">Regular Expression (POSIX Extended)</a></li>\n<li><a href=\"http://de.php.net/manual/en/function.ereg.php\" rel=\"nofollow noreferrer\">ereg()</a></li>\n</ul>\n\n<p>The correct sample code has already been given above.</p>\n"
},
{
"answer_id": 229109,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<p>It's the <code>[0-9\\\\- ]</code> part of your RE - it's not escaping the \"<code>-</code>\" properly. Change it to <code>[0-9 -]</code> and you should be OK (a \"<code>-</code>\" at the last position in a character class is treated as literal, not part of a range specification).</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.
Any help would be much appreciated.
```
function validate_phone($phone)
{
$phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";
$phonevalid = 0;
if (ereg($phoneregexp, $phone))
{
$phonevalid = 1;
}else{
$phonevalid = 0;
}
}
```
|
If this is PHP, then the regex must be enclosed in quotes. ~~Furthermore, what's `preg`? Did you mean `preg_match`?~~
Another thing. PHP knows boolean values. The canonical solution would rather look like this:
```
return preg_match($regex, $phone) !== 0;
```
EDIT: Or, using `ereg`:
```
return ereg($regex, $phone) !== FALSE;
```
(Here, the explicit test against `FALSE` isn't strictly necessary but since `ereg` returns a number upon success I feel safer coercing the value into a `bool`).
|
229,080 |
<p>Is there a best-practice or common way in JavaScript to have class members as event handlers?</p>
<p>Consider the following simple example:</p>
<pre><code><head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked;
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="Click me" />
<script language="javascript" type="text/javascript">
var btn1counter = new ClickCounter('btn1');
</script>
</body>
</code></pre>
<p>The event handler buttonClicked gets called, but the _clickCount member is inaccessible, or <em>this</em> points to some other object.</p>
<p>Any good tips/articles/resources about this kind of problems?</p>
|
[
{
"answer_id": 229110,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 6,
"selected": true,
"text": "<pre><code>ClickCounter = function(buttonId) {\n this._clickCount = 0;\n var that = this;\n document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };\n}\n\nClickCounter.prototype = {\n buttonClicked: function() {\n this._clickCount++;\n alert('the button was clicked ' + this._clickCount + ' times');\n }\n}\n</code></pre>\n\n<p>EDIT almost 10 years later, with ES6, arrow functions and <a href=\"https://babeljs.io/docs/plugins/transform-class-properties/\" rel=\"noreferrer\">class properties</a></p>\n\n<pre><code>class ClickCounter {\n count = 0;\n constructor( buttonId ){\n document.getElementById(buttonId)\n .addEventListener( \"click\", this.buttonClicked );\n }\n buttonClicked = e => {\n this.count += 1;\n console.log(`clicked ${this.count} times`);\n }\n}\n</code></pre>\n\n<p><a href=\"https://codepen.io/anon/pen/zaYvqq\" rel=\"noreferrer\">https://codepen.io/anon/pen/zaYvqq</a></p>\n"
},
{
"answer_id": 229189,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 3,
"selected": false,
"text": "<p>A function attached directly to the onclick property will have the execution context's <code>this</code> property pointing at the element.</p>\n\n<p>When you need to an element event to run against a specific instance of an object (a la a delegate in .NET) then you'll need a closure:-</p>\n\n<pre><code>function MyClass() {this.count = 0;}\nMyClass.prototype.onclickHandler = function(target)\n{\n // use target when you need values from the object that had the handler attached\n this.count++;\n}\nMyClass.prototype.attachOnclick = function(elem)\n{\n var self = this;\n elem.onclick = function() {self.onclickHandler(this); }\n elem = null; //prevents memleak\n}\n\nvar o = new MyClass();\no.attachOnclick(document.getElementById('divThing'))\n</code></pre>\n"
},
{
"answer_id": 36102050,
"author": "kucherenkovova",
"author_id": 3900376,
"author_profile": "https://Stackoverflow.com/users/3900376",
"pm_score": 4,
"selected": false,
"text": "<p>I don't know why <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"noreferrer\"><code>Function.prototype.bind</code></a> wasn't mentioned here yet. So I'll just leave this here ;)</p>\n\n<pre><code>ClickCounter = function(buttonId) {\n this._clickCount = 0;\n document.getElementById(buttonId).onclick = this.buttonClicked.bind(this);\n}\n\nClickCounter.prototype = {\n buttonClicked: function() {\n this._clickCount++;\n alert('the button was clicked ' + this._clickCount + ' times');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36104114,
"author": "Tero Tolonen",
"author_id": 2287682,
"author_profile": "https://Stackoverflow.com/users/2287682",
"pm_score": 3,
"selected": false,
"text": "<p>You can use fat-arrow syntax, which binds to the lexical scope of the function</p>\n\n<pre><code>function doIt() {\n this.f = () => {\n console.log(\"f called ok\");\n this.g();\n }\n this.g = () => {\n console.log(\"g called ok\");\n }\n}\n</code></pre>\n\n<p>After that you can try</p>\n\n<pre><code>var n = new doIt();\nsetTimeout(n.f,1000);\n</code></pre>\n\n<p>You can try it on <a href=\"https://babeljs.io/repl/#?evaluate=true&presets=es2015%2Ces2015-loose%2Creact%2Cstage-0&experimental=true&loose=true&spec=false&code=%0Afunction%20doIt2()%20%7B%0A%20%20this.f%20%3D%20()%20%3D%3E%20%7B%0A%20%20%20%20console.log(%22f%20called%20ok%22)%3B%0A%20%20%20%20this.g()%3B%0A%20%20%7D%0A%20%20this.g%20%3D%20()%20%3D%3E%20%7B%0A%20%20%20%20console.log(%22g%20called%20ok%22)%3B%0A%20%20%7D%0A%7D%0Aclass%20doIt%20%7B%0A%20%20%20%20f()%20%7B%0A%20%20%20%20%20%20console.log(%22f%20called%22)%3B%0A%20%20%20%20%20%20this.g()%3B%0A%20%20%20%20%7D%0A%20%20%20%20g()%20%7B%0A%20%20%20%20%20%20console.log(%22g%20called%22)%3B%0A%20%20%20%20%7D%0A%7D%0A%0Avar%20n%20%3D%20new%20doIt()%3B%0An.f()%3B%0Avar%20n2%20%3D%20new%20doIt2()%3B%0An2.f()%3B%0A%0AsetTimeout(n.f%2C1000)%3B%0AsetTimeout(n2.f%2C1000)%3B%0A%0A%0A%0A%0A%0A%0A%0A\" rel=\"noreferrer\">babel</a> or if your browser supports ES6 on <a href=\"https://jsfiddle.net/tbr976b7/\" rel=\"noreferrer\">jsFiddle</a>.</p>\n\n<p>Unfortunately the ES6 Class -syntax does not seem to allow creating function lexically binded to this. I personally think it might as well do that. EDIT: There seems to be <a href=\"https://stackoverflow.com/questions/31362292/can-i-use-es6-fat-arrow-in-class-methods\">experimental ES7 feature to allow it</a>.</p>\n"
},
{
"answer_id": 65633153,
"author": "Herman Van Der Blom",
"author_id": 2111313,
"author_profile": "https://Stackoverflow.com/users/2111313",
"pm_score": 2,
"selected": false,
"text": "<p>I like to use <code>unnamed</code> functions, just implemented a navigation Class which handles this correctly:</p>\n<pre><code>this.navToggle.addEventListener('click', () => this.toggleNav() );\n</code></pre>\n<p>then <code>this.toggleNav()</code> can be just a function in the <code>Class</code>.</p>\n<p>I know I used to call a named function but it can be any code you put in between like this :</p>\n<pre><code>this.navToggle.addEventListener('click', () => { [any code] } );\n</code></pre>\n<p>Because of the <code>arrow</code> you pass the this instance and can use it there.</p>\n<p>Pawel had a little different convention but I think its better to use <code>functions</code> because the naming conventions for <code>Classes</code> and <code>Methods</code> in it is the way to go :-)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30056/"
] |
Is there a best-practice or common way in JavaScript to have class members as event handlers?
Consider the following simple example:
```
<head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked;
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="Click me" />
<script language="javascript" type="text/javascript">
var btn1counter = new ClickCounter('btn1');
</script>
</body>
```
The event handler buttonClicked gets called, but the \_clickCount member is inaccessible, or *this* points to some other object.
Any good tips/articles/resources about this kind of problems?
|
```
ClickCounter = function(buttonId) {
this._clickCount = 0;
var that = this;
document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
```
EDIT almost 10 years later, with ES6, arrow functions and [class properties](https://babeljs.io/docs/plugins/transform-class-properties/)
```
class ClickCounter {
count = 0;
constructor( buttonId ){
document.getElementById(buttonId)
.addEventListener( "click", this.buttonClicked );
}
buttonClicked = e => {
this.count += 1;
console.log(`clicked ${this.count} times`);
}
}
```
<https://codepen.io/anon/pen/zaYvqq>
|
229,117 |
<p>I <em>sometimes</em> get the following exception for a custom control of mine:</p>
<p><code>XamlParseException occurred</code> <code>Unknown attribute Points in element SectionClickableArea [Line: 10 Position 16]</code></p>
<p>The stack trace:</p>
<pre><code>{System.Windows.Markup.XamlParseException: Unknown attribute Points on element SectionClickableArea. [Line: 10 Position: 16]
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at SomeMainDialog.InitializeComponent()
at SomeMainDialog..ctor()}
</code></pre>
<p>The element declaration where this happens looks like this (the <strong>event handler</strong> referenced here is defined, of course):</p>
<pre><code><l:SectionClickableArea x:Name="SomeButton"
Points="528,350, 508,265, 520,195, 515,190, 517,165, 530,120, 555,75, 570,61, 580,60, 600,66, 615,80, 617,335, 588,395, 550,385, 540,390, 525,393, 520,385"
Click="SomeButton_Click"/>
</code></pre>
<p>This is part of the code of <code>SectionClickableArea</code>:</p>
<pre><code>public partial class SectionClickableArea : Button {
public static readonly DependencyProperty PointsProperty
= DependencyProperty.Register("Points", typeof(PointCollection), typeof(SectionClickableArea),
new PropertyMetadata((s, e) => {
SectionClickableArea area = (SectionClickableArea) s;
area.areaInfo.Points = (PointCollection) e.NewValue;
area.UpdateLabelPosition();
}));
public PointCollection Points {
get { return (PointCollection) GetValue(PointsProperty); }
set { SetValue(PointsProperty, value); }
}
</code></pre>
<p>I use this control for something like a polygon-shaped button. Therefore I'm inheriting from button. I've had similar problems (<code>E_AG_BAD_PROPERTY_VALUE</code> on another <code>DependencyProperty</code> of type string, according to the line and column given, etc) with this control for weeks, but I have absolutely no idea why.</p>
<hr>
<p>Another exception for the same control occurred this morning for another user (taken from a log and translated from German):</p>
<pre><code>Type: System.InvalidCastException Message: The object of type System.Windows.Controls.ContentControl could not be converted to type [...]SectionClickableArea. at SomeOtherMainDialog.InitializeComponent()
at SomeOtherMainDialog..ctor()
</code></pre>
<p>Inner exception:</p>
<pre><code>Type: System.Exception Message: An HRESULT E_FAIL error was returned when calling COM component at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, DependencyObject doh)
at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper doh, DependencyProperty property, Object obj)
at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet, Boolean isSetByStyle, Boolean isSetByBuiltInStyle)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
at System.Windows.Controls.Control.set_DefaultStyleKey(Object value)
at System.Windows.Controls.ContentControl..ctor()
at System.Windows.CoreTypes.GetCoreWrapper(Int32 typeId)
at MS.Internal.ManagedPeerTable.EnsureManagedPeer(IntPtr unmanagedPointer, Int32 typeIndex, Type type, Boolean preserveManagedObjectReference)
at MS.Internal.ManagedPeerTable.EnsureManagedPeer(IntPtr unmanagedPointer, Int32 typeIndex, Type type)
at MS.Internal.ManagedPeerTable.GetManagedPeer(IntPtr nativeObject)
at MS.Internal.FrameworkCallbacks.SetPropertyAttribute(IntPtr nativeTarget, String attrName, String attrValue, String attachedDPOwnerNamespace, String attachedDPOwnerAssembly)
</code></pre>
<p>Any ideas what's wrong with the control, or what I can do to find the source of these exceptions? As I said, these problem occur only every few dozen times the control is instantiated.</p>
|
[
{
"answer_id": 232549,
"author": "Tim Stewart",
"author_id": 26002,
"author_profile": "https://Stackoverflow.com/users/26002",
"pm_score": 0,
"selected": false,
"text": "<p>I'm no XAML expert but are you missing a namespace on Points (e.g. l:Points)?</p>\n"
},
{
"answer_id": 473015,
"author": "caryden",
"author_id": 313,
"author_profile": "https://Stackoverflow.com/users/313",
"pm_score": 0,
"selected": false,
"text": "<p>I think that we are seeing the same problem. I just get the invalidcast exception more frequently. When, through blind commenting of stuff, I can suppress the invalidcast, I do sometimes get the attribute missing error for an attribute that is, in fact, there. Have you found a solution?</p>\n\n<p>BTW: the easy way to repro it is to just load the offending app and repeatedly hit F5 to refresh the page. You will get it eventually.</p>\n\n<p>I have also seen an intermittent InvalidOperationException that is through from DependencyObject.get_NativeObject().</p>\n\n<p>see my SO question here:\n<a href=\"https://stackoverflow.com/questions/470942/intermittent-inavlidcastexception-in-a-usercontrol-initializecomponent\">Intermittent InavlidCastException in a UserControl.InitializeComponent()</a></p>\n\n<p>See my silverlight.net bug report here:\n<a href=\"http://silverlight.net/forums/t/67732.aspx\" rel=\"nofollow noreferrer\">http://silverlight.net/forums/t/67732.aspx</a></p>\n"
},
{
"answer_id": 1063206,
"author": "Nikolay R",
"author_id": 18635,
"author_profile": "https://Stackoverflow.com/users/18635",
"pm_score": 1,
"selected": false,
"text": "<p>I've also came across this issue. I do not have a good explanation for that (seems to be XAML parse bug), but I've fixed it by adding following code to XAML:</p>\n\n<pre><code><UserControl.Resources>\n <customNamespace:InheritedControl x:Name=\"dummyInstance\"/>\n</UserControl.Resources>\n</code></pre>\n"
},
{
"answer_id": 4334325,
"author": "Samvel Siradeghyan",
"author_id": 205595,
"author_profile": "https://Stackoverflow.com/users/205595",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem. In my case error was on one of members. Exception was thrown on members constructor.<br>\nI solved it by putting breakpoint before InitializeComponent() method and on debug mode pressed F11 to Step Into and found error.<br>\nHope this will help.<br>\nThanks.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23222/"
] |
I *sometimes* get the following exception for a custom control of mine:
`XamlParseException occurred` `Unknown attribute Points in element SectionClickableArea [Line: 10 Position 16]`
The stack trace:
```
{System.Windows.Markup.XamlParseException: Unknown attribute Points on element SectionClickableArea. [Line: 10 Position: 16]
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at SomeMainDialog.InitializeComponent()
at SomeMainDialog..ctor()}
```
The element declaration where this happens looks like this (the **event handler** referenced here is defined, of course):
```
<l:SectionClickableArea x:Name="SomeButton"
Points="528,350, 508,265, 520,195, 515,190, 517,165, 530,120, 555,75, 570,61, 580,60, 600,66, 615,80, 617,335, 588,395, 550,385, 540,390, 525,393, 520,385"
Click="SomeButton_Click"/>
```
This is part of the code of `SectionClickableArea`:
```
public partial class SectionClickableArea : Button {
public static readonly DependencyProperty PointsProperty
= DependencyProperty.Register("Points", typeof(PointCollection), typeof(SectionClickableArea),
new PropertyMetadata((s, e) => {
SectionClickableArea area = (SectionClickableArea) s;
area.areaInfo.Points = (PointCollection) e.NewValue;
area.UpdateLabelPosition();
}));
public PointCollection Points {
get { return (PointCollection) GetValue(PointsProperty); }
set { SetValue(PointsProperty, value); }
}
```
I use this control for something like a polygon-shaped button. Therefore I'm inheriting from button. I've had similar problems (`E_AG_BAD_PROPERTY_VALUE` on another `DependencyProperty` of type string, according to the line and column given, etc) with this control for weeks, but I have absolutely no idea why.
---
Another exception for the same control occurred this morning for another user (taken from a log and translated from German):
```
Type: System.InvalidCastException Message: The object of type System.Windows.Controls.ContentControl could not be converted to type [...]SectionClickableArea. at SomeOtherMainDialog.InitializeComponent()
at SomeOtherMainDialog..ctor()
```
Inner exception:
```
Type: System.Exception Message: An HRESULT E_FAIL error was returned when calling COM component at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, DependencyObject doh)
at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper doh, DependencyProperty property, Object obj)
at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet, Boolean isSetByStyle, Boolean isSetByBuiltInStyle)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
at System.Windows.Controls.Control.set_DefaultStyleKey(Object value)
at System.Windows.Controls.ContentControl..ctor()
at System.Windows.CoreTypes.GetCoreWrapper(Int32 typeId)
at MS.Internal.ManagedPeerTable.EnsureManagedPeer(IntPtr unmanagedPointer, Int32 typeIndex, Type type, Boolean preserveManagedObjectReference)
at MS.Internal.ManagedPeerTable.EnsureManagedPeer(IntPtr unmanagedPointer, Int32 typeIndex, Type type)
at MS.Internal.ManagedPeerTable.GetManagedPeer(IntPtr nativeObject)
at MS.Internal.FrameworkCallbacks.SetPropertyAttribute(IntPtr nativeTarget, String attrName, String attrValue, String attachedDPOwnerNamespace, String attachedDPOwnerAssembly)
```
Any ideas what's wrong with the control, or what I can do to find the source of these exceptions? As I said, these problem occur only every few dozen times the control is instantiated.
|
I've also came across this issue. I do not have a good explanation for that (seems to be XAML parse bug), but I've fixed it by adding following code to XAML:
```
<UserControl.Resources>
<customNamespace:InheritedControl x:Name="dummyInstance"/>
</UserControl.Resources>
```
|
229,143 |
<p>How can i map a date from a java object to a database with Hibernate? I try different approaches, but i am not happy with them. Why? Let me explain my issue. I have the following class [1] including the main method i invoke and with the following mapping [2]. The issue about this approach you can see, when you look at the console output.</p>
<blockquote>
<p>false </p>
<p>false</p>
<p>1</p>
<p>-1</p>
<p>1224754335648</p>
<p>1224754335000 </p>
<p>Thu Oct 23 11:32:15 CEST 2008</p>
<p>Clock@67064</p>
</blockquote>
<p>As you can see the the to dates are not exactly equal, although they should, so it is hard to compare them without goofing around with return value of <code>getTime</code>. I also tried java.sql.Date, Timestamp and date instead of timestamp in the mapping, but without success. </p>
<p>I wonder why the last three digits are zero and if this is a hibernate or a java issue or my own stupidity.</p>
<p>Thank you for reading.</p>
<p>[1]</p>
<pre><code>public class Clock {
int id;
java.util.Date date;
public static void main(String[] args) {
HibernateUtil.init();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Clock clock = new Clock();
clock.date = new java.util.Date();
HibernateUtil.getSessionFactory().getCurrentSession().saveOrUpdate(clock);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Clock fromDBClock = (Clock)HibernateUtil.getSessionFactory()
.getCurrentSession().get(Clock.class, 1);
System.out.println(clock.date.equals(fromDBClock.date));
System.out.println(fromDBClock.date.equals(clock.date));
System.out.println(clock.date.compareTo(fromDBClock.date));
System.out.println(fromDBClock.date.compareTo(clock.date));
System.out.println(clock.date.getTime());
System.out.println(fromDBClock.date.getTime());
System.out.println(clock.date.toString());
System.out.println(fromDBClock.toString());
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
HibernateUtil.end();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
}
</code></pre>
<p>[2]</p>
<pre><code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Clock" table="CLOCK">
<id name="id" column="CLOCK_ID">
<generator class="native"/>
</id>
<property name="date" type="timestamp"/>
</class>
</hibernate-mapping>
</code></pre>
|
[
{
"answer_id": 229240,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 1,
"selected": false,
"text": "<p>Apparently, TIMESTAMP type on your target RDBMS (<em>what are you using, btw?</em>) doesn't store milliseconds. Try to find another native type that does, or map your time onto something else, like long = ms-since-epoch.</p>\n"
},
{
"answer_id": 230484,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 2,
"selected": false,
"text": "<p>SQL Server stores datetime with a precision of 3 milliseconds which can definitely cause the problem you're seeing. One fallout of this is that 23:59:59.999 in Java ends up being the next day in SQL Server. I've never had a problem with Oracle, Informix, or MySQL, but other databases may have less precision also. You can work around it by using Hibernate custom types. You have to round to something less precise than the underlying database precision when you write out the date values. Search for UserType in the Hibernate documentation, you'll be changing the nullSafeSet method to do the rounding.</p>\n"
},
{
"answer_id": 231434,
"author": "Skip Head",
"author_id": 23271,
"author_profile": "https://Stackoverflow.com/users/23271",
"pm_score": 3,
"selected": true,
"text": "<p>MySql DateTime precision is only to the second. Java Date precision is to the millisecond.\nThat is why the last three digits are zeros after it has been put in the database.</p>\n\n<p>Do this to your original Date:</p>\n\n<p>date = date.setTime((date.getTime() / 1000) * 1000);</p>\n\n<p>This will set it to the last exact second, and all your comparisons will then match.</p>\n\n<p>(BTW, \n System.out.println(fromDBClock.toString()); \nshould be\n System.out.println(fromDBClock.date.toString());</p>\n"
},
{
"answer_id": 244022,
"author": "Frederic Morin",
"author_id": 4064,
"author_profile": "https://Stackoverflow.com/users/4064",
"pm_score": 0,
"selected": false,
"text": "<p>Personnaly, I truncate every date I receive in my POJO object with the Apache commons lang package class named DateUtils.</p>\n\n<p>See [Apache commons site][1]</p>\n\n<p>[1]: <a href=\"http://commons.apache.org/lang/api/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date\" rel=\"nofollow noreferrer\">http://commons.apache.org/lang/api/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date</a>, int)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038/"
] |
How can i map a date from a java object to a database with Hibernate? I try different approaches, but i am not happy with them. Why? Let me explain my issue. I have the following class [1] including the main method i invoke and with the following mapping [2]. The issue about this approach you can see, when you look at the console output.
>
> false
>
>
> false
>
>
> 1
>
>
> -1
>
>
> 1224754335648
>
>
> 1224754335000
>
>
> Thu Oct 23 11:32:15 CEST 2008
>
>
> Clock@67064
>
>
>
As you can see the the to dates are not exactly equal, although they should, so it is hard to compare them without goofing around with return value of `getTime`. I also tried java.sql.Date, Timestamp and date instead of timestamp in the mapping, but without success.
I wonder why the last three digits are zero and if this is a hibernate or a java issue or my own stupidity.
Thank you for reading.
[1]
```
public class Clock {
int id;
java.util.Date date;
public static void main(String[] args) {
HibernateUtil.init();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Clock clock = new Clock();
clock.date = new java.util.Date();
HibernateUtil.getSessionFactory().getCurrentSession().saveOrUpdate(clock);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Clock fromDBClock = (Clock)HibernateUtil.getSessionFactory()
.getCurrentSession().get(Clock.class, 1);
System.out.println(clock.date.equals(fromDBClock.date));
System.out.println(fromDBClock.date.equals(clock.date));
System.out.println(clock.date.compareTo(fromDBClock.date));
System.out.println(fromDBClock.date.compareTo(clock.date));
System.out.println(clock.date.getTime());
System.out.println(fromDBClock.date.getTime());
System.out.println(clock.date.toString());
System.out.println(fromDBClock.toString());
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
HibernateUtil.end();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
}
```
[2]
```
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Clock" table="CLOCK">
<id name="id" column="CLOCK_ID">
<generator class="native"/>
</id>
<property name="date" type="timestamp"/>
</class>
</hibernate-mapping>
```
|
MySql DateTime precision is only to the second. Java Date precision is to the millisecond.
That is why the last three digits are zeros after it has been put in the database.
Do this to your original Date:
date = date.setTime((date.getTime() / 1000) \* 1000);
This will set it to the last exact second, and all your comparisons will then match.
(BTW,
System.out.println(fromDBClock.toString());
should be
System.out.println(fromDBClock.date.toString());
|
229,153 |
<pre><code><div>
<h1>Title</h1>
<table>
...
</table>
</div>
</code></pre>
<p>Now, the</p>
<pre><code><h1>
</code></pre>
<p>has a margin: 0;
so it is at the top of the div. The height of the div is 300px.</p>
<p>However I'd like the table to be placed at the bottom of the div, eg. valign="bottom" but for the whole table.</p>
|
[
{
"answer_id": 229184,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<p>What about this:</p>\n\n<pre><code><style type=\"text/css\">\n#container { \n position: absolute; \n margin: 0;\n height:300px;\n border:1px solid #000; }\n#container h1 { \n margin:0; }\n#tableContainer { \n position: absolute;\n bottom:0; }\n</style>\n\n<div id=\"container\">\n <h1>Title</h1>\n <div id=\"tableContainer\">\n <table id=\"tableLayout\">\n <tr><td>...</td></tr>\n </table>\n </div>\n</div>\n</code></pre>\n\n<p>The only problem is that both the container div and the tableContainer divs need to be absolute positioned. Not sure if this will work for your layout.</p>\n"
},
{
"answer_id": 229215,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 3,
"selected": true,
"text": "<p>Try this: <a href=\"http://jsbin.com/emoce\" rel=\"nofollow noreferrer\">http://jsbin.com/emoce</a></p>\n\n<p>Though it's similar to Darryl's solution. Except I'm not using position:absolute on the wrapping div, but rather position: relative to make the table's position absolute to that.</p>\n"
},
{
"answer_id": 229223,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 2,
"selected": false,
"text": "<p>Here is what Remy Sharp suggested:</p>\n\n<pre><code><style type=\"text/css\" media=\"screen\">\n#container { \n position: relative; \n margin: 0;\n height:300px;\n border:1px solid #000; \n}\n#container h1 { \n margin:0; \n}\n#tableLayout { \n position: absolute;\n bottom:0; \n border: 1px solid #c00;\n}\n</style>\n\n<div id=\"container\">\n <h1>Title</h1>\n <table id=\"tableLayout\">\n <tr><td>example cell</td></tr>\n </table>\n</div>\n</code></pre>\n\n<p>Looks like it works!</p>\n\n<p>I posted it here so it will always be here.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
<div>
<h1>Title</h1>
<table>
...
</table>
</div>
```
Now, the
```
<h1>
```
has a margin: 0;
so it is at the top of the div. The height of the div is 300px.
However I'd like the table to be placed at the bottom of the div, eg. valign="bottom" but for the whole table.
|
Try this: <http://jsbin.com/emoce>
Though it's similar to Darryl's solution. Except I'm not using position:absolute on the wrapping div, but rather position: relative to make the table's position absolute to that.
|
229,168 |
<p>I find print_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?</p>
|
[
{
"answer_id": 229175,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p>Note @tchrist recommends <a href=\"http://search.cpan.org/~gaas/Data-Dump-1.21/lib/Data/Dump.pm\" rel=\"noreferrer\">Data::Dump</a> over <a href=\"http://search.cpan.org/~jhi/perl-5.8.0/ext/Data/Dumper/Dumper.pm\" rel=\"noreferrer\">Data::Dumper</a>. I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to interpret results.</p>\n\n<p><a href=\"http://search.cpan.org/~jhi/perl-5.8.0/ext/Data/Dumper/Dumper.pm\" rel=\"noreferrer\">Data::Dumper</a> :</p>\n\n<p>A snippet of the examples shown in the above link.</p>\n\n<pre><code>use Data::Dumper;\n\npackage Foo;\nsub new {bless {'a' => 1, 'b' => sub { return \"foo\" }}, $_[0]};\n\npackage Fuz; # a weird REF-REF-SCALAR object\nsub new {bless \\($_ = \\ 'fu\\'z'), $_[0]};\n\npackage main;\n$foo = Foo->new;\n$fuz = Fuz->new;\n$boo = [ 1, [], \"abcd\", \\*foo,\n {1 => 'a', 023 => 'b', 0x45 => 'c'}, \n \\\\\"p\\q\\'r\", $foo, $fuz];\n\n########\n# simple usage\n########\n\n$bar = eval(Dumper($boo));\nprint($@) if $@;\nprint Dumper($boo), Dumper($bar); # pretty print (no array indices)\n\n$Data::Dumper::Terse = 1; # don't output names where feasible\n$Data::Dumper::Indent = 0; # turn off all pretty print\nprint Dumper($boo), \"\\n\";\n\n$Data::Dumper::Indent = 1; # mild pretty print\nprint Dumper($boo);\n\n$Data::Dumper::Indent = 3; # pretty print with array indices\nprint Dumper($boo);\n\n$Data::Dumper::Useqq = 1; # print strings in double quotes\nprint Dumper($boo);\n</code></pre>\n"
},
{
"answer_id": 230010,
"author": "mirod",
"author_id": 11095,
"author_profile": "https://Stackoverflow.com/users/11095",
"pm_score": 3,
"selected": false,
"text": "<p>As usually with Perl, you might prefer alternative solutions to the venerable Data::Dumper:</p>\n\n<ul>\n<li><a href=\"http://search.cpan.org/dist/Data-Dump-Streamer/\" rel=\"nofollow noreferrer\">Data::Dump::Streamer</a> has a terser output than Data::Dumper, and can also serialize some data better than Data::Dumper,</li>\n<li><a href=\"http://search.cpan.org/dist/YAML\" rel=\"nofollow noreferrer\">YAML</a> (or <a href=\"http://search.cpan.org/dist/YAML-Syck/\" rel=\"nofollow noreferrer\">Yaml::Syck</a>, or an other YAML module) generate the data in YAML, which is quite legible.</li>\n</ul>\n\n<p>And of course with the debugger, you can display any variable with the 'x' command. I particularly like the form '<code>x 2 $complex_structure</code>' where 2 (or any number) tells the debugger to display only 2 levels of nested data.</p>\n"
},
{
"answer_id": 230020,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "<p>An alternative to <a href=\"http://perldoc.perl.org/Data/Dumper.html\" rel=\"noreferrer\">Data::Dumper</a> that does not produce valid Perl code but instead a more skimmable format (same as the <code>x</code> command of the Perl debugger) is <a href=\"http://perldoc.perl.org/Dumpvalue.html\" rel=\"noreferrer\">Dumpvalue</a>. It also consumes a lot less memory.</p>\n\n<p>As well, there is <a href=\"http://p3rl.org/Data::Dump::Streamer\" rel=\"noreferrer\">Data::Dump::Streamer</a>, which is more accurate in various edge and corner cases than <a href=\"http://perldoc.perl.org/Data/Dumper.html\" rel=\"noreferrer\">Data::Dumper</a> is.</p>\n"
},
{
"answer_id": 230255,
"author": "kixx",
"author_id": 11260,
"author_profile": "https://Stackoverflow.com/users/11260",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://search.cpan.org/dist/Data-Dump/lib/Data/Dump.pm\" rel=\"nofollow noreferrer\">Data::Dump</a>, it's output is a bit cleaner than Data::Dumper's (no $VAR1), it provides quick shortcuts and it also tries to DTRT, i.e. it will print to STDERR when called in void context and return the dump string when not.</p>\n"
},
{
"answer_id": 489152,
"author": "Stan James",
"author_id": 59913,
"author_profile": "https://Stackoverflow.com/users/59913",
"pm_score": 2,
"selected": false,
"text": "<p>I went looking for the same thing and found <a href=\"http://web.archive.org/web/20090730012843/http://netmesh.org/odds-ends/\" rel=\"nofollow noreferrer\">this lovely little Perl function</a>, explicitly meant to generate results like print_r(). </p>\n\n<p>The author of the script was asking your exact question in a forum <a href=\"http://www.nntp.perl.org/group/perl.beginners/2006/04/msg83026.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>print objectToString($json_data);\n</code></pre>\n\n<p>Gives this output:</p>\n\n<pre><code>HASH {\ntime => 1233173875\nerror => 0\nnode => HASH {\n vid => 1011\n moderate => 0\n field_datestring => ARRAY {\n HASH {\n value => August 30, 1979\n }\n }\n\n field_tagged_persons => ARRAY {\n HASH {\n nid => undef\n }\n }\n\n...and so on...\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] |
I find print\_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?
|
Note @tchrist recommends [Data::Dump](http://search.cpan.org/~gaas/Data-Dump-1.21/lib/Data/Dump.pm) over [Data::Dumper](http://search.cpan.org/~jhi/perl-5.8.0/ext/Data/Dumper/Dumper.pm). I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to interpret results.
[Data::Dumper](http://search.cpan.org/~jhi/perl-5.8.0/ext/Data/Dumper/Dumper.pm) :
A snippet of the examples shown in the above link.
```
use Data::Dumper;
package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
package Fuz; # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};
package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
{1 => 'a', 023 => 'b', 0x45 => 'c'},
\\"p\q\'r", $foo, $fuz];
########
# simple usage
########
$bar = eval(Dumper($boo));
print($@) if $@;
print Dumper($boo), Dumper($bar); # pretty print (no array indices)
$Data::Dumper::Terse = 1; # don't output names where feasible
$Data::Dumper::Indent = 0; # turn off all pretty print
print Dumper($boo), "\n";
$Data::Dumper::Indent = 1; # mild pretty print
print Dumper($boo);
$Data::Dumper::Indent = 3; # pretty print with array indices
print Dumper($boo);
$Data::Dumper::Useqq = 1; # print strings in double quotes
print Dumper($boo);
```
|
229,185 |
<p>I've been trying for a while now to write a unit test for a UserViewControl in ASP.NET MVC. I'd like to get to code that looks something like this:</p>
<pre><code>[TestMethod]
public void HaveControlToDisplayThings()
{
var listControl = new ControlUnderTest();
var viewData = new ViewDataDictionary<IList<string>>(this.repo.GetMeSomeData());
// Set up a ViewContext using Moq.
listControl.SetFakeViewContext(viewData);
listControl.ViewData = viewData;
listControl.RenderView(listControl.ViewContext);
// Never got this far, no idea if this will work :)
string s = listControl.ViewContext.HttpContext.Response.Output.ToString();
Assert.AreNotEqual(0, s.Length);
foreach (var item in this.repo.GetMeSomeData())
{
Assert.IsTrue(s.IndexOf(item) != -1);
}
}
</code></pre>
<p>Unfortunately, no matter what I try I get errors from deep inside RenderView. This is caused (as far as I can tell) by the static HttpContext.Current object being useless - I get <code>NullReferenceException</code>s from <code>System.Web.UI.Page.SetIntrinsics</code>.</p>
<p>I tried using Phil Haack's <a href="http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx" rel="nofollow noreferrer">HttpSimulator</a> which gave me a HttpContext object but I found I also needed to specify a fake <code>HttpBrowserCapabilities</code> object to get slightly further:</p>
<pre><code>Subtext.TestLibrary.HttpSimulator simulator = new HttpSimulator();
simulator.SimulateRequest();
var browserMock = new Mock<HttpBrowserCapabilities>();
browserMock.Expect(b => b.PreferredRenderingMime).Returns("text/html");
browserMock.Expect(b => b.PreferredResponseEncoding).Returns("UTF-8");
browserMock.Expect(b => b.PreferredRequestEncoding).Returns("UTF-8");
HttpContext.Current.Request.Browser = browserMock.Object;
</code></pre>
<p>Now I get exceptions on property accesses on that object. I mocked as many as I could, but seemed to be getting nowhere fast. </p>
<p>Has anyone managed to make this work?</p>
|
[
{
"answer_id": 390363,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 2,
"selected": false,
"text": "<p>One option would be to run unit tests inside the browser. I've had success with <a href=\"http://seleniumhq.org/\" rel=\"nofollow noreferrer\">Selenium</a> for such cases.</p>\n"
},
{
"answer_id": 390386,
"author": "bh213",
"author_id": 28912,
"author_profile": "https://Stackoverflow.com/users/28912",
"pm_score": 2,
"selected": false,
"text": "<p>We gave up on unit testing views and are now using WatiN browser tests as part of our build. </p>\n\n<p>We also use Resharper Solution Wide Analysis to check if there are compiler errors. Not perfect, but it gets very similar results. Downside - WatiN tests are slow.</p>\n"
},
{
"answer_id": 390393,
"author": "Matthew",
"author_id": 20162,
"author_profile": "https://Stackoverflow.com/users/20162",
"pm_score": 3,
"selected": true,
"text": "<p>Unfortunately, the ASP.NET viewengine uses the VirtualPathProvider in the ASP.NET hosting environment. To make matters worse, I traced some of the other code using Reflector and found that there is other dependencies to some hardcode references to VirtualPath utilities.\nI hope they fix this in the release so we can truly test our Views and how they are rendered.</p>\n"
},
{
"answer_id": 396816,
"author": "Matthew M. Osborn",
"author_id": 5235,
"author_profile": "https://Stackoverflow.com/users/5235",
"pm_score": 1,
"selected": false,
"text": "<p>These are the values that need to be set in the HttpBrowserCapabilities object for a asp.net webforms site to run, I would try making sure these are set and see if that fixes your problem, I'm not sure if it would but hey it worth a shot right?</p>\n\n<ul>\n<li>Browser (aka name)</li>\n<li>useragent (passed in the request)</li>\n<li>tables (true/false)</li>\n<li>version (version of browser eg 1.0)</li>\n<li>w3cdomversion (eg 1.0)</li>\n<li>cookies (true/false)</li>\n<li>ecmascriptversion (eg 1.0)</li>\n</ul>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 400619,
"author": "Gailin",
"author_id": 31684,
"author_profile": "https://Stackoverflow.com/users/31684",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend <a href=\"http://seleniumhq.org/\" rel=\"nofollow noreferrer\">selenium</a> as well for the UI testing. There is a quite a bit in a standard MVC application that can be unit tested, but the UI level components always seemed a better fit for in-browser testing like Selenium. You can integrate Selenium testing with your unit testing using <a href=\"http://cruisecontrol.sourceforge.net/\" rel=\"nofollow noreferrer\">cruisecontrol.net</a>. </p>\n\n<p>Here is a <a href=\"http://wiki.openqa.org/display/SEL/Integrating+Selenium+And+CruiseControl.Net\" rel=\"nofollow noreferrer\">guide</a> for integrating Selenium with your CC.Net.</p>\n"
},
{
"answer_id": 400636,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 1,
"selected": false,
"text": "<p>Use TypeMock to mock away the dependencies. I have written <a href=\"http://itscommonsensestupid.blogspot.com/2008/09/testing-aspnet-mvc-using-typemock-aaa.html\" rel=\"nofollow noreferrer\">one blog post</a> about how to mock out the Request and Response dependencies in Controller layer. Maybe it's helpful. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4591/"
] |
I've been trying for a while now to write a unit test for a UserViewControl in ASP.NET MVC. I'd like to get to code that looks something like this:
```
[TestMethod]
public void HaveControlToDisplayThings()
{
var listControl = new ControlUnderTest();
var viewData = new ViewDataDictionary<IList<string>>(this.repo.GetMeSomeData());
// Set up a ViewContext using Moq.
listControl.SetFakeViewContext(viewData);
listControl.ViewData = viewData;
listControl.RenderView(listControl.ViewContext);
// Never got this far, no idea if this will work :)
string s = listControl.ViewContext.HttpContext.Response.Output.ToString();
Assert.AreNotEqual(0, s.Length);
foreach (var item in this.repo.GetMeSomeData())
{
Assert.IsTrue(s.IndexOf(item) != -1);
}
}
```
Unfortunately, no matter what I try I get errors from deep inside RenderView. This is caused (as far as I can tell) by the static HttpContext.Current object being useless - I get `NullReferenceException`s from `System.Web.UI.Page.SetIntrinsics`.
I tried using Phil Haack's [HttpSimulator](http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx) which gave me a HttpContext object but I found I also needed to specify a fake `HttpBrowserCapabilities` object to get slightly further:
```
Subtext.TestLibrary.HttpSimulator simulator = new HttpSimulator();
simulator.SimulateRequest();
var browserMock = new Mock<HttpBrowserCapabilities>();
browserMock.Expect(b => b.PreferredRenderingMime).Returns("text/html");
browserMock.Expect(b => b.PreferredResponseEncoding).Returns("UTF-8");
browserMock.Expect(b => b.PreferredRequestEncoding).Returns("UTF-8");
HttpContext.Current.Request.Browser = browserMock.Object;
```
Now I get exceptions on property accesses on that object. I mocked as many as I could, but seemed to be getting nowhere fast.
Has anyone managed to make this work?
|
Unfortunately, the ASP.NET viewengine uses the VirtualPathProvider in the ASP.NET hosting environment. To make matters worse, I traced some of the other code using Reflector and found that there is other dependencies to some hardcode references to VirtualPath utilities.
I hope they fix this in the release so we can truly test our Views and how they are rendered.
|
229,186 |
<p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
|
[
{
"answer_id": 229192,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>You could use <a href=\"http://www.python.org/doc/2.5.2/lib/os-file-dir.html\" rel=\"noreferrer\"><code>os.listdir()</code></a> which returns a list of names (for both files and directories) in a given directory. If you need to distinguish between files and directories, call <code>os.stat()</code> on each name.</p>\n"
},
{
"answer_id": 229219,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 8,
"selected": false,
"text": "<p>Don't use os.walk.</p>\n\n<p>Example:</p>\n\n<pre><code>import os\n\nroot = \"C:\\\\\"\nfor item in os.listdir(root):\n if os.path.isfile(os.path.join(root, item)):\n print item\n</code></pre>\n"
},
{
"answer_id": 229293,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 5,
"selected": false,
"text": "<p>The suggestion to use <code>listdir</code> is a good one. The direct answer to your question in Python 2 is <code>root, dirs, files = os.walk(dir_name).next()</code>.</p>\n\n<p>The equivalent Python 3 syntax is <code>root, dirs, files = next(os.walk(dir_name))</code></p>\n"
},
{
"answer_id": 229300,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "<p>If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.</p>\n\n<p>ie:</p>\n\n<pre><code>def _dir_list(self, dir_name, whitelist):\n outputList = []\n for root, dirs, files in os.walk(dir_name):\n dirs[:] = [d for d in dirs if is_good(d)]\n for f in files:\n do_stuff()\n</code></pre>\n\n<p>Note - be careful to mutate the list, rather than just rebind it. Obviously os.walk doesn't know about the external rebinding.</p>\n"
},
{
"answer_id": 234329,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 8,
"selected": true,
"text": "<p>Use the <code>walklevel</code> function.</p>\n\n<pre><code>import os\n\ndef walklevel(some_dir, level=1):\n some_dir = some_dir.rstrip(os.path.sep)\n assert os.path.isdir(some_dir)\n num_sep = some_dir.count(os.path.sep)\n for root, dirs, files in os.walk(some_dir):\n yield root, dirs, files\n num_sep_this = root.count(os.path.sep)\n if num_sep + level <= num_sep_this:\n del dirs[:]\n</code></pre>\n\n<p>It works just like <code>os.walk</code>, but you can pass it a <code>level</code> parameter that indicates how deep the recursion will go.</p>\n"
},
{
"answer_id": 12965151,
"author": "Diana G",
"author_id": 187696,
"author_profile": "https://Stackoverflow.com/users/187696",
"pm_score": 2,
"selected": false,
"text": "<p>You could also do the following:</p>\n\n<pre><code>for path, subdirs, files in os.walk(dir_name):\n for name in files:\n if path == \".\": #this will filter the files in the current directory\n #code here\n</code></pre>\n"
},
{
"answer_id": 20868760,
"author": "Pieter",
"author_id": 2367867,
"author_profile": "https://Stackoverflow.com/users/2367867",
"pm_score": 6,
"selected": false,
"text": "<p>I think the solution is actually very simple.</p>\n\n<p>use </p>\n\n<pre><code>break\n</code></pre>\n\n<p>to only do first iteration of the for loop, there must be a more elegant way.</p>\n\n<pre><code>for root, dirs, files in os.walk(dir_name):\n for f in files:\n ...\n ...\n break\n...\n</code></pre>\n\n<p>The first time you call os.walk, it returns tulips for the current directory, then on next loop the contents of the next directory. </p>\n\n<p>Take original script and just add a <strong>break</strong>.</p>\n\n<pre><code>def _dir_list(self, dir_name, whitelist):\n outputList = []\n for root, dirs, files in os.walk(dir_name):\n for f in files:\n if os.path.splitext(f)[1] in whitelist:\n outputList.append(os.path.join(root, f))\n else:\n self._email_to_(\"ignore\")\n break\n return outputList\n</code></pre>\n"
},
{
"answer_id": 24418093,
"author": "Oleg Gryb",
"author_id": 1152643,
"author_profile": "https://Stackoverflow.com/users/1152643",
"pm_score": 2,
"selected": false,
"text": "<p>The same idea with <code>listdir</code>, but shorter:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>[f for f in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, f))]\n</code></pre>\n"
},
{
"answer_id": 27804208,
"author": "Deifyed",
"author_id": 1037328,
"author_profile": "https://Stackoverflow.com/users/1037328",
"pm_score": 0,
"selected": false,
"text": "<p>This is how I solved it</p>\n\n<pre><code>if recursive:\n items = os.walk(target_directory)\nelse:\n items = [next(os.walk(target_directory))]\n\n...\n</code></pre>\n"
},
{
"answer_id": 32747111,
"author": "Kemin Zhou",
"author_id": 2407363,
"author_profile": "https://Stackoverflow.com/users/2407363",
"pm_score": 0,
"selected": false,
"text": "<p>There is a catch when using listdir. The os.path.isdir(identifier) must be an absolute path. To pick subdirectories you do:</p>\n\n<pre><code>for dirname in os.listdir(rootdir):\n if os.path.isdir(os.path.join(rootdir, dirname)):\n print(\"I got a subdirectory: %s\" % dirname)\n</code></pre>\n\n<p>The alternative is to change to the directory to do the testing without the os.path.join().</p>\n"
},
{
"answer_id": 36358596,
"author": "Jay Sheth",
"author_id": 2761777,
"author_profile": "https://Stackoverflow.com/users/2761777",
"pm_score": 2,
"selected": false,
"text": "<p>In Python 3, I was able to do this:</p>\n\n<pre><code>import os\ndir = \"/path/to/files/\"\n\n#List all files immediately under this folder:\nprint ( next( os.walk(dir) )[2] )\n\n#List all folders immediately under this folder:\nprint ( next( os.walk(dir) )[1] )\n</code></pre>\n"
},
{
"answer_id": 37008598,
"author": "masterxilo",
"author_id": 524504,
"author_profile": "https://Stackoverflow.com/users/524504",
"pm_score": 3,
"selected": false,
"text": "<pre><code>for path, dirs, files in os.walk('.'):\n print path, dirs, files\n del dirs[:] # go only one level deep\n</code></pre>\n"
},
{
"answer_id": 39118773,
"author": "alexandre-rousseau",
"author_id": 5935198,
"author_profile": "https://Stackoverflow.com/users/5935198",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this snippet</p>\n\n<pre><code>for root, dirs, files in os.walk(directory):\n if level > 0:\n # do some stuff\n else:\n break\n level-=1\n</code></pre>\n"
},
{
"answer_id": 44323989,
"author": "Matt R",
"author_id": 8102025,
"author_profile": "https://Stackoverflow.com/users/8102025",
"pm_score": 3,
"selected": false,
"text": "<p>Felt like throwing my 2 pence in.</p>\n<pre><code>baselevel = len(rootdir.split(os.path.sep))\nfor subdirs, dirs, files in os.walk(rootdir):\n curlevel = len(subdirs.split(os.path.sep))\n if curlevel <= baselevel + 1:\n [do stuff]\n</code></pre>\n"
},
{
"answer_id": 47409969,
"author": "Hamsavardhini",
"author_id": 5348858,
"author_profile": "https://Stackoverflow.com/users/5348858",
"pm_score": 0,
"selected": false,
"text": "<p>create a list of excludes, use fnmatch to skip the directory structure and do the process</p>\n\n<pre><code>excludes= ['a\\*\\b', 'c\\d\\e']\nfor root, directories, files in os.walk('Start_Folder'):\n if not any(fnmatch.fnmatch(nf_root, pattern) for pattern in excludes):\n for root, directories, files in os.walk(nf_root):\n ....\n do the process\n ....\n</code></pre>\n\n<p>same as for 'includes':</p>\n\n<pre><code>if **any**(fnmatch.fnmatch(nf_root, pattern) for pattern in **includes**):\n</code></pre>\n"
},
{
"answer_id": 53547750,
"author": "PiMathCLanguage",
"author_id": 5462449,
"author_profile": "https://Stackoverflow.com/users/5462449",
"pm_score": 0,
"selected": false,
"text": "<p>Why not simply use a <code>range</code> and <code>os.walk</code> combined with the <code>zip</code>? Is not the best solution, but would work too.</p>\n\n<p>For example like this:</p>\n\n<pre><code># your part before\nfor count, (root, dirs, files) in zip(range(0, 1), os.walk(dir_name)):\n # logic stuff\n# your later part\n</code></pre>\n\n<p>Works for me on python 3.</p>\n\n<p>Also: A <code>break</code> is simpler too btw. (Look at the answer from @Pieter)</p>\n"
},
{
"answer_id": 54442325,
"author": "Oleg",
"author_id": 1555328,
"author_profile": "https://Stackoverflow.com/users/1555328",
"pm_score": 0,
"selected": false,
"text": "<p>A slight change to Alex's answer, but using <code>__next__()</code>:</p>\n\n<p><code>print(next(os.walk('d:/'))[2])</code>\nor\n <code>print(os.walk('d:/').__next__()[2])</code></p>\n\n<p>with the <code>[2]</code> being the <code>file</code> in <code>root, dirs, file</code> mentioned in other answers</p>\n"
},
{
"answer_id": 56325893,
"author": "ascripter",
"author_id": 3104974,
"author_profile": "https://Stackoverflow.com/users/3104974",
"pm_score": 2,
"selected": false,
"text": "<p>Since <strong>Python 3.5</strong> you can use <a href=\"https://docs.python.org/3.5/library/os.html#os.scandir\" rel=\"nofollow noreferrer\"><code>os.scandir</code></a> instead of <a href=\"https://docs.python.org/3.5/library/os.html#os.listdir\" rel=\"nofollow noreferrer\"><code>os.listdir</code></a>. Instead of strings you get an iterator of <a href=\"https://docs.python.org/3.5/library/os.html#os.DirEntry\" rel=\"nofollow noreferrer\"><code>DirEntry</code></a> objects in return. From the docs:</p>\n\n<blockquote>\n <p>Using <code>scandir()</code> instead of <code>listdir()</code> can significantly increase the performance of code that also needs file type or file attribute information, because <code>DirEntry</code> objects expose this information if the operating system provides it when scanning a directory. All <code>DirEntry</code> methods may perform a system call, but <code>is_dir()</code> and <code>is_file()</code> usually only require a system call for symbolic links; <code>DirEntry.stat()</code> always requires a system call on Unix but only requires one for symbolic links on Windows.</p>\n</blockquote>\n\n<p>You can access the name of the object via <code>DirEntry.name</code> which is then equivalent to the output of <code>os.listdir</code></p>\n"
},
{
"answer_id": 56463621,
"author": "Pedro J. Sola",
"author_id": 6460022,
"author_profile": "https://Stackoverflow.com/users/6460022",
"pm_score": 0,
"selected": false,
"text": "<p>root folder changes for every directory os.walk finds. I solver that checking if root == directory</p>\n\n<pre><code>def _dir_list(self, dir_name, whitelist):\n outputList = []\n for root, dirs, files in os.walk(dir_name):\n if root == dir_name: #This only meet parent folder\n for f in files:\n if os.path.splitext(f)[1] in whitelist:\n outputList.append(os.path.join(root, f))\n else:\n self._email_to_(\"ignore\")\n return outputList\n</code></pre>\n"
},
{
"answer_id": 58172376,
"author": "Rich",
"author_id": 12144392,
"author_profile": "https://Stackoverflow.com/users/12144392",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import os\n\ndef listFiles(self, dir_name):\n names = []\n for root, directory, files in os.walk(dir_name):\n if root == dir_name:\n for name in files:\n names.append(name)\n return names\n</code></pre>\n"
},
{
"answer_id": 65420645,
"author": "Alon Barad",
"author_id": 8622976,
"author_profile": "https://Stackoverflow.com/users/8622976",
"pm_score": 0,
"selected": false,
"text": "<p>This is a nice python example</p>\n<pre class=\"lang-py prettyprint-override\"><code>def walk_with_depth(root_path, depth):\n if depth < 0:\n for root, dirs, files in os.walk(root_path):\n yield [root, dirs[:], files]\n\n return\n\n elif depth == 0:\n return\n\n base_depth = root_path.rstrip(os.path.sep).count(os.path.sep)\n for root, dirs, files in os.walk(root_path):\n yield [root, dirs[:], files]\n\n cur_depth = root.count(os.path.sep)\n \n if base_depth + depth <= cur_depth:\n del dirs[:]\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
How do I limit `os.walk` to only return files in the directory I provide it?
```
def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
```
|
Use the `walklevel` function.
```
import os
def walklevel(some_dir, level=1):
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
num_sep = some_dir.count(os.path.sep)
for root, dirs, files in os.walk(some_dir):
yield root, dirs, files
num_sep_this = root.count(os.path.sep)
if num_sep + level <= num_sep_this:
del dirs[:]
```
It works just like `os.walk`, but you can pass it a `level` parameter that indicates how deep the recursion will go.
|
229,196 |
<p>I have the problem, that getting a ressource from my archive failed with a <code>MalformedURLException: unknown protocol: jndi</code></p>
<p>The archive is a war file and is deployed into Websphere successfully.</p>
<p>When I try to access some files inside the archive via</p>
<pre><code>jndi://server/context/filename
</code></pre>
<p>I get the <code>MalformedURLException</code>.</p>
|
[
{
"answer_id": 3836668,
"author": "Isaac",
"author_id": 443716,
"author_profile": "https://Stackoverflow.com/users/443716",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you registered a custom URL handler, \"jndi\" is not a supported protocol.</p>\n\n<p>Are you trying to read the file through Java code?</p>\n"
},
{
"answer_id": 8193872,
"author": "Andreas Veithen",
"author_id": 958954,
"author_profile": "https://Stackoverflow.com/users/958954",
"pm_score": 1,
"selected": false,
"text": "<p>URLs with the \"jndi\" scheme are returned by the ServletContext#getResource method in Tomcat. However, this is non standard (i.e. the J2EE specs don't impose a URL scheme to be used in the return value of that method) and on other application servers it will be different. Always use the ServletContext#getResource method instead of trying to compose the URL directly.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30724/"
] |
I have the problem, that getting a ressource from my archive failed with a `MalformedURLException: unknown protocol: jndi`
The archive is a war file and is deployed into Websphere successfully.
When I try to access some files inside the archive via
```
jndi://server/context/filename
```
I get the `MalformedURLException`.
|
URLs with the "jndi" scheme are returned by the ServletContext#getResource method in Tomcat. However, this is non standard (i.e. the J2EE specs don't impose a URL scheme to be used in the return value of that method) and on other application servers it will be different. Always use the ServletContext#getResource method instead of trying to compose the URL directly.
|
229,206 |
<p>I have some code which needs to ensure some data is in a mysql enum prior to insertion in the database. The cleanest way I've found of doing this is the following code:</p>
<pre><code>sub enum_values {
my ( $self, $schema, $table, $column ) = @_;
# don't eval to let the error bubble up
my $columns = $schema->storage->dbh->selectrow_hashref(
"SHOW COLUMNS FROM `$table` like ?",
{},
$column
);
unless ($columns) {
X::Internal::Database::UnknownColumn->throw(
column => $column,
table => $table,
);
}
my $type = $columns->{Type} or X::Panic->throw(
details => "Could not determine type for $table.$column",
);
unless ( $type =~ /\Aenum\((.*)\)\z/ ) {
X::Internal::Database::IncorrectTypeForColumn->throw(
type_wanted => 'enum',
type_found => $type,
);
}
$type = $1;
require Text::CSV_XS;
my $csv = Text::CSV_XS->new;
$csv->parse($type) or X::Panic->throw(
details => "Could not parse enum CSV data: ".$csv->error_input,
);
return map { /\A'(.*)'\z/; $1 }$csv->fields;
}
</code></pre>
<p>We're using <a href="http://search.cpan.org/dist/DBIx-Class/" rel="noreferrer">DBIx::Class</a>. Surely there is a better way of accomplishing this? (Note that the $table variable is coming from our code, <em>not</em> from any external source. Thus, no security issue).</p>
|
[
{
"answer_id": 229278,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "<p>I'd say using Text::CSV_XS may be an overkill, unless you have weird things like commas in enums (a bad idea anyway if you ask me). I'd probably use this instead.</p>\n\n<pre><code>my @fields = $type =~ / ' ([^']+) ' (?:,|\\z) /msgx;\n</code></pre>\n\n<p>Other than that, I don't think there are shortcuts.</p>\n"
},
{
"answer_id": 229561,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 5,
"selected": true,
"text": "<p>No need to be so heroic. Using a reasonably modern version of <a href=\"http://search.cpan.org/dist/DBD-mysql/\" rel=\"noreferrer\">DBD::mysql</a>, the hash returned by <a href=\"http://search.cpan.org/dist/DBI/\" rel=\"noreferrer\">DBI</a>'s <a href=\"http://search.cpan.org/dist/DBI/DBI.pm#column_info\" rel=\"noreferrer\">column info</a> method contains a pre-split version of the valid enum values in the key <code>mysql_values</code>:</p>\n\n<pre><code>my $sth = $dbh->column_info(undef, undef, 'mytable', '%');\n\nforeach my $col_info ($sth->fetchrow_hashref)\n{\n if($col_info->{'TYPE_NAME'} eq 'ENUM')\n {\n # The mysql_values key contains a reference to an array of valid enum values\n print \"Valid enum values for $col_info->{'COLUMN_NAME'}: \", \n join(', ', @{$col_info->{'mysql_values'}}), \"\\n\";\n }\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 28756632,
"author": "cjac",
"author_id": 1110823,
"author_profile": "https://Stackoverflow.com/users/1110823",
"pm_score": 0,
"selected": false,
"text": "<p>I spent part of the day asking the #dbix-class channel over on MagNet the same question and came across this lack of answer. Since I found the answer and nobody else seems to have done so yet, I'll paste the transcript below the TL;DR here:</p>\n\n<pre><code>my $cfg = new Config::Simple( $rc_file );\nmy $mysql = $cfg->get_block('mysql');\nmy $dsn =\n \"DBI:mysql:database=$mysql->{database};\".\n \"host=$mysql->{hostname};port=$mysql->{port}\";\n\nmy $schema =\n DTSS::CDN::Schema->connect( $dsn, $mysql->{user}, $mysql->{password} );\n\nmy $valid_enum_values =\n $schema->source('Cdnurl')->column_info('scheme')->{extra}->{list};\n</code></pre>\n\n<p>And now the IRC log of me beating my head against a wall:</p>\n\n<pre><code>14:40 < cj> is there a cross-platform way to get the valid values of an \n enum?\n15:11 < cj> it looks like I could add 'InflateColumn::Object::Enum' to the \n __PACKAGE__->load_components(...) list for tables with enum \n columns\n15:12 < cj> and then call values() on the enum column\n15:13 < cj> but how do I get dbic-dump to add \n 'InflateColumn::Object::Enum' to \n __PACKAGE__->load_components(...) for only tables with enum \n columns?\n15:20 < cj> I guess I could just add it for all tables, since I'm doing \n the same for InflateColumn::DateTime\n15:39 < cj> hurm... is there a way to get a column without making a \n request to the db?\n15:40 < cj> I know that we store in the DTSS::CDN::Schema::Result::Cdnurl \n class all of the information that I need to know about the \n scheme column before any request is issued\n15:42 <@ilmari> cj: for Pg and mysql Schema::Loader will add the list of \n valid values to the ->{extra}->{list} column attribute\n15:43 <@ilmari> cj: if you're using some other database that has enums, \n patches welcome :)\n15:43 <@ilmari> or even just a link to the documentation on how to extract \n the values\n15:43 <@ilmari> and a willingness to test if it's not a database I have \n access to\n15:43 < cj> thanks, but I'm using mysql. if I were using sqlite for this \n project, I'd probably oblige :-)\n15:44 <@ilmari> cj: to add components to only some tables, use \n result_components_map\n15:44 < cj> and is there a way to get at those attributes without making a \n query?\n15:45 < cj> can we do $schema->resultset('Cdnurl') without having it issue \n a query, for instance?\n15:45 <@ilmari> $result_source->column_info('colname')->{extra}->{list}\n15:45 < cj> and $result_source is $schema->resultset('Cdnurl') ?\n15:45 <@ilmari> dbic never issues a query until you start retrieving the \n results\n15:45 < cj> oh, nice.\n15:46 <@ilmari> $schema->source('Cdnurl')\n15:46 <@ilmari> the result source is where the result set gets the results \n from when they are needed\n15:47 <@ilmari> names have meanings :)\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8003/"
] |
I have some code which needs to ensure some data is in a mysql enum prior to insertion in the database. The cleanest way I've found of doing this is the following code:
```
sub enum_values {
my ( $self, $schema, $table, $column ) = @_;
# don't eval to let the error bubble up
my $columns = $schema->storage->dbh->selectrow_hashref(
"SHOW COLUMNS FROM `$table` like ?",
{},
$column
);
unless ($columns) {
X::Internal::Database::UnknownColumn->throw(
column => $column,
table => $table,
);
}
my $type = $columns->{Type} or X::Panic->throw(
details => "Could not determine type for $table.$column",
);
unless ( $type =~ /\Aenum\((.*)\)\z/ ) {
X::Internal::Database::IncorrectTypeForColumn->throw(
type_wanted => 'enum',
type_found => $type,
);
}
$type = $1;
require Text::CSV_XS;
my $csv = Text::CSV_XS->new;
$csv->parse($type) or X::Panic->throw(
details => "Could not parse enum CSV data: ".$csv->error_input,
);
return map { /\A'(.*)'\z/; $1 }$csv->fields;
}
```
We're using [DBIx::Class](http://search.cpan.org/dist/DBIx-Class/). Surely there is a better way of accomplishing this? (Note that the $table variable is coming from our code, *not* from any external source. Thus, no security issue).
|
No need to be so heroic. Using a reasonably modern version of [DBD::mysql](http://search.cpan.org/dist/DBD-mysql/), the hash returned by [DBI](http://search.cpan.org/dist/DBI/)'s [column info](http://search.cpan.org/dist/DBI/DBI.pm#column_info) method contains a pre-split version of the valid enum values in the key `mysql_values`:
```
my $sth = $dbh->column_info(undef, undef, 'mytable', '%');
foreach my $col_info ($sth->fetchrow_hashref)
{
if($col_info->{'TYPE_NAME'} eq 'ENUM')
{
# The mysql_values key contains a reference to an array of valid enum values
print "Valid enum values for $col_info->{'COLUMN_NAME'}: ",
join(', ', @{$col_info->{'mysql_values'}}), "\n";
}
...
}
```
|
229,254 |
<p>I have a server application that receives information over a network and processes it.
The server is multi-threaded and handles multiple sockets at time, and threads are created without my control through BeginInvoke and EndInvoke style methods, which are chained by corresponding callback functions.</p>
<p>I'm trying to create a form, in addition to the main GUI, that displays a ListBox item populated by items describing the currently connected sockets.
So, what I'm basically trying to do is add an item to the ListBox using its Add() function, from the thread the appropriate callback function is running on.
I'm accessing my forms controls through the Controls property - I.E:</p>
<pre><code>(ListBox)c.Controls["listBox1"].Items.Add();
</code></pre>
<p>Naturally I don't just call the function, I've tried several ways I've found here and on the web to communicate between threads, including <code>MethodInvoker</code>, using a <code>delegate</code>, in combination with <code>Invoke()</code>, <code>BeginInvoke()</code> etc.
Nothing seems to work, I always get the same exception telling me my control was accessed from a thread other than the one it was created on.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 229287,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Using BeginInvoke or Invoke should work fine. Could you post a short but complete program which demonstrates the problem? You should be able to work one up which doesn't actually need any server-side stuff - just have a bunch of threads which \"pretend\" to receive incoming connections.</p>\n"
},
{
"answer_id": 229292,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 3,
"selected": false,
"text": "<p>I've always used something along these lines:</p>\n\n<pre><code> c = <your control>\n if (c.InvokeRequired)\n {\n c.BeginInvoke((MethodInvoker)delegate\n {\n //do something with c\n });\n }\n else\n {\n //do something with c\n }\n</code></pre>\n\n<p>I also wrote a bunch of helper extension methods to... help.</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\npublic static class CrossThreadHelper\n{\n public static bool CrossThread<T,R>(this ISynchronizeInvoke value, Action<T, R> action, T sender, R e)\n {\n if (value.InvokeRequired)\n {\n value.BeginInvoke(action, new object[] { sender, e });\n }\n\n return value.InvokeRequired;\n }\n}\n</code></pre>\n\n<p>used like this:</p>\n\n<pre><code> private void OnServerMessageReceived(object sender, ClientStateArgs e)\n {\n if (this.CrossThread((se, ev) => OnServerMessageReceived(se, ev), sender, e)) return;\n this.statusTextBox.Text += string.Format(\"Message Received From: {0}\\r\\n\", e.ClientState);\n }\n</code></pre>\n"
},
{
"answer_id": 229294,
"author": "Magnus Lindhe",
"author_id": 966,
"author_profile": "https://Stackoverflow.com/users/966",
"pm_score": 3,
"selected": true,
"text": "<p>You have to call Invoke (or BeginInvoke) on the ListBox control you are accessing in order for the delegate to be called on the thread that created that control.</p>\n\n<pre><code>ListBox listBox = c.Controls[\"listBox1\"] as ListBox;\nif(listBox != null)\n{\n listBox.Invoke(...);\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a server application that receives information over a network and processes it.
The server is multi-threaded and handles multiple sockets at time, and threads are created without my control through BeginInvoke and EndInvoke style methods, which are chained by corresponding callback functions.
I'm trying to create a form, in addition to the main GUI, that displays a ListBox item populated by items describing the currently connected sockets.
So, what I'm basically trying to do is add an item to the ListBox using its Add() function, from the thread the appropriate callback function is running on.
I'm accessing my forms controls through the Controls property - I.E:
```
(ListBox)c.Controls["listBox1"].Items.Add();
```
Naturally I don't just call the function, I've tried several ways I've found here and on the web to communicate between threads, including `MethodInvoker`, using a `delegate`, in combination with `Invoke()`, `BeginInvoke()` etc.
Nothing seems to work, I always get the same exception telling me my control was accessed from a thread other than the one it was created on.
Any thoughts?
|
You have to call Invoke (or BeginInvoke) on the ListBox control you are accessing in order for the delegate to be called on the thread that created that control.
```
ListBox listBox = c.Controls["listBox1"] as ListBox;
if(listBox != null)
{
listBox.Invoke(...);
}
```
|
229,272 |
<pre><code><div style="width: 300px">
<div id="one" style="float: left">saved</div><input type="submit" id="two" style="float: right" value="Submit" />
</div>
</code></pre>
<p>I would like div#one to be centred in the space between the left edge of the parent div and the left edge of the submit button.</p>
|
[
{
"answer_id": 229277,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 1,
"selected": false,
"text": "<p>There are a number of techniques listed <a href=\"http://css-discuss.incutio.com/?page=CenteringBlockElement\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>However, if you simply wanted the \"saved\" text to be centred, I think you'll need to give a width to #one, e.g.</p>\n\n<pre><code><div style=\"width: 300px\">\n<div id=\"one\" style=\"float: left;text-align:center;width:80%\">saved</div>\n<input type=\"submit\" id=\"two\" style=\"float: right;width:20%\" value=\"Submit\" />\n</div>\n</code></pre>\n"
},
{
"answer_id": 229323,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>A few more ways to do it:</p>\n\n<pre><code><div style=\"width: 300px\">\n <input type=\"submit\" id=\"two\" style=\"float: right\" value=\"Submit\" />\n <div id=\"one\" style=\"text-align:center;\">saved</div>\n</div>\n</code></pre>\n\n<p>It's hard to tell that the text <code>saved</code> isn't centered between the left edge of the container <code>div</code> and the left edge of the submit button.</p>\n\n<p>Here is an exact version of the above:</p>\n\n<pre><code><div style=\"width: 300px;\">\n <input type=\"submit\" id=\"two\" style=\"float: right; width:64px;\" value=\"Submit\" />\n <div id=\"one\" style=\"text-align:center;margin-right:64px;\">saved</div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 1350218,
"author": "sho",
"author_id": 59465,
"author_profile": "https://Stackoverflow.com/users/59465",
"pm_score": 0,
"selected": false,
"text": "<p>This is an example of a general problem with CSS, which is that there is no way to compute the 'remaining space' in various layouts. </p>\n\n<p>I've run into situations where you (a) need an exact layout, and (b) where you don't know the size of the floating item.</p>\n\n<p>Example:</p>\n\n<blockquote>\n <p>[---- input field that takes 100% of the remaining space ----] [button of unknown width] </p>\n</blockquote>\n\n<p>You would think that this was possible, but AFAIK, you have to use tables to achieve this. There isn't even a proposal in CSS for how this would be fixed in the future. <em>sigh</em></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
<div style="width: 300px">
<div id="one" style="float: left">saved</div><input type="submit" id="two" style="float: right" value="Submit" />
</div>
```
I would like div#one to be centred in the space between the left edge of the parent div and the left edge of the submit button.
|
A few more ways to do it:
```
<div style="width: 300px">
<input type="submit" id="two" style="float: right" value="Submit" />
<div id="one" style="text-align:center;">saved</div>
</div>
```
It's hard to tell that the text `saved` isn't centered between the left edge of the container `div` and the left edge of the submit button.
Here is an exact version of the above:
```
<div style="width: 300px;">
<input type="submit" id="two" style="float: right; width:64px;" value="Submit" />
<div id="one" style="text-align:center;margin-right:64px;">saved</div>
</div>
```
|
229,310 |
<p>I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:</p>
<pre><code>DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance();
docfactory.setIgnoringElementContentWhitespace(true);
</code></pre>
<p>I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.</p>
<p>What can I do?</p>
<p>Update</p>
<p>I don't like the idea of introduce mySelf < !ELEMENT... declarations and i have tried the
solution proposed in the <a href="http://forums.sun.com/thread.jspa?messageID=2054303#2699961" rel="noreferrer">forum</a> pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes</p>
|
[
{
"answer_id": 229520,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 5,
"selected": true,
"text": "<p>‘IgnoringElementContentWhitespace’ is not about removing <em>all</em> pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT content — that is to say, they only contain other elements and never text.</p>\n\n<p>If you don't have a schema (DTD or XSD) in use, element content defaults to MIXED, so this parameter will never have any effect. (Unless the parser provides a non-standard DOM extension to treat all unknown elements as containing ELEMENT content, which as far as I know the ones available for Java do not.)</p>\n\n<p>You could hack the document on the way into the parser to include the schema information, for example by adding an internal subset to the < !DOCTYPE ... [...] > declaration containing < !ELEMENT ... > declarations, then use the IgnoringElementContentWhitespace parameter.</p>\n\n<p>Or, possibly easier, you could just strip out the whitespace nodes, either in a post-process, or as they come in using an LSParserFilter.</p>\n"
},
{
"answer_id": 5851888,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 3,
"selected": false,
"text": "<p>This is a (really) late answer, but here is how I solved it. I wrote my own implementation of a <code>NodeList</code> class. It simply ignores text nodes that are empty. Code follows:</p>\n\n<pre><code>private static class NdLst implements NodeList, Iterable<Node> {\n\n private List<Node> nodes;\n\n public NdLst(NodeList list) {\n nodes = new ArrayList<Node>();\n for (int i = 0; i < list.getLength(); i++) {\n if (!isWhitespaceNode(list.item(i))) {\n nodes.add(list.item(i));\n }\n }\n }\n\n @Override\n public Node item(int index) {\n return nodes.get(index);\n }\n\n @Override\n public int getLength() {\n return nodes.size();\n }\n\n private static boolean isWhitespaceNode(Node n) {\n if (n.getNodeType() == Node.TEXT_NODE) {\n String val = n.getNodeValue();\n return val.trim().length() == 0;\n } else {\n return false;\n }\n }\n\n @Override\n public Iterator<Node> iterator() {\n return nodes.iterator();\n }\n}\n</code></pre>\n\n<p>You then wrap all of your <code>NodeList</code>s in this class and it will effectively ignore all whitespace nodes. (Which I define as Text Nodes with 0-length trimmed text.)</p>\n\n<p>It also has the added benefit of being able to be used in a for-each loop.</p>\n"
},
{
"answer_id": 19602644,
"author": "huppyuy",
"author_id": 528900,
"author_profile": "https://Stackoverflow.com/users/528900",
"pm_score": 2,
"selected": false,
"text": "<p>I made it works by doing this </p>\n\n<pre><code>DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n dbFactory.setIgnoringElementContentWhitespace(true);\n dbFactory.setSchema(schema);\n dbFactory.setNamespaceAware(true);\nNodeList nodeList = element.getElementsByTagNameNS(\"*\", \"associate\");\n</code></pre>\n"
},
{
"answer_id": 48835894,
"author": "ImGroot",
"author_id": 2203209,
"author_profile": "https://Stackoverflow.com/users/2203209",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>private static Document prepareXML(String param) throws ParserConfigurationException, SAXException, IOException {\n\n param = param.replaceAll(\">\\\\s+<\", \"><\").trim();\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setIgnoringElementContentWhitespace(true);\n DocumentBuilder builder = factory.newDocumentBuilder();\n InputSource in = new InputSource(new StringReader(param));\n return builder.parse(in);\n\n }\n</code></pre>\n"
},
{
"answer_id": 51219452,
"author": "Tamias",
"author_id": 5799033,
"author_profile": "https://Stackoverflow.com/users/5799033",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up following @bobince's idea of using an LSParserFilter. Yes, the interface is documented at <a href=\"https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/LSParserFilter.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/LSParserFilter.html</a> but it's very hard to find good example/explanation material. After considerable searching I located DOM Level 3 Load and Save XML Reference Guide at <a href=\"http://www.informit.com/articles/article.aspx?p=31297&seqNum=29\" rel=\"nofollow noreferrer\">http://www.informit.com/articles/article.aspx?p=31297&seqNum=29</a> (Nicholas Chase, Mar 14, 2003). That helped me considerably. Here are portions of my code, which does an XML diff with org.custommonkey.xmlunit. (This is a tool written on my own time to help me with paid work, so I have left a lot of things, like better exception handling, for when things are slow.)</p>\n\n<p>I especially like the use of an LSParserFilter because, for my purpose, I will likely add an option in the future to ignore id attributes too, which should be an easy enhancement with this framework.</p>\n\n<pre><code>// A small portion of my main class.\n// Other imports may be necessary...\nimport org.w3c.dom.bootstrap.DOMImplementationRegistry;\nimport org.w3c.dom.ls.DOMImplementationLS;\nimport org.w3c.dom.ls.LSParser;\nimport org.w3c.dom.ls.LSParserFilter;\n\nDocument controlDoc = null;\nDocument testDoc = null;\ntry {\n System.setProperty(DOMImplementationRegistry.PROPERTY, \"org.apache.xerces.dom.DOMImplementationSourceImpl\");\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(\"LS\");\n LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);\n LSParserFilter filter = new InputFilter();\n builder.setFilter(filter);\n controlDoc = builder.parseURI(files[0].getPath());\n testDoc = builder.parseURI(files[1].getPath());\n} catch (Exception exc) {\n System.out.println(exc.getMessage());\n}\n\n//--------------------------------------\n\nimport org.w3c.dom.ls.LSParserFilter;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.traversal.NodeFilter;\n\npublic class InputFilter implements LSParserFilter {\n\n public short acceptNode(Node node) {\n if (Utils.isNewline(node)) {\n return NodeFilter.FILTER_REJECT;\n }\n return NodeFilter.FILTER_ACCEPT;\n }\n\n public int getWhatToShow() {\n return NodeFilter.SHOW_ALL;\n }\n\n public short startElement(Element elem) {\n return LSParserFilter.FILTER_ACCEPT;\n }\n\n}\n\n//-------------------------------------\n// From my Utils.java:\n\n public static boolean isNewline(Node node) {\n return (node.getNodeType() == Node.TEXT_NODE) && node.getTextContent().equals(\"\\n\");\n }\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518/"
] |
I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:
```
DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance();
docfactory.setIgnoringElementContentWhitespace(true);
```
I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.
What can I do?
Update
I don't like the idea of introduce mySelf < !ELEMENT... declarations and i have tried the
solution proposed in the [forum](http://forums.sun.com/thread.jspa?messageID=2054303#2699961) pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes
|
‘IgnoringElementContentWhitespace’ is not about removing *all* pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT content — that is to say, they only contain other elements and never text.
If you don't have a schema (DTD or XSD) in use, element content defaults to MIXED, so this parameter will never have any effect. (Unless the parser provides a non-standard DOM extension to treat all unknown elements as containing ELEMENT content, which as far as I know the ones available for Java do not.)
You could hack the document on the way into the parser to include the schema information, for example by adding an internal subset to the < !DOCTYPE ... [...] > declaration containing < !ELEMENT ... > declarations, then use the IgnoringElementContentWhitespace parameter.
Or, possibly easier, you could just strip out the whitespace nodes, either in a post-process, or as they come in using an LSParserFilter.
|
229,346 |
<p>I have a String which I would like to modify in some way. For example: reverse it or upcase it. </p>
<p>I have discovered that the fastest way to do this is by using a unsafe block and pointers. </p>
<p>For example: </p>
<pre><code> unsafe
{
fixed (char* str = text)
{
*str = 'X';
}
}
</code></pre>
<p>Are there any reasons why I should never ever do this? </p>
|
[
{
"answer_id": 229351,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 5,
"selected": true,
"text": "<p>The .Net framework requires strings to be immutable. Due to this requirement it is able to optimise all sorts of operations. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/String_intern_pool\" rel=\"noreferrer\">String interning</a> is one great example of this requirement is leveraged heavily. To speed up some string comparisons (and reduce memory consumption) the .Net framework maintains a Dictionary of pointers, all pre-defined strings will live in this dictionary or any strings where you call the <code>String.intern</code> method on. When the IL instruction ldstr is called it will check the interned dictionary and avoid memory allocation if we already have the string allocated, note: <a href=\"http://bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx\" rel=\"noreferrer\">String.Concat</a> will not check for interned strings. </p>\n\n<p>This property of the .net framework means that if you start mucking around directly with strings you can corrupt your intern table and in turn corrupt other references to the same string.</p>\n\n<p>For example:</p>\n\n<pre><code> // these strings get interned\n string hello = \"hello\";\n string hello2 = \"hello\";\n\n string helloworld, helloworld2;\n\n helloworld = hello;\n helloworld += \" world\";\n\n helloworld2 = hello;\n helloworld2 += \" world\"; \n\n unsafe\n {\n // very bad, this changes an interned string which affects \n // all app domains.\n fixed (char* str = hello2)\n {\n *str = 'X';\n }\n\n fixed (char* str = helloworld2)\n {\n *str = 'X';\n }\n\n }\n\n Console.WriteLine(\"hello = {0} , hello2 = {1}\", hello, hello2);\n // output: hello = Xello , hello2 = Xello \n\n\n Console.WriteLine(\"helloworld = {0} , helloworld2 = {1}\", helloworld, helloworld2);\n // output : helloworld = hello world , helloworld2 = Xello world \n</code></pre>\n"
},
{
"answer_id": 229354,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>Are there any reasons why I should never ever do this? </p>\n</blockquote>\n\n<p>Yes, very simple: Because .NET relies on the fact that strings are immutable. Some operations (e.g. <code>s.SubString(0, s.Length)</code>) actually return a reference to the original string. If this now gets modified, all other references will as well.</p>\n\n<p>Better use a <code>StringBuilder</code> to modify a string since this is the default way.</p>\n"
},
{
"answer_id": 229359,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 1,
"selected": false,
"text": "<p>Oh dear lord yes.</p>\n\n<p>1) Because that class is not designed to be tampered with. </p>\n\n<p>2) Because strings are designed and expected throughout the framework to be immutable. That means that code that everyone else writes (including MSFT) is expecting a string's underlying value never to change.</p>\n\n<p>3) Because this is premature optimization and that is E V I L.</p>\n"
},
{
"answer_id": 229406,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Put it this way: how would you feel if another programmer decided to replace 0 with 1 everywhere in your code, at execution time? It would play hell with all your assumptions. The same is true with strings. <em>Everyone</em> expects them to be immutable, and codes with that assumption in mind. If you violate that, you are likely to introduce bugs - and they'll be <em>really</em> hard to trace.</p>\n"
},
{
"answer_id": 230704,
"author": "Coderer",
"author_id": 26286,
"author_profile": "https://Stackoverflow.com/users/26286",
"pm_score": 0,
"selected": false,
"text": "<p>Agreed about StringBuilder, or just convert your string to an array of chars/bytes and work there. Also, you gave the example of \"upcasing\" -- the String class has a ToUpper method, and if that's not <em>at least</em> as fast as your unsafe \"upcasing\", I'll eat my hat.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
I have a String which I would like to modify in some way. For example: reverse it or upcase it.
I have discovered that the fastest way to do this is by using a unsafe block and pointers.
For example:
```
unsafe
{
fixed (char* str = text)
{
*str = 'X';
}
}
```
Are there any reasons why I should never ever do this?
|
The .Net framework requires strings to be immutable. Due to this requirement it is able to optimise all sorts of operations.
[String interning](http://en.wikipedia.org/wiki/String_intern_pool) is one great example of this requirement is leveraged heavily. To speed up some string comparisons (and reduce memory consumption) the .Net framework maintains a Dictionary of pointers, all pre-defined strings will live in this dictionary or any strings where you call the `String.intern` method on. When the IL instruction ldstr is called it will check the interned dictionary and avoid memory allocation if we already have the string allocated, note: [String.Concat](http://bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx) will not check for interned strings.
This property of the .net framework means that if you start mucking around directly with strings you can corrupt your intern table and in turn corrupt other references to the same string.
For example:
```
// these strings get interned
string hello = "hello";
string hello2 = "hello";
string helloworld, helloworld2;
helloworld = hello;
helloworld += " world";
helloworld2 = hello;
helloworld2 += " world";
unsafe
{
// very bad, this changes an interned string which affects
// all app domains.
fixed (char* str = hello2)
{
*str = 'X';
}
fixed (char* str = helloworld2)
{
*str = 'X';
}
}
Console.WriteLine("hello = {0} , hello2 = {1}", hello, hello2);
// output: hello = Xello , hello2 = Xello
Console.WriteLine("helloworld = {0} , helloworld2 = {1}", helloworld, helloworld2);
// output : helloworld = hello world , helloworld2 = Xello world
```
|
229,352 |
<p>I am using Python to extract the filename from a link using rfind like below:</p>
<pre><code>url = "http://www.google.com/test.php"
print url[url.rfind("/") +1 : ]
</code></pre>
<p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "<a href="http://www.google.com/test.php/" rel="nofollow noreferrer">http://www.google.com/test.php/</a>". I am have trouble getting the page name when there is a "/" at the end, can anyone help?</p>
<p>Cheers</p>
|
[
{
"answer_id": 229386,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": -1,
"selected": false,
"text": "<p>You could use</p>\n\n<pre><code>print url[url.rstrip(\"/\").rfind(\"/\") +1 : ]\n</code></pre>\n"
},
{
"answer_id": 229394,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 1,
"selected": false,
"text": "<p>Filenames with a slash at the end are technically still path definitions and indicate that the index file is to be read. If you actually have one that' ends in <code>test.php/</code>, I would consider that an error. In any case, you can strip the / from the end before running your code as follows:</p>\n\n<pre><code>url = url.rstrip('/')\n</code></pre>\n"
},
{
"answer_id": 229399,
"author": "Andrew Cox",
"author_id": 27907,
"author_profile": "https://Stackoverflow.com/users/27907",
"pm_score": 0,
"selected": false,
"text": "<p>There is a library called <a href=\"http://www.python.org/doc/2.4/lib/module-urlparse.html\" rel=\"nofollow noreferrer\">urlparse</a> that will parse the url for you, but still doesn't remove the / at the end so one of the above will be the best option</p>\n"
},
{
"answer_id": 229401,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "<p>Just removing the slash at the end won't work, as you can probably have a URL that looks like this:</p>\n\n<pre><code>http://www.google.com/test.php?filepath=tests/hey.xml\n</code></pre>\n\n<p>...in which case you'll get back \"hey.xml\". Instead of manually checking for this, you can use <b>urlparse</b> to get rid of the parameters, then do the check other people suggested:</p>\n\n<pre><code>from urlparse import urlparse\nurl = \"http://www.google.com/test.php?something=heyharr/sir/a.txt\"\nf = urlparse(url)[2].rstrip(\"/\")\nprint f[f.rfind(\"/\")+1:]\n</code></pre>\n"
},
{
"answer_id": 229417,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "<p>Just for fun, you can use a Regexp:</p>\n\n<pre><code>import re\nprint re.search('/([^/]+)/?$', url).group(1)\n</code></pre>\n"
},
{
"answer_id": 229430,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 2,
"selected": false,
"text": "<p>Use [r]strip to remove trailing slashes:</p>\n\n<pre><code>url.rstrip('/').rsplit('/', 1)[-1]\n</code></pre>\n\n<p>If a wider range of possible URLs is possible, including URLs with ?queries, #anchors or without a path, do it properly with urlparse:</p>\n\n<pre><code>path= urlparse.urlparse(url).path\nreturn path.rstrip('/').rsplit('/', 1)[-1] or '(root path)'\n</code></pre>\n"
},
{
"answer_id": 229650,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": -1,
"selected": false,
"text": "<pre><code>filter(None, url.split('/'))[-1]\n</code></pre>\n\n<p>(But urlparse is probably more readable, even if more verbose.)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am using Python to extract the filename from a link using rfind like below:
```
url = "http://www.google.com/test.php"
print url[url.rfind("/") +1 : ]
```
This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "<http://www.google.com/test.php/>". I am have trouble getting the page name when there is a "/" at the end, can anyone help?
Cheers
|
Just removing the slash at the end won't work, as you can probably have a URL that looks like this:
```
http://www.google.com/test.php?filepath=tests/hey.xml
```
...in which case you'll get back "hey.xml". Instead of manually checking for this, you can use **urlparse** to get rid of the parameters, then do the check other people suggested:
```
from urlparse import urlparse
url = "http://www.google.com/test.php?something=heyharr/sir/a.txt"
f = urlparse(url)[2].rstrip("/")
print f[f.rfind("/")+1:]
```
|
229,353 |
<p>In my main page (call it <code>index.aspx</code>) I call </p>
<pre><code><%Html.RenderPartial("_PowerSearch", ViewData.Model);%>
</code></pre>
<p>Here the <code>viewdata.model != null</code>
When I arrive at my partial:</p>
<pre><code><%=ViewData.Model%>
</code></pre>
<p>Says <code>viewdata.model == null</code></p>
<p>What gives?!</p>
|
[
{
"answer_id": 229367,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 2,
"selected": true,
"text": "<p>Have you tried just passing in ViewData instead of ViewData.Model? This is an abridged version what I use in my helpers (shamelessly stolen from the Storefront series):</p>\n\n<pre><code> /// <summary>\n /// Renders a LoggingWeb user control.\n /// </summary>\n /// <param name=\"helper\">Helper to extend.</param>\n /// <param name=\"control\">Type of control.</param>\n /// <param name=\"data\">ViewData to pass in.</param>\n public static void RenderLoggingControl(this System.Web.Mvc.HtmlHelper helper, LoggingControls control, object data)\n {\n string controlName = string.Format(\"{0}.ascx\", control);\n string controlPath = string.Format(\"~/Controls/{0}\", controlName);\n string absControlPath = VirtualPathUtility.ToAbsolute(controlPath);\n if (data == null)\n {\n helper.RenderPartial(absControlPath, helper.ViewContext.ViewData);\n }\n else\n {\n helper.RenderPartial(absControlPath, data, helper.ViewContext.ViewData);\n }\n }\n</code></pre>\n\n<p>Note that I pass in the current ViewData and not the Model.</p>\n"
},
{
"answer_id": 229453,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 0,
"selected": false,
"text": "<p>This is untested:</p>\n\n<pre><code><%=Html.RenderPartial(\"_ColorList.ascx\", new ViewDataDictionary(ViewData.Model.Colors));%>\n</code></pre>\n\n<p>Your control view is expecting view data specific to it in this case. If your control wants a property on the model called Colors then perhaps:</p>\n\n<pre><code><%=Html.RenderPartial(\"_ColorList.ascx\", new ViewDataDictionary(new { Colors = ViewData.Model.Colors }));%>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
In my main page (call it `index.aspx`) I call
```
<%Html.RenderPartial("_PowerSearch", ViewData.Model);%>
```
Here the `viewdata.model != null`
When I arrive at my partial:
```
<%=ViewData.Model%>
```
Says `viewdata.model == null`
What gives?!
|
Have you tried just passing in ViewData instead of ViewData.Model? This is an abridged version what I use in my helpers (shamelessly stolen from the Storefront series):
```
/// <summary>
/// Renders a LoggingWeb user control.
/// </summary>
/// <param name="helper">Helper to extend.</param>
/// <param name="control">Type of control.</param>
/// <param name="data">ViewData to pass in.</param>
public static void RenderLoggingControl(this System.Web.Mvc.HtmlHelper helper, LoggingControls control, object data)
{
string controlName = string.Format("{0}.ascx", control);
string controlPath = string.Format("~/Controls/{0}", controlName);
string absControlPath = VirtualPathUtility.ToAbsolute(controlPath);
if (data == null)
{
helper.RenderPartial(absControlPath, helper.ViewContext.ViewData);
}
else
{
helper.RenderPartial(absControlPath, data, helper.ViewContext.ViewData);
}
}
```
Note that I pass in the current ViewData and not the Model.
|
229,357 |
<p>What is the best way in <strong>Perl</strong> to copy files to a yet-to-be-created destination directory tree?</p>
<p>Something like</p>
<pre><code>copy("test.txt","tardir/dest1/dest2/text.txt");
</code></pre>
<p>won't work since the directory <em>tardir/dest1/dest2</em> does not yet exist. What is the best way to copy with directory creation in Perl?</p>
|
[
{
"answer_id": 229382,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": false,
"text": "<pre><code>use File::Basename qw/dirname/;\nuse File::Copy;\n\nsub mkdir_recursive {\n my $path = shift;\n mkdir_recursive(dirname($path)) if not -d dirname($path);\n mkdir $path or die \"Could not make dir $path: $!\" if not -d $path;\n return;\n}\n\nsub mkdir_and_copy {\n my ($from, $to) = @_;\n mkdir_recursive(dirname($to));\n copy($from, $to) or die \"Couldn't copy: $!\";\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 229402,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 6,
"selected": true,
"text": "<pre><code>use File::Path;\nuse File::Copy;\n\nmy $path = \"tardir/dest1/dest2/\";\nmy $file = \"test.txt\";\n\nif (! -d $path)\n{\n my $dirs = eval { mkpath($path) };\n die \"Failed to create $path: $@\\n\" unless $dirs;\n}\n\ncopy($file,$path) or die \"Failed to copy $file: $!\\n\";\n</code></pre>\n"
},
{
"answer_id": 231539,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://search.cpan.org/perldoc?File::Copy::Recursive\" rel=\"nofollow noreferrer\">File::Copy::Recursive</a>::fcopy() is non-core but combines the File::Path::mkpath() and File::Copy::copy() solution into something even shorter, and preserves permissions unlike File::Copy. It also contains other nifty utility functions.</p>\n"
},
{
"answer_id": 232812,
"author": "EvdB",
"author_id": 5349,
"author_profile": "https://Stackoverflow.com/users/5349",
"pm_score": 1,
"selected": false,
"text": "<p>See the other answers for doing the copying, but for creating the directory <a href=\"http://search.cpan.org/dist/Path-Class/\" rel=\"nofollow noreferrer\">Path::Class</a> is very nice to use:</p>\n\n<pre><code>use Path::Class;\n\nmy $destination_file = file('tardir/dest1/dest2/test.txt');\n$destination_file->dir->mkpath;\n\n# ... do the copying here\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6511/"
] |
What is the best way in **Perl** to copy files to a yet-to-be-created destination directory tree?
Something like
```
copy("test.txt","tardir/dest1/dest2/text.txt");
```
won't work since the directory *tardir/dest1/dest2* does not yet exist. What is the best way to copy with directory creation in Perl?
|
```
use File::Path;
use File::Copy;
my $path = "tardir/dest1/dest2/";
my $file = "test.txt";
if (! -d $path)
{
my $dirs = eval { mkpath($path) };
die "Failed to create $path: $@\n" unless $dirs;
}
copy($file,$path) or die "Failed to copy $file: $!\n";
```
|
229,362 |
<p>I am trying to call out to a legacy dll compiled from FORTRAN code. I am new to Interop, but I've read some articles on it and it seems like my case should be fairly straightforward. </p>
<p>The method I really want to call has a complex method signature, but I can't even call this simple GetVersion method without getting a protected memory violation.</p>
<p>Here's my DllImport code:</p>
<pre><code>[DllImport("GeoConvert.dll",
EntryPoint="_get_version@4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPStr, SizeConst=8)]
ref string version);
</code></pre>
<p>Here's the FORTRAN code:</p>
<pre><code>SUBROUTINE GetVer( VRSION )
C
!MS$DEFINE MSDLL
!MS$IF DEFINED (MSDLL)
ENTRY Get_Version (VRSION)
!MS$ATTRIBUTES DLLEXPORT,STDCALL :: Get_Version
!MS$ATTRIBUTES REFERENCE :: VRSION
!MS$ENDIF
!MS$UNDEFINE MSDLL
C
CHARACTER*8 VRSION
C
VRSION = '1.0a_FhC'
C
RETURN
END
</code></pre>
<p>Here's my unit test that fails:</p>
<pre><code>[Test]
public void TestGetVersion()
{
string version = "";
LatLonUtils.GetGeoConvertVersion(ref version);
StringAssert.IsNonEmpty(version);
}
</code></pre>
<p>Here's the error message I get:</p>
<pre><code>System.AccessViolationException
Message: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
</code></pre>
<p>Other things I've tried:</p>
<ul>
<li>Using the default marshalling</li>
<li>Passing a char[] instead of a string (get method signature errors instead)</li>
</ul>
|
[
{
"answer_id": 229507,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using a StringBuilder?</p>\n\n<p>Create your String as a StringBuilder and pass that into the dll function. </p>\n\n<p>Im unsure as to what Marashlling statement to use, perhapse the default might work.</p>\n\n<p>Have a look at: <a href=\"https://stackoverflow.com/questions/158628/marshal-c-string-class-in-c-pinvoke\">Marshal C++ “string” class in C# P/Invoke</a></p>\n\n<p>Heres a good article the might help as well: <a href=\"http://www.arstdesign.com/articles/interopmarshaling.html\" rel=\"nofollow noreferrer\">Interop Marshalling</a></p>\n"
},
{
"answer_id": 229525,
"author": "brien",
"author_id": 4219,
"author_profile": "https://Stackoverflow.com/users/4219",
"pm_score": 2,
"selected": true,
"text": "<p>OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works:</p>\n\n<pre><code>[DllImport(\"GeoConvert.dll\", \n EntryPoint=\"_get_version@4\", \n CallingConvention=CallingConvention.StdCall)]\n public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPArray)]\n byte[] version);\n</code></pre>\n\n<p>With this test:</p>\n\n<pre><code>[Test]\n public void TestGetVersion()\n {\n //string version = \"\";\n byte[] version = new byte[8];\n LatLonUtils.GetGeoConvertVersion(version);\n char[] versionChars = System.Text.Encoding.ASCII.GetChars(version);\n\n string versionString = new string(versionChars);\n }\n</code></pre>\n"
},
{
"answer_id": 229873,
"author": "Jeremy",
"author_id": 19174,
"author_profile": "https://Stackoverflow.com/users/19174",
"pm_score": 0,
"selected": false,
"text": "<p>I cannot try this solution since I do not have a FORTRAN compiler, but I think this would work for you:</p>\n\n<pre><code> [DllImport(\"GeoConvert.dll\", \n EntryPoint=\"_get_version@4\", \n CallingConvention=CallingConvention.StdCall,\n CharSet=CharSet.Ansi)]\n public static extern void GetGeoConvertVersion(StringBuilder version);\n</code></pre>\n"
},
{
"answer_id": 230737,
"author": "Todd",
"author_id": 30841,
"author_profile": "https://Stackoverflow.com/users/30841",
"pm_score": 2,
"selected": false,
"text": "<p>...snip...\nOK, I got it to work, the problem was passing by ref. I'm not sure why, but this works:\n...snip...</p>\n\n<p>You need to pass by reference because that is the semantic being used by the FORTRAN code. The client code is passing in a buffer that the FORTRAN code is going to write to in lieu of using a return value. </p>\n\n<p>...snip...\n!MS$ATTRIBUTES REFERENCE :: VRSION\n...snip...</p>\n\n<p>This attribute in your FORTRAN code specifies that this parameter is passed by reference. That means the FORTRAN code is going to write to this address. If the DllImport doesn't declare it as a ref value also, you will get an access violation.</p>\n"
},
{
"answer_id": 4966330,
"author": "fnz",
"author_id": 612621,
"author_profile": "https://Stackoverflow.com/users/612621",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you all guys, I've been trying to pass a string from c# to a subroutine from fortran dll and this method was the only working one among lots of others</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4219/"
] |
I am trying to call out to a legacy dll compiled from FORTRAN code. I am new to Interop, but I've read some articles on it and it seems like my case should be fairly straightforward.
The method I really want to call has a complex method signature, but I can't even call this simple GetVersion method without getting a protected memory violation.
Here's my DllImport code:
```
[DllImport("GeoConvert.dll",
EntryPoint="_get_version@4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPStr, SizeConst=8)]
ref string version);
```
Here's the FORTRAN code:
```
SUBROUTINE GetVer( VRSION )
C
!MS$DEFINE MSDLL
!MS$IF DEFINED (MSDLL)
ENTRY Get_Version (VRSION)
!MS$ATTRIBUTES DLLEXPORT,STDCALL :: Get_Version
!MS$ATTRIBUTES REFERENCE :: VRSION
!MS$ENDIF
!MS$UNDEFINE MSDLL
C
CHARACTER*8 VRSION
C
VRSION = '1.0a_FhC'
C
RETURN
END
```
Here's my unit test that fails:
```
[Test]
public void TestGetVersion()
{
string version = "";
LatLonUtils.GetGeoConvertVersion(ref version);
StringAssert.IsNonEmpty(version);
}
```
Here's the error message I get:
```
System.AccessViolationException
Message: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
```
Other things I've tried:
* Using the default marshalling
* Passing a char[] instead of a string (get method signature errors instead)
|
OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works:
```
[DllImport("GeoConvert.dll",
EntryPoint="_get_version@4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPArray)]
byte[] version);
```
With this test:
```
[Test]
public void TestGetVersion()
{
//string version = "";
byte[] version = new byte[8];
LatLonUtils.GetGeoConvertVersion(version);
char[] versionChars = System.Text.Encoding.ASCII.GetChars(version);
string versionString = new string(versionChars);
}
```
|
229,385 |
<p>Visual Studio gives many navigation hotkeys:
<kbd>F8</kbd> for next item in current panel (search results, errors ...),
<kbd>Control</kbd>+<kbd>K</kbd>, <kbd>N</kbd> for bookmarks,
<kbd>Alt</kbd>+<kbd>-</kbd> for going back and more.</p>
<p>There is one hotkey that I can't find, and I can't even find the menu-command for it, so I can't create the hotkey myself.</p>
<p>I don't know if such exist: Previous and Next call-stack frame.</p>
<p>I try not using the mouse when programming, but when I need to go back the stack, I must use it to double click the previous frame.</p>
<p>Anyone? How about a macro that does it?</p>
|
[
{
"answer_id": 229400,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": -1,
"selected": false,
"text": "<p>Look in <strong>Tools->Options->Environment->Keyboard</strong>. Enter \"stack\" or \"frame\" and related menus will appear. It seems that there's no next and previous call-stack frame.</p>\n"
},
{
"answer_id": 230658,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think theres an explict next-frame / prev-frame key binding but heres what I do.</p>\n\n<p>CTRL-ALT-C is already bound to \"Debug.CallStack\"\n This will focus you in the Call Stack Tool Window</p>\n\n<p>Once focused in the Callstack window... Up & Down arrows will move you through the call stack frames</p>\n\n<p>I've then bound </p>\n\n<p>CTRL-C, CTRL-S to \"DebuggerContextMenus.CallStackWindow.SwitchToFrame\"\nand\nCTRL-C, CTRL-C to \"DebuggerContextMenus.CallStackWindow.SwitchToCode\"</p>\n\n<p>both of which will take you back into the code window at the particular frame.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 1211782,
"author": "Oleg Svechkarenko",
"author_id": 148405,
"author_profile": "https://Stackoverflow.com/users/148405",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote 2 macros to gain it: <code>PreviousStackFrame</code> and <code>NextStackFrame</code> and assigned shortcuts to</p>\n\n<pre><code>Function StackFrameIndex(ByRef aFrames As EnvDTE.StackFrames, ByRef aFrame As EnvDTE.StackFrame) As Long\n For StackFrameIndex = 1 To aFrames.Count\n If aFrames.Item(StackFrameIndex) Is aFrame Then Exit Function\n Next\n StackFrameIndex = -1\nEnd Function\n\nSub NavigateStack(ByVal aShift As Long)\n If DTE.Debugger.CurrentProgram Is Nothing Then\n DTE.StatusBar.Text = \"No program is currently being debugged.\"\n Exit Sub\n End If\n\n Dim ind As Long = StackFrameIndex(DTE.Debugger.CurrentThread.StackFrames, DTE.Debugger.CurrentStackFrame)\n If ind = -1 Then\n DTE.StatusBar.Text = \"Stack navigation failed\"\n Exit Sub\n End If\n\n ind = ind + aShift\n If ind <= 0 Or ind > DTE.Debugger.CurrentThread.StackFrames.Count Then\n DTE.StatusBar.Text = \"Stack frame index is out of range\"\n Exit Sub\n End If\n\n DTE.Debugger.CurrentStackFrame = DTE.Debugger.CurrentThread.StackFrames.Item(ind)\n DTE.StatusBar.Text = \"Stack frame index: \" & ind & \" of \" & DTE.Debugger.CurrentThread.StackFrames.Count\nEnd Sub\n\nSub PreviousStackFrame()\n NavigateStack(1)\nEnd Sub\n\nSub NextStackFrame()\n NavigateStack(-1)\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 26718512,
"author": "Programmer Paul",
"author_id": 2482416,
"author_profile": "https://Stackoverflow.com/users/2482416",
"pm_score": 2,
"selected": false,
"text": "<p>I have solved this problem with <a href=\"http://www.ahkscript.org\" rel=\"nofollow\">AutoHotkey</a>. I made this a few months ago.\nSuppose you wanted to use Control+1 and Control+2 and that Control+Alt+C is bound to showing the Call Stack window:</p>\n\n<pre><code>^1::SendInput !^c{down}{enter}\n^2::SendInput !^c{up}{enter}\n</code></pre>\n\n<p>It seems to work pretty well. If you aren't already using AutoHotkey to show Visual Studio who's boss, please give it a shot. Your question indicates that you would benefit greatly from it. It's a game changer. Good luck.</p>\n"
},
{
"answer_id": 51183643,
"author": "Mills",
"author_id": 1088467,
"author_profile": "https://Stackoverflow.com/users/1088467",
"pm_score": 1,
"selected": false,
"text": "<p>Huge thanks to @Oleg Svechkarenko for his answer that gave me a starting point in crafting this solution. Since modern versions of Visual Studio no longer have official macro support, this should drop in for those who use the <a href=\"https://marketplace.visualstudio.com/items?itemName=SergeyVlasov.VisualCommander\" rel=\"nofollow noreferrer\" title=\"Visual Commander\">Visual Commander</a> plugin, but probably can be easily adapted for any other macro extension. </p>\n\n<p>Here is the code for the command, I created one for navigating up the call stack and one for navigating down with the same code except the parameter passed to <code>MoveStackIndex()</code>, then bound keyboard shortcuts to them:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using EnvDTE;\nusing EnvDTE80;\nusing System;\n\npublic class C : VisualCommanderExt.ICommand\n{\n enum MoveDirection\n {\n Up,\n Down,\n }\n\n private bool IsValidFrame(StackFrame frame)\n {\n string language = frame.Language;\n\n bool result = (language == \"C#\" || \n language == \"C++\" || \n language == \"VB\" || \n language == \"Python\");\n\n return result;\n }\n\n private void MoveStackIndex(EnvDTE80.DTE2 DTE, MoveDirection direction)\n {\n StackFrame currentFrame = DTE.Debugger.CurrentStackFrame;\n\n bool foundTarget = false;\n bool pastCurrent = false;\n\n StackFrame lastValid = null;\n foreach (StackFrame frame in DTE.Debugger.CurrentThread.StackFrames)\n {\n bool isCurrent = frame == currentFrame;\n\n if (direction == MoveDirection.Down)\n {\n if (isCurrent)\n {\n if (lastValid == null)\n {\n // No valid frames below this one\n break;\n }\n else\n {\n DTE.Debugger.CurrentStackFrame = lastValid;\n foundTarget = true;\n break; \n }\n }\n else\n {\n if (IsValidFrame(frame))\n {\n lastValid = frame;\n }\n }\n }\n\n if (direction == MoveDirection.Up && pastCurrent)\n {\n if (IsValidFrame(frame))\n {\n DTE.Debugger.CurrentStackFrame = frame;\n foundTarget = true;\n break;\n } \n }\n\n if (isCurrent)\n {\n pastCurrent = true;\n }\n }\n\n if (!foundTarget)\n {\n DTE.StatusBar.Text = \"Failed to find valid stack frame in that direction.\";\n }\n }\n\n public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) \n {\n if (DTE.Debugger.CurrentProgram == null)\n {\n DTE.StatusBar.Text = \"Debug session not active.\";\n }\n else\n {\n // NOTE: Change param 2 to MoveDirection.Up for the up command\n MoveStackIndex(DTE, MoveDirection.Down);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Visual Studio gives many navigation hotkeys:
`F8` for next item in current panel (search results, errors ...),
`Control`+`K`, `N` for bookmarks,
`Alt`+`-` for going back and more.
There is one hotkey that I can't find, and I can't even find the menu-command for it, so I can't create the hotkey myself.
I don't know if such exist: Previous and Next call-stack frame.
I try not using the mouse when programming, but when I need to go back the stack, I must use it to double click the previous frame.
Anyone? How about a macro that does it?
|
I wrote 2 macros to gain it: `PreviousStackFrame` and `NextStackFrame` and assigned shortcuts to
```
Function StackFrameIndex(ByRef aFrames As EnvDTE.StackFrames, ByRef aFrame As EnvDTE.StackFrame) As Long
For StackFrameIndex = 1 To aFrames.Count
If aFrames.Item(StackFrameIndex) Is aFrame Then Exit Function
Next
StackFrameIndex = -1
End Function
Sub NavigateStack(ByVal aShift As Long)
If DTE.Debugger.CurrentProgram Is Nothing Then
DTE.StatusBar.Text = "No program is currently being debugged."
Exit Sub
End If
Dim ind As Long = StackFrameIndex(DTE.Debugger.CurrentThread.StackFrames, DTE.Debugger.CurrentStackFrame)
If ind = -1 Then
DTE.StatusBar.Text = "Stack navigation failed"
Exit Sub
End If
ind = ind + aShift
If ind <= 0 Or ind > DTE.Debugger.CurrentThread.StackFrames.Count Then
DTE.StatusBar.Text = "Stack frame index is out of range"
Exit Sub
End If
DTE.Debugger.CurrentStackFrame = DTE.Debugger.CurrentThread.StackFrames.Item(ind)
DTE.StatusBar.Text = "Stack frame index: " & ind & " of " & DTE.Debugger.CurrentThread.StackFrames.Count
End Sub
Sub PreviousStackFrame()
NavigateStack(1)
End Sub
Sub NextStackFrame()
NavigateStack(-1)
End Sub
```
|
229,404 |
<p>I am trying to extract a table of values from an excel (2003) spreadsheet using vb6, the result of which needs to be stored in a (adodb) recordset. The table looks like this:</p>
<pre>
Name Option.1 Option.2 Option.3 Option.4 Option.5 Option.6
-----------------------------------------------------------------
Name1 2 3 4
Name2 2 3 4
Name3 2 3 4
Name4 2 3 4
Name5 2 3 4
Name6 2 3 4
Name7 2 3 4
Name8 2 3 4
Name9 2 3 4 5 6 7
</pre>
<p>Upon connecting and executing the query "<code>SELECT * FROM [Sheet1$]</code>" or even a column-specific, "<code>SELECT [Option#6] FROM [Sheet1$]</code>" (see footnote 1) and looping through the results, I am given <code>Null</code> values for the row <code>Name9</code>, <code>Option.4</code> --> <code>Option.6</code> rather than the correct values 5, 6, and 7. It seems the connection to the spreadsheet is using a "best guess" of deciding what the valid table limits are, and only takes a set number of rows into account. </p>
<p>To connect to the spreadsheet, I have tried both connection providers <code>Microsoft.Jet.OLEDB.4.0</code> and <code>MSDASQL</code> and get the same problem.</p>
<p>Here are the connection settings I use:</p>
<pre><code>Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & filePath & ";Extended Properties=Excel 8.0;"
- - - - OR - - - -
.Provider = "MSDASQL"
.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};" & _
"DBQ=" & filePath & ";MaxScanRows=0;"
.CursorLocation = adUseClient
.Open
End With
Set rsSelects = New ADODB.Recordset
Set rsSelects = cn.Execute("SELECT [Option#5] FROM " & "[" & strTbl & "]")
</code></pre>
<p>This problem only occurs when there are more than 8 rows (excluding the column names), and I have set <code>MaxScanRow=0</code> for the <code>MSDASQL</code> connection, but this has produced the same results.</p>
<p>Notable project references I have included are: </p>
<ul>
<li>MS ActiveX Data Objects 2.8 Library</li>
<li>MS ActiveX Data Objects Recordset 2.8 Library</li>
<li>MS Excel 11.0 Object Library</li>
<li>MS Data Binding Collection VB 6.0 (SP4)</li>
</ul>
<p>Any help in this matter would be very appreciated!</p>
<p>(1) For some reason, when including a decimal point in the column name, it is interpreted as a #.</p>
<hr>
<p>Thanks everyone! Halfway through trying to set up a <code>Schema.ini</code> "programmatically" from <a href="http://support.microsoft.com/kb/155512" rel="nofollow noreferrer">KB155512</a> <a href="https://stackoverflow.com/questions/229404/ignored-columns-using-vb6-to-extract-from-excel#229721">onedaywhen</a>'s excellent <a href="http://www.dailydoseofexcel.com/archives/2004/06/03/external-data-mixed-data-types/" rel="nofollow noreferrer">post</a> pointed me towards the solution:</p>
<pre><code>.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & filePath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
</code></pre>
<p>I would encourage anyone with similar problems to read the post and comments, since there are slight variations to a solution from one person to another.</p>
|
[
{
"answer_id": 229477,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>The Excel ISAM driver by default looks into the first handful of your rows and guesses their data type. Should there be (later in the table) data that does not fit into the initial assumption, it frowns and turns it to NULL.</p>\n\n<p>Your <code>MaxScanRows=0</code> setting is the key to this problem. It sounds like it would do the Right Thing (scan the whole table for the data type to use), but really it doesn't.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/229404/ignored-columns-using-vb6-to-extract-from-excel#229721\">onedaywhen</a>'s answer for further details, my first info about <a href=\"http://support.microsoft.com/kb/282263/\" rel=\"nofollow noreferrer\">KB282263</a> was not the correct advice.</p>\n"
},
{
"answer_id": 229631,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 0,
"selected": false,
"text": "<p>The best advice I can give you is to stop doing it in the VB6 environment. Open Excel, press ALT+F11 and load the VBA IDE. Put your code in there. From within this environment you can access the full Excel object model. </p>\n\n<p>I've seen many people try and interact with Excel in many different ways and they all have problems. Using either the VBA macro, or Add-in method is a best way I have found of getting at the data. It's how Microsoft get Excel and Project to integrate with TFS.</p>\n\n<p>Sometimes you need to rethink the process a little for this approach to be suitable. E.g. You may need to get the user who is using the spreadsheet to run a macro that will push the data out of the spreadsheet instead of you running a process to pull the data from the spreadsheet but usually it is quite doable. </p>\n"
},
{
"answer_id": 229721,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": true,
"text": "<p>You are correct: it is guessing the data type based on a number of rows. There are local machine registry keys you may be able to alter to influence the data type chosen. For more details, see <a href=\"https://stackoverflow.com/a/10102515/15354\">this answer</a>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30757/"
] |
I am trying to extract a table of values from an excel (2003) spreadsheet using vb6, the result of which needs to be stored in a (adodb) recordset. The table looks like this:
```
Name Option.1 Option.2 Option.3 Option.4 Option.5 Option.6
-----------------------------------------------------------------
Name1 2 3 4
Name2 2 3 4
Name3 2 3 4
Name4 2 3 4
Name5 2 3 4
Name6 2 3 4
Name7 2 3 4
Name8 2 3 4
Name9 2 3 4 5 6 7
```
Upon connecting and executing the query "`SELECT * FROM [Sheet1$]`" or even a column-specific, "`SELECT [Option#6] FROM [Sheet1$]`" (see footnote 1) and looping through the results, I am given `Null` values for the row `Name9`, `Option.4` --> `Option.6` rather than the correct values 5, 6, and 7. It seems the connection to the spreadsheet is using a "best guess" of deciding what the valid table limits are, and only takes a set number of rows into account.
To connect to the spreadsheet, I have tried both connection providers `Microsoft.Jet.OLEDB.4.0` and `MSDASQL` and get the same problem.
Here are the connection settings I use:
```
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & filePath & ";Extended Properties=Excel 8.0;"
- - - - OR - - - -
.Provider = "MSDASQL"
.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};" & _
"DBQ=" & filePath & ";MaxScanRows=0;"
.CursorLocation = adUseClient
.Open
End With
Set rsSelects = New ADODB.Recordset
Set rsSelects = cn.Execute("SELECT [Option#5] FROM " & "[" & strTbl & "]")
```
This problem only occurs when there are more than 8 rows (excluding the column names), and I have set `MaxScanRow=0` for the `MSDASQL` connection, but this has produced the same results.
Notable project references I have included are:
* MS ActiveX Data Objects 2.8 Library
* MS ActiveX Data Objects Recordset 2.8 Library
* MS Excel 11.0 Object Library
* MS Data Binding Collection VB 6.0 (SP4)
Any help in this matter would be very appreciated!
(1) For some reason, when including a decimal point in the column name, it is interpreted as a #.
---
Thanks everyone! Halfway through trying to set up a `Schema.ini` "programmatically" from [KB155512](http://support.microsoft.com/kb/155512) [onedaywhen](https://stackoverflow.com/questions/229404/ignored-columns-using-vb6-to-extract-from-excel#229721)'s excellent [post](http://www.dailydoseofexcel.com/archives/2004/06/03/external-data-mixed-data-types/) pointed me towards the solution:
```
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & filePath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
```
I would encourage anyone with similar problems to read the post and comments, since there are slight variations to a solution from one person to another.
|
You are correct: it is guessing the data type based on a number of rows. There are local machine registry keys you may be able to alter to influence the data type chosen. For more details, see [this answer](https://stackoverflow.com/a/10102515/15354).
|
229,423 |
<p>We have a need to take dozens of different protocols from systems such as security systems, fire alarms, camera systems etc.. and integrate them into a single common protocol.</p>
<p>I would like this to be a messaging server that many systems could subscribe to and or communicate through.</p>
<ul>
<li>polling and non-polling "drivers" (protocol converters)</li>
<li>handle RS232 / RS485 / tcp</li>
<li>programmable "drivers" in a managed language like Java or C#</li>
<li>rules engine capability</li>
</ul>
<p>Does biztalk fit this? </p>
<p>Are there open source alternatives?</p>
<p>Is there a Java / Java EE way to do this?</p>
<p>At one end the system would be a SCADA system at the other is is kind of a middleware / messaging server.</p>
<p>Any thoughts on the best way to proceed would be appreciated. I know that there will be a considerable amount of programming involved on the driver side, however as tempted as I am, building the whole system from scratch would not be appropriate.</p>
|
[
{
"answer_id": 229793,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 3,
"selected": true,
"text": "<p>If you don't mind working on the Java platform there's a lightweight protocol switcher and implementation of the <a href=\"http://activemq.apache.org/camel/enterprise-integration-patterns.html\" rel=\"nofollow noreferrer\">Enterprise Integration Patterns</a> in an open source project called <a href=\"http://activemq.apache.org/camel/\" rel=\"nofollow noreferrer\">Apache Camel</a>.</p>\n\n<p>Camel can already speak most of the <a href=\"http://activemq.apache.org/camel/components.html\" rel=\"nofollow noreferrer\">common protocols and technologies</a> like <a href=\"http://activemq.apache.org/camel/file.html\" rel=\"nofollow noreferrer\">files</a>, <a href=\"http://activemq.apache.org/camel/mail.html\" rel=\"nofollow noreferrer\">email</a>, <a href=\"http://activemq.apache.org/camel/jms.html\" rel=\"nofollow noreferrer\">JMS</a>, <a href=\"http://activemq.apache.org/camel/xmpp.html\" rel=\"nofollow noreferrer\">XMPP</a> and so forth so there'd be no actual coding required for those things.</p>\n\n<p>To add new custom protocols the simplest route is to build on top of the <a href=\"http://activemq.apache.org/camel/mina.html\" rel=\"nofollow noreferrer\">MINA component</a> which takes care of all the networking, socket handling, threading and so forth (e.g. NIO versus BIO et al).</p>\n\n<p>Then you just extend it to add your own protocol codec (how to marshal/unmarshal messages on the socket with possibly using framing etc).</p>\n\n<p>The <a href=\"http://activemq.apache.org/camel/hl7.html\" rel=\"nofollow noreferrer\">HL7 component</a> is an example of doing this. More <a href=\"http://mina.apache.org/tutorial-on-protocolcodecfilter.html\" rel=\"nofollow noreferrer\">detail on writing MINA codecs here</a>.</p>\n\n<p>Then once you've got your camel component (lets call it foo) you could then bridge from any protocol to any other protocol using simple URIs to implement any of the <a href=\"http://activemq.apache.org/camel/enterprise-integration-patterns.html\" rel=\"nofollow noreferrer\">Enterprise Integration Patterns</a> such as <a href=\"http://activemq.apache.org/camel/content-based-router.html\" rel=\"nofollow noreferrer\">Content Based Router</a>, <a href=\"http://activemq.apache.org/camel/recipient-list.html\" rel=\"nofollow noreferrer\">Recipient List</a>, <a href=\"http://activemq.apache.org/camel/routing-slip.html\" rel=\"nofollow noreferrer\">Routing Slip</a> etc</p>\n\n<p>e.g. in Java code</p>\n\n<pre><code>// route all messages from foo\n// to a single queue on JMS\nfrom(\"foo://somehost:1234\").\n to(\"jms:MyQueue\");\n\n// route all messages from foo component\n// to a queue using a header\nfrom(\"foo://somehost:1234\").\n recipientList().\n simple(\"activemq:MyPrefix.${headers.cheese}\");\n</code></pre>\n"
},
{
"answer_id": 229972,
"author": "ckarras",
"author_id": 5688,
"author_profile": "https://Stackoverflow.com/users/5688",
"pm_score": 3,
"selected": false,
"text": "<p>I would avoid BizTalk for SCADA and RS232/RS485 because these typically require realtime (or at least low latency) solutions. BizTalk is optimized for high throughtput, but has the drawback of having high latency by default. </p>\n\n<p>You can tweak BizTalk for low latency, but at this point you'll find you bypass almost everything BizTalk has built-in and it would probably get in the way instead of helping you.</p>\n"
},
{
"answer_id": 1274587,
"author": "Mauli",
"author_id": 917,
"author_profile": "https://Stackoverflow.com/users/917",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest <a href=\"http://www.openscada.org\" rel=\"nofollow noreferrer\">OpenSCADA</a>. The website is at the moment a bit of a mess, but the software is actively in use and in active development. A explicit goal is to create a common, technology independent, interface for SCADA use cases (although at the moment the direction is more or less oriented towards java [but we experiment also with ikvm to create a .NET version]).</p>\n\n<p>So you could use OpenSCADA to communicate with all the \"hardware\" devices and then create a bridge to the rest of your middleware, or create a OpenSCADA bridge as a plugin within your middleware. We already have for instance drivers which connect to card readers linked via a serial server to the LAN.</p>\n"
},
{
"answer_id": 3050732,
"author": "silvrhand",
"author_id": 367887,
"author_profile": "https://Stackoverflow.com/users/367887",
"pm_score": 2,
"selected": false,
"text": "<p>www.livedata.com</p>\n\n<p>It's a bit pricey but it's a python based engine that can take one protocol and spit out another, it's already setup for multiple scada protocols such as ICCP, modbus, OPC, and DNP out of the box. Then you can talk whatever you want downstream.</p>\n\n<ul>\n<li>John</li>\n</ul>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
We have a need to take dozens of different protocols from systems such as security systems, fire alarms, camera systems etc.. and integrate them into a single common protocol.
I would like this to be a messaging server that many systems could subscribe to and or communicate through.
* polling and non-polling "drivers" (protocol converters)
* handle RS232 / RS485 / tcp
* programmable "drivers" in a managed language like Java or C#
* rules engine capability
Does biztalk fit this?
Are there open source alternatives?
Is there a Java / Java EE way to do this?
At one end the system would be a SCADA system at the other is is kind of a middleware / messaging server.
Any thoughts on the best way to proceed would be appreciated. I know that there will be a considerable amount of programming involved on the driver side, however as tempted as I am, building the whole system from scratch would not be appropriate.
|
If you don't mind working on the Java platform there's a lightweight protocol switcher and implementation of the [Enterprise Integration Patterns](http://activemq.apache.org/camel/enterprise-integration-patterns.html) in an open source project called [Apache Camel](http://activemq.apache.org/camel/).
Camel can already speak most of the [common protocols and technologies](http://activemq.apache.org/camel/components.html) like [files](http://activemq.apache.org/camel/file.html), [email](http://activemq.apache.org/camel/mail.html), [JMS](http://activemq.apache.org/camel/jms.html), [XMPP](http://activemq.apache.org/camel/xmpp.html) and so forth so there'd be no actual coding required for those things.
To add new custom protocols the simplest route is to build on top of the [MINA component](http://activemq.apache.org/camel/mina.html) which takes care of all the networking, socket handling, threading and so forth (e.g. NIO versus BIO et al).
Then you just extend it to add your own protocol codec (how to marshal/unmarshal messages on the socket with possibly using framing etc).
The [HL7 component](http://activemq.apache.org/camel/hl7.html) is an example of doing this. More [detail on writing MINA codecs here](http://mina.apache.org/tutorial-on-protocolcodecfilter.html).
Then once you've got your camel component (lets call it foo) you could then bridge from any protocol to any other protocol using simple URIs to implement any of the [Enterprise Integration Patterns](http://activemq.apache.org/camel/enterprise-integration-patterns.html) such as [Content Based Router](http://activemq.apache.org/camel/content-based-router.html), [Recipient List](http://activemq.apache.org/camel/recipient-list.html), [Routing Slip](http://activemq.apache.org/camel/routing-slip.html) etc
e.g. in Java code
```
// route all messages from foo
// to a single queue on JMS
from("foo://somehost:1234").
to("jms:MyQueue");
// route all messages from foo component
// to a queue using a header
from("foo://somehost:1234").
recipientList().
simple("activemq:MyPrefix.${headers.cheese}");
```
|
229,425 |
<p>I'm trying to populate a DataTable, to build a LocalReport, using the following:<br></p>
<pre><code>MySqlCommand cmd = new MySqlCommand();
cmd.Connection = new MySqlConnection(Properties.Settings.Default.dbConnectionString);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ... LEFT JOIN ... WHERE ..."; /* query snipped */
// prepare data
dataTable.Clear();
cn.Open();
// fill datatable
dt.Load(cmd.ExecuteReader());
// fill report
rds = new ReportDataSource("InvoicesDataSet_InvoiceTable",dt);
reportViewerLocal.LocalReport.DataSources.Clear();
reportViewerLocal.LocalReport.DataSources.Add(rds);
</code></pre>
<p>At one point I noticed that the report was incomplete and it was missing one record. I've changed a few conditions so that the query would return exactly two rows and... <b>surprise</b>: The report shows only one row instead of two. I've tried to debug it to find where the problem is and I got stuck at</p>
<pre><code> dt.Load(cmd.ExecuteReader());
</code></pre>
<p>When I've noticed that the <code>DataReader</code> contains two records but the <code>DataTable</code> contains only one. By accident, I've added an <code>ORDER BY</code> clause to the query and noticed that this time the report showed correctly.<br><br>
Apparently, the DataReader contains two rows but the DataTable only reads both of them if the SQL query string contains an <code>ORDER BY</code> (otherwise it only reads the last one). Can anyone explain why this is happening and how it can be fixed?</p>
<p><b>Edit:</b>
When I first posted the question, I said it was skipping the first row; later I realized that it actually only read the last row and I've edited the text accordingly (at that time all the records were grouped in two rows and it appeared to skip the first when it actually only showed the last). This may be caused by the fact that it didn't have a unique identifier by which to distinguish between the rows returned by MySQL so adding the <code>ORDER BY</code> statement caused it to create a unique identifier for each row.<br />
This is just a theory and I have nothing to support it, but all my tests seem to lead to the same result.</p>
|
[
{
"answer_id": 229458,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": "<p>Can you grab the actual query that is running from SQL profiler and try running it? It may not be what you expected. </p>\n\n<p>Do you get the same result when using a SqlDataAdapter.Fill(dataTable)? </p>\n\n<p>Have you tried different command behaviors on the reader? <a href=\"http://msdn.microsoft.com/en-us/library/y6wy5a0f.aspx\" rel=\"nofollow noreferrer\">MSDN Docs</a></p>\n"
},
{
"answer_id": 241423,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure why you're missing the row in the datatable, is it possible you need to close the reader? In any case, here is how I normally load reports and it works every time...</p>\n\n<pre><code> Dim deals As New DealsProvider()\n Dim adapter As New ReportingDataTableAdapters.ReportDealsAdapter\n Dim report As ReportingData.ReportDealsDataTable = deals.GetActiveDealsReport()\n rptReports.LocalReport.DataSources.Add(New ReportDataSource(\"ActiveDeals_Data\", report))\n</code></pre>\n\n<p>Curious to see if it still happens. </p>\n"
},
{
"answer_id": 243563,
"author": "Brian",
"author_id": 17356,
"author_profile": "https://Stackoverflow.com/users/17356",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried calling <code>dt.AcceptChanges()</code> after the <code>dt.Load(cmd.ExecuteReader())</code> call to see if that helps?</p>\n"
},
{
"answer_id": 452962,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>I had same issue. I took hint from your blog and put up the ORDER BY clause in the query so that they could form together the unique key for all the records returned by query. It solved the problem. Kinda weird.</p>\n"
},
{
"answer_id": 3398766,
"author": "canceriens",
"author_id": 409916,
"author_profile": "https://Stackoverflow.com/users/409916",
"pm_score": 0,
"selected": false,
"text": "<p>In my case neither ORDER BY, nor dt.AcceptChanges() is working. I dont know why is that problem for. I am having 50 records in database but it only shows 49 in the datatable. skipping first row, and if there is only one record in datareader it shows nothing at all.</p>\n\n<p>what a bizzareeee.....</p>\n"
},
{
"answer_id": 4640518,
"author": "tant",
"author_id": 568956,
"author_profile": "https://Stackoverflow.com/users/568956",
"pm_score": 3,
"selected": false,
"text": "<p>Just in case anyone is having a similar problem as canceriens, I was using If <code>DataReader.Read</code> ... instead of If <code>DataReader.HasRows</code> to check existence before calling <code>dt.load(DataReader)</code> Doh!</p>\n"
},
{
"answer_id": 9210238,
"author": "Majnu",
"author_id": 1016144,
"author_profile": "https://Stackoverflow.com/users/1016144",
"pm_score": 4,
"selected": false,
"text": "<p>After fiddling around quite a bit I found that the <code>DataTable.Load</code> method expects a primary key column in the underlying data. If you read the documentation carefully, this becomes obvious, although it is not stated very explicitly.</p>\n<p>If you have a column named "id" it seems to use that (which fixed it for me). Otherwise, it just seems to use the first column, whether it is unique or not, and overwrites rows with the same value in that column as they are being read. If you don't have a column named "id" and your first column isn't unique, I'd suggest trying to explicitly set the primary key column(s) of the datatable before loading the datareader.</p>\n"
},
{
"answer_id": 9489550,
"author": "Bluebaron",
"author_id": 511273,
"author_profile": "https://Stackoverflow.com/users/511273",
"pm_score": 2,
"selected": false,
"text": "<p>Had the same issue. It is because the primary key on all the rows is the same. It's probably what's being used to key the results, and therefore it's just overwriting the same row over and over again.</p>\n\n<p>Datatables.Load points to the fill method to understand how it works. This page states that it is primary key aware. Since primary keys can only occur once and are used as the keys for the row ...</p>\n\n<p>\"The Fill operation then adds the rows to destination DataTable objects in the DataSet, creating the DataTable objects if they do not already exist. When creating DataTable objects, the Fill operation normally creates only column name metadata. However, if the MissingSchemaAction property is set to AddWithKey, appropriate primary keys and constraints are also created.\" (http://msdn.microsoft.com/en-us/library/zxkb3c3d.aspx)</p>\n"
},
{
"answer_id": 20471735,
"author": "James",
"author_id": 2865852,
"author_profile": "https://Stackoverflow.com/users/2865852",
"pm_score": 3,
"selected": false,
"text": "<p>Don't use</p>\n\n<pre><code>dr.Read()\n</code></pre>\n\n<p>Because It moves the pointer to the next row.\nRemove this line hope it will work.</p>\n"
},
{
"answer_id": 22664787,
"author": "waka",
"author_id": 2099119,
"author_profile": "https://Stackoverflow.com/users/2099119",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an old question, but I was experiencing the same problem and none of the workarounds mentioned here did help.</p>\n\n<p>In my case, using an alias on the colum that is used as the <code>PrimaryKey</code> solved the issue.</p>\n\n<p>So, instead of</p>\n\n<pre><code>SELECT a\n , b\nFROM table\n</code></pre>\n\n<p>I used</p>\n\n<pre><code>SELECT a as gurgleurp\n , b\nFROM table\n</code></pre>\n\n<p>and it worked.</p>\n"
},
{
"answer_id": 23083491,
"author": "Jamie Hartnoll",
"author_id": 956482,
"author_profile": "https://Stackoverflow.com/users/956482",
"pm_score": 2,
"selected": false,
"text": "<p>Came across this problem today.</p>\n\n<p>Nothing in this thread fixed it unfortunately, but then I wrapped my SQL query in another SELECT statement and it work!</p>\n\n<p>Eg:</p>\n\n<pre><code>SELECT * FROM (\n SELECT ..... < YOUR NORMAL SQL STATEMENT HERE />\n) allrecords\n</code></pre>\n\n<p>Strange....</p>\n"
},
{
"answer_id": 26276936,
"author": "IFlyHigh",
"author_id": 2745909,
"author_profile": "https://Stackoverflow.com/users/2745909",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem.. do not used dataReader.Read() at all.. it will takes the pointer to the next row. Instead use directly datatable.load(dataReader).</p>\n"
},
{
"answer_id": 36909763,
"author": "ullevi83",
"author_id": 1712112,
"author_profile": "https://Stackoverflow.com/users/1712112",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an old question, but for me the think that worked whilst querying an access database and noticing it was missing 1 row from query, was to change the following:-</p>\n\n<pre><code> if(dataset.read()) - Misses a row.\n\n if(dataset.hasrows) - Missing row appears.\n</code></pre>\n"
},
{
"answer_id": 58509759,
"author": "XtoxictoneX",
"author_id": 12258929,
"author_profile": "https://Stackoverflow.com/users/12258929",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone else that comes across this thread as I have, the answer regarding the DataTable being populated by a unique ID from MySql is correct. </p>\n\n<p>However, if a table contains multiple unique IDs but only a single ID is returned from a MySql command (instead of receiving all Columns by using '*') then that DataTable will only organize by the single ID that was given and act as if a 'GROUP BY' was used in your query.</p>\n\n<p>So in short, the DataReader will pull all records while the DataTable.Load() will only see the unique ID retrieved and use that to populate the DataTable thus skipping rows of information</p>\n"
},
{
"answer_id": 73047332,
"author": "mohammadAli",
"author_id": 9826453,
"author_profile": "https://Stackoverflow.com/users/9826453",
"pm_score": 0,
"selected": false,
"text": "<p>Encountered the same problem, I have also tried selecting unique first column but the datatable still missing a row.</p>\n<p>But selecting the first column(which is also unique) in group by solved the problem.</p>\n<p>i.e</p>\n<pre><code>select uniqueData,.....\nfrom mytable\ngroup by uniqueData;\n</code></pre>\n<p>This solves the problem.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26155/"
] |
I'm trying to populate a DataTable, to build a LocalReport, using the following:
```
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = new MySqlConnection(Properties.Settings.Default.dbConnectionString);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ... LEFT JOIN ... WHERE ..."; /* query snipped */
// prepare data
dataTable.Clear();
cn.Open();
// fill datatable
dt.Load(cmd.ExecuteReader());
// fill report
rds = new ReportDataSource("InvoicesDataSet_InvoiceTable",dt);
reportViewerLocal.LocalReport.DataSources.Clear();
reportViewerLocal.LocalReport.DataSources.Add(rds);
```
At one point I noticed that the report was incomplete and it was missing one record. I've changed a few conditions so that the query would return exactly two rows and... **surprise**: The report shows only one row instead of two. I've tried to debug it to find where the problem is and I got stuck at
```
dt.Load(cmd.ExecuteReader());
```
When I've noticed that the `DataReader` contains two records but the `DataTable` contains only one. By accident, I've added an `ORDER BY` clause to the query and noticed that this time the report showed correctly.
Apparently, the DataReader contains two rows but the DataTable only reads both of them if the SQL query string contains an `ORDER BY` (otherwise it only reads the last one). Can anyone explain why this is happening and how it can be fixed?
**Edit:**
When I first posted the question, I said it was skipping the first row; later I realized that it actually only read the last row and I've edited the text accordingly (at that time all the records were grouped in two rows and it appeared to skip the first when it actually only showed the last). This may be caused by the fact that it didn't have a unique identifier by which to distinguish between the rows returned by MySQL so adding the `ORDER BY` statement caused it to create a unique identifier for each row.
|
I had same issue. I took hint from your blog and put up the ORDER BY clause in the query so that they could form together the unique key for all the records returned by query. It solved the problem. Kinda weird.
|
229,446 |
<p>On our site, we get a large amount of photos uploaded from various sources. </p>
<p>In order to keep the file sizes down, we strip all <a href="http://en.wikipedia.org/wiki/Exif" rel="noreferrer">exif data</a> from the source using <a href="http://www.imagemagick.org/www/mogrify.html" rel="noreferrer">mogrify</a>:</p>
<pre><code>mogrify -strip image.jpg
</code></pre>
<p>What we'd like to be able to do is to insert some basic exif data (Copyright Initrode, etc) back onto this new "clean" image, but I can't seem to find anything in the docs that would achieve this.</p>
<p>Has anybody any experience of doing this? </p>
<p>If it can't be done through imagemagick, a PHP-based solution would be the next best thing!</p>
<p>Thanks.</p>
|
[
{
"answer_id": 229479,
"author": "Colin Pickard",
"author_id": 12744,
"author_profile": "https://Stackoverflow.com/users/12744",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.sno.phy.queensu.ca/~phil/exiftool/\" rel=\"noreferrer\">Exiftool</a> looks like it would be an exact match for you.</p>\n\n<p>I haven't tried it but I'm now tempted to go and fix all my honeymoon photos which are marked 01/01/2074 because I forgot to reset the date after the batteries died.</p>\n"
},
{
"answer_id": 229489,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a <a href=\"https://github.com/pel/pel\" rel=\"nofollow noreferrer\">PHP Exif Library</a> that should do what you need.</p>\n\n<blockquote>\n <p>The PHP Exif Library (PEL) lets you\n fully manipulate Exif (Exchangeable\n Image File Format) data. This is the\n data that digital cameras place in\n their images, such as the date and\n time, shutter speed, ISO value and so\n on.</p>\n \n <p>Using PEL, one can fully modify the\n Exif data, meaning that it can be both\n read and written. Completely new Exif\n data can also be added to images. PEL\n is written completely in PHP and\n depends on nothing except a standard\n installation of PHP, version 5. PEL is\n hosted on SourceForge.</p>\n</blockquote>\n"
},
{
"answer_id": 230160,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>I doubt you will gain lot of space by removing Exif information...</p>\n\n<p>Anyway, I can be wrong, but Exif metadata belongs more to store technical (and contextual) information. For stuff like copyright, you should use IPTC instead.</p>\n\n<p>That's something you can do, apparently, with ImageMagick: <a href=\"http://www.experts-exchange.com/Software/Photos_Graphics/Web_Graphics/Q_21093317.html\" rel=\"nofollow noreferrer\" title=\"Write IPTC Data to Jpeg with ImageMagick\">Write IPTC Data to Jpeg with ImageMagick</a>.</p>\n"
},
{
"answer_id": 230480,
"author": "Ciaran",
"author_id": 5048,
"author_profile": "https://Stackoverflow.com/users/5048",
"pm_score": 5,
"selected": true,
"text": "<p>You can save a large amount of space, especially if you have a large number of images..</p>\n\n<p>Add the following to text.txt (format of the IPTC tags taken from <a href=\"http://www.narf.ssji.net/~shtrom/wiki/tips/imagemanipulation\" rel=\"noreferrer\">here</a>):</p>\n\n<pre><code>2#110#Credit=\"My Company\"\n2#05#Object Name=\"THE_OBJECT_NAME\"\n2#55#Date Created=\"2011-02-03 12:45\"\n2#80#By-line=\"BY-LINE?\"\n2#110#Credit=\"The CREDIT\"\n2#115#Source=\"SOURCE\"\n2#116#Copyright Notice=\"THE COPYRIGHT\"\n2#118#Contact=\"THE CONTACT\"\n2#120#Caption=\"AKA Title\"\n</code></pre>\n\n<p>Strip all existing exif data from the image</p>\n\n<pre><code>mogrify -strip image.jpg\n</code></pre>\n\n<p>Add the credit to your image</p>\n\n<pre><code>mogrify -profile 8BIMTEXT:text.txt image.jpg\n</code></pre>\n"
},
{
"answer_id": 2030031,
"author": "Bastiaan",
"author_id": 246653,
"author_profile": "https://Stackoverflow.com/users/246653",
"pm_score": 3,
"selected": false,
"text": "<p>on linux there is a program called jhead. It can add a minimal exif header with the command:</p>\n\n<p>jhead -mkexif img.jpg</p>\n"
},
{
"answer_id": 46179681,
"author": "Andreas Bergström",
"author_id": 1202214,
"author_profile": "https://Stackoverflow.com/users/1202214",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this directly in PHP using the <a href=\"https://packagist.org/packages/lsolesen/pel\" rel=\"nofollow noreferrer\">PEL</a> library. You would do this by simply overwriting the existing EXIF-headers,</p>\n\n<pre><code>// Load image data\n$data = new PelDataWindow(file_get_contents('IMAGE PATH'));\n\n// Prepare image data\n$jpeg = $file = new PelJpeg();\n$jpeg->load($data);\n\n// Create new EXIF-headers, overwriting any existing ones (when writing to disk)\n$exif = new PelExif();\n$jpeg->setExif($exif);\n$tiff = new PelTiff();\n$exif->setTiff($tiff);\n\n// Create Ifd-data that will hold EXIF-tags\n$ifd0 = new PelIfd(PelIfd::IFD0);\n$tiff->setIfd($ifd0);\n\n// Create EXIF-data for copyright\n$make = new PelEntryAscii(PelTag::COPYRIGHT, '2008-2017 Conroy');\n$ifd0->addEntry($make);\n\n// Add more EXIF-data...\n\n// Save to disk\n$file->saveFile('IMAGE.jpg');\n</code></pre>\n\n<p>You can find a complete list of all supported EXIF-data (PelTag) <a href=\"https://lsolesen.github.io/pel/doc/PEL/PelTag.html#sec-description\" rel=\"nofollow noreferrer\">in the PEL docs</a>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287/"
] |
On our site, we get a large amount of photos uploaded from various sources.
In order to keep the file sizes down, we strip all [exif data](http://en.wikipedia.org/wiki/Exif) from the source using [mogrify](http://www.imagemagick.org/www/mogrify.html):
```
mogrify -strip image.jpg
```
What we'd like to be able to do is to insert some basic exif data (Copyright Initrode, etc) back onto this new "clean" image, but I can't seem to find anything in the docs that would achieve this.
Has anybody any experience of doing this?
If it can't be done through imagemagick, a PHP-based solution would be the next best thing!
Thanks.
|
You can save a large amount of space, especially if you have a large number of images..
Add the following to text.txt (format of the IPTC tags taken from [here](http://www.narf.ssji.net/~shtrom/wiki/tips/imagemanipulation)):
```
2#110#Credit="My Company"
2#05#Object Name="THE_OBJECT_NAME"
2#55#Date Created="2011-02-03 12:45"
2#80#By-line="BY-LINE?"
2#110#Credit="The CREDIT"
2#115#Source="SOURCE"
2#116#Copyright Notice="THE COPYRIGHT"
2#118#Contact="THE CONTACT"
2#120#Caption="AKA Title"
```
Strip all existing exif data from the image
```
mogrify -strip image.jpg
```
Add the credit to your image
```
mogrify -profile 8BIMTEXT:text.txt image.jpg
```
|
229,447 |
<p>How can I efficiently create a unique index on two fields in a table like this:
create table t (a integer, b integer);</p>
<p>where any unique combination of two different numbers cannot appear more than once on the same row in the table.</p>
<p>In order words if a row exists such that a=1 and b=2, another row cannot exist where a=2 and b=1 or a=1 and b=2. In other words two numbers cannot appear together more than once in any order.</p>
<p>I have no idea what such a constraint is called, hence the 'two-sided unique index' name in the title.</p>
<p><strong>Update</strong>: If I have a composite key on columns (a,b), and a row (1,2) exists in the database, it is possible to insert another row (2,1) without an error. What I'm looking for is a way to prevent the same pair of numbers from being used more than once <strong><em>in any order</em></strong>...</p>
|
[
{
"answer_id": 229461,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/208666/two-foreign-keys-instead-of-primary\">Two foreign keys instead of primary</a></p>\n"
},
{
"answer_id": 229521,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I think this can only be done using a FOR INSERT trigger (in combination with a unique constraint on the two columns). I'm not really fluent in MySql syntax (my T-SQL is better), so I guess the following will contain some errors:</p>\n\n<p><strong>Edit:</strong> Cleaned up the syntax so it works for MySQL. Also, note you'll probably want to put this as a <code>BEFORE UPDATE</code> trigger too (with a different name of course).</p>\n\n<p>Also, this method relies on having a primary or otherwise unique key on the two fields (ie. this trigger only checks the reverse doesn't already exist.) There doesn't seem to be any way of throwing an error from a trigger, so I dare say this is as good as it gets.</p>\n\n<pre><code>CREATE TRIGGER tr_CheckDuplicates_insert\nBEFORE INSERT ON t\nFOR EACH ROW\nBEGIN\n DECLARE rowCount INT;\n SELECT COUNT(*) INTO rowCount\n FROM t\n WHERE a = NEW.b AND b = NEW.a;\n\n IF rowCount > 0 THEN\n -- Oops, we need a temporary variable here. Oh well.\n -- Switch the values so that the key will cause the insert to fail.\n SET rowCount = NEW.a, NEW.a = NEW.b, NEW.b = rowCount;\n END IF;\nEND;\n</code></pre>\n"
},
{
"answer_id": 229527,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "<p>In Oracle you could use a function-based index like this:</p>\n\n<pre><code>create unique index mytab_idx on mytab (least(a,b), greatest(a,b));\n</code></pre>\n\n<p>I don't know mySQL, but maybe something similar is possible? For example, you could add 2 new columns leastab and greatestab to the table, with a trigger to maintain them with the values of least(a,b) and greatest(a,b) respectively, and then create a unique index on (leastab, greatestab).</p>\n"
},
{
"answer_id": 229803,
"author": "neonski",
"author_id": 17112,
"author_profile": "https://Stackoverflow.com/users/17112",
"pm_score": 4,
"selected": true,
"text": "<p>How about controlling what goes into the table so that you always store the smallest number into the first column and the largest one in the second? As long as it 'means' the same thing of course. It's probably less expensive to do it before it even gets to the database.</p>\n\n<p>If this is impossible, you could save the fields as is but have them duplicated in numerical order into two OTHER fields, on which you would create the primary key (pseudo code-ish) : </p>\n\n<pre><code>COLUMN A : 2\nCOLUMN B : 1\n\nCOLUMN A_PK : 1 ( if new.a < new.b then new.a else new.b )\nCOLUMN B_PK : 2 ( if new.b > new.a then new.b else new.a )\n</code></pre>\n\n<p>This could easily be done with a trigger (as in Ronald's response) or handled higher up, in the application.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6475/"
] |
How can I efficiently create a unique index on two fields in a table like this:
create table t (a integer, b integer);
where any unique combination of two different numbers cannot appear more than once on the same row in the table.
In order words if a row exists such that a=1 and b=2, another row cannot exist where a=2 and b=1 or a=1 and b=2. In other words two numbers cannot appear together more than once in any order.
I have no idea what such a constraint is called, hence the 'two-sided unique index' name in the title.
**Update**: If I have a composite key on columns (a,b), and a row (1,2) exists in the database, it is possible to insert another row (2,1) without an error. What I'm looking for is a way to prevent the same pair of numbers from being used more than once ***in any order***...
|
How about controlling what goes into the table so that you always store the smallest number into the first column and the largest one in the second? As long as it 'means' the same thing of course. It's probably less expensive to do it before it even gets to the database.
If this is impossible, you could save the fields as is but have them duplicated in numerical order into two OTHER fields, on which you would create the primary key (pseudo code-ish) :
```
COLUMN A : 2
COLUMN B : 1
COLUMN A_PK : 1 ( if new.a < new.b then new.a else new.b )
COLUMN B_PK : 2 ( if new.b > new.a then new.b else new.a )
```
This could easily be done with a trigger (as in Ronald's response) or handled higher up, in the application.
|
229,468 |
<p>I am new to programming, and am wondering if there is a correct way to order your control structure logic.</p>
<p>It seems more natural to check for the most likely case first, but I have the feeling that some control structures won't work unless they check everything that's false to arrive at something that's true (logical deduction?)</p>
<p>It would be hard to adapt to this 'negative' view, I prefer a more positive outlook, presuming everything is true :)</p>
|
[
{
"answer_id": 229475,
"author": "ZCHudson",
"author_id": 30610,
"author_profile": "https://Stackoverflow.com/users/30610",
"pm_score": 0,
"selected": false,
"text": "<p>Either / Or. I generally use the 'negative' approach though.</p>\n\n<p>if (!something)\n{</p>\n\n<p>}</p>\n"
},
{
"answer_id": 229488,
"author": "biozinc",
"author_id": 30698,
"author_profile": "https://Stackoverflow.com/users/30698",
"pm_score": 2,
"selected": false,
"text": "<p>Generally, I'd check the unexpected items first, which forces me to deal with exceptional flow of the programme.</p>\n\n<p>That way, I can throw exceptions/abort operations before I start \"setting up\" for the normal programme flow.</p>\n"
},
{
"answer_id": 229493,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 3,
"selected": false,
"text": "<p>There are things to consider in addition to the value of the condition statement. For example, if the blocks of code are significantly different in size, you may want to put the small block first so that it is easier to see. (If the larger block is really large, it may need to be refactored, or perhaps pulled out into a separate method.)</p>\n\n<pre><code>if( condition is true ) {\n do something small;\n} else { \n do something;\n and something else; \n . . .\n and the 20th something;\n}\n</code></pre>\n\n<p>Within the condition, yes, there are some languages that will stop evaluating an expression once one part of it is false. This is important to remember if you include some sort of is-defined logic in your code: if your language evaluates the entire expression, you should do this:</p>\n\n<pre><code>if( variable is defined ) {\n if( variable == value ) {\n ...\n }\n}\n</code></pre>\n\n<p>rather than this:</p>\n\n<pre><code>if( (variable is defined) && (variable == value) ) {\n ...\n}\n</code></pre>\n\n<p>I don't think there is a \"correct\" way to design your conditions. If you are working for a company that has coding standards, you should check to see if that is included in the standards. (The last place I worked had a reasonable number of standards defined, but did not specify how to write conditional logic.) </p>\n"
},
{
"answer_id": 229494,
"author": "Onorio Catenacci",
"author_id": 2820,
"author_profile": "https://Stackoverflow.com/users/2820",
"pm_score": 4,
"selected": false,
"text": "<p>There is an excellent discussion of just this topic in McConnell's <em><a href=\"http://cc2e.com/\" rel=\"nofollow noreferrer\">Code Complete</a></em>. It's a book that I highly recommend. Anyway the relevant discussion is on pages 706-708 of the first edition or pg. 749-750 of second edition (thanks plinth). From that book:</p>\n\n<blockquote>\n <p>Arrange tests so that the one that's\n fastest and most likely to be true is\n performed first. It should be easy to\n drop through the normal case, and if\n there are inefficiencies, they should\n be in processing the exceptions.</p>\n</blockquote>\n"
},
{
"answer_id": 229497,
"author": "Tom Carter",
"author_id": 2839,
"author_profile": "https://Stackoverflow.com/users/2839",
"pm_score": 2,
"selected": false,
"text": "<p>I aim to structure my conditions in a way to minimize the amount of information the reader has to take in. Sometimes it is easier to test for the negative to prove the positive :</p>\n\n<p>An example - the test to see if a period of 2 dates intersects with another period of 2 dates is easier to write as test of no intersection of 2 periods</p>\n"
},
{
"answer_id": 229516,
"author": "Sol",
"author_id": 27029,
"author_profile": "https://Stackoverflow.com/users/27029",
"pm_score": 1,
"selected": false,
"text": "<p>If it's a simple yes or error question, then I usually structure things so that the error-handling branch is the else clause. If it's a yes or no question (ie neither branch is an error), it's purely a judgment call on what feels more natural. If there are a lot of tests which must be made before the heart of the code can execute, I usually try to structure things so that the negative tests come first and somehow skip the code that follows (return from the function, break or continue from a loop).</p>\n"
},
{
"answer_id": 229541,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 2,
"selected": false,
"text": "<p>See also this question:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/166550/what-to-put-in-the-if-block-and-what-to-put-in-the-else-block\">What to put in the IF block and what to put in the ELSE block?</a></p>\n"
},
{
"answer_id": 229620,
"author": "mfx",
"author_id": 8015,
"author_profile": "https://Stackoverflow.com/users/8015",
"pm_score": 3,
"selected": true,
"text": "<p>In most situations, readability is more important than execution speed. I therefore try\nto optimize for ease of understanding, by using the following approach:</p>\n\n<p>All \"assertion\" checks are done up front. this guarantees that all erroneous cases are dealt with at the very start. this is especially important for null-pointer-checks, e.g.</p>\n\n<pre>\n if(arg == null){ \n throw new IllegalArgumentException(); // harsh (correct)\n }\n // or \n if(arg == null){\n arg = \"\"; // forgiving (lazy)\n }\n</pre>\n\n<p>Next, i try to check for 1 condition only in each if-statement. instead of</p>\n\n<pre>\n if(condition1 && condition2) {\n ...\n } else {\n ...\n }\n</pre> \n\n<p>i generally prefer</p>\n\n<pre>\n if(condition1) {\n if(condition2) {\n ...\n } else {\n ...\n }\n } else {\n ...\n }\n</pre>\n\n<p>This approach is easier for setting breakpoints, and it makes the logic more obvous.</p>\n\n<p>I avoid negations; instead of</p>\n\n<pre>\n if(! condition) {\n ...a...\n } else {\n ...b...\n }\n</pre>\n\n<p>things are better rearranged to </p>\n\n<pre>\n if(condition) {\n ...b...\n } else {\n ...a...\n }\n</pre>\n\n<p>Finally, all methods that return a boolean result should have a \"positive\" name that indicates what the results means:</p>\n\n<pre>\n boolean checkSomething(Something x){ ... } // bad -- whats the result?\n boolean isSomethingInvalid(Something x){ ... } // better, but ...\n boolean isSomethingValid(Something x){ ... } // best, no \"mental negation\"\n</pre>\n"
},
{
"answer_id": 229674,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>This is a little out of the scope of the question, but generally you also want your methods to fail fast. For this reason I tend to do all of my argument validation at the top of the method, even if I'm not going to use the argument until later in the code. This hurts readability, but only in the case where the method is really long (have to scroll off the screen to see it). Of course, that's a code smell in itself and tends to get refactored out.</p>\n\n<p>On the other hand, if the check isn't simple and I'll be passing it off to another method that is just going to check it anyway, I won't repeat the code to check in the current method. As with most things there is a balance.</p>\n"
},
{
"answer_id": 229714,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>(Context: Java)</p>\n\n<p>READABILITY1: Condition that resolves to a smaller block of code goes first</p>\n\n<pre><code>if (condition) {\n smallBlock();\n} else {\n bigBlockStart();\n ........\n bigBlockEnd();\n}\n</code></pre>\n\n<p>READABILITY2: Positive assertion goes first, as it's easier not to notice a negation sign</p>\n\n<p>MAKING SENSE: Assert all the pre-conditions for a method using Assert.blabla() and use conditionals only for what the method does.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
I am new to programming, and am wondering if there is a correct way to order your control structure logic.
It seems more natural to check for the most likely case first, but I have the feeling that some control structures won't work unless they check everything that's false to arrive at something that's true (logical deduction?)
It would be hard to adapt to this 'negative' view, I prefer a more positive outlook, presuming everything is true :)
|
In most situations, readability is more important than execution speed. I therefore try
to optimize for ease of understanding, by using the following approach:
All "assertion" checks are done up front. this guarantees that all erroneous cases are dealt with at the very start. this is especially important for null-pointer-checks, e.g.
```
if(arg == null){
throw new IllegalArgumentException(); // harsh (correct)
}
// or
if(arg == null){
arg = ""; // forgiving (lazy)
}
```
Next, i try to check for 1 condition only in each if-statement. instead of
```
if(condition1 && condition2) {
...
} else {
...
}
```
i generally prefer
```
if(condition1) {
if(condition2) {
...
} else {
...
}
} else {
...
}
```
This approach is easier for setting breakpoints, and it makes the logic more obvous.
I avoid negations; instead of
```
if(! condition) {
...a...
} else {
...b...
}
```
things are better rearranged to
```
if(condition) {
...b...
} else {
...a...
}
```
Finally, all methods that return a boolean result should have a "positive" name that indicates what the results means:
```
boolean checkSomething(Something x){ ... } // bad -- whats the result?
boolean isSomethingInvalid(Something x){ ... } // better, but ...
boolean isSomethingValid(Something x){ ... } // best, no "mental negation"
```
|
229,491 |
<pre><code>foreach($arrayOne as $value){
do function
}
</code></pre>
<p>In the above example, I'd like to pass $arrayOne into a loop, have a function operate that removes some elements of $arrayOne and then have the loop pass over the reduced $arrayOne on the elements that are left until the loop returns false.</p>
<p>Recommendations?</p>
|
[
{
"answer_id": 229499,
"author": "Aditya Mukherji",
"author_id": 25990,
"author_profile": "https://Stackoverflow.com/users/25990",
"pm_score": 1,
"selected": false,
"text": "<p>i would recommend having two arrays,\n<br>one with the data - dataarray, \n<br>the other initially empty - emptyarray <br>\nand whatever qualifies in the first foreachloop, u push into the 2nd array, and at the end of that, empty the first array, swap the identifiers of the two arrays (dataarray becomes emptyarray and viceversa) and repeat until you return false or whatever</p>\n"
},
{
"answer_id": 229513,
"author": "Dinoboff",
"author_id": 1771,
"author_profile": "https://Stackoverflow.com/users/1771",
"pm_score": 3,
"selected": false,
"text": "<p>Do you just need a function to remove some elements of an array?</p>\n\n<p>If so, you can use <a href=\"http://uk.php.net/array_filter\" rel=\"nofollow noreferrer\">array_filter</a>.</p>\n"
},
{
"answer_id": 229799,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>If you want to make modifications to the value of array items, use by reference. If you want to entirely remove array items, split out the key / value pairs.</p>\n\n<pre><code>$arrayOne = array('example', 'listing of', 'stuff');\n\nforeach ($arrayOne as $key => &$value) {\n $value .= ' alteration';\n\n if ($value == 'listing of alteration') {\n unset($arrayOne[ $key ]);\n }\n\n}\n</code></pre>\n\n<p>The above code will add the text \" alteration\" to the end of each item in the array.\nIt will also remove the second index when it matches \"listing of alteration\". Tested on PHP 5.2</p>\n"
},
{
"answer_id": 230132,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Rabbit has the right answer for using references to edit values and index to unset in a foreach loop (I would vote you up but this is my first post so I don't have 15 rep yet, sorry)</p>\n\n<p>be sure to remember to use the reference if you pass it through to a function that needs to edit the value as well.\nYou would also need to pass the array as a reference if it's to remove the value from it.</p>\n\n<p>I'd recommend making the function return boolean on whether to remove to prevent creating more references. e.g.</p>\n\n<pre><code>foreach ($array AS $key => &$value) {\n //& reference only needed if execFunction must edit $value\n if (execFunction(&$value)) { \n unset($array[$key]);\n } else {\n $value['exec_failed']+=1;\n }\n}\nunset($value);\n</code></pre>\n\n<p>also the $value reference will persist past the scope of the loop, thus the trailing unset.</p>\n\n<p>A last thought, it sounded as if you wanted to loop through the array multiple times. Be sure to pay attention to how your loop stops executing.</p>\n"
},
{
"answer_id": 230607,
"author": "kevtrout",
"author_id": 1149,
"author_profile": "https://Stackoverflow.com/users/1149",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks everyone for their help. The unset() function is, in the end, what is useful to me in today's specific need. Here's the short story of my use of unset():</p>\n\n<pre><code>//array to be processed\n$one=array('1','2','3');\n//array of terms previously defined as a group to compare against\n$against=array('1','2');\n\nforeach($one as $key=>$value){\n\n //pull out matching terms \n $match=array_intersect($one,$against);\n //my need is to sum grouped numbers\n $sum=array_sum($match);\n echo $sum.\"<br />\";\n\n //remove matching terms from original array\n foreach($match as $key=>$value){\n unset($one[$key]);\n }\n}\n//now a parent looping function will process the remaining array elements. In this case, the only one left is '3'.\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] |
```
foreach($arrayOne as $value){
do function
}
```
In the above example, I'd like to pass $arrayOne into a loop, have a function operate that removes some elements of $arrayOne and then have the loop pass over the reduced $arrayOne on the elements that are left until the loop returns false.
Recommendations?
|
If you want to make modifications to the value of array items, use by reference. If you want to entirely remove array items, split out the key / value pairs.
```
$arrayOne = array('example', 'listing of', 'stuff');
foreach ($arrayOne as $key => &$value) {
$value .= ' alteration';
if ($value == 'listing of alteration') {
unset($arrayOne[ $key ]);
}
}
```
The above code will add the text " alteration" to the end of each item in the array.
It will also remove the second index when it matches "listing of alteration". Tested on PHP 5.2
|
229,508 |
<p>Can anyone tell me why this code behaves the way it does? See comments embedded in the code...</p>
<p>Am I missing something really obvious here?</p>
<pre><code>using System;
namespace ConsoleApplication3
{
public class Program
{
static void Main(string[] args)
{
var c = new MyChild();
c.X();
Console.ReadLine();
}
}
public class MyParent
{
public virtual void X()
{
Console.WriteLine("Executing MyParent");
}
}
delegate void MyDelegate();
public class MyChild : MyParent
{
public override void X()
{
Console.WriteLine("Executing MyChild");
MyDelegate md = base.X;
// The following two calls look like they should behave the same,
// but they behave differently!
// Why does Invoke() call the base class as expected here...
md.Invoke();
// ... and yet BeginInvoke() performs a recursive call within
// this child class and not call the base class?
md.BeginInvoke(CallBack, null);
}
public void CallBack(IAsyncResult iAsyncResult)
{
return;
}
}
}
</code></pre>
|
[
{
"answer_id": 229537,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>I don't have an answer yet, but I have what I believe to be a slightly clearer program to demonstrate the oddity:</p>\n\n<pre><code>using System;\n\ndelegate void MyDelegate();\n\npublic class Program\n{\n static void Main(string[] args)\n {\n var c = new MyChild();\n c.DisplayOddity();\n Console.ReadLine();\n }\n}\n\npublic class MyParent\n{\n public virtual void X()\n {\n Console.WriteLine(\"Executing MyParent.X\");\n }\n}\n\npublic class MyChild : MyParent\n{\n public void DisplayOddity()\n {\n MyDelegate md = base.X;\n\n Console.WriteLine(\"Calling Invoke()\");\n md.Invoke(); // Executes base method... fair enough\n\n Console.WriteLine(\"Calling BeginInvoke()\");\n md.BeginInvoke(null, null); // Executes overridden method!\n }\n\n public override void X()\n {\n Console.WriteLine(\"Executing MyChild.X\");\n }\n}\n</code></pre>\n\n<p>This doesn't involve any recursive calls. The result is still the same oddity though:</p>\n\n<pre><code>Calling Invoke()\nExecuting MyParent.X\nCalling BeginInvoke()\nExecuting MyChild.X\n</code></pre>\n\n<p>(If you agree that this is a simpler repro, feel free to replace the code in the original question and I'll remove it from my answer :)</p>\n\n<p>To be honest, this looks like a bug to me. I'll dig around a bit more.</p>\n"
},
{
"answer_id": 230049,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe not the answer you are looking for, but this seems to work:</p>\n\n<pre><code>ThreadPool.QueueUserWorkItem(x => md());\n</code></pre>\n\n<p>or</p>\n\n<pre><code>new Thread(() => md()).Start();\n</code></pre>\n\n<p>But you will need to do your own accounting :(</p>\n"
},
{
"answer_id": 255360,
"author": "foson",
"author_id": 22539,
"author_profile": "https://Stackoverflow.com/users/22539",
"pm_score": 1,
"selected": false,
"text": "<p>While Delegate.Invoke calls the delegate method directly, Delegate.BeginInvoke internally uses ThreadPool.QueueUserWorkItem( ). md.Invoke() was only able to call base.X because a base class's methods are accessible within the derived class through the base keyword. Since the delegate started by the thread pool is external to your class, the reference to its X method is subjected to overloading, just like the code below. </p>\n\n<pre><code>\n\n public class Program\n {\n static void Main(string[] args)\n {\n MyChild a = new MyChild();\n MyDelegate ma = new MyDelegate(a.X);\n\n MyParent b = new MyChild();\n MyDelegate mb = new MyDelegate(b.X);\n\n ma.Invoke();\n mb.Invoke();\n ma.BeginInvoke(CallBack, null);\n mb.BeginInvoke(CallBack, null); //all four calls call derived MyChild.X\n\n Console.ReadLine();\n }\n\n public static void CallBack(IAsyncResult iAsyncResult)\n {\n return;\n }\n }\n\n</code></pre>\n\n<p>Debug into .NET Framework code: <a href=\"http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24207/"
] |
Can anyone tell me why this code behaves the way it does? See comments embedded in the code...
Am I missing something really obvious here?
```
using System;
namespace ConsoleApplication3
{
public class Program
{
static void Main(string[] args)
{
var c = new MyChild();
c.X();
Console.ReadLine();
}
}
public class MyParent
{
public virtual void X()
{
Console.WriteLine("Executing MyParent");
}
}
delegate void MyDelegate();
public class MyChild : MyParent
{
public override void X()
{
Console.WriteLine("Executing MyChild");
MyDelegate md = base.X;
// The following two calls look like they should behave the same,
// but they behave differently!
// Why does Invoke() call the base class as expected here...
md.Invoke();
// ... and yet BeginInvoke() performs a recursive call within
// this child class and not call the base class?
md.BeginInvoke(CallBack, null);
}
public void CallBack(IAsyncResult iAsyncResult)
{
return;
}
}
}
```
|
I don't have an answer yet, but I have what I believe to be a slightly clearer program to demonstrate the oddity:
```
using System;
delegate void MyDelegate();
public class Program
{
static void Main(string[] args)
{
var c = new MyChild();
c.DisplayOddity();
Console.ReadLine();
}
}
public class MyParent
{
public virtual void X()
{
Console.WriteLine("Executing MyParent.X");
}
}
public class MyChild : MyParent
{
public void DisplayOddity()
{
MyDelegate md = base.X;
Console.WriteLine("Calling Invoke()");
md.Invoke(); // Executes base method... fair enough
Console.WriteLine("Calling BeginInvoke()");
md.BeginInvoke(null, null); // Executes overridden method!
}
public override void X()
{
Console.WriteLine("Executing MyChild.X");
}
}
```
This doesn't involve any recursive calls. The result is still the same oddity though:
```
Calling Invoke()
Executing MyParent.X
Calling BeginInvoke()
Executing MyChild.X
```
(If you agree that this is a simpler repro, feel free to replace the code in the original question and I'll remove it from my answer :)
To be honest, this looks like a bug to me. I'll dig around a bit more.
|
229,551 |
<p>I have a string in Bash:</p>
<pre class="lang-sh prettyprint-override"><code>string="My string"
</code></pre>
<p>How can I test if it contains another string?</p>
<pre class="lang-sh prettyprint-override"><code>if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
</code></pre>
<p>Where <code>??</code> is my unknown operator. Do I use <code>echo</code> and <code>grep</code>?</p>
<pre class="lang-sh prettyprint-override"><code>if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
</code></pre>
<p>That looks a bit clumsy.</p>
|
[
{
"answer_id": 229585,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 9,
"selected": false,
"text": "<p>I am not sure about using an if statement, but you can get a similar effect with a case statement:</p>\n\n<pre><code>case \"$string\" in \n *foo*)\n # Do stuff\n ;;\nesac\n</code></pre>\n"
},
{
"answer_id": 229606,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 13,
"selected": true,
"text": "<p>You can use <a href=\"https://stackoverflow.com/a/229585/3755692\">Marcus's answer (* wildcards)</a> outside a case statement, too, if you use double brackets:</p>\n\n<pre><code>string='My long string'\nif [[ $string == *\"My long\"* ]]; then\n echo \"It's there!\"\nfi\n</code></pre>\n\n<p>Note that spaces in the needle string need to be placed between double quotes, and the <code>*</code> wildcards should be outside. Also note that a simple comparison operator is used (i.e. <code>==</code>), not the regex operator <code>=~</code>.</p>\n"
},
{
"answer_id": 229993,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 7,
"selected": false,
"text": "<p>The accepted answer is best, but since there's more than one way to do it, here's another solution:</p>\n\n<pre><code>if [ \"$string\" != \"${string/foo/}\" ]; then\n echo \"It's there!\"\nfi\n</code></pre>\n\n<p><code>${var/search/replace}</code> is <code>$var</code> with the first instance of <code>search</code> replaced by <code>replace</code>, if it is found (it doesn't change <code>$var</code>). If you try to replace <code>foo</code> by nothing, and the string has changed, then obviously <code>foo</code> was found.</p>\n"
},
{
"answer_id": 231298,
"author": "Matt Tardiff",
"author_id": 27925,
"author_profile": "https://Stackoverflow.com/users/27925",
"pm_score": 10,
"selected": false,
"text": "<p>If you prefer the regex approach:</p>\n<pre><code>string='My string';\n\nif [[ $string =~ "My" ]]; then\n echo "It's there!"\nfi\n</code></pre>\n"
},
{
"answer_id": 240181,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 7,
"selected": false,
"text": "<p>You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this \"language\" requires you to follow an <code>if</code> with a <code>[</code> or a <code>[[</code>. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use <code>grep</code>, and not the <code>[</code> command.</p>\n\n<p>Just do:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>if grep -q foo <<<\"$string\"; then\n echo \"It's there\"\nfi\n</code></pre>\n\n<p>Now that you are thinking of <code>if</code> as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>## Instead of this\nfiletype=\"$(file -b \"$1\")\"\nif grep -q \"tar archive\" <<<\"$filetype\"; then\n#...\n\n## Simply do this\nif file -b \"$1\" | grep -q \"tar archive\"; then\n#...\n</code></pre>\n\n<p>The <code>-q</code> option makes grep not output anything, as we only want the return code. <code><<<</code> makes the shell expand the next word and use it as the input to the command, a one-line version of the <code><<</code> here document (I'm not sure whether this is standard or a Bashism).</p>\n"
},
{
"answer_id": 384516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p><code>grep -q</code> is useful for this purpose.</p>\n\n<p>The same using <code>awk</code>:</p>\n\n<pre><code>string=\"unix-bash 2389\"\ncharacter=\"@\"\nprintf '%s' \"$string\" | awk -vc=\"$character\" '{ if (gsub(c, \"\")) { print \"Found\" } else { print \"Not Found\" } }'\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>Not Found</p>\n</blockquote>\n\n\n\n<pre><code>string=\"unix-bash 2389\"\ncharacter=\"-\"\nprintf '%s' \"$string\" | awk -vc=\"$character\" '{ if (gsub(c, \"\")) { print \"Found\" } else { print \"Not Found\" } }'\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>Found</p>\n</blockquote>\n\n<p>Original source: <a href=\"http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html\" rel=\"nofollow noreferrer\">http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html</a></p>\n"
},
{
"answer_id": 527231,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>text=\" <tag>bmnmn</tag> \"\nif [[ \"$text\" =~ \"<tag>\" ]]; then\n echo \"matched\"\nelse\n echo \"not matched\"\nfi\n</code></pre>\n"
},
{
"answer_id": 3587443,
"author": "andreas",
"author_id": 432376,
"author_profile": "https://Stackoverflow.com/users/432376",
"pm_score": 2,
"selected": false,
"text": "<p>Try oobash.</p>\n\n<p>It is an OO-style string library for Bash 4. It has support for German umlauts. It is written in Bash.</p>\n\n<p>Many functions are available: <code>-base64Decode</code>, <code>-base64Encode</code>, <code>-capitalize</code>, <code>-center</code>, <code>-charAt</code>, <code>-concat</code>, <code>-contains</code>, <code>-count</code>, <code>-endsWith</code>, <code>-equals</code>, <code>-equalsIgnoreCase</code>, <code>-reverse</code>, <code>-hashCode</code>, <code>-indexOf</code>, <code>-isAlnum</code>, <code>-isAlpha</code>, <code>-isAscii</code>, <code>-isDigit</code>, <code>-isEmpty</code>, <code>-isHexDigit</code>, <code>-isLowerCase</code>, <code>-isSpace</code>, <code>-isPrintable</code>, <code>-isUpperCase</code>, <code>-isVisible</code>, <code>-lastIndexOf</code>, <code>-length</code>, <code>-matches</code>, <code>-replaceAll</code>, <code>-replaceFirst</code>, <code>-startsWith</code>, <code>-substring</code>, <code>-swapCase</code>, <code>-toLowerCase</code>, <code>-toString</code>, <code>-toUpperCase</code>, <code>-trim</code>, and <code>-zfill</code>.</p>\n\n<p>Look at the <em>contains</em> example:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>[Desktop]$ String a testXccc\n[Desktop]$ a.contains tX\ntrue\n[Desktop]$ a.contains XtX\nfalse\n</code></pre>\n\n<p><a href=\"http://sourceforge.net/projects/oobash/\" rel=\"nofollow noreferrer\">oobash is available at Sourceforge.net</a>.</p>\n"
},
{
"answer_id": 8090175,
"author": "chemila",
"author_id": 889064,
"author_profile": "https://Stackoverflow.com/users/889064",
"pm_score": 3,
"selected": false,
"text": "<p>One is:</p>\n\n<pre><code>[ $(expr $mystring : \".*${search}.*\") -ne 0 ] && echo 'yes' || echo 'no'\n</code></pre>\n"
},
{
"answer_id": 11281580,
"author": "Kurt Pfeifle",
"author_id": 359307,
"author_profile": "https://Stackoverflow.com/users/359307",
"pm_score": 3,
"selected": false,
"text": "<p>I found to need this functionality quite frequently, so I'm using a home-made shell function in my <code>.bashrc</code> like this which allows me to reuse it as often as I need to, with an easy to remember name:</p>\n\n<pre><code>function stringinstring()\n{\n case \"$2\" in\n *\"$1\"*)\n return 0\n ;;\n esac\n return 1\n}\n</code></pre>\n\n<p>To test if <code>$string1</code> (say, <em>abc</em>) is contained in <code>$string2</code> (say, <em>123abcABC</em>) I just need to run <code>stringinstring \"$string1\" \"$string2\"</code> and check for the return value, for example</p>\n\n<pre><code>stringinstring \"$str1\" \"$str2\" && echo YES || echo NO\n</code></pre>\n"
},
{
"answer_id": 13660953,
"author": "kevinarpe",
"author_id": 257299,
"author_profile": "https://Stackoverflow.com/users/257299",
"pm_score": 5,
"selected": false,
"text": "<p>This also works:</p>\n\n<pre><code>if printf -- '%s' \"$haystack\" | egrep -q -- \"$needle\"\nthen\n printf \"Found needle in haystack\"\nfi\n</code></pre>\n\n<p>And the negative test is:</p>\n\n<pre><code>if ! printf -- '%s' \"$haystack\" | egrep -q -- \"$needle\"\nthen\n echo \"Did not find needle in haystack\"\nfi\n</code></pre>\n\n<p>I suppose this style is a bit more classic -- less dependent upon features of Bash shell.</p>\n\n<p>The <code>--</code> argument is pure POSIX paranoia, used to protected against input strings similar to options, such as <code>--abc</code> or <code>-a</code>.</p>\n\n<p>Note: In a tight loop this code will be <em>much</em> slower than using internal Bash shell features, as one (or two) separate processes will be created and connected via pipes.</p>\n"
},
{
"answer_id": 18441709,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/229606/65706\">This Stack Overflow answer</a> was the only one to trap space and dash characters:</p>\n\n<pre><code># For null cmd arguments checking \nto_check=' -t'\nspace_n_dash_chars=' -'\n[[ $to_check == *\"$space_n_dash_chars\"* ]] && echo found\n</code></pre>\n"
},
{
"answer_id": 20460402,
"author": "F. Hauri - Give Up GitHub",
"author_id": 1765658,
"author_profile": "https://Stackoverflow.com/users/1765658",
"pm_score": 8,
"selected": false,
"text": "<h1><code>stringContain</code> variants (compatible or case independent)</h1>\n\n<p>As these Stack Overflow answers tell mostly about <a href=\"https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29\" rel=\"noreferrer\">Bash</a>, I've posted a <strong><em>case independent</em></strong> Bash function at the very bottom of this post...</p>\n\n<p>Anyway, there is my</p>\n\n<h2>Compatible answer</h2>\n\n<p>As there are already a lot of answers using Bash-specific features, there is a way working under poorer-featured shells, like <a href=\"https://en.wikipedia.org/wiki/BusyBox\" rel=\"noreferrer\">BusyBox</a>:</p>\n\n<pre><code>[ -z \"${string##*$reqsubstr*}\" ]\n</code></pre>\n\n<p>In practice, this could give:</p>\n\n<pre><code>string='echo \"My string\"'\nfor reqsubstr in 'o \"M' 'alt' 'str';do\n if [ -z \"${string##*$reqsubstr*}\" ] ;then\n echo \"String '$string' contain substring: '$reqsubstr'.\"\n else\n echo \"String '$string' don't contain substring: '$reqsubstr'.\"\n fi\n done\n</code></pre>\n\n<p>This was tested under Bash, <a href=\"https://en.wikipedia.org/wiki/Almquist_shell#dash:_Ubuntu,_Debian_and_POSIX_compliance_of_Linux_distributions\" rel=\"noreferrer\">Dash</a>, <a href=\"https://en.wikipedia.org/wiki/KornShell\" rel=\"noreferrer\">KornShell</a> (<code>ksh</code>) and <a href=\"https://en.wikipedia.org/wiki/Almquist_shell\" rel=\"noreferrer\">ash</a> (BusyBox), and the result is always:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>String 'echo \"My string\"' contain substring: 'o \"M'.\nString 'echo \"My string\"' don't contain substring: 'alt'.\nString 'echo \"My string\"' contain substring: 'str'.\n</code></pre>\n\n<h3>Into one function</h3>\n\n<p>As asked by @EeroAaltonen here is a version of the same demo, tested under the same shells:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>myfunc() {\n reqsubstr=\"$1\"\n shift\n string=\"$@\"\n if [ -z \"${string##*$reqsubstr*}\" ] ;then\n echo \"String '$string' contain substring: '$reqsubstr'.\";\n else\n echo \"String '$string' don't contain substring: '$reqsubstr'.\"\n fi\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ myfunc 'o \"M' 'echo \"My String\"'\nString 'echo \"My String\"' contain substring 'o \"M'.\n\n$ myfunc 'alt' 'echo \"My String\"'\nString 'echo \"My String\"' don't contain substring 'alt'.\n</code></pre>\n\n<p><strong>Notice:</strong> you have to escape or double enclose quotes and/or double quotes:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ myfunc 'o \"M' echo \"My String\"\nString 'echo My String' don't contain substring: 'o \"M'.\n\n$ myfunc 'o \"M' echo \\\"My String\\\"\nString 'echo \"My String\"' contain substring: 'o \"M'.\n</code></pre>\n\n<h2>Simple function</h2>\n\n<p>This was tested under BusyBox, Dash, and, of course Bash:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>stringContain() { [ -z \"${2##*$1*}\" ]; }\n</code></pre>\n\n<p>Then now:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ if stringContain 'o \"M3' 'echo \"My String\"';then echo yes;else echo no;fi\nno\n$ if stringContain 'o \"M' 'echo \"My String\"';then echo yes;else echo no;fi\nyes\n</code></pre>\n\n<p>... Or if the submitted string could be empty, as pointed out by @Sjlver, the function would become:</p>\n\n<pre><code>stringContain() { [ -z \"${2##*$1*}\" ] && [ -z \"$1\" -o -n \"$2\" ]; }\n</code></pre>\n\n<p>or as suggested by <a href=\"https://stackoverflow.com/posts/comments/86532588\">Adrian Günter's comment</a>, avoiding <code>-o</code> switches:</p>\n\n<p><s></p>\n\n<pre><code>stringContain() { [ -z \"${2##*$1*}\" ] && { [ -z \"$1\" ] || [ -n \"$2\" ];};}\n</code></pre>\n\n<p></s></p>\n\n<h3>Final (simple) function:</h3>\n\n<p>And inverting the tests to make them potentially quicker:</p>\n\n<pre><code>stringContain() { [ -z \"$1\" ] || { [ -z \"${2##*$1*}\" ] && [ -n \"$2\" ];};}\n</code></pre>\n\n<p>With empty strings:</p>\n\n<pre><code>$ if stringContain '' ''; then echo yes; else echo no; fi\nyes\n$ if stringContain 'o \"M' ''; then echo yes; else echo no; fi\nno\n</code></pre>\n\n<h2>Case independent (Bash only!)</h2>\n\n<p>For testing strings without care of case, simply convert each string to lower case:</p>\n\n<pre><code>stringContain() {\n local _lc=${2,,}\n [ -z \"$1\" ] || { [ -z \"${_lc##*${1,,}*}\" ] && [ -n \"$2\" ] ;} ;}\n</code></pre>\n\n<p>Check:</p>\n\n<pre><code>stringContain 'o \"M3' 'echo \"my string\"' && echo yes || echo no\nno\nstringContain 'o \"My' 'echo \"my string\"' && echo yes || echo no\nyes\nif stringContain '' ''; then echo yes; else echo no; fi\nyes\nif stringContain 'o \"M' ''; then echo yes; else echo no; fi\nno\n</code></pre>\n"
},
{
"answer_id": 25535717,
"author": "Paul Hedderly",
"author_id": 75528,
"author_profile": "https://Stackoverflow.com/users/75528",
"pm_score": 6,
"selected": false,
"text": "<p>So there are lots of useful solutions to the question - but which is fastest / uses the fewest resources?</p>\n\n<p>Repeated tests using this frame:</p>\n\n<pre><code>/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do TEST ; x=$(($x-1)); done'\n</code></pre>\n\n<p>Replacing TEST each time:</p>\n\n<pre><code>[[ $b =~ $a ]] 2.92 user 0.06 system 0:02.99 elapsed 99% CPU\n\n[ \"${b/$a//}\" = \"$b\" ] 3.16 user 0.07 system 0:03.25 elapsed 99% CPU\n\n[[ $b == *$a* ]] 1.85 user 0.04 system 0:01.90 elapsed 99% CPU\n\ncase $b in *$a):;;esac 1.80 user 0.02 system 0:01.83 elapsed 99% CPU\n\ndoContain $a $b 4.27 user 0.11 system 0:04.41 elapsed 99%CPU\n</code></pre>\n\n<p>(doContain was in F. Houri's answer)</p>\n\n<p>And for giggles:</p>\n\n<pre><code>echo $b|grep -q $a 12.68 user 30.86 system 3:42.40 elapsed 19% CPU !ouch!\n</code></pre>\n\n<p>So the simple substitution option predictably wins whether in an extended test or a case. The case is portable.</p>\n\n<p>Piping out to 100000 greps is predictably painful! The old rule about using external utilities without need holds true.</p>\n"
},
{
"answer_id": 27726913,
"author": "Samuel",
"author_id": 1045004,
"author_profile": "https://Stackoverflow.com/users/1045004",
"pm_score": 5,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/229551/how-to-check-if-a-string-contains-a-substring-in-bash/25535717#25535717\">Paul mentioned</a> in his performance comparison:</p>\n\n<pre><code>if echo \"abcdefg\" | grep -q \"bcdef\"; then\n echo \"String contains is true.\"\nelse\n echo \"String contains is not true.\"\nfi\n</code></pre>\n\n<p>This is POSIX compliant like the 'case \"$string\" in' <a href=\"https://stackoverflow.com/questions/229551/how-to-check-if-a-string-contains-a-substring-in-bash/229585#229585\">the answer provided by Marcus</a>, but it is slightly easier to read than the case statement answer. Also note that this will be much much slower than using a case statement. As Paul pointed out, don't use it in a loop.</p>\n"
},
{
"answer_id": 29928695,
"author": "Jahid",
"author_id": 3744681,
"author_profile": "https://Stackoverflow.com/users/3744681",
"pm_score": 4,
"selected": false,
"text": "<pre><code>[[ $string == *foo* ]] && echo \"It's there\" || echo \"Couldn't find\"\n</code></pre>\n"
},
{
"answer_id": 35780975,
"author": "ride",
"author_id": 3457750,
"author_profile": "https://Stackoverflow.com/users/3457750",
"pm_score": 3,
"selected": false,
"text": "<p>I like sed.</p>\n\n<pre><code>substr=\"foo\"\nnonsub=\"$(echo \"$string\" | sed \"s/$substr//\")\"\nhassub=0 ; [ \"$string\" != \"$nonsub\" ] && hassub=1\n</code></pre>\n\n<p>Edit, Logic:</p>\n\n<ul>\n<li><p>Use sed to remove instance of substring from string</p></li>\n<li><p>If new string differs from old string, substring exists</p></li>\n</ul>\n"
},
{
"answer_id": 40530610,
"author": "Eduardo Cuomo",
"author_id": 717267,
"author_profile": "https://Stackoverflow.com/users/717267",
"pm_score": 2,
"selected": false,
"text": "<p>Exact word match:</p>\n\n<pre><code>string='My long string'\nexactSearch='long'\n\nif grep -E -q \"\\b${exactSearch}\\b\" <<<${string} >/dev/null 2>&1\n then\n echo \"It's there\"\n fi\n</code></pre>\n"
},
{
"answer_id": 41647131,
"author": "Leslie Satenstein",
"author_id": 1445782,
"author_profile": "https://Stackoverflow.com/users/1445782",
"pm_score": 3,
"selected": false,
"text": "<p>My <em>.bash_profile</em> file and how I used grep:</p>\n\n<p>If the PATH environment variable includes my two <code>bin</code> directories, don't append them,</p>\n\n<pre><code># .bash_profile\n# Get the aliases and functions\nif [ -f ~/.bashrc ]; then\n . ~/.bashrc\nfi\n\nU=~/.local.bin:~/bin\n\nif ! echo \"$PATH\" | grep -q \"home\"; then\n export PATH=$PATH:${U}\nfi\n</code></pre>\n"
},
{
"answer_id": 49765399,
"author": "Ethan Post",
"author_id": 4527,
"author_profile": "https://Stackoverflow.com/users/4527",
"pm_score": 2,
"selected": false,
"text": "<p>I use this function (one dependency not included but obvious). It passes the tests shown below. If the function returns a value > 0 then the string was found. You could just as easily return 1 or 0 instead.</p>\n\n<pre><code>function str_instr {\n # Return position of ```str``` within ```string```.\n # >>> str_instr \"str\" \"string\"\n # str: String to search for.\n # string: String to search.\n typeset str string x\n # Behavior here is not the same in bash vs ksh unless we escape special characters.\n str=\"$(str_escape_special_characters \"${1}\")\"\n string=\"${2}\"\n x=\"${string%%$str*}\"\n if [[ \"${x}\" != \"${string}\" ]]; then\n echo \"${#x} + 1\" | bc -l\n else\n echo 0\n fi\n}\n\nfunction test_str_instr {\n str_instr \"(\" \"'foo@host (dev,web)'\" | assert_eq 11\n str_instr \")\" \"'foo@host (dev,web)'\" | assert_eq 19\n str_instr \"[\" \"'foo@host [dev,web]'\" | assert_eq 11\n str_instr \"]\" \"'foo@host [dev,web]'\" | assert_eq 19\n str_instr \"a\" \"abc\" | assert_eq 1\n str_instr \"z\" \"abc\" | assert_eq 0\n str_instr \"Eggs\" \"Green Eggs And Ham\" | assert_eq 7\n str_instr \"a\" \"\" | assert_eq 0\n str_instr \"\" \"\" | assert_eq 0\n str_instr \" \" \"Green Eggs\" | assert_eq 6\n str_instr \" \" \" Green \" | assert_eq 1\n}\n</code></pre>\n"
},
{
"answer_id": 52671757,
"author": "Mike Q",
"author_id": 1618630,
"author_profile": "https://Stackoverflow.com/users/1618630",
"pm_score": 6,
"selected": false,
"text": "<p>Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash, IMO.</p>\n<p>Here are some examples Bash 4+:</p>\n<p>Example 1, check for 'yes' in string (case insensitive):</p>\n<pre><code> if [[ "${str,,}" == *"yes"* ]] ;then\n</code></pre>\n<p>Example 2, check for 'yes' in string (case insensitive):</p>\n<pre><code> if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then\n</code></pre>\n<p>Example 3, check for 'yes' in string (case sensitive):</p>\n<pre><code> if [[ "${str}" == *"yes"* ]] ;then\n</code></pre>\n<p>Example 4, check for 'yes' in string (case sensitive):</p>\n<pre><code> if [[ "${str}" =~ "yes" ]] ;then\n</code></pre>\n<p>Example 5, exact match (case sensitive):</p>\n<pre><code> if [[ "${str}" == "yes" ]] ;then\n</code></pre>\n<p>Example 6, exact match (case insensitive):</p>\n<pre><code> if [[ "${str,,}" == "yes" ]] ;then\n</code></pre>\n<p>Example 7, exact match:</p>\n<pre><code> if [ "$a" = "$b" ] ;then\n</code></pre>\n<p>Example 8, wildcard match .ext (case insensitive):</p>\n<pre><code> if echo "$a" | egrep -iq "\\.(mp[3-4]|txt|css|jpg|png)" ; then\n</code></pre>\n<p>Example 9, use grep on a string case sensitive:</p>\n<pre><code> if echo "SomeString" | grep -q "String"; then\n</code></pre>\n<p>Example 10, use grep on a string case insensitive:</p>\n<pre><code> if echo "SomeString" | grep -iq "string"; then\n</code></pre>\n<p>Example 11, use grep on a string case insensitive w/ wildcard:</p>\n<pre><code> if echo "SomeString" | grep -iq "Some.*ing"; then\n</code></pre>\n<p>Example 12, use doublehash to compare (if variable empty could cause false postitives etc) (case sensitive):</p>\n<pre><code> if [[ ! ${str##*$substr*} ]] ;then #found\n</code></pre>\n<p>Enjoy.</p>\n"
},
{
"answer_id": 54490453,
"author": "Alex Skrypnyk",
"author_id": 712666,
"author_profile": "https://Stackoverflow.com/users/712666",
"pm_score": 3,
"selected": false,
"text": "<p>Extension of the question answered here <em><a href=\"https://stackoverflow.com/questions/2829613/how-do-you-tell-if-a-string-contains-another-string-in-posix-sh/8811800#8811800\">How do you tell if a string contains another string in POSIX sh?</a></em>:</p>\n\n<p>This solution works with special characters:</p>\n\n<pre><code># contains(string, substring)\n#\n# Returns 0 if the specified string contains the specified substring,\n# otherwise returns 1.\ncontains() {\n string=\"$1\"\n substring=\"$2\"\n\n if echo \"$string\" | $(type -p ggrep grep | head -1) -F -- \"$substring\" >/dev/null; then\n return 0 # $substring is in $string\n else\n return 1 # $substring is not in $string\n fi\n}\n\ncontains \"abcd\" \"e\" || echo \"abcd does not contain e\"\ncontains \"abcd\" \"ab\" && echo \"abcd contains ab\"\ncontains \"abcd\" \"bc\" && echo \"abcd contains bc\"\ncontains \"abcd\" \"cd\" && echo \"abcd contains cd\"\ncontains \"abcd\" \"abcd\" && echo \"abcd contains abcd\"\ncontains \"\" \"\" && echo \"empty string contains empty string\"\ncontains \"a\" \"\" && echo \"a contains empty string\"\ncontains \"\" \"a\" || echo \"empty string does not contain a\"\ncontains \"abcd efgh\" \"cd ef\" && echo \"abcd efgh contains cd ef\"\ncontains \"abcd efgh\" \" \" && echo \"abcd efgh contains a space\"\n\ncontains \"abcd [efg] hij\" \"[efg]\" && echo \"abcd [efg] hij contains [efg]\"\ncontains \"abcd [efg] hij\" \"[effg]\" || echo \"abcd [efg] hij does not contain [effg]\"\n\ncontains \"abcd *efg* hij\" \"*efg*\" && echo \"abcd *efg* hij contains *efg*\"\ncontains \"abcd *efg* hij\" \"d *efg* h\" && echo \"abcd *efg* hij contains d *efg* h\"\ncontains \"abcd *efg* hij\" \"*effg*\" || echo \"abcd *efg* hij does not contain *effg*\"\n</code></pre>\n"
},
{
"answer_id": 59179141,
"author": "FifthAxiom",
"author_id": 8353248,
"author_profile": "https://Stackoverflow.com/users/8353248",
"pm_score": 3,
"selected": false,
"text": "<p>Since the <a href=\"http://stackoverflow.com/questions/2829613/how-do-you-tell-if-a-string-contains-another-string-in-unix-shell-scripting\">POSIX</a>/BusyBox question is closed without providing the right answer (IMHO), I'll post an answer here.</p>\n\n<p><strong>The shortest possible answer is:</strong></p>\n\n<pre><code>[ ${_string_##*$_substring_*} ] || echo Substring found!\n</code></pre>\n\n<p><em>or</em></p>\n\n<pre><code>[ \"${_string_##*$_substring_*}\" ] || echo 'Substring found!'\n</code></pre>\n\n<p>Note that the <strong><em>double hash</em></strong> is <strong>obligatory</strong> with some shells (<code>ash</code>). Above will evaluate <code>[ stringvalue ]</code> when the substring is not found. It returns no error. When the substring is found the result is empty and it evaluates <code>[ ]</code>. This will throw error code 1 since the string is completely substituted (due to <code>*</code>).</p>\n\n<p><strong>The shortest more common syntax:</strong></p>\n\n<pre><code>[ -z \"${_string_##*$_substring_*}\" ] && echo 'Substring found!'\n</code></pre>\n\n<p><em>or</em></p>\n\n<pre><code>[ -n \"${_string_##*$_substring_*}\" ] || echo 'Substring found!'\n</code></pre>\n\n<p><strong>Another one:</strong></p>\n\n<pre><code>[ \"${_string_##$_substring_}\" != \"$_string_\" ] && echo 'Substring found!'\n</code></pre>\n\n<p><em>or</em></p>\n\n<pre><code>[ \"${_string_##$_substring_}\" = \"$_string_\" ] || echo 'Substring found!'\n</code></pre>\n\n<p>Note the <em>single</em> equal sign!</p>\n"
},
{
"answer_id": 60198800,
"author": "BobMonk",
"author_id": 7351088,
"author_profile": "https://Stackoverflow.com/users/7351088",
"pm_score": 0,
"selected": false,
"text": "<pre><code>msg=\"message\"\n\nfunction check {\n echo $msg | egrep [abc] 1> /dev/null\n\n if [ $? -ne 1 ];\n then \n echo \"found\" \n else \n echo \"not found\" \n fi\n}\n\ncheck\n</code></pre>\n\n<p>This will find any occurance of a or b or c</p>\n"
},
{
"answer_id": 60720551,
"author": "Pipo",
"author_id": 2118777,
"author_profile": "https://Stackoverflow.com/users/2118777",
"pm_score": 3,
"selected": false,
"text": "<p>The generic <strong>needle haystack</strong> example is following with <strong>variables</strong></p>\n\n<pre><code>#!/bin/bash\n\nneedle=\"a_needle\"\nhaystack=\"a_needle another_needle a_third_needle\"\nif [[ $haystack == *\"$needle\"* ]]; then\n echo \"needle found\"\nelse\n echo \"needle NOT found\"\nfi\n</code></pre>\n"
},
{
"answer_id": 60884380,
"author": "Koichi Nakashima",
"author_id": 11267590,
"author_profile": "https://Stackoverflow.com/users/11267590",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-sh prettyprint-override\"><code>case $string in (*foo*)\n # Do stuff\nesac\n</code></pre>\n\n<p>This is the same answer as <a href=\"https://stackoverflow.com/a/229585/11267590\">https://stackoverflow.com/a/229585/11267590</a>. But simple style and also POSIX Compliant.</p>\n"
},
{
"answer_id": 70175482,
"author": "Piotr Henryk Dabrowski",
"author_id": 10245694,
"author_profile": "https://Stackoverflow.com/users/10245694",
"pm_score": 4,
"selected": false,
"text": "<p>Accepted answer is correct but it is hard to read and understand.<br>\nFor problems related to searching you should always use the <em>$needle in a $haystack</em> idiom.<br>\nSince its <em>suggested edit queue is full</em>, I post this:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>haystack='There are needles here.'\nif [[ "$haystack" == *"needle"* ]]; then\n echo "It's there!"\nfi\n</code></pre>\n"
},
{
"answer_id": 71937360,
"author": "franzisk",
"author_id": 2716142,
"author_profile": "https://Stackoverflow.com/users/2716142",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a logic <em>&&</em> to be more compact</p>\n<pre><code>#!/bin/bash\n\n# NO MATCH EXAMPLE\nstring="test"\n[[ "$string" == *"foo"* ]] && {\n echo "YES"\n}\n\n# MATCH EXAMPLE\nstring="tefoost"\n[[ "$string" == *"foo"* ]] && {\n echo "YES"\n}\n</code></pre>\n"
},
{
"answer_id": 72555962,
"author": "JanB",
"author_id": 16978791,
"author_profile": "https://Stackoverflow.com/users/16978791",
"pm_score": 0,
"selected": false,
"text": "<p>With <a href=\"https://stedolan.github.io/jq/manual/v1.6/\" rel=\"nofollow noreferrer\">jq</a>:</p>\n<pre><code>string='My long string'\necho $string | jq -Rr 'select(contains("long"))|"It is there"'\n</code></pre>\n<p>The hardest thing in jq is to print the single quote:</p>\n<pre><code>echo $string | jq --arg quote "'" -Rr 'select(contains("long"))|"It\\($quote)s there"'\n</code></pre>\n<p>Using jq just to check the condition:</p>\n<pre><code>if jq -Re 'select(contains("long"))|halt' <<< $string; then\n echo "It's there!"\nfi\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30773/"
] |
I have a string in Bash:
```sh
string="My string"
```
How can I test if it contains another string?
```sh
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
```
Where `??` is my unknown operator. Do I use `echo` and `grep`?
```sh
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
```
That looks a bit clumsy.
|
You can use [Marcus's answer (\* wildcards)](https://stackoverflow.com/a/229585/3755692) outside a case statement, too, if you use double brackets:
```
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
```
Note that spaces in the needle string need to be placed between double quotes, and the `*` wildcards should be outside. Also note that a simple comparison operator is used (i.e. `==`), not the regex operator `=~`.
|
229,554 |
<p>Just wondering what the difference between <code>BeginInvoke()</code> and <code>Invoke()</code> are? </p>
<p>Mainly what each one would be used for.</p>
<p>EDIT: What is the difference between creating a threading object and calling invoke on that and just calling <code>BeginInvoke()</code> on a delegate? or are they the same thing?</p>
|
[
{
"answer_id": 229558,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 10,
"selected": true,
"text": "<p>Do you mean <code>Delegate.Invoke</code>/<code>BeginInvoke</code> or <code>Control.Invoke</code>/<code>BeginInvoke</code>?</p>\n\n<ul>\n<li><code>Delegate.Invoke</code>: Executes synchronously, on the same thread.</li>\n<li><code>Delegate.BeginInvoke</code>: Executes asynchronously, on a <code>threadpool</code> thread.</li>\n<li><code>Control.Invoke</code>: Executes on the UI thread, but calling thread waits for completion before continuing.</li>\n<li><code>Control.BeginInvoke</code>: Executes on the UI thread, and calling thread doesn't wait for completion.</li>\n</ul>\n\n<p>Tim's answer mentions when you might want to use <code>BeginInvoke</code> - although it was mostly geared towards <code>Delegate.BeginInvoke</code>, I suspect.</p>\n\n<p>For Windows Forms apps, I would suggest that you should <em>usually</em> use <code>BeginInvoke</code>. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a <code>Person</code> with <code>FirstName</code> and <code>LastName</code> properties, and you did:</p>\n\n<pre><code>person.FirstName = \"Kevin\"; // person is a shared reference\nperson.LastName = \"Spacey\";\ncontrol.BeginInvoke(UpdateName);\nperson.FirstName = \"Keyser\";\nperson.LastName = \"Soze\";\n</code></pre>\n\n<p>Then the UI may well end up displaying \"Keyser Spacey\". (There's an outside chance it could display \"Kevin Soze\" but only through the weirdness of the memory model.)</p>\n\n<p>Unless you have this sort of issue, however, <code>Control.BeginInvoke</code> is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use <code>Control.BeginInvoke</code> in a \"fire and forget\" manner - i.e. without ever calling <code>EndInvoke</code>. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.</p>\n"
},
{
"answer_id": 229584,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 3,
"selected": false,
"text": "<p>Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.</p>\n\n<p>Delegate.Invoke() synchronously calls the delegate in the same thread.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/22t547yb(VS.71).aspx\" rel=\"noreferrer\">MSDN Article</a></p>\n"
},
{
"answer_id": 229593,
"author": "Tim Stewart",
"author_id": 26002,
"author_profile": "https://Stackoverflow.com/users/26002",
"pm_score": 6,
"selected": false,
"text": "<p>Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.</p>\n\n<p>In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).</p>\n\n<p>In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.</p>\n\n<p>Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.</p>\n"
},
{
"answer_id": 12364477,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 5,
"selected": false,
"text": "<p>The difference between <code>Control.Invoke()</code> and <code>Control.BeginInvoke()</code> is,</p>\n\n<ul>\n<li><code>BeginInvoke()</code> will schedule the asynchronous action on the GUI thread. When the asynchronous action is scheduled, your code continues. Some time later (you don't know exactly when) your asynchronous action will be executed</li>\n<li><code>Invoke()</code> will execute your asynchronous action (on the GUI thread) and wait until your action has completed.</li>\n</ul>\n\n<p>A logical conclusion is that a delegate you pass to <code>Invoke()</code> can have out-parameters or a return-value, while a delegate you pass to <code>BeginInvoke()</code> cannot (you have to use EndInvoke to retrieve the results).</p>\n"
},
{
"answer_id": 13873045,
"author": "KMC",
"author_id": 529310,
"author_profile": "https://Stackoverflow.com/users/529310",
"pm_score": 5,
"selected": false,
"text": "<p>Just to give a short, working example to see an effect of their difference</p>\n\n<pre><code>new Thread(foo).Start();\n\nprivate void foo()\n{\n this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,\n (ThreadStart)delegate()\n {\n myTextBox.Text = \"bing\";\n Thread.Sleep(TimeSpan.FromSeconds(3));\n });\n MessageBox.Show(\"done\");\n}\n</code></pre>\n\n<p>If use <strong>BeginInvoke</strong>, MessageBox pops simultaneous to the text update. If use <strong>Invoke</strong>, MessageBox pops after the 3 second sleep. Hence, showing the effect of an asynchronous (<strong>BeginInvoke</strong>) and a synchronous (<strong>Invoke</strong>) call. </p>\n"
},
{
"answer_id": 27792089,
"author": "Ingako",
"author_id": 3103185,
"author_profile": "https://Stackoverflow.com/users/3103185",
"pm_score": 3,
"selected": false,
"text": "<p>Just adding why and when to use Invoke().</p>\n\n<p>Both Invoke() and BeginInvoke() marshal the code you specify to the dispatcher thread.</p>\n\n<p>But unlike BeginInvoke(), Invoke() stalls your thread until the dispatcher executes your code. <strong>You might want to use Invoke() if you need to pause an asynchronous operation until the user has supplied some sort of feedback.</strong></p>\n\n<p>For example, you could call Invoke() to run a snippet of code that shows an OK/Cancel dialog box. After the user clicks a button and your marshaled code completes, the invoke() method will return, and you can act upon the user's response. </p>\n\n<p>See Pro WPF in C# chapter 31</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
Just wondering what the difference between `BeginInvoke()` and `Invoke()` are?
Mainly what each one would be used for.
EDIT: What is the difference between creating a threading object and calling invoke on that and just calling `BeginInvoke()` on a delegate? or are they the same thing?
|
Do you mean `Delegate.Invoke`/`BeginInvoke` or `Control.Invoke`/`BeginInvoke`?
* `Delegate.Invoke`: Executes synchronously, on the same thread.
* `Delegate.BeginInvoke`: Executes asynchronously, on a `threadpool` thread.
* `Control.Invoke`: Executes on the UI thread, but calling thread waits for completion before continuing.
* `Control.BeginInvoke`: Executes on the UI thread, and calling thread doesn't wait for completion.
Tim's answer mentions when you might want to use `BeginInvoke` - although it was mostly geared towards `Delegate.BeginInvoke`, I suspect.
For Windows Forms apps, I would suggest that you should *usually* use `BeginInvoke`. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a `Person` with `FirstName` and `LastName` properties, and you did:
```
person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";
```
Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)
Unless you have this sort of issue, however, `Control.BeginInvoke` is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use `Control.BeginInvoke` in a "fire and forget" manner - i.e. without ever calling `EndInvoke`. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.
|
229,565 |
<p>The Mutex class is very misunderstood, and Global mutexes even more so.</p>
<p>What is good, safe pattern to use when creating Global mutexes?</p>
<p>One that will work</p>
<ul>
<li>Regardless of the locale my machine is in</li>
<li>Is guaranteed to release the mutex properly</li>
<li>Optionally does not hang forever if the mutex is not acquired</li>
<li>Deals with cases where other processes abandon the mutex </li>
</ul>
|
[
{
"answer_id": 229567,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 10,
"selected": true,
"text": "<p>I want to make sure this is out there, because it's so hard to get right:</p>\n\n<pre><code>using System.Runtime.InteropServices; //GuidAttribute\nusing System.Reflection; //Assembly\nusing System.Threading; //Mutex\nusing System.Security.AccessControl; //MutexAccessRule\nusing System.Security.Principal; //SecurityIdentifier\n\nstatic void Main(string[] args)\n{\n // get application GUID as defined in AssemblyInfo.cs\n string appGuid =\n ((GuidAttribute)Assembly.GetExecutingAssembly().\n GetCustomAttributes(typeof(GuidAttribute), false).\n GetValue(0)).Value.ToString();\n\n // unique id for global mutex - Global prefix means it is global to the machine\n string mutexId = string.Format( \"Global\\\\{{{0}}}\", appGuid );\n\n // Need a place to store a return value in Mutex() constructor call\n bool createdNew;\n\n // edited by Jeremy Wiebe to add example of setting up security for multi-user usage\n // edited by 'Marc' to work also on localized systems (don't use just \"Everyone\") \n var allowEveryoneRule =\n new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid\n , null)\n , MutexRights.FullControl\n , AccessControlType.Allow\n );\n var securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n\n // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen\n using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))\n {\n // edited by acidzombie24\n var hasHandle = false;\n try\n {\n try\n {\n // note, you may want to time out here instead of waiting forever\n // edited by acidzombie24\n // mutex.WaitOne(Timeout.Infinite, false);\n hasHandle = mutex.WaitOne(5000, false);\n if (hasHandle == false)\n throw new TimeoutException(\"Timeout waiting for exclusive access\");\n }\n catch (AbandonedMutexException)\n {\n // Log the fact that the mutex was abandoned in another process,\n // it will still get acquired\n hasHandle = true;\n }\n\n // Perform your work here.\n }\n finally\n {\n // edited by acidzombie24, added if statement\n if(hasHandle)\n mutex.ReleaseMutex();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1213517,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 3,
"selected": false,
"text": "<p>This example will exit after 5 seconds if another instance is already running.</p>\n\n<pre><code>// unique id for global mutex - Global prefix means it is global to the machine\nconst string mutex_id = \"Global\\\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}\";\n\nstatic void Main(string[] args)\n{\n\n using (var mutex = new Mutex(false, mutex_id))\n {\n try\n {\n try\n {\n if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))\n {\n Console.WriteLine(\"Another instance of this program is running\");\n Environment.Exit(0);\n }\n }\n catch (AbandonedMutexException)\n {\n // Log the fact the mutex was abandoned in another process, it will still get aquired\n }\n\n // Perform your work here.\n }\n finally\n {\n mutex.ReleaseMutex();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7810107,
"author": "deepee1",
"author_id": 483179,
"author_profile": "https://Stackoverflow.com/users/483179",
"pm_score": 7,
"selected": false,
"text": "<p>Using the accepted answer I create a helper class so you could use it in a similar way you would use the Lock statement. Just thought I'd share. </p>\n\n<p>Use: </p>\n\n<pre><code>using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock\n{\n //Only 1 of these runs at a time\n RunSomeStuff();\n}\n</code></pre>\n\n<p>And the helper class:</p>\n\n<pre><code>class SingleGlobalInstance : IDisposable\n{\n //edit by user \"jitbit\" - renamed private fields to \"_\"\n public bool _hasHandle = false;\n Mutex _mutex;\n\n private void InitMutex()\n {\n string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;\n string mutexId = string.Format(\"Global\\\\{{{0}}}\", appGuid);\n _mutex = new Mutex(false, mutexId);\n\n var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);\n var securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n _mutex.SetAccessControl(securitySettings);\n }\n\n public SingleGlobalInstance(int timeOut)\n {\n InitMutex();\n try\n {\n if(timeOut < 0)\n _hasHandle = _mutex.WaitOne(Timeout.Infinite, false);\n else\n _hasHandle = _mutex.WaitOne(timeOut, false);\n\n if (_hasHandle == false)\n throw new TimeoutException(\"Timeout waiting for exclusive access on SingleInstance\");\n }\n catch (AbandonedMutexException)\n {\n _hasHandle = true;\n }\n }\n\n\n public void Dispose()\n {\n if (_mutex != null)\n {\n if (_hasHandle)\n _mutex.ReleaseMutex();\n _mutex.Close();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 15290536,
"author": "sol",
"author_id": 1936816,
"author_profile": "https://Stackoverflow.com/users/1936816",
"pm_score": 3,
"selected": false,
"text": "<p>Neither Mutex nor WinApi CreateMutex() works for me.</p>\n\n<p>An alternate solution:</p>\n\n<pre><code>static class Program\n{\n [STAThread]\n static void Main()\n {\n if (SingleApplicationDetector.IsRunning()) {\n return;\n }\n\n Application.Run(new MainForm());\n\n SingleApplicationDetector.Close();\n }\n}\n</code></pre>\n\n<p>And the <code>SingleApplicationDetector</code>:</p>\n\n<pre><code>using System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Threading;\n\npublic static class SingleApplicationDetector\n{\n public static bool IsRunning()\n {\n string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();\n var semaphoreName = @\"Global\\\" + guid;\n try {\n __semaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize);\n\n Close();\n return true;\n }\n catch (Exception ex) {\n __semaphore = new Semaphore(0, 1, semaphoreName);\n return false;\n }\n }\n\n public static void Close()\n {\n if (__semaphore != null) {\n __semaphore.Close();\n __semaphore = null;\n }\n }\n\n private static Semaphore __semaphore;\n}\n</code></pre>\n\n<p>Reason to use Semaphore instead of Mutex:</p>\n\n<blockquote>\n <p>The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity.</p>\n \n <p><< <a href=\"http://msdn.microsoft.com/zh-cn/library/system.threading.mutex.aspx\" rel=\"noreferrer\">System.Threading.Mutex</a></p>\n</blockquote>\n\n<p>Ref: <a href=\"http://msdn.microsoft.com/zh-cn/library/8ye97d5d.aspx\" rel=\"noreferrer\">Semaphore.OpenExisting()</a></p>\n"
},
{
"answer_id": 52340464,
"author": "user3248578",
"author_id": 1051237,
"author_profile": "https://Stackoverflow.com/users/1051237",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes learning by example helps the most. Run this console application in three different console windows. You'll see that the application you ran first acquires the mutex first, while the other two are waiting their turn. Then press enter in the first application, you'll see that application 2 now continues running by acquiring the mutex, however application 3 is waiting its turn. After you press enter in application 2 you'll see that application 3 continues. This illustrates the concept of a mutex protecting a section of code to be executed only by one thread (in this case a process) like writing to a file as an example.</p>\n\n<pre><code>using System;\nusing System.Threading;\n\nnamespace MutexExample\n{\n class Program\n {\n static Mutex m = new Mutex(false, \"myMutex\");//create a new NAMED mutex, DO NOT OWN IT\n static void Main(string[] args)\n {\n Console.WriteLine(\"Waiting to acquire Mutex\");\n m.WaitOne(); //ask to own the mutex, you'll be queued until it is released\n Console.WriteLine(\"Mutex acquired.\\nPress enter to release Mutex\");\n Console.ReadLine();\n m.ReleaseMutex();//release the mutex so other processes can use it\n }\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/LbJAH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LbJAH.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 58326849,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 0,
"selected": false,
"text": "<p>A global Mutex is not only to ensure to have only one instance of an application. I personally prefer using Microsoft.VisualBasic to ensure single instance application like described in <a href=\"https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-wpf-application\">What is the correct way to create a single-instance WPF application?</a> (Dale Ragan answer)... I found that's easier to pass arguments received on new application startup to the initial single instance application.</p>\n\n<p>But regarding some previous code in this thread, I would prefer to not create a Mutex each time I want to have a lock on it. It could be fine for a single instance application but in other usage it appears to me has overkill.</p>\n\n<p>That's why I suggest this implementation instead:</p>\n\n<p>Usage:</p>\n\n<pre><code>static MutexGlobal _globalMutex = null;\nstatic MutexGlobal GlobalMutexAccessEMTP\n{\n get\n {\n if (_globalMutex == null)\n {\n _globalMutex = new MutexGlobal();\n }\n return _globalMutex;\n }\n}\n\nusing (GlobalMutexAccessEMTP.GetAwaiter())\n{\n ...\n} \n</code></pre>\n\n<p>Mutex Global Wrapper:</p>\n\n<pre><code>using System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading;\n\nnamespace HQ.Util.General.Threading\n{\n public class MutexGlobal : IDisposable\n {\n // ************************************************************************\n public string Name { get; private set; }\n internal Mutex Mutex { get; private set; }\n public int DefaultTimeOut { get; set; }\n public Func<int, bool> FuncTimeOutRetry { get; set; }\n\n // ************************************************************************\n public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)\n {\n return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);\n }\n\n // ************************************************************************\n public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)\n {\n try\n {\n if (string.IsNullOrEmpty(specificName))\n {\n Name = Guid.NewGuid().ToString();\n }\n else\n {\n Name = specificName;\n }\n\n Name = string.Format(\"Global\\\\{{{0}}}\", Name);\n\n DefaultTimeOut = defaultTimeOut;\n\n FuncTimeOutRetry = DefaultFuncTimeOutRetry;\n\n var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);\n var securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n\n Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);\n\n if (Mutex == null)\n {\n throw new Exception($\"Unable to create mutex: {Name}\");\n }\n }\n catch (Exception ex)\n {\n Log.Log.Instance.AddEntry(Log.LogType.LogException, $\"Unable to create Mutex: {Name}\", ex);\n throw;\n }\n }\n\n // ************************************************************************\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"timeOut\"></param>\n /// <returns></returns>\n public MutexGlobalAwaiter GetAwaiter(int timeOut)\n {\n return new MutexGlobalAwaiter(this, timeOut);\n }\n\n // ************************************************************************\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"timeOut\"></param>\n /// <returns></returns>\n public MutexGlobalAwaiter GetAwaiter()\n {\n return new MutexGlobalAwaiter(this, DefaultTimeOut);\n }\n\n // ************************************************************************\n /// <summary>\n /// This method could either throw any user specific exception or return \n /// true to retry. Otherwise, retruning false will let the thread continue\n /// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to \n /// take proper action depending on timeout or not. \n /// </summary>\n /// <param name=\"timeOutUsed\"></param>\n /// <returns></returns>\n private bool DefaultFuncTimeOutRetry(int timeOutUsed)\n {\n // throw new TimeoutException($\"Mutex {Name} timed out {timeOutUsed}.\");\n\n Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $\"Mutex {Name} timeout: {timeOutUsed}.\");\n return true; // retry\n }\n\n // ************************************************************************\n public void Dispose()\n {\n if (Mutex != null)\n {\n Mutex.ReleaseMutex();\n Mutex.Close();\n }\n }\n\n // ************************************************************************\n\n }\n}\n</code></pre>\n\n<p>Awaiter</p>\n\n<pre><code>using System;\n\nnamespace HQ.Util.General.Threading\n{\n public class MutexGlobalAwaiter : IDisposable\n {\n MutexGlobal _mutexGlobal = null;\n\n public bool HasTimedOut { get; set; } = false;\n\n internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)\n {\n _mutexGlobal = mutexEx;\n\n do\n {\n HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);\n if (! HasTimedOut) // Signal received\n {\n return;\n }\n } while (_mutexGlobal.FuncTimeOutRetry(timeOut));\n }\n\n #region IDisposable Support\n private bool disposedValue = false; // To detect redundant calls\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposedValue)\n {\n if (disposing)\n {\n _mutexGlobal.Mutex.ReleaseMutex();\n }\n\n // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.\n // TODO: set large fields to null.\n\n disposedValue = true;\n }\n }\n // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.\n // ~MutexExAwaiter()\n // {\n // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.\n // Dispose(false);\n // }\n\n // This code added to correctly implement the disposable pattern.\n public void Dispose()\n {\n // Do not change this code. Put cleanup code in Dispose(bool disposing) above.\n Dispose(true);\n // TODO: uncomment the following line if the finalizer is overridden above.\n // GC.SuppressFinalize(this);\n }\n #endregion\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59079638,
"author": "Wouter",
"author_id": 4491768,
"author_profile": "https://Stackoverflow.com/users/4491768",
"pm_score": 2,
"selected": false,
"text": "<p>A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException.\nThis solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.</p>\n<p>Global vs local mutex see note in:\n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8</a></p>\n<pre><code>private Mutex mutex;\nprivate bool mutexCreated;\n\npublic App()\n{\n string mutexId = $"Global\\\\{GetType().GUID}";\n mutex = new Mutex(true, mutexId, out mutexCreated);\n}\n\nprotected override void OnStartup(StartupEventArgs e)\n{\n base.OnStartup(e);\n if (!mutexCreated)\n {\n MessageBox.Show("Already started!");\n Shutdown();\n }\n}\n</code></pre>\n<p>Because Mutex implements IDisposable it is released automatically but for completeness call dispose:</p>\n<pre><code>protected override void OnExit(ExitEventArgs e)\n{\n base.OnExit(e);\n mutex.Dispose();\n}\n</code></pre>\n<p>Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).</p>\n<pre><code>public class SingleApplication : Application\n{\n private Mutex mutex;\n private bool mutexCreated;\n\n public SingleApplication()\n {\n string mutexId = $"Global\\\\{GetType().GUID}";\n\n MutexAccessRule allowEveryoneRule = new MutexAccessRule(\n new SecurityIdentifier(WellKnownSidType.WorldSid, null),\n MutexRights.FullControl, \n AccessControlType.Allow);\n MutexSecurity securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n\n // initiallyOwned: true == false + mutex.WaitOne()\n mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings); \n }\n\n protected override void OnExit(ExitEventArgs e)\n {\n base.OnExit(e);\n if (mutexCreated)\n {\n try\n {\n mutex.ReleaseMutex();\n }\n catch (ApplicationException ex)\n {\n MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n mutex.Dispose();\n }\n\n protected override void OnStartup(StartupEventArgs e)\n {\n base.OnStartup(e);\n if (!mutexCreated)\n {\n MessageBox.Show("Already started!");\n Shutdown();\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
The Mutex class is very misunderstood, and Global mutexes even more so.
What is good, safe pattern to use when creating Global mutexes?
One that will work
* Regardless of the locale my machine is in
* Is guaranteed to release the mutex properly
* Optionally does not hang forever if the mutex is not acquired
* Deals with cases where other processes abandon the mutex
|
I want to make sure this is out there, because it's so hard to get right:
```
using System.Runtime.InteropServices; //GuidAttribute
using System.Reflection; //Assembly
using System.Threading; //Mutex
using System.Security.AccessControl; //MutexAccessRule
using System.Security.Principal; //SecurityIdentifier
static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid =
((GuidAttribute)Assembly.GetExecutingAssembly().
GetCustomAttributes(typeof(GuidAttribute), false).
GetValue(0)).Value.ToString();
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format( "Global\\{{{0}}}", appGuid );
// Need a place to store a return value in Mutex() constructor call
bool createdNew;
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule =
new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
, null)
, MutexRights.FullControl
, AccessControlType.Allow
);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
{
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access");
}
catch (AbandonedMutexException)
{
// Log the fact that the mutex was abandoned in another process,
// it will still get acquired
hasHandle = true;
}
// Perform your work here.
}
finally
{
// edited by acidzombie24, added if statement
if(hasHandle)
mutex.ReleaseMutex();
}
}
}
```
|
229,579 |
<p>I have an xml file where I need to comment out a whole piece of text with Ant.</p>
<p>There's this Ant task</p>
<pre><code><replace file="${src.dir}/Version.as"
token="@revisionPrana" value="${revision}"/>
</code></pre>
<p>that I use to replace words, but in my case I need to replace a whole block like this:</p>
<pre><code><value>
<object class="edumatic.backoffice.view.modules.NavigationModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsNavigationModule.swf"/>
<property name="icon"
value="edumatic/backoffice/view/modules/support/assets/book.png" />
<property name="title" value="Assessments" />
<property name="pluginID" value="EXAM" />
</object>
</value>
<value>
<object class="edumatic.backoffice.view.modules.ContentModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsContentModule.swf" />
<property name="pluginID" value="EXAM" />
</object>
</value>
</code></pre>
<p>Into</p>
<pre><code><!--value>
<object class="edumatic.backoffice.view.modules.NavigationModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsNavigationModule.swf"/>
<property name="icon"
value="edumatic/backoffice/view/modules/support/assets/book.png" />
<property name="title" value="Assessments" />
<property name="pluginID" value="EXAM" />
</object>
</value>
<value>
<object class="edumatic.backoffice.view.modules.ContentModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsContentModule.swf" />
<property name="pluginID" value="EXAM" />
</object>
</value-->
</code></pre>
<p>So, basically I need to comment out a whole block of XML. Can I do this with a replace task (putting the whole block in the attribute token and value doesn't really work)? Or is there a quick way to read in the xml with ant and delete some nodes and save the xml again?</p>
<p>Searching for and replace it by isn't an option because there are multiple value children and not all of them need to be commented out.</p>
<p>Adding a attribute like isn't an option either because the xml is being parsed by an IOC container (Prana). Maybe prana will ignore the id="1" but it still iss messy, and I don't like messy on the long term.</p>
|
[
{
"answer_id": 229658,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 4,
"selected": true,
"text": "<p>If you can identify what is to be replaced through a regular expression, I recommend using the optional task <strong>replaceregexp</strong>. Here's the doc: <a href=\"http://ant.apache.org/manual/Tasks/replaceregexp.html\" rel=\"nofollow noreferrer\">http://ant.apache.org/manual/Tasks/replaceregexp.html</a>\nYou can call it twice, one for the start tag and other for the end tag.</p>\n\n<p>The regexp for replacing your <em></em> can be a bit cumbersome, since you say you do not want to replace all <em></em> tags, but I think this is the easiest way. </p>\n\n<p>Another option would be to create a custom ant task to do what you want.</p>\n"
},
{
"answer_id": 235576,
"author": "Mads Hansen",
"author_id": 14419,
"author_profile": "https://Stackoverflow.com/users/14419",
"pm_score": 2,
"selected": false,
"text": "<p>If it is an XML file, then you could also call an XSLT transform</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26521/"
] |
I have an xml file where I need to comment out a whole piece of text with Ant.
There's this Ant task
```
<replace file="${src.dir}/Version.as"
token="@revisionPrana" value="${revision}"/>
```
that I use to replace words, but in my case I need to replace a whole block like this:
```
<value>
<object class="edumatic.backoffice.view.modules.NavigationModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsNavigationModule.swf"/>
<property name="icon"
value="edumatic/backoffice/view/modules/support/assets/book.png" />
<property name="title" value="Assessments" />
<property name="pluginID" value="EXAM" />
</object>
</value>
<value>
<object class="edumatic.backoffice.view.modules.ContentModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsContentModule.swf" />
<property name="pluginID" value="EXAM" />
</object>
</value>
```
Into
```
<!--value>
<object class="edumatic.backoffice.view.modules.NavigationModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsNavigationModule.swf"/>
<property name="icon"
value="edumatic/backoffice/view/modules/support/assets/book.png" />
<property name="title" value="Assessments" />
<property name="pluginID" value="EXAM" />
</object>
</value>
<value>
<object class="edumatic.backoffice.view.modules.ContentModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsContentModule.swf" />
<property name="pluginID" value="EXAM" />
</object>
</value-->
```
So, basically I need to comment out a whole block of XML. Can I do this with a replace task (putting the whole block in the attribute token and value doesn't really work)? Or is there a quick way to read in the xml with ant and delete some nodes and save the xml again?
Searching for and replace it by isn't an option because there are multiple value children and not all of them need to be commented out.
Adding a attribute like isn't an option either because the xml is being parsed by an IOC container (Prana). Maybe prana will ignore the id="1" but it still iss messy, and I don't like messy on the long term.
|
If you can identify what is to be replaced through a regular expression, I recommend using the optional task **replaceregexp**. Here's the doc: <http://ant.apache.org/manual/Tasks/replaceregexp.html>
You can call it twice, one for the start tag and other for the end tag.
The regexp for replacing your can be a bit cumbersome, since you say you do not want to replace all tags, but I think this is the easiest way.
Another option would be to create a custom ant task to do what you want.
|
229,603 |
<p>I have an ASP.NET MVC (Beta 1) website that I'm using themes with. When I start my site (I'm still running using the ASP.Net Development Web Server) the default page gives me this error:</p>
<pre><code>Server Error in '/' Application.
Using themed css files requires a header control on the page. (e.g. <head runat="server" />).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Using themed css files requires a header control on the page. (e.g. <head runat="server" />).
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Using themed css files requires a header control on the page. (e.g. <head runat="server" />).]
System.Web.UI.PageTheme.SetStyleSheet() +2458366
System.Web.UI.Page.OnInit(EventArgs e) +8694828
System.Web.UI.Control.InitRecursive(Control namingContainer) +333
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +378
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053
</code></pre>
<p>Do I need to change something with my routes? Or do I need to do something else to my site?</p>
|
[
{
"answer_id": 229846,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": true,
"text": "<p>The error is telling you that your ASP.NET page (or master page) needs to have a <head runat=\"server\"> tag. Without it, you cannot use themes.</p>\n\n<p>Since server side header tags shouldn't have a dependency on viewstate (as they are not contained in forms), it might still work.</p>\n\n<p>Having said that, themes don't necessarily sit well in the MVC paradigm so you should consider whether you really need them.</p>\n"
},
{
"answer_id": 230015,
"author": "Jason Whitehorn",
"author_id": 27860,
"author_profile": "https://Stackoverflow.com/users/27860",
"pm_score": 2,
"selected": false,
"text": "<p>A cleaner idea is to just have a \"theme\" consisting of CSS. In your master page (or individual views) link to the appropriate CSS files. </p>\n\n<p>For example, I keep my \"themes\" in a theme directory under the Content directory of the site root. Each theme lives in its own folder, and has a main.css. The main.css is responsible for referencing all the other required CSS. So the master page in my example just links to the one main.css. You can even set the ViewData[\"theme\"] variable (if you wanted) to the theme name, so the Master page could simply use that as a place holder for the correct theme directory.</p>\n"
},
{
"answer_id": 233353,
"author": "Michael DeLorenzo",
"author_id": 1383003,
"author_profile": "https://Stackoverflow.com/users/1383003",
"pm_score": 0,
"selected": false,
"text": "<p>I like your idea Jason, thanks for the tip. That would actually be very easy for me to implement. :)</p>\n\n<p>Just as an fyi for anyone trying to do what I am/was doing with the Themes, I simply added the header element to the default.aspx page, and all was taken care of - just what Richard suggested.</p>\n"
},
{
"answer_id": 288832,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This was my solution <a href=\"http://frugalcoder.us/post/2008/11/ASPNet-MVC-Theming.aspx\" rel=\"nofollow noreferrer\">http://frugalcoder.us/post/2008/11/ASPNet-MVC-Theming.aspx</a> just posted about this today...</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1383003/"
] |
I have an ASP.NET MVC (Beta 1) website that I'm using themes with. When I start my site (I'm still running using the ASP.Net Development Web Server) the default page gives me this error:
```
Server Error in '/' Application.
Using themed css files requires a header control on the page. (e.g. <head runat="server" />).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Using themed css files requires a header control on the page. (e.g. <head runat="server" />).
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Using themed css files requires a header control on the page. (e.g. <head runat="server" />).]
System.Web.UI.PageTheme.SetStyleSheet() +2458366
System.Web.UI.Page.OnInit(EventArgs e) +8694828
System.Web.UI.Control.InitRecursive(Control namingContainer) +333
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +378
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053
```
Do I need to change something with my routes? Or do I need to do something else to my site?
|
The error is telling you that your ASP.NET page (or master page) needs to have a <head runat="server"> tag. Without it, you cannot use themes.
Since server side header tags shouldn't have a dependency on viewstate (as they are not contained in forms), it might still work.
Having said that, themes don't necessarily sit well in the MVC paradigm so you should consider whether you really need them.
|
229,622 |
<p>I am working on a stored procedure with several optional parameters. Some of these parameters are single values and it's easy enough to use a WHERE clause like:</p>
<pre><code>WHERE (@parameter IS NULL OR column = @parameter)
</code></pre>
<p>However, in some instances, the WHERE condition is more complicated:</p>
<pre><code>WHERE (@NewGroupId IS NULL OR si.SiteId IN (SELECT gs.SiteId
FROM [UtilityWeb].[dbo].[GroupSites] AS gs
WHERE gs.GroupId = @NewGroupId))
</code></pre>
<p>When I uncomment these complicated WHERE clauses, the query execution time doubles and the execution plan becomes remarkably more complicated. While the execution plan doesn't bother me, doubling the execution time of a query is a definite problem.</p>
<p>Is there a best practice or pattern that others have found for working with optional parameters in their stored procedures?</p>
<p>Is this one of those instances where dynamic SQL would be a better solution?</p>
|
[
{
"answer_id": 229641,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 3,
"selected": false,
"text": "<p>I would create separate queries for the parameter being available or not.</p>\n\n<p>This will create simpler SQL, and the optimizer will do a better job.</p>\n\n<p>Like this:</p>\n\n<pre><code>if (@parameter IS NULL) then begin\n select * from foo\nend\nelse begin\n select * from foo where value = @parameter\nend\n</code></pre>\n\n<p>In you have to many parameters to redesign like this, and you go for the dynamic sql solution, then also always use parameters, you might get bitten by the <a href=\"https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks#2040\">SQL-Injection</a> bug.</p>\n\n<p>A combination is also possible. The most likely used query/queries you code in full, and get precompiled. All other combinations are created dynamically.</p>\n"
},
{
"answer_id": 229655,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "<p>Dynamic SQL is probably a better solution in this case, particularly if the stored procedure only wraps this one query.</p>\n\n<p>One thing to keep in mind is that SQL Server doesn't do short circuiting of boolean expressions inside a single query. In many languages \"(a) || (b)\" will not cause b to be evaluated if a is true. Similarly, \"(a) && (b)\" will not cause b to be evaluated if a is false. In SQL Server, this is not the case. So in the example you give, the query on the back end of the \"or\" will get evaluated even if @NewGroupId is not null.</p>\n"
},
{
"answer_id": 229689,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "<p>For a small number of optional parameters, conditional choosing from one of several static queries as GvS suggests is OK.</p>\n\n<p>However, this becomes unwieldy if there a several parameters, since you need to handle all permutations - with 5 parameters that is 32 static queries! Using dynamic SQL you can construct the exact query that best fits the parameters given. Be sure to use bind variables though!</p>\n"
},
{
"answer_id": 229709,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": true,
"text": "<p>The main problem is likely to be <a href=\"http://omnibuzz-sql.blogspot.com/2006/11/parameter-sniffing-stored-procedures.html\" rel=\"nofollow noreferrer\">parameter sniffing</a>, and wildly different optimal execution plans depending on which of your parameters are NULL. Try running the stored proc with <a href=\"http://www.sqlmag.com/Article/ArticleID/94369/sql_server_94369.html\" rel=\"nofollow noreferrer\">RECOMPILE</a>. </p>\n\n<p>Contrary to some beliefs, Sql Server <a href=\"http://weblogs.sqlteam.com/jeffs/archive/2008/02/22/sql-server-short-circuit.aspx\" rel=\"nofollow noreferrer\"><em>does</em></a> <a href=\"http://technet.microsoft.com/en-us/cc678236.aspx\" rel=\"nofollow noreferrer\">do</a> short circuit evaluations - though (as with all query optimizations) it may not be exactly what you wanted.</p>\n\n<p>BTW - I would probably rewrite that portion of the query as a JOINed derived table:</p>\n\n<pre><code>SELECT * \nFROM Table as si\nJOIN (\n SELECT SiteId\n FROM [UtilityWeb].[dbo].[GroupSites]\n WHERE GroupId = ISNULL(@NewGroupId, GroupId)\n /* --Or, if all SiteIds aren't in GroupSites, or GroupSites is unusually large \n --this might work better\n SELECT @newGroupId\n UNION ALL\n SELECT SiteId FROM [UtilityWeb].[dbo].[GroupSites]\n WHERE GroupId = @NewGroupId\n */\n) as gs ON\n si.SiteId = gs.SiteId\n</code></pre>\n\n<p>It may or may not influence the query plan, but it's a bit cleaner to me.</p>\n"
},
{
"answer_id": 229729,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 2,
"selected": false,
"text": "<p>CASE statements are your friend...</p>\n\n<p>Rather than:</p>\n\n<pre><code>if (@parameter IS NULL) then begin\n select * from foo\nend\nelse begin\n select * from foo where value = @parameter\nend\n</code></pre>\n\n<p>You can use:</p>\n\n<pre><code>SELECT * FROM foo \nWHERE value = CASE WHEN @parameter IS NULL THEN value ELSE @parameter END\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>SELECT * FROM foo \nWHERE value = ISNULL(@parameter,value)\n</code></pre>\n\n<p>I tend to use CASE statements more because my optional parameters may use certain values instead of NULL's...</p>\n"
},
{
"answer_id": 729874,
"author": "Irawan Soetomo",
"author_id": 54908,
"author_profile": "https://Stackoverflow.com/users/54908",
"pm_score": 1,
"selected": false,
"text": "<p>IMHO, the parameter sniffing issue can be solved by copying all parameters into variables; then avoid using the parameters directly at all cost, use the variables instead. Example:</p>\n\n<pre><code>\ncreate proc ManyParams\n(\n @pcol1 int,\n @pcol2 int,\n @pcol3 int\n)\nas\ndeclare\n @col1 int,\n @col2 int,\n @col3 int\n\nselect\n @col1 = @pcol1,\n @col2 = @pcol2,\n @col3 = @pcol3\n\nselect \n col1,\n col2,\n col3\nfrom \n tbl \nwhere \n 1 = case when @col1 is null then 1 else case when col1 = @col1 then 1 else 0 end end\nand 1 = case when @col2 is null then 1 else case when col2 = @col2 then 1 else 0 end end\nand 1 = case when @col3 is null then 1 else case when col3 = @col3 then 1 else 0 end end\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11780/"
] |
I am working on a stored procedure with several optional parameters. Some of these parameters are single values and it's easy enough to use a WHERE clause like:
```
WHERE (@parameter IS NULL OR column = @parameter)
```
However, in some instances, the WHERE condition is more complicated:
```
WHERE (@NewGroupId IS NULL OR si.SiteId IN (SELECT gs.SiteId
FROM [UtilityWeb].[dbo].[GroupSites] AS gs
WHERE gs.GroupId = @NewGroupId))
```
When I uncomment these complicated WHERE clauses, the query execution time doubles and the execution plan becomes remarkably more complicated. While the execution plan doesn't bother me, doubling the execution time of a query is a definite problem.
Is there a best practice or pattern that others have found for working with optional parameters in their stored procedures?
Is this one of those instances where dynamic SQL would be a better solution?
|
The main problem is likely to be [parameter sniffing](http://omnibuzz-sql.blogspot.com/2006/11/parameter-sniffing-stored-procedures.html), and wildly different optimal execution plans depending on which of your parameters are NULL. Try running the stored proc with [RECOMPILE](http://www.sqlmag.com/Article/ArticleID/94369/sql_server_94369.html).
Contrary to some beliefs, Sql Server [*does*](http://weblogs.sqlteam.com/jeffs/archive/2008/02/22/sql-server-short-circuit.aspx) [do](http://technet.microsoft.com/en-us/cc678236.aspx) short circuit evaluations - though (as with all query optimizations) it may not be exactly what you wanted.
BTW - I would probably rewrite that portion of the query as a JOINed derived table:
```
SELECT *
FROM Table as si
JOIN (
SELECT SiteId
FROM [UtilityWeb].[dbo].[GroupSites]
WHERE GroupId = ISNULL(@NewGroupId, GroupId)
/* --Or, if all SiteIds aren't in GroupSites, or GroupSites is unusually large
--this might work better
SELECT @newGroupId
UNION ALL
SELECT SiteId FROM [UtilityWeb].[dbo].[GroupSites]
WHERE GroupId = @NewGroupId
*/
) as gs ON
si.SiteId = gs.SiteId
```
It may or may not influence the query plan, but it's a bit cleaner to me.
|
229,623 |
<pre><code><input type="submit"/>
<style>
input {
background: url(tick.png) bottom left no-repeat;
padding-left: 18px;
}
</style>
</code></pre>
<p>But the bevel goes away, how can I add an icon to submit button and keep the bevel?<br>
Edit: I want it to look like the browser default.</p>
|
[
{
"answer_id": 229640,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>Use border. For example:</p>\n\n<pre><code>INPUT.button {\n BORDER-RIGHT: #999999 1px solid;\n BORDER-TOP: #999999 1px solid;\n FONT-SIZE: 11px;\n BACKGROUND: url(tick.png) bottom left no-repeat;\n BORDER-LEFT: #999999 1px solid;\n CURSOR: pointer;\n COLOR: #333333;\n BORDER-BOTTOM: #999999 1px solid\n}\n\n<input type=\"submit\" class=\"button\" />\n</code></pre>\n"
},
{
"answer_id": 229647,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "<p>You could use border-style outset:</p>\n\n<p>border: 2px outset #cccccc;</p>\n"
},
{
"answer_id": 229662,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 1,
"selected": false,
"text": "<p>For a true button effect, I also like to introduce a hover or a focus style. Similar to what @Roburg has mentioned, I normally do something like:</p>\n\n<pre><code>input#button {\n border: 2px outset rgb(0, 0, 0);\n}\n\ninput#button:focus {\n border: 2px inset rgb(0, 0, 0);\n}\n</code></pre>\n\n<p>This will give the illusion that the button has been pressed even though it isn't a true button, per se.</p>\n"
},
{
"answer_id": 229691,
"author": "John Dunagan",
"author_id": 28939,
"author_profile": "https://Stackoverflow.com/users/28939",
"pm_score": 1,
"selected": false,
"text": "<p>My old shop used to rock the input type=\"image\" syntax - it works as Submit. As one of my favorite poker people likes to say, \"all you can eat, baby!\" - anything you want to put there as a graphic.</p>\n"
},
{
"answer_id": 229748,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 2,
"selected": false,
"text": "<p>Using <.input type=\"submit\" /> with a background will look different depending on what browser / OS you're on.</p>\n\n<p>If you want to keep the browser styles, you could use the button element, which allows HTML inside the tag:</p>\n\n<pre><code><button type=\"submit\"><img src=\"image.gif\" /> Text</button>\nor \n<button type=\"submit\"><span class=\"icon\"></span> Text</button>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
<input type="submit"/>
<style>
input {
background: url(tick.png) bottom left no-repeat;
padding-left: 18px;
}
</style>
```
But the bevel goes away, how can I add an icon to submit button and keep the bevel?
Edit: I want it to look like the browser default.
|
Using <.input type="submit" /> with a background will look different depending on what browser / OS you're on.
If you want to keep the browser styles, you could use the button element, which allows HTML inside the tag:
```
<button type="submit"><img src="image.gif" /> Text</button>
or
<button type="submit"><span class="icon"></span> Text</button>
```
|
229,630 |
<p>My application has several threads:
1) Main Thread
2) 2 Sub-Main Threads (each with Message Loop, as shown below), used by TFQM
3) n Worker Threads (simple loop, containing Sleep())</p>
<p>My problem is, when I close my application, the Worker Threads manage to exit properly, but 1 of the 2 Sub-Main Threads hangs (never exits) when I issue WM_QUIT to close them.</p>
<hr>
<pre><code>procedure ThreadProcFQM(P: Integer); stdcall;
var
Msg: TMsg;
_FQM: TFQM;
begin
_FQM := Ptr(P);
try
_FQM.fHandle := AllocateHwnd(_FQM.WndProc);
while GetMessage(Msg, 0, 0, 0) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
finally
DeallocateHWnd(_FQM.fHandle);
SetEvent(_FQM.hTerminated);
end;
end;
</code></pre>
<hr>
<pre><code>procedure TFQM.Stop;
begin
PostMessage(fHandle, WM_QUIT, 0, 0);
WaitForSingleObject(hTerminated, INFINITE);
if hThread <> INVALID_HANDLE_VALUE then
begin
CloseHandle(hThread);
hThread := INVALID_HANDLE_VALUE;
end;
end;
</code></pre>
|
[
{
"answer_id": 229808,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 3,
"selected": false,
"text": "<p>I've had the same problem, and I found out I <strong>shouldn't</strong> create a hidden window just to recieve messages. Threads already have a message system. </p>\n\n<p>I think that you're creating your windows handle and store it in fHandle, but GetMessage checks your thread's message loop. Therefore the message PostMessage(fHandle, WM_QUIT, 0, 0); is never recieved by the getmesssage.</p>\n\n<p>You can post messages to your thread using PostThreadMessage, and in the thread you use GetMessage(CurrentMessage, 0, 0, 0). The only important difference is that you have to start the message loop from your thread by calling </p>\n\n<pre><code>PeekMessage(CurrentMessage, 0, WM_USER, WM_USER, PM_NOREMOVE);\n</code></pre>\n\n<p>You should start with this, than do your setup and than start your loop.</p>\n\n<p>The reason why you should start with the peek message is to make sure messages which are sent during the initialization of your threadprocedure are not lost.</p>\n\n<p>The weird thing is, at the moment I can't find the reference where I learned this, but my guess is the newsgroup community.</p>\n"
},
{
"answer_id": 230288,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>1) You don't need in AllocateHwnd within your thread. First call to GetMessage will create a separate message queue for this thread. But in order to send message to the thread you should use PostThreadMessage function.</p>\n\n<p>Be aware that at the moment of calling PostThreadMessage the queue still could not be created. I usually use construction:</p>\n\n<pre><code>while not PostThreadMessage(ThreadID, idStartMessage, 0, 0) do\n Sleep(1);\n</code></pre>\n\n<p>to ensure that message queue created.</p>\n\n<p>2) For terminating thread loop I define my own message:</p>\n\n<pre><code> idExitMessage = WM_USER + 777; // you are free to use your own constant here\n</code></pre>\n\n<p>3) There is no need for separate event, because you can pass thread handle to\nWaitForSingleObject function. So, your code could look like:</p>\n\n<pre><code> PostThreadMessage(ThreadID, idExitMessage, 0, 0);\n WaitForSingleObject(ThreadHandle, INFINITE);\n</code></pre>\n\n<p>Take into consideration that ThreadID and ThreadHandle are different values.</p>\n\n<p>4) So, your ThreadProc will look like:</p>\n\n<pre><code>procedure ThreadProcFQM; stdcall;\nvar\n Msg: TMsg;\nbegin\n while GetMessage(Msg, 0, 0, 0) \n and (Msg.Message <> idExitMessage) do\n begin\n TranslateMessage(Msg);\n DispatchMessage(Msg);\n end;\nend;\n</code></pre>\n"
},
{
"answer_id": 230565,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 4,
"selected": false,
"text": "<p>If I may point to few problems in your code ...</p>\n\n<p>1) You're not checking output of AllocateHwnd. Yes, most probably it will never fail, but still ...</p>\n\n<p>2) AllocateHwnd belogs OUT of try..finally! If it fails, DeallocateHwnd should not be called.</p>\n\n<p>3) AllocateHwnd is not threadsafe. If you call it from multiple threads at the same time, you can run into poblems. <a href=\"http://17slon.com/blogs/gabr/2007/06/allocatehwnd-is-not-thread-safe.html\" rel=\"noreferrer\">Read more.</a></p>\n\n<p>As Davy said, use MsgWaitForMultipleObjects instead of creating hidden message window. Then use PostThreadMessage to send messages to thread.</p>\n\n<p>If I may put a plug for a totally free product here - use my <a href=\"http://otl.17slon.com/\" rel=\"noreferrer\">OmniThreadLibrary</a> instead. Much simpler than messing directly with Windows messaging.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30787/"
] |
My application has several threads:
1) Main Thread
2) 2 Sub-Main Threads (each with Message Loop, as shown below), used by TFQM
3) n Worker Threads (simple loop, containing Sleep())
My problem is, when I close my application, the Worker Threads manage to exit properly, but 1 of the 2 Sub-Main Threads hangs (never exits) when I issue WM\_QUIT to close them.
---
```
procedure ThreadProcFQM(P: Integer); stdcall;
var
Msg: TMsg;
_FQM: TFQM;
begin
_FQM := Ptr(P);
try
_FQM.fHandle := AllocateHwnd(_FQM.WndProc);
while GetMessage(Msg, 0, 0, 0) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
finally
DeallocateHWnd(_FQM.fHandle);
SetEvent(_FQM.hTerminated);
end;
end;
```
---
```
procedure TFQM.Stop;
begin
PostMessage(fHandle, WM_QUIT, 0, 0);
WaitForSingleObject(hTerminated, INFINITE);
if hThread <> INVALID_HANDLE_VALUE then
begin
CloseHandle(hThread);
hThread := INVALID_HANDLE_VALUE;
end;
end;
```
|
If I may point to few problems in your code ...
1) You're not checking output of AllocateHwnd. Yes, most probably it will never fail, but still ...
2) AllocateHwnd belogs OUT of try..finally! If it fails, DeallocateHwnd should not be called.
3) AllocateHwnd is not threadsafe. If you call it from multiple threads at the same time, you can run into poblems. [Read more.](http://17slon.com/blogs/gabr/2007/06/allocatehwnd-is-not-thread-safe.html)
As Davy said, use MsgWaitForMultipleObjects instead of creating hidden message window. Then use PostThreadMessage to send messages to thread.
If I may put a plug for a totally free product here - use my [OmniThreadLibrary](http://otl.17slon.com/) instead. Much simpler than messing directly with Windows messaging.
|
229,632 |
<p>In a C program (p1), how to launch a dynamically constructed command (and its arguments) that reads its standard input from p1's standard output?</p>
<p>Note that: </p>
<ol>
<li><p>A method other than this stdout -->
stdin piping is also OK <strong>provided</strong>
it is <strong>PORTABLE</strong> across Windows and
Linux.</p></li>
<li><p>I cannot use C++, Java, Perl, Ruby,
Python, etc here.</p></li>
</ol>
<p>Also, will this have a MinGW dependency for its Windows build?</p>
<p><strong>REOPENED</strong>: The question below answers it for Linux, but this question wants a portable method.
<a href="https://stackoverflow.com/questions/70842/execute-program-from-within-a-c-program">Execute program from within a C program</a></p>
|
[
{
"answer_id": 229786,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 2,
"selected": false,
"text": "<p>It's not 100% clear to me what you're trying to achieve exactly to be honest.</p>\n\n<p>But as I understand it, you could take a look at <a href=\"http://www.netbsd.org/~jmmv/process/\" rel=\"nofollow noreferrer\">Boost.Process</a></p>\n\n<p>You can do things like</p>\n\n<pre><code> bp::child cs = p.start();\n bp::postream& os = cs.get_stdin();\n</code></pre>\n\n<p>And then use the <em>os</em> as any stream to dump stuff in the standard input of your child process.</p>\n\n<p>Anyway, an awful lot can be achieved with the library w.r.t. pipe redirecting and chaining.</p>\n"
},
{
"answer_id": 230046,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>The linked anser (which you reject) refers to POSIX pipes. POSIX is an extension to C, which adds features missing from standard C. POSIX pipes are a good example of such a feature: they were added to POSIX because standard C does not have that functionality.</p>\n"
},
{
"answer_id": 230091,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "<p>The Microsoft C runtime calls it <a href=\"http://msdn.microsoft.com/en-us/library/96ayss4b.aspx\" rel=\"nofollow noreferrer\"><code>_popen</code></a> instead of <a href=\"http://linux.die.net/man/3/popen\" rel=\"nofollow noreferrer\"><code>popen</code></a>, but it appears to have the same functionality in Windows (for console applications) and Linux.</p>\n"
},
{
"answer_id": 230317,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 1,
"selected": false,
"text": "<p>The glib library is written in C and has implementations that are well tested on both Linux and Windows. <a href=\"https://developer.gnome.org/glib/stable/glib-Spawning-Processes.html\" rel=\"nofollow noreferrer\">The manual section on spawning new processes</a> will give you information about how to start a new process and hook into its stdin and stdout handles using the <strong>g_spawn_async_with_pipes</strong> call.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10955/"
] |
In a C program (p1), how to launch a dynamically constructed command (and its arguments) that reads its standard input from p1's standard output?
Note that:
1. A method other than this stdout -->
stdin piping is also OK **provided**
it is **PORTABLE** across Windows and
Linux.
2. I cannot use C++, Java, Perl, Ruby,
Python, etc here.
Also, will this have a MinGW dependency for its Windows build?
**REOPENED**: The question below answers it for Linux, but this question wants a portable method.
[Execute program from within a C program](https://stackoverflow.com/questions/70842/execute-program-from-within-a-c-program)
|
It's not 100% clear to me what you're trying to achieve exactly to be honest.
But as I understand it, you could take a look at [Boost.Process](http://www.netbsd.org/~jmmv/process/)
You can do things like
```
bp::child cs = p.start();
bp::postream& os = cs.get_stdin();
```
And then use the *os* as any stream to dump stuff in the standard input of your child process.
Anyway, an awful lot can be achieved with the library w.r.t. pipe redirecting and chaining.
|
229,633 |
<p>I want my <kbd>AltGr</kbd> key to behave exactly like left <kbd>Alt</kbd>.<br>
Usually, I do this kind of stuff with <a href="http://www.autohotkey.com/" rel="noreferrer">Autohotkey</a>, but I'm open to different solutions. </p>
<p>I tried this:</p>
<pre><code>LControl & RAlt::Alt
</code></pre>
<p>And Autohotkey displayed error about <code>Alt</code> not being recognized action.<br>
Then I tried the following code:</p>
<pre><code>LControl & RAlt::
Send {Alt down}
KeyWait LCtrl
KeyWait Ralt
Send {Alt up}
return
</code></pre>
<p>which sort of works - I'm able to use the <kbd>AltGr</kbd> key for accessing hotkeys, but it still behaves differently:<br>
When I press and release the left <kbd>Alt</kbd>, the first menu item in the current program receives focus.<br>
Pressing and releasing <kbd>AltGr</kbd> with this script does nothing. </p>
<p>Any ideas? Is this even possible with Autohotkey? (remapping right <kbd>Ctrl</kbd> and <kbd>Shift</kbd> to their left siblings was piece of cake)</p>
<p><hr>
Note: I tried switching <code>Alt</code> to <code>LAlt</code> in the code and it made no difference.</p>
|
[
{
"answer_id": 229716,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 0,
"selected": false,
"text": "<p>In AHK, Can you do:</p>\n\n<pre><code>LControl & RAlt::!\n</code></pre>\n\n<p>Or</p>\n\n<pre><code><^>!::!\n</code></pre>\n"
},
{
"answer_id": 230369,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>I got a decent behavior by combining two hotkeys:</p>\n\n<pre><code>LControl & RAlt::Send {Alt}\nRAlt::Alt\n</code></pre>\n\n<p>The first one is for the standalone keypress (avoid to hold it down...), the second one to be used as combination (<kbd>Alt</kbd>+<kbd>F</kbd>, etc.).<br>\nIt isn't perfect, you can't do a combination like <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>T</kbd>, but perhaps it is enough for your needs.</p>\n\n<p>Note that you can do a permanent remapping using the registry. See <a href=\"http://www.autohotkey.com/forum/viewtopic.php?t=9150\" rel=\"nofollow noreferrer\" title=\"problem remapping key in cygwin and putty\">this forum post</a> for an example. Not sure that it applies to compound keys like this one, but I thought I should mention it...</p>\n"
},
{
"answer_id": 396859,
"author": "Ronald Blaschke",
"author_id": 49604,
"author_profile": "https://Stackoverflow.com/users/49604",
"pm_score": 3,
"selected": false,
"text": "<p>As pointed out by PhiLho, Windows provides a way to remap any key, through the registry key <code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout</code>. A basic overview can be found at <a href=\"http://www.microsoft.com/whdc/archive/w2kscan-map.mspx\" rel=\"nofollow noreferrer\">Scan Code Mapper for Windows</a>. A better description is probably <a href=\"https://web.archive.org/web/20120323030858/www.annoyances.org/exec/forum/win2000/n1019911460\" rel=\"nofollow noreferrer\">Answers to Scancode Mapping or Changing Key Values</a>.</p>\n\n<p>I'm using this approach to put the <code>Windows Key</code> on the <code>Caps Lock</code>, because my keyboard doesn't have a <code>Windows Key</code> and I don't need the <code>Caps Lock</code>.</p>\n"
},
{
"answer_id": 460800,
"author": "Tomas Sedovic",
"author_id": 2239,
"author_profile": "https://Stackoverflow.com/users/2239",
"pm_score": 7,
"selected": true,
"text": "<p>Thank you all for answers. I was unable to solve this using AutoHotkey -- PhilLho's answer was close, but I really needed exatly the same behaviour as with left <kbd>Alt</kbd> key. </p>\n\n<p>However, the <a href=\"https://stackoverflow.com/questions/229633/how-to-globally-map-altgr-key-to-alt-key#396859\">registry thing</a> actually worked as I needed. </p>\n\n<p>Save this as <em>AltGR_to_LeftAlt.reg</em> file and run it:</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout]\n\"Scancode Map\"=hex:00,00,00,00,00,00,00,00,02,00,00,00,38,00,38,e0,00,00,00,00\n</code></pre>\n\n<p>Or, there is a GUI tool that does this for you -- it's called <a href=\"https://github.com/randyrants/sharpkeys\" rel=\"noreferrer\">SharpKeys</a> and works peachy:<br>\n<img src=\"https://i361.photobucket.com/albums/oo51/Stark3000/SharpKeys.png\" alt=\"SharpKeys in action\"></p>\n\n<p>Oh, and don't forget to reboot or log off -- it won't work until then!</p>\n"
},
{
"answer_id": 3079446,
"author": "Dave James Miller",
"author_id": 167815,
"author_profile": "https://Stackoverflow.com/users/167815",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code>LControl & *RAlt::Send {LAlt Down}\nLControl & *RAlt Up::Send {LAlt Up}\n</code></pre>\n\n<p>And this for mapping it to the Windows key:</p>\n\n<pre><code>LControl & *RAlt::Send {LWin Down}\nLControl & *RAlt Up::Send {LWin Up}\n</code></pre>\n\n<p>Registry modification using SharpKeys (see above) is more reliable though (if you have administrator access).</p>\n"
},
{
"answer_id": 12771949,
"author": "pbies",
"author_id": 1701812,
"author_profile": "https://Stackoverflow.com/users/1701812",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to map this key globally and with no need to restart system for every change (but once), you may need to write a keyboard filter driver for this purpose. Look <a href=\"https://stackoverflow.com/questions/12612355/swap-alt-keys-functionality\">here</a>.</p>\n"
},
{
"answer_id": 26817583,
"author": "Ashish Porwal",
"author_id": 4230206,
"author_profile": "https://Stackoverflow.com/users/4230206",
"pm_score": 1,
"selected": false,
"text": "<p>Windows Registry Editor Version 5.00:</p>\n<pre><code>[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout]\n"Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,38,00,38,e0,00,00,00,00\n</code></pre>\n<ol>\n<li>Save the above code in reg file.</li>\n<li>Merge it in registry.</li>\n<li>Restart your PC.</li>\n<li>Now check.</li>\n</ol>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239/"
] |
I want my `AltGr` key to behave exactly like left `Alt`.
Usually, I do this kind of stuff with [Autohotkey](http://www.autohotkey.com/), but I'm open to different solutions.
I tried this:
```
LControl & RAlt::Alt
```
And Autohotkey displayed error about `Alt` not being recognized action.
Then I tried the following code:
```
LControl & RAlt::
Send {Alt down}
KeyWait LCtrl
KeyWait Ralt
Send {Alt up}
return
```
which sort of works - I'm able to use the `AltGr` key for accessing hotkeys, but it still behaves differently:
When I press and release the left `Alt`, the first menu item in the current program receives focus.
Pressing and releasing `AltGr` with this script does nothing.
Any ideas? Is this even possible with Autohotkey? (remapping right `Ctrl` and `Shift` to their left siblings was piece of cake)
---
Note: I tried switching `Alt` to `LAlt` in the code and it made no difference.
|
Thank you all for answers. I was unable to solve this using AutoHotkey -- PhilLho's answer was close, but I really needed exatly the same behaviour as with left `Alt` key.
However, the [registry thing](https://stackoverflow.com/questions/229633/how-to-globally-map-altgr-key-to-alt-key#396859) actually worked as I needed.
Save this as *AltGR\_to\_LeftAlt.reg* file and run it:
```
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,38,00,38,e0,00,00,00,00
```
Or, there is a GUI tool that does this for you -- it's called [SharpKeys](https://github.com/randyrants/sharpkeys) and works peachy:

Oh, and don't forget to reboot or log off -- it won't work until then!
|
229,643 |
<p>Following on from a <a href="https://stackoverflow.com/questions/221417/how-do-i-programmatically-access-the-target-path-of-a-windows-symbolic-link">previous question</a>, I am creating a symbolic link on a Server 2008 from a Vista machine using UNC paths. I can create the link just fine. I can go to the Server 2008 box and double click on the link in explorer to open the target file. What I cannot do though is use FileCreateW to get a handle to the UNC path link (from the Vista box). When I try it, it fails and GetLastError() returns error code 1463 (0x5B7), which is:</p>
<blockquote>
<p>The symbolic link cannot be followed because its type is disabled.</p>
</blockquote>
<p>How to enable its "type" in Server 2008 (assuming the error means what it says)?</p>
|
[
{
"answer_id": 230047,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 6,
"selected": false,
"text": "<p>Well I found the answer, though to describe it as badly documented is an understatement!</p>\n\n<p>First of all, <a href=\"http://technet.microsoft.com/en-us/library/cc754077.aspx\" rel=\"noreferrer\">this TechEd article</a> highlights the fact that users can \"enable or disable any of the four evaluations that are available in symbolic links\". Those four \"evaluations\" include remote to local and local to remote. It doesn't give any clue as to how to do this.</p>\n\n<p>However a further search revealed <a href=\"http://itsvista.com/2007/03/fsutil/\" rel=\"noreferrer\">this fsutil help page</a>, which does actually document how to \"enable or disable any of the four evaluations that are available in symbolic links\". So to fix the problem I was having, I need to issue the following command <b>on the Vista box</b>:</p>\n\n<pre><code>fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1\n</code></pre>\n\n<p>in order to allow full access to where symlinks are pointing on both local and remote machines. </p>\n"
},
{
"answer_id": 375543,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks David for the tip, I was becoming desperate to fix this problem which made symlinks mostly useless.</p>\n\n<p>One should note that the default configuration for Vista is L2L and L2R enabled, but R2R and R2L disabled.</p>\n\n<p>I first tried to enable only R2R, but this is not sufficient. R2L has to be enabled too.</p>\n\n<p>The next question on my list: How to get rid of that stupid /D switch for the mklink command for directory links. The default link type should be inferred automatically from the target pathname type!</p>\n"
},
{
"answer_id": 1535604,
"author": "Ian Kelling",
"author_id": 14456,
"author_profile": "https://Stackoverflow.com/users/14456",
"pm_score": 1,
"selected": false,
"text": "<p>Remote junction points work by default. For files you still need symlinks.</p>\n"
},
{
"answer_id": 2556247,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 7,
"selected": true,
"text": "<p>To add to <a href=\"https://stackoverflow.com/a/230047/45375\">@David Arno's helpful answer</a>, based on W7:</p>\n<hr />\n<p><code>fsutil.exe</code> can be made to show what arguments it takes by simply running:</p>\n<pre><code>fsutil behavior set /?\n</code></pre>\n<p>To <strong>report the <em>current</em> configuration</strong>, run <code>fsutil behavior query SymlinkEvaluation</code> - see <a href=\"https://stackoverflow.com/a/24364595/45375\">@Jake1164's answer</a>, particularly with respect to how a <strong>group policy</strong> may be controlling the behavior.</p>\n<p>The <strong>symbolic-link resolution behavior is set on the machine that <em>accesses</em> a given link</strong>, not the machine that hosts it.</p>\n<p>The <strong>behavior codes</strong> for <code>fsutil behavior set SymlinkEvaluation</code> - namely <code>L2L</code>, <code>L2R</code>, <code>R2L</code>, and <code>R2R</code> - mean the following:</p>\n<ul>\n<li><code>L</code> stands for "Local", and <code>R</code> for "Remote"</li>\n<li>The FIRST <code>L</code> or <code>R</code> - <em>before</em> the <code>2</code> - refers to the location of the link itself (as opposed to its target) <em>relative to the machine ACCESSING the link</em>.</li>\n<li>The SECOND <code>L</code> or <code>R</code> - <em>after</em> the <code>2</code> - refers to the location of the link's <em>target relative to the machine where the LINK itself is located</em>.</li>\n</ul>\n<p>Thus, for instance, executing <code>fsutil behavior set SymlinkEvaluation R2L</code> means that you can access links:</p>\n<ul>\n<li>located on a remote machine (<code>R</code>)</li>\n<li>that point to targets on that same remote machine (<code>L</code>)</li>\n</ul>\n<hr />\n<p>Unlike what David experienced on Vista, I, on W7, was able to resolve a remote link that pointed to a resource on another remote machine by enabling R2R alone (and not also having to enable R2L).</p>\n"
},
{
"answer_id": 23746597,
"author": "mwolfe02",
"author_id": 154439,
"author_profile": "https://Stackoverflow.com/users/154439",
"pm_score": 2,
"selected": false,
"text": "<p>These settings can also be manipulated directly via the registry (requires local admin to write):</p>\n\n<p>Registry key: <code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\FileSystem</code></p>\n\n<p>Registry values (name/data pairs):</p>\n\n<pre><code>Name Type Data (1: Enabled; 0: Disabled)\n-------------------------------------------------\nSymlinkLocalToLocalEvaluation REG_DWORD 1\nSymlinkLocalToRemoteEvaluation REG_DWORD 1\nSymlinkRemoteToLocalEvaluation REG_DWORD 1\nSymlinkRemoteToRemoteEvaluation REG_DWORD 1\n</code></pre>\n\n<p>Official documentation is difficult to find, but this appears to be an official Microsoft page: <a href=\"http://gpsearch.azurewebsites.net/default.aspx?policyid=286&ref=1#286\" rel=\"nofollow\">Selectively allow the evaluation of a symbolic link</a></p>\n"
},
{
"answer_id": 24364595,
"author": "Jake1164",
"author_id": 373334,
"author_profile": "https://Stackoverflow.com/users/373334",
"pm_score": 4,
"selected": false,
"text": "<p>I recently found this on all my corporate Windows 7 boxes when one of my legacy programs stopped working. After some searching and finding these settings I tried setting via the command line and via the registry with no relief.</p>\n\n<p>I found that you can use the command from an elevated prompt:</p>\n\n<pre><code>fsutil behavior query SymlinkEvaluation\n</code></pre>\n\n<p>This will return the status of these links AND in my case that they are being controlled by a group policy! Thanks IT department (you f@$#%$rs)!</p>\n\n<p><img src=\"https://i.stack.imgur.com/LE8th.jpg\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 24769314,
"author": "Ryan",
"author_id": 3842837,
"author_profile": "https://Stackoverflow.com/users/3842837",
"pm_score": 2,
"selected": false,
"text": "<p>FYI if you have Group Policies in place controlling SymlinkEvaluation settings you CAN still set them yourself from the command line. They will be overwritten by GP at next reboot/login but your settings will work during your user session.</p>\n\n<p>So as a workaround if you need to set it to something other than what GP dictates you could even run a script at logon to set them after GP is applied.</p>\n"
},
{
"answer_id": 29816288,
"author": "Bulki S Maslom",
"author_id": 1775844,
"author_profile": "https://Stackoverflow.com/users/1775844",
"pm_score": 3,
"selected": false,
"text": "<p>These settings can also be manipulated directly via the registry at <strong><em>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\FileSystem</em></strong>:\nSee SymlinkLocalToLocalEvaluation, SymlinkLocalToRemoteEvaluation, SymlinkRemoteToLocalEvaluation, SymlinkRemoteToRemoteEvaluation.</p>\n\n<p>if with \"fsutil behavior query SymlinkEvaluation\" you get message ..\"<strong>is currently controlled by group policy</strong>\"..., check <strong><em>HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows\\Filesystems\\NTFS</em></strong>\nor simply search throug registry for \"Symlink\"</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7122/"
] |
Following on from a [previous question](https://stackoverflow.com/questions/221417/how-do-i-programmatically-access-the-target-path-of-a-windows-symbolic-link), I am creating a symbolic link on a Server 2008 from a Vista machine using UNC paths. I can create the link just fine. I can go to the Server 2008 box and double click on the link in explorer to open the target file. What I cannot do though is use FileCreateW to get a handle to the UNC path link (from the Vista box). When I try it, it fails and GetLastError() returns error code 1463 (0x5B7), which is:
>
> The symbolic link cannot be followed because its type is disabled.
>
>
>
How to enable its "type" in Server 2008 (assuming the error means what it says)?
|
To add to [@David Arno's helpful answer](https://stackoverflow.com/a/230047/45375), based on W7:
---
`fsutil.exe` can be made to show what arguments it takes by simply running:
```
fsutil behavior set /?
```
To **report the *current* configuration**, run `fsutil behavior query SymlinkEvaluation` - see [@Jake1164's answer](https://stackoverflow.com/a/24364595/45375), particularly with respect to how a **group policy** may be controlling the behavior.
The **symbolic-link resolution behavior is set on the machine that *accesses* a given link**, not the machine that hosts it.
The **behavior codes** for `fsutil behavior set SymlinkEvaluation` - namely `L2L`, `L2R`, `R2L`, and `R2R` - mean the following:
* `L` stands for "Local", and `R` for "Remote"
* The FIRST `L` or `R` - *before* the `2` - refers to the location of the link itself (as opposed to its target) *relative to the machine ACCESSING the link*.
* The SECOND `L` or `R` - *after* the `2` - refers to the location of the link's *target relative to the machine where the LINK itself is located*.
Thus, for instance, executing `fsutil behavior set SymlinkEvaluation R2L` means that you can access links:
* located on a remote machine (`R`)
* that point to targets on that same remote machine (`L`)
---
Unlike what David experienced on Vista, I, on W7, was able to resolve a remote link that pointed to a resource on another remote machine by enabling R2R alone (and not also having to enable R2L).
|
229,656 |
<p>I've got an error in my build which says:</p>
<blockquote>
<p>Error 12 Cannot implicitly convert
type
'System.Collections.Generic.IEnumerator< BaseClass>'
to
'System.Collections.Generic.IEnumerator< IParentClass>'.
An explicit conversion exists (are you
missing a cast?)</p>
</blockquote>
<p>Is it wrong to simply cast it away?</p>
<p>This is my code:</p>
<pre><code>public Dictionary<Int32, BaseClass> Map { get; private set; }
public IEnumerator<BaseClass> GetEnumerator()
{
return this.Map.Values.GetEnumerator();
}
public IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
{
return this.GetEnumerator(); // ERROR!
}
</code></pre>
<p>My question is, can I just change this line:</p>
<pre><code>return this.GetEnumerator();
</code></pre>
<p>to:</p>
<pre><code>return (IEnumerator<IParentClass>)this.GetEnumerator();
</code></pre>
<p>(without any bad side effects)?</p>
<p><strong>Accepted Answer:</strong><br>
I've changed the function to the following (after reading Jon Skeet's post):</p>
<pre><code>IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
{
return this.Map.Values.Cast<IParentClass>().GetEnumerator();
}
</code></pre>
|
[
{
"answer_id": 229667,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "<p><code>IEnumerator<BaseClass></code> and <code>IEnumerator<ParentClass></code> are unrelated, eventhough their generic parameters are. I would instead use a LINQ <code>Select</code> extension method like so:</p>\n\n<pre><code>return this.Select(x => (IParentClass)x).GetEnumerator();\n</code></pre>\n\n<p>or the <code>Cast</code> extension method:</p>\n\n<pre><code>return this.Cast<IParentClass>().GetEnumerator();\n</code></pre>\n"
},
{
"answer_id": 229668,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 2,
"selected": false,
"text": "<p>No, you can't, at least in C# 3.0 and below interface variance is not supported. See Eric Lippert's excellent series on this, and specifically <a href=\"http://blogs.msdn.com/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx\" rel=\"nofollow noreferrer\">this one</a>.</p>\n"
},
{
"answer_id": 229670,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>No you can't, because generics aren't covariant in C# at the moment. .NET itself has some support (for delegates and interfaces) but it's not really used yet.</p>\n\n<p>If you were returning <code>IEnumerable<BaseClass></code> instead of <code>IEnumerator<BaseClass></code> (and assuming .NEt 3.5) you could use <code>Enumerable.Cast</code> - but you'll currently need to write your own extension method, e.g.</p>\n\n<pre><code>public static IEnumerator<TParent> Upcast<TParent, TChild>\n (this IEnumerator<TChild> source)\n where TChild : TParent\n{\n while (source.MoveNext())\n {\n yield return source.Current;\n }\n}\n</code></pre>\n\n<p>Alternatively in your case you could use Cast earlier:</p>\n\n<pre><code>return this.Map.Values.Cast<BaseClass>().GetEnumerator();\n</code></pre>\n"
},
{
"answer_id": 229682,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>No, it isn't safe, see below:</p>\n\n<p>using System.Collections.Generic;\nclass Foo { }\nclass Bar : Foo { }</p>\n\n<pre><code>static class Program\n{\n static IEnumerator<Foo> GetBase() {\n yield return new Foo();\n yield return new Bar();\n }\n static IEnumerator<Bar> GetDerived()\n {\n return (IEnumerator<Bar>)GetBase();\n }\n static void Main()\n {\n var obj = GetDerived(); // EXCEPTION\n }\n}\n</code></pre>\n\n<p>However, you should be able to use an iterator block to do the cast for you?</p>\n\n<pre><code>static IEnumerator<Bar> GetDerived()\n{\n using (IEnumerator<Foo> e = GetBase())\n {\n while (e.MoveNext())\n {\n // or use \"as\" and only return valid data\n yield return (Bar)e.Current;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 229695,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 0,
"selected": false,
"text": "<p>To reason <em>why</em> this isn't appropriate, picture instead of an <code>Enumerator</code>, a <code>List</code>. Both use generics - the compiler doesn't handle either one in a special way in relation to generic arguments.</p>\n\n<pre><code>void doStuff() {\n List<IParentThing> list = getList();\n list.add(new ChildThing2());\n}\n\nList<IParentThing> getList() {\n return new List<ChildThing1>(); //ERROR!\n}\n</code></pre>\n\n<p>This first method is fine - a list of <code>IParentThing</code>s should be able to recieve a <code>ChildThing2</code>. But a list of <code>ChildThing1</code>s cannot handle a <code>ChildThing2</code>, or indeed any implementor of <code>IParentThing</code> other than <code>ChildThing1</code> - in other words, if the <code>List&lt;ChildThing1></code> was allowed to cast as a <code>List&lt;IParent></code>, it would have to be able to deal with <em>all</em> subclasses of <code>IParentThing</code>, not just <code>IParentThing</code> and <code>ChildThing1</code>.</p>\n\n<p>Note that Java generics have a way to say that \"I want a list of anything that inherits from this\" in addition to \"I want a list of anything that this inherits,\" which allows for more interesting (and in my opinion elegant) solutions to some problems.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
I've got an error in my build which says:
>
> Error 12 Cannot implicitly convert
> type
> 'System.Collections.Generic.IEnumerator< BaseClass>'
> to
> 'System.Collections.Generic.IEnumerator< IParentClass>'.
> An explicit conversion exists (are you
> missing a cast?)
>
>
>
Is it wrong to simply cast it away?
This is my code:
```
public Dictionary<Int32, BaseClass> Map { get; private set; }
public IEnumerator<BaseClass> GetEnumerator()
{
return this.Map.Values.GetEnumerator();
}
public IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
{
return this.GetEnumerator(); // ERROR!
}
```
My question is, can I just change this line:
```
return this.GetEnumerator();
```
to:
```
return (IEnumerator<IParentClass>)this.GetEnumerator();
```
(without any bad side effects)?
**Accepted Answer:**
I've changed the function to the following (after reading Jon Skeet's post):
```
IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
{
return this.Map.Values.Cast<IParentClass>().GetEnumerator();
}
```
|
No you can't, because generics aren't covariant in C# at the moment. .NET itself has some support (for delegates and interfaces) but it's not really used yet.
If you were returning `IEnumerable<BaseClass>` instead of `IEnumerator<BaseClass>` (and assuming .NEt 3.5) you could use `Enumerable.Cast` - but you'll currently need to write your own extension method, e.g.
```
public static IEnumerator<TParent> Upcast<TParent, TChild>
(this IEnumerator<TChild> source)
where TChild : TParent
{
while (source.MoveNext())
{
yield return source.Current;
}
}
```
Alternatively in your case you could use Cast earlier:
```
return this.Map.Values.Cast<BaseClass>().GetEnumerator();
```
|
229,671 |
<p>I read the following in a review of Knuth's "The Art of Computer Programming":</p>
<p>"The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop."</p>
<p>(<a href="http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N" rel="nofollow noreferrer">http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N</a>)</p>
<p>What is this guy talking about? How could you implement a for loop that wasn't just syntactic sugar for a while loop?</p>
|
[
{
"answer_id": 229694,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "<p>He probably refers to for loops like <code>for i:=0 to N</code> and for-each loops that iterate over the elements of a set. I suspect all languages that have a C-style for loop actually got it from C.</p>\n"
},
{
"answer_id": 229704,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 6,
"selected": true,
"text": "<p>Consider this:</p>\n\n<pre><code>for i:=0 to 100 do { ... }\n</code></pre>\n\n<p>In this case, we could replace the final value, 100, by a function call:</p>\n\n<pre><code>for i:=0 to final_value() do { ... }\n</code></pre>\n\n<p>... and the <code>final_value</code>-function would be called only once.</p>\n\n<p>In C, however:</p>\n\n<pre><code>for (int i=0; i<final_value(); ++i) // ...\n</code></pre>\n\n<p>... the <code>final_value</code>-function would be called for each iteration through the loop, thus making it a good practice to be more verbose:</p>\n\n<pre><code>int end = final_value();\nfor (int i=0; i<end; ++i) // ...\n</code></pre>\n"
},
{
"answer_id": 229723,
"author": "Tarski",
"author_id": 27653,
"author_profile": "https://Stackoverflow.com/users/27653",
"pm_score": 2,
"selected": false,
"text": "<p>Loop unrolling perhaps? If you know how many time the for loop is going to execute you can literally copy and paste the contents of the loop. Most while loops are going to be be based on some condition that isn't a simple counting from 0 to N, so won't be able to use this optimization.</p>\n\n<p>Take this example</p>\n\n<pre><code>int x;\nfor (x = 10; x != 0; --x)\n{\n printf (\"Hello\\n\");\n}\n</code></pre>\n\n<p>I know you would normally do <code>x = 0; x <= 10; ++x</code>, but all will be revealed in the assembly.</p>\n\n<p>some pseudo assembly:</p>\n\n<pre><code>mov 10, eax\nloop:\nprint \"hello\"\ndec eax\njne loop\n</code></pre>\n\n<p>In this example we keep jumping back around the loop to print \"hello\" 10 times. However we are evaluating the condition with the <code>jne</code> instruction each time around the loop.</p>\n\n<p>If we unrolled it we could simply put</p>\n\n<pre><code>print \"hello\"\nprint \"hello\"\nprint \"hello\"\nprint \"hello\"\nprint \"hello\"\nprint \"hello\"\nprint \"hello\"\nprint \"hello\"\nprint \"hello\"\nprint \"hello\"\n</code></pre>\n\n<p>We wouldn't need any of the other instructions, so it is faster. This is only a simple example - I'll try to find a better one!</p>\n"
},
{
"answer_id": 229732,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Magnus has it right, but one should also note that in most languages (pre-C), the conditional is the <em>end</em> criterion (i.e. \"stop when i equals 100\"). In C (and most post-C languages), it's the <em>continue</em> criterion (i.e., \"continue while i is less than 100\").</p>\n"
},
{
"answer_id": 229736,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>Basically, the C (and Java, JavaScript, and lot of C-derived languages) <code>for</code> loop is indeed syntactic sugar for a <code>while</code> loop:</p>\n\n<pre><code>for (int i = 0; i < max; i++) { DoStuff(); }\n</code></pre>\n\n<p>which is a very current idiom is strictly equivalent to:</p>\n\n<pre><code>int i = 0; while (i < max) { DoStuff(); i++; }\n</code></pre>\n\n<p>(Putting apart scope issues, which changed between versions of C anyway.)</p>\n\n<p>The stop condition is evaluated on each iteration. It can be interesting in some cases, but it can be a pitfall: I saw <code>i < strlen(longConstantString)</code> in a source, which is a major way to slow down a program, because <code>strlen</code> is a costly function in C.<br>\nSomehow, the <code>for</code> loop is mostly designed to run a number of times know in advance, you can still use <code>break</code> to terminate early, so the dynamic evaluation of the stop term is more annoying than useful: if you really need dynamic evaluation, you use <code>while () {}</code> (or <code>do {} while ()</code>).</p>\n\n<p>On some other languages, like Lua, the stop condition is evaluated only once, at loop init. It helps predicting loop behavior and it is often more performant.</p>\n"
},
{
"answer_id": 229743,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 2,
"selected": false,
"text": "<p>On x86, for looping can be done on assembly level without making a while loop. The <strong>loop</strong> instruction decreases the value of the register ecx and jumps to the operand if ecx is greater than 0, it does nothing otherwise. This is a classic for loop.</p>\n\n<pre><code>mov ecx, 0x00000010h\nloop_start:\n;loop body\nloop loop_start\n;end of loop\n</code></pre>\n"
},
{
"answer_id": 229915,
"author": "codebunny",
"author_id": 13667,
"author_profile": "https://Stackoverflow.com/users/13667",
"pm_score": 3,
"selected": false,
"text": "<p>If all you want is a simple counting loop, then</p>\n\n<pre><code>for (i=0; i<100; i++) dostuff();\n</code></pre>\n\n<p>will be fine, and the compiler can optimize it.</p>\n\n<p>If you use a function in the continue part of the for statement, like</p>\n\n<pre><code>for (i=0; i<strlen(s); i++) dostuff();\n</code></pre>\n\n<p>then the function will be evaluated every time and this is usually not a good idea as the function overheads will slow your process. Sometimes it can slow your process to the point of unusability.</p>\n\n<p>If the function's return value will not change during the iteration, extract it from the loop:</p>\n\n<pre><code>slen = strlen(s);\nfor (i=0; i<slen; i++) dostuff();\n</code></pre>\n\n<p>But there are times when the function will be returning different values each call, and then you do not want it extracted from the loop:</p>\n\n<pre><code>for (isread(fd, &buffer, ISFIRST);\n isstat(fd) >= 0;\n isread(fd, &buffer, ISNEXT)\n{\n dostuff(buffer);\n}\n</code></pre>\n\n<p>and you want it evaluated each time. (That is a slightly contrived example based on work that I do, but it shows the potential).</p>\n\n<p>C gives you the raw ability to roll your loop any way you can. You have to know how your loop is supposed to work, and you optimize it as best you can, depending on your needs.</p>\n\n<p>That last example could have been expressed as a while loop:</p>\n\n<pre><code>isread(fd, &buffer, ISFIRST);\nwhile (isstat(fd) >= 0)\n{\n dostuff(buffer);\n isread(fd, &buffer, ISNEXT);\n}\n</code></pre>\n\n<p>but it's not as neat, and if I use a continue in the loop, then I have to call the iterating isread again. Putting the whole thing in a for loop makes it neater, and ensures that the iterating isread is called each loop.</p>\n\n<p>I write lower-level functions so they can be used in for loops like this. It brings all elements of the while loop together so you can understand it more easily.</p>\n"
},
{
"answer_id": 229922,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 2,
"selected": false,
"text": "<p>In Ada (and I believe most other Algol-derived languages) the terminating condition of a \"for\" loop is evaluated only once, at the beginning of the loop. For example, suppose you have the following code in Ada</p>\n\n<pre><code>q := 10;\nfor i in 1..q loop\n q := 20;\n --// Do some stuff\nend loop;\n</code></pre>\n\n<p>This loop will iterate exactly 10 times, because q was 10 when the loop started. However, if I write the seemingly equivalent loop in C:</p>\n\n<pre><code>q = 10;\nfor (int i=0;i<q;i++) {\n q = 20;\n // Do some stuff\n}\n</code></pre>\n\n<p>Then the loop iterates 20 times, because q was changed to 20 by the time i got large enough for it to matter.</p>\n\n<p>The C way is more flexible, of course. However this has quite a few negative implications. The obvious is that the program has to waste effort rechecking the loop condition every cycle. A good optimizer might be smart enough to work around the problem in simple cases like this, but what happens if \"q\" is a global and \"do some stuff\" includes a procedure call (and thus in theory could modify q)? </p>\n\n<p>The hard fact is that we just know <em>way</em> more about the Ada loop than we do about the C loop. That means that with the same level of intelligence and effort in its optimizer, Ada can do a lot better job of optimizing. For instance, the Ada compiler knows that it can replace the entire loop with 10 copies of the contents, no matter what those contents are. A C optimizer would have to examine and analyze the contents.</p>\n\n<p>This is actually just one of many ways where the design of the C syntax hamstrings the compiler.</p>\n"
},
{
"answer_id": 229988,
"author": "RuntimeException",
"author_id": 15789,
"author_profile": "https://Stackoverflow.com/users/15789",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe Knuth is referring to BASIC. </p>\n\n<p>In BASIC (the older one, I dont know about VB), FOR loops were implemented differently. </p>\n\n<p>E.g. to loop ten times</p>\n\n<p>FOR N=1 TO 10</p>\n\n<p>... </p>\n\n<p>NEXT N</p>\n\n<p>---- OR ----\nto find sum of even numbers below 100</p>\n\n<p>FOR N=0 TO 100 STEP 2</p>\n\n<p>...</p>\n\n<p>NEXT N</p>\n\n<p>In C, you may have any condition in \"for\" to check for exiting the loop. More flexible, I think.</p>\n"
},
{
"answer_id": 230017,
"author": "FredV",
"author_id": 30829,
"author_profile": "https://Stackoverflow.com/users/30829",
"pm_score": 1,
"selected": false,
"text": "<p>What these language purist never seem to realize is the whole point of C, and to an extent C++, is giving the possibility to implement what you want and how you want it. Now admittedly if the result of your end expression changes, it would be better to just use a while loop. Maybe the problem is programmers get the impression C implements a \"high level\" for, but everyone should know C is a pretty low-level language.</p>\n"
},
{
"answer_id": 232833,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<blockquote>\n<p>The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop.</p>\n</blockquote>\n</blockquote>\n<p><em>Muaahahahaa!</em></p>\n<p>I like the basic (pun intented) assertions of the reviewer:</p>\n<ul>\n<li>Kernighan's mistakes</li>\n<li>infamous fact</li>\n<li>fails to match the behavior of most other languages</li>\n</ul>\n<p>For me, it smells of someone who never succeeded mastering C's basic features/philosphy.</p>\n<h2>Introduction</h2>\n<p>As I was still studying physics in university, I found C (i.e. C-like languages) were to become my language of choice when I discovered C's <strong>for</strong> loop.</p>\n<p>So apparently, one's style failure is another's style success. This will end the subjective part of this discussion.</p>\n<h2>Perhaps Kernigan's for should have been called loop?</h2>\n<p>Just kidding? Perhaps not.</p>\n<p>The author of the review apparently decided that each language construct should have the same behavior across languages. So renaming <strong>for</strong> as <strong>loop</strong> would have eased his/her discomfort.</p>\n<p>The problem is that the author fails to understand that C's <strong>for</strong> is an extension of <strong>while</strong>, not a different loop. This means <strong>while</strong> is a syntactic sugar light version of <strong>for</strong>, instead of the <strong>while</strong> other languages where <strong>for</strong> may have been castrated down.</p>\n<h2>Is C for really needed?</h2>\n<p>Quoting the author of the review, he/she makes the following assertions about <strong>for</strong> and <strong>while</strong>:</p>\n<ul>\n<li><strong>for</strong> is for constant loops, from a beginning to an end</li>\n<li><strong>while</strong> is for loops evaluating a condition at each iteration</li>\n</ul>\n<p>Having orthogonal features is a good thing when you can combine them. But in all languages I know, there is no way to combine both <strong>for</strong> and <strong>while</strong> together.</p>\n<p>Example: What if, for the reviewer's language, you need a loop going from a beginning to an end (like a <strong>for</strong>), but still able to evaluate at each loop iteration (like a <strong>while</strong>): You could need to find in a subset of a container (not the whole container), a value according to some stateful test?</p>\n<p>In a C-like language, you use the <strong>for</strong>. In the reviewer's ideal language, you just, well, hack some ugly code, crying because you don't have a <strong>for_while</strong> loop (or C's <strong>for</strong> loop).</p>\n<h2>Conclusion</h2>\n<p>I believe we can summarize the reviewer's critic of C (and C-like languages) with the following statement "<em>Kernigan's infamous mistake of not giving C the syntax of the previous, existing languages</em>", which can be summarized again as "<em>Never think different</em>".</p>\n<p>Quoting Bjarne Stroustrup:</p>\n<blockquote>\n<blockquote>\n<p>There are only two kinds of languages: the ones people complain about and the ones nobody uses.</p>\n</blockquote>\n</blockquote>\n<p>So, all in all, the reviewer's comment should be considered as a praise.</p>\n<p>^_^</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] |
I read the following in a review of Knuth's "The Art of Computer Programming":
"The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop."
(<http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N>)
What is this guy talking about? How could you implement a for loop that wasn't just syntactic sugar for a while loop?
|
Consider this:
```
for i:=0 to 100 do { ... }
```
In this case, we could replace the final value, 100, by a function call:
```
for i:=0 to final_value() do { ... }
```
... and the `final_value`-function would be called only once.
In C, however:
```
for (int i=0; i<final_value(); ++i) // ...
```
... the `final_value`-function would be called for each iteration through the loop, thus making it a good practice to be more verbose:
```
int end = final_value();
for (int i=0; i<end; ++i) // ...
```
|
229,676 |
<p>Greetings,</p>
<p>The VBA code below will create an Excel QueryTable object and display it starting on Range("D2"). The specific address of this target range is immaterial.</p>
<p>My question is -- is it possible to manually feed in values to an in-memory Recordset, and then have the table read from it? In other words, I want to specify the table columns and values in VBA, not have them come from a database or file.</p>
<pre><code>Public Sub Foo()
Dim blah As QueryTable
Dim rngTarget As Range
Dim strQuery As String
strQuery = "SELECT * FROM MY_TABLE"
Set rngTarget = Range("D2")
Dim qt As QueryTable
Set qt = rngTarget.Worksheet.QueryTables.Add(Connection:= _
"ODBC;DRIVER=SQL Server;SERVER=MY_SQL_SERVER;APP=MY_APP;Trusted_Connection=Yes", Destination:=rngTarget)
With qt
.CommandText = strQuery
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.Name = "MY_RANGE_NAME"
.MaintainConnection = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = False
.Refresh BackgroundQuery:=False
End With
End Sub
</code></pre>
|
[
{
"answer_id": 231714,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 0,
"selected": false,
"text": "<p>From the Excel VB Help\nThe connection parameter can be:</p>\n\n<p>\"An ADO or DAO Recordset object. Data is read from the ADO or DAO recordset. Microsoft Excel retains the recordset until the query table is deleted or the connection is changed. The resulting query table cannot be edited\"</p>\n\n<p>So yes it looks like you can do it.</p>\n"
},
{
"answer_id": 248530,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, sure.</p>\n\n<pre><code> Dim vConnection As Variant, vCommandText As Variant\n Dim r As ADODB.Recordset\n Dim i As Long\n\n 'Save query table definition\n vConnection = QueryTable.Connection\n vCommandText = QueryTable.CommandText\n\n\n Set r = New ADODB.Recordset\n <populate r>\n\n Set QueryTable.Recordset = r\n QueryTable.Refresh False\n\n 'Restore Query Table definition\n Set QueryTable.Recordset = Nothing\n QueryTable.Connection = vConnection\n QueryTable.CommandText = vCommandText\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7311/"
] |
Greetings,
The VBA code below will create an Excel QueryTable object and display it starting on Range("D2"). The specific address of this target range is immaterial.
My question is -- is it possible to manually feed in values to an in-memory Recordset, and then have the table read from it? In other words, I want to specify the table columns and values in VBA, not have them come from a database or file.
```
Public Sub Foo()
Dim blah As QueryTable
Dim rngTarget As Range
Dim strQuery As String
strQuery = "SELECT * FROM MY_TABLE"
Set rngTarget = Range("D2")
Dim qt As QueryTable
Set qt = rngTarget.Worksheet.QueryTables.Add(Connection:= _
"ODBC;DRIVER=SQL Server;SERVER=MY_SQL_SERVER;APP=MY_APP;Trusted_Connection=Yes", Destination:=rngTarget)
With qt
.CommandText = strQuery
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.Name = "MY_RANGE_NAME"
.MaintainConnection = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = False
.Refresh BackgroundQuery:=False
End With
End Sub
```
|
Yes, sure.
```
Dim vConnection As Variant, vCommandText As Variant
Dim r As ADODB.Recordset
Dim i As Long
'Save query table definition
vConnection = QueryTable.Connection
vCommandText = QueryTable.CommandText
Set r = New ADODB.Recordset
<populate r>
Set QueryTable.Recordset = r
QueryTable.Refresh False
'Restore Query Table definition
Set QueryTable.Recordset = Nothing
QueryTable.Connection = vConnection
QueryTable.CommandText = vCommandText
```
|
229,726 |
<p>I've seen <a href="https://stackoverflow.com/questions/49156/importing-javascript-in-jsp-tags">this question</a> regading the importing of js-files related to the tag content itself. I have a similar problem, here I have a jsp tag that generates some HTML and has a generic js-implementation that handles the behavior of this HTML. Furthermore I need to write some initialization statements, so I can use it afterwards through JavaScript. To be possible to use this "handler" within my JavaScript, it should be somehow accessible.</p>
<p>The question is... Is it Ok to write inline <script> tags along with my HTML for instantiation and initialization purposes (personally I don't think its very elegant)? And about being accessible to the JS world, should I leave a global var referencing my handler object (not very elegant aswell I think), are there better ways to do it? </p>
|
[
{
"answer_id": 229771,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Although I agree that it's not entirely elegant, I've been known to do it a few times when combining server-side decisions with an AJAX-integrated environment. Echoing inline <script> tags in order to initialize some variables isn't a terrible thing, as long as no one sees it.</p>\n\n<p>As for better methods, I am unaware of these. I've done this so rarely that I haven't sought a more elegant or \"proper\" solution.</p>\n"
},
{
"answer_id": 229772,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not entirely sure what you asking here, but I don't there's anything wrong with including <code><script></code> tags in the JSP to instantiate javascript code. I often follow this model, writing the library code in external javascript files, and then calling the constructors to my objects from the <code><script></code> tags.</p>\n\n<p>This makes debugging easy, since the logic is all in the external files (and firebug seems to have trouble with debugging inline javascript code). The libraries get cached, but the data instantiating them doesn't (which is the desired behavior).</p>\n\n<p>The alternative is to have the instantiation code dynamically generated in an external javascript file or AJAX call. I've done this too, with positive results.</p>\n\n<p>I think the deciding factor is how much dynamic data you have. If you need to represent large data structures, I would serve it out via an AJAX call that returns JSON. If its a simple call to a constructor, put it in the JSP.</p>\n\n<p>As for the global variable, I will often have a global for the top-level object that kicks everything off. Inside that, are all the other references to the helper objects.</p>\n"
},
{
"answer_id": 229775,
"author": "Dennis",
"author_id": 17874,
"author_profile": "https://Stackoverflow.com/users/17874",
"pm_score": 0,
"selected": false,
"text": "<p>It is ok with use <code><script></code> tags in line with HTML. There are times when it is needed, but as far as any better ways I do not know. Without making things seem more complicated it is easier to use the <code><script></code> tag then trying to find a way to implement js files.</p>\n"
},
{
"answer_id": 229776,
"author": "Magnar",
"author_id": 1123,
"author_profile": "https://Stackoverflow.com/users/1123",
"pm_score": 4,
"selected": true,
"text": "<p>You should strive for javascript in its own files. This is usually done with <a href=\"http://accessites.org/site/2007/02/graceful-degradation-progressive-enhancement/\" rel=\"noreferrer\">Progressive Enhancement</a>. But some times you don't have a choice, for instance when the same JSP renders pages in different languages. Here's a real-life example:</p>\n\n<p>The JSP:</p>\n\n<pre><code> <script src=\"/javascript/article_admin.js\"></script> \n <script type=\"text/javascript\"> \n NP_ArticleAdmin.initialize({ \n text: { \n please_confirm_deletion_of: '<i18n:output text=\"please.confirm.deletion.of\"/>', \n this_cannot_be_undone: '<i18n:output text=\"this.cannot.be.undone\"/>' \n } \n }); \n </script> \n</code></pre>\n\n<p>The javascript (article_admin.js):</p>\n\n<pre><code> /*global NP_ArticleAdmin, jQuery, confirm */ \n NP_ArticleAdmin = function ($) { \n var text; \n\n function delete_article(event) { \n var article = $(this).parents(\"li.article\"), \n id = article.attr(\"id\"), \n name = article.find(\"h3.name\").html(); \n if (confirm(text.please_confirm_deletion_of + name + text.this_cannot_be_undone)) { \n $.post(\"/admin/delete_article\", {id: id}); \n article.fadeOut(); \n } \n event.preventDefault(); \n return false; \n } \n\n function initialize(data) { \n text = data.text; \n $(\"#articles a.delete\").click(delete_article); \n } \n\n return {initialize: initialize}; \n }(jQuery);\n</code></pre>\n\n<p>In this example, the only javascript in the JSP-file is the part that needs to be there. The core functionality is separated in its own js-file.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540/"
] |
I've seen [this question](https://stackoverflow.com/questions/49156/importing-javascript-in-jsp-tags) regading the importing of js-files related to the tag content itself. I have a similar problem, here I have a jsp tag that generates some HTML and has a generic js-implementation that handles the behavior of this HTML. Furthermore I need to write some initialization statements, so I can use it afterwards through JavaScript. To be possible to use this "handler" within my JavaScript, it should be somehow accessible.
The question is... Is it Ok to write inline <script> tags along with my HTML for instantiation and initialization purposes (personally I don't think its very elegant)? And about being accessible to the JS world, should I leave a global var referencing my handler object (not very elegant aswell I think), are there better ways to do it?
|
You should strive for javascript in its own files. This is usually done with [Progressive Enhancement](http://accessites.org/site/2007/02/graceful-degradation-progressive-enhancement/). But some times you don't have a choice, for instance when the same JSP renders pages in different languages. Here's a real-life example:
The JSP:
```
<script src="/javascript/article_admin.js"></script>
<script type="text/javascript">
NP_ArticleAdmin.initialize({
text: {
please_confirm_deletion_of: '<i18n:output text="please.confirm.deletion.of"/>',
this_cannot_be_undone: '<i18n:output text="this.cannot.be.undone"/>'
}
});
</script>
```
The javascript (article\_admin.js):
```
/*global NP_ArticleAdmin, jQuery, confirm */
NP_ArticleAdmin = function ($) {
var text;
function delete_article(event) {
var article = $(this).parents("li.article"),
id = article.attr("id"),
name = article.find("h3.name").html();
if (confirm(text.please_confirm_deletion_of + name + text.this_cannot_be_undone)) {
$.post("/admin/delete_article", {id: id});
article.fadeOut();
}
event.preventDefault();
return false;
}
function initialize(data) {
text = data.text;
$("#articles a.delete").click(delete_article);
}
return {initialize: initialize};
}(jQuery);
```
In this example, the only javascript in the JSP-file is the part that needs to be there. The core functionality is separated in its own js-file.
|
229,756 |
<p>I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the <a href="http://www.secdev.org/projects/scapy/build_your_own_tools.html" rel="noreferrer">scapy site</a>, they give a sample program which I'm not able to run on my own machine:</p>
<pre><code>#! /usr/bin/env python
import sys
from scapy import sr1,IP,ICMP
p=sr1(IP(dst=sys.argv[1])/ICMP())
if p:
p.show()
</code></pre>
<p>To which I get:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 4, in <module>
from scapy import sr1,IP,ICMP
ImportError: cannot import name sr1
</code></pre>
<p>So my question then is: when installing Python libraries, do I need to change my path or anything similar? Also, is there something I can run in the interpreter to tell me the contents of the scapy package? I can run <code>from scapy import *</code> just fine, but since I have no idea what's inside it, it's hard to use it.</p>
|
[
{
"answer_id": 229819,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 4,
"selected": true,
"text": "<p>With the caveat from Federico Ramponi \"You should use scapy as an interpreter by its own, not as a library\", I want to answer the non-scapy-specific parts of the question.</p>\n\n<p><strong>Q:</strong> when installing Python libraries, do I need to change my path or anything similar?</p>\n\n<p><strong>A:</strong> I think you are talking about changing <code>PYTHONPATH</code> system-wide. This is usually not required or a good idea.</p>\n\n<p>Third party Python libraries should either be installed in system directories, such as <code>/usr/lib/python2.5/site-packages</code>, or installed locally, in which case you might want to set <code>PYTHONPATH</code> in your Makefile or a in driver shell script.</p>\n\n<p><strong>Q:</strong> Also, is there something I can run in the interpreter to tell me the contents of the scapy package?</p>\n\n<p><strong>A:</strong> You can do something like this:</p>\n\n<pre><code>>>> import scapy\n>>> dir(scapy)\n</code></pre>\n\n<p>Or even better:</p>\n\n<pre><code>>>> import scapy\n>>> help(scapy)\n</code></pre>\n\n<p>Bonus question asked in a comment.</p>\n\n<p><strong>Q:</strong> Is 'import scapy' the same as 'from scapy import *'?</p>\n\n<p><strong>A:</strong> <code>import scapy</code> binds the scapy name in the local namespace to the scapy module object. OTOH, <code>from scapy import *</code> does not bind the module name, but all public names defined in the scapy module are bound in the local namespace.</p>\n\n<p>See paragraphs 6 and 7 of the Python Reference Manual, <a href=\"http://www.python.org/doc/2.5.2/ref/import.html\" rel=\"nofollow noreferrer\">6.12 The import statement</a>.</p>\n"
},
{
"answer_id": 229842,
"author": "kaleissin",
"author_id": 30368,
"author_profile": "https://Stackoverflow.com/users/30368",
"pm_score": 2,
"selected": false,
"text": "<p>It tells you that it can't find sr1 in scapy. Not sure just how newbite you are, but the interpreter is always your friend. Fire up the interpreter (just type \"python\" on the commandline), and at the prompt (>>>) type (but don't type the >'s, they'll show up by themselves):</p>\n\n<pre><code>>>> import scapy\n>>> from pprint import pformat\n>>> pformat(dir(scapy))\n</code></pre>\n\n<p>The last line should print a lot of stuff. Do you see 'sr1', 'IP', and 'ICMP' there anywhere? If not, the example is at fault.</p>\n\n<p>Try also help(scapy)</p>\n\n<p>That's about how much I can help you without installing scapy and looking at your actual source-file myself.</p>\n"
},
{
"answer_id": 230333,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"http://www.secdev.org/projects/scapy/index.html\" rel=\"nofollow noreferrer\">scapy</a> package is a tool for network manipulation and monitoring. I'm curious as to what you're trying to do with it. It's rude to spy on your friends. :-)</p>\n\n<pre><code>coventry@metta:~/src$ wget -q http://www.secdev.org/projects/scapy/files/scapy-latest.zip\ncoventry@metta:~/src$ unzip -qq scapy-latest.zip \nwarning [scapy-latest.zip]: 61 extra bytes at beginning or within zipfile\n (attempting to process anyway)\ncoventry@metta:~/src$ find scapy-2.0.0.10 -name \\*.py | xargs grep sr1\nscapy-2.0.0.10/scapy/layers/dns.py: r=sr1(IP(dst=nameserver)/UDP()/DNS(opcode=5,\nscapy-2.0.0.10/scapy/layers/dns.py: r=sr1(IP(dst=nameserver)/UDP()/DNS(opcode=5,\nscapy-2.0.0.10/scapy/layers/inet6.py:from scapy.sendrecv import sr,sr1,srp1\nscapy-2.0.0.10/scapy/layers/snmp.py: r = sr1(IP(dst=dst)/UDP(sport=RandShort())/SNMP(community=community, PDU=SNMPnext(varbindlist=[SNMPvarbind(oid=oid)])),timeout=2, chainCC=1, verbose=0, retry=2)\nscapy-2.0.0.10/scapy/layers/inet.py:from scapy.sendrecv import sr,sr1,srp1\nscapy-2.0.0.10/scapy/layers/inet.py: p = sr1(IP(dst=target, options=\"\\x00\"*40, proto=200)/\"XXXXYYYYYYYYYYYY\",timeout=timeout,verbose=0)\nscapy-2.0.0.10/scapy/sendrecv.py:def sr1(x,filter=None,iface=None, nofilter=0, *args,**kargs):\n</code></pre>\n\n<p>According to the last line, <code>sr1</code> is a function defined in <code>scapy.sendrecv</code>. Someone should file a documentation bug with the author.</p>\n"
},
{
"answer_id": 942244,
"author": "Emilio",
"author_id": 39796,
"author_profile": "https://Stackoverflow.com/users/39796",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem, in the scapy v2.x use </p>\n\n<pre><code> from scapy.all import * \n</code></pre>\n\n<p>instead the v1.x</p>\n\n<pre><code> from scapy import *\n</code></pre>\n\n<p>as written <a href=\"http://www.secdev.org/projects/scapy/doc/installation.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Enjoy it =)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the [scapy site](http://www.secdev.org/projects/scapy/build_your_own_tools.html), they give a sample program which I'm not able to run on my own machine:
```
#! /usr/bin/env python
import sys
from scapy import sr1,IP,ICMP
p=sr1(IP(dst=sys.argv[1])/ICMP())
if p:
p.show()
```
To which I get:
```
Traceback (most recent call last):
File "test.py", line 4, in <module>
from scapy import sr1,IP,ICMP
ImportError: cannot import name sr1
```
So my question then is: when installing Python libraries, do I need to change my path or anything similar? Also, is there something I can run in the interpreter to tell me the contents of the scapy package? I can run `from scapy import *` just fine, but since I have no idea what's inside it, it's hard to use it.
|
With the caveat from Federico Ramponi "You should use scapy as an interpreter by its own, not as a library", I want to answer the non-scapy-specific parts of the question.
**Q:** when installing Python libraries, do I need to change my path or anything similar?
**A:** I think you are talking about changing `PYTHONPATH` system-wide. This is usually not required or a good idea.
Third party Python libraries should either be installed in system directories, such as `/usr/lib/python2.5/site-packages`, or installed locally, in which case you might want to set `PYTHONPATH` in your Makefile or a in driver shell script.
**Q:** Also, is there something I can run in the interpreter to tell me the contents of the scapy package?
**A:** You can do something like this:
```
>>> import scapy
>>> dir(scapy)
```
Or even better:
```
>>> import scapy
>>> help(scapy)
```
Bonus question asked in a comment.
**Q:** Is 'import scapy' the same as 'from scapy import \*'?
**A:** `import scapy` binds the scapy name in the local namespace to the scapy module object. OTOH, `from scapy import *` does not bind the module name, but all public names defined in the scapy module are bound in the local namespace.
See paragraphs 6 and 7 of the Python Reference Manual, [6.12 The import statement](http://www.python.org/doc/2.5.2/ref/import.html).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.